sootsim 0.1.66 → 0.1.67

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 (147) hide show
  1. package/dist-cli/bin.js +3 -3
  2. package/dist-cli/chunks/{agent-IW7CCSSI.js → agent-Z45KTLTP.js} +2 -2
  3. package/dist-cli/chunks/{agent-wrapper-5DJBERZP.js → agent-wrapper-EEKVEJOC.js} +2 -2
  4. package/dist-cli/chunks/{assert-RHILK3WR.js → assert-MDYZKXZ6.js} +2 -2
  5. package/dist-cli/chunks/auto-bootstrap-YZ6C6VYO.js +2 -0
  6. package/dist-cli/chunks/beta-WXH75XUE.js +2 -0
  7. package/dist-cli/chunks/chunk-2HKCZLY7.js +372 -0
  8. package/dist-cli/chunks/{chunk-UMXVWFST.js → chunk-2I535GZU.js} +1 -1
  9. package/dist-cli/chunks/{chunk-TJEP4DBA.js → chunk-3KVVIZ6M.js} +2 -2
  10. package/dist-cli/chunks/chunk-42NMKOVE.js +3 -0
  11. package/dist-cli/chunks/{chunk-WAOLC7WV.js → chunk-4H6LBA4A.js} +1 -1
  12. package/dist-cli/chunks/{chunk-LVFWALS4.js → chunk-4QSGVTBE.js} +2 -2
  13. package/dist-cli/chunks/{chunk-T4YLDM5C.js → chunk-52RZ6TSZ.js} +3 -3
  14. package/dist-cli/chunks/{chunk-AYBGSHQK.js → chunk-5WRBVYML.js} +2 -2
  15. package/dist-cli/chunks/{chunk-BD76YSRN.js → chunk-67566AJS.js} +2 -2
  16. package/dist-cli/chunks/chunk-6O64VUC6.js +2 -0
  17. package/dist-cli/chunks/chunk-7PQHQOCI.js +186 -0
  18. package/dist-cli/chunks/{chunk-V4SZERWD.js → chunk-AQ7YR4MO.js} +14 -14
  19. package/dist-cli/chunks/{chunk-6AP6LXVV.js → chunk-ATRGAFJD.js} +1 -1
  20. package/dist-cli/chunks/{chunk-LRBMW2WC.js → chunk-BCVVANS5.js} +2 -2
  21. package/dist-cli/chunks/chunk-CUNQTNH4.js +35 -0
  22. package/dist-cli/chunks/{chunk-DEQ7RED3.js → chunk-DOWYG3HG.js} +2 -2
  23. package/dist-cli/chunks/{chunk-XZ5SQJM2.js → chunk-EJTXYZEF.js} +128 -36
  24. package/dist-cli/chunks/{chunk-4NT6VRUU.js → chunk-F23Y4HMT.js} +1 -1
  25. package/dist-cli/chunks/{chunk-M2Q4FXRE.js → chunk-F4RC4AOY.js} +1 -1
  26. package/dist-cli/chunks/chunk-GFVC6EEB.js +1 -0
  27. package/dist-cli/chunks/{chunk-BEQD2DSK.js → chunk-HW5YHSIE.js} +1 -1
  28. package/dist-cli/chunks/{chunk-VRV2X4X2.js → chunk-IB4BRND4.js} +1 -1
  29. package/dist-cli/chunks/{chunk-22CO2ZE3.js → chunk-IBWN764Q.js} +2 -2
  30. package/dist-cli/chunks/chunk-JE4JBSNJ.js +119 -0
  31. package/dist-cli/chunks/{chunk-HWCZYW6M.js → chunk-K4PKR2EO.js} +2 -2
  32. package/dist-cli/chunks/chunk-KBJ2WHII.js +73 -0
  33. package/dist-cli/chunks/chunk-KR36VJSN.js +1 -0
  34. package/dist-cli/chunks/{chunk-EEMGSSWY.js → chunk-LQ5BA5JU.js} +2 -2
  35. package/dist-cli/chunks/chunk-MIAAZSSE.js +12 -0
  36. package/dist-cli/chunks/{chunk-BTHB3PMG.js → chunk-N4JRDJMN.js} +3 -3
  37. package/dist-cli/chunks/{chunk-FXF2FHPI.js → chunk-NYR3Z44O.js} +2 -2
  38. package/dist-cli/chunks/{chunk-EIQLQDKX.js → chunk-O624O5MO.js} +2 -2
  39. package/dist-cli/chunks/{chunk-4LYNJPUM.js → chunk-SH6HMUCY.js} +2 -2
  40. package/dist-cli/chunks/chunk-SVFSMAZN.js +2 -0
  41. package/dist-cli/chunks/chunk-TEMZK6Q2.js +1 -0
  42. package/dist-cli/chunks/{chunk-D4VEI6MI.js → chunk-TLTS533S.js} +1 -1
  43. package/dist-cli/chunks/chunk-U47AHSGE.js +23 -0
  44. package/dist-cli/chunks/{chunk-LCKLQSZX.js → chunk-XCRUPKWB.js} +2 -2
  45. package/dist-cli/chunks/{chunk-NCSGLZRV.js → chunk-YGQV3CUV.js} +2 -2
  46. package/dist-cli/chunks/{chunk-UNSLXX7V.js → chunk-ZJJKYJMH.js} +2 -2
  47. package/dist-cli/chunks/{chunk-GDCMTHEU.js → chunk-ZO7SGE65.js} +1 -1
  48. package/dist-cli/chunks/{chunk-HIN5TAAL.js → chunk-ZP2HMCKS.js} +1 -1
  49. package/dist-cli/chunks/cli-version-5LGQQE5P.js +2 -0
  50. package/dist-cli/chunks/{compat-I7JXYUJN.js → compat-5MMZ4R3Q.js} +3 -3
  51. package/dist-cli/chunks/{config-3HR5RKVH.js → config-YWN44WJQ.js} +2 -2
  52. package/dist-cli/chunks/control-LUCFDAZI.js +2 -0
  53. package/dist-cli/chunks/{cpu-profile-ZVHMTVAU.js → cpu-profile-VFGUVXU5.js} +2 -2
  54. package/dist-cli/chunks/{daemon-VYRTYH55.js → daemon-ONX5ZBXF.js} +2 -2
  55. package/dist-cli/chunks/{debug-CQ6Y7GJ2.js → debug-CPOG32OT.js} +5 -5
  56. package/dist-cli/chunks/demo-app-registry-LWT6JLU6.js +2 -0
  57. package/dist-cli/chunks/{detox-7ZKTGLDR.js → detox-J6NGSZR5.js} +2 -2
  58. package/dist-cli/chunks/{device-4M6Z7E2N.js → device-QYOQXI2P.js} +2 -2
  59. package/dist-cli/chunks/{diagnose-SMQLYGNX.js → diagnose-MMW4LJLA.js} +2 -2
  60. package/dist-cli/chunks/drivers-NRWUJJCD.js +2 -0
  61. package/dist-cli/chunks/{electron-6N2MIN5W.js → electron-IK3HIZY4.js} +3 -3
  62. package/dist-cli/chunks/flow-2MB7HINM.js +2 -0
  63. package/dist-cli/chunks/{hints-RJCZS2E3.js → hints-KZOD56U5.js} +2 -2
  64. package/dist-cli/chunks/{home-paths-DCUNA3CD.js → home-paths-R2YZZTUM.js} +2 -2
  65. package/dist-cli/chunks/inspect-ZARO3HQ4.js +970 -0
  66. package/dist-cli/chunks/install-O67RTYCX.js +2 -0
  67. package/dist-cli/chunks/{install-desktop-C7424OSW.js → install-desktop-4GH5I7SC.js} +3 -3
  68. package/dist-cli/chunks/{keys-TXUQOAZ3.js → keys-AXEFZUUI.js} +2 -2
  69. package/dist-cli/chunks/{launch-MVA44QTC.js → launch-QLE56ON7.js} +3 -3
  70. package/dist-cli/chunks/{login-NHO2WTHC.js → login-J45NQQM6.js} +4 -4
  71. package/dist-cli/chunks/{logout-SRRWADCE.js → logout-ZE5OUBB7.js} +2 -2
  72. package/dist-cli/chunks/{maestro-UHNXEZAN.js → maestro-FS6CAKDD.js} +2 -2
  73. package/dist-cli/chunks/{preview-ETIUP7KC.js → preview-TSU5IXVR.js} +2 -2
  74. package/dist-cli/chunks/{profile-MY5JFVIF.js → profile-ZBJ4TYWA.js} +2 -2
  75. package/dist-cli/chunks/{react-KCMC4GL3.js → react-TGZLTTYN.js} +2 -2
  76. package/dist-cli/chunks/record-JSBFUNOD.js +54 -0
  77. package/dist-cli/chunks/runtime-DGDQ7NVY.js +2 -0
  78. package/dist-cli/chunks/{runtime-delivery-LQZIWQU6.js → runtime-delivery-36UMAXOV.js} +2 -2
  79. package/dist-cli/chunks/screenshot-3CHMALUJ.js +33 -0
  80. package/dist-cli/chunks/{screenshot-mode-USPWASI3.js → screenshot-mode-C547UT5H.js} +2 -2
  81. package/dist-cli/chunks/{screenshots-EPEDNA6H.js → screenshots-XCNGSNYG.js} +2 -2
  82. package/dist-cli/chunks/{server-222QT33M.js → server-W37X3IW7.js} +6 -6
  83. package/dist-cli/chunks/setup-repo-DETS5ZJT.js +2 -0
  84. package/dist-cli/chunks/{skills-6XRREE2M.js → skills-OXZLDNDW.js} +2 -2
  85. package/dist-cli/chunks/{start-YCAZBZEX.js → start-N6ZQYUBP.js} +4 -4
  86. package/dist-cli/chunks/store-QOXJKJUZ.js +2 -0
  87. package/dist-cli/chunks/telemetry-74LX7WG4.js +2 -0
  88. package/dist-cli/chunks/{test-6TNRHSWC.js → test-DWZ7PRSW.js} +3 -3
  89. package/dist-cli/chunks/{three-mode-MDOLHGXW.js → three-mode-P2R7KA62.js} +2 -2
  90. package/dist-cli/chunks/{timeline-72MWE44G.js → timeline-VPES3YCN.js} +3 -3
  91. package/dist-cli/chunks/{upgrade-IHZ4DFAE.js → upgrade-NYQLA4UJ.js} +2 -2
  92. package/dist-cli/chunks/upload-YOMMYESV.js +2 -0
  93. package/dist-cli/chunks/{web-JLJSJUS2.js → web-OTALJKK5.js} +2 -2
  94. package/dist-cli/chunks/what-happened-GZ73H6KF.js +22 -0
  95. package/dist-cli/chunks/{whoami-2EYGCRDQ.js → whoami-UDLQK7IY.js} +2 -2
  96. package/dist-lib/agent-daemon-client.cjs +1 -1
  97. package/dist-lib/agent-events.cjs +1 -1
  98. package/dist-lib/agent-sessions.cjs +1 -1
  99. package/dist-lib/attached-projects.cjs +1 -1
  100. package/dist-lib/auth/shared-session.cjs +1 -1
  101. package/dist-lib/backend-origin.cjs +1 -1
  102. package/dist-lib/bridge-constants.cjs +1 -1
  103. package/dist-lib/cli-constants.cjs +1 -1
  104. package/dist-lib/config.cjs +1 -1
  105. package/dist-lib/dev-bundle-resolution.cjs +9 -2
  106. package/dist-lib/home-paths.cjs +1 -1
  107. package/dist-lib/host/bridge-host.cjs +23 -7
  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/index.cjs +1 -1
  111. package/dist-lib/metro.cjs +1 -1
  112. package/dist-lib/profiles.cjs +1 -1
  113. package/dist-lib/render-mode.cjs +1 -1
  114. package/dist-lib/vite-base.cjs +23 -7
  115. package/dist-lib/vite.cjs +1 -1
  116. package/package.json +1 -1
  117. package/dist-cli/chunks/auto-bootstrap-PS2UDBP7.js +0 -2
  118. package/dist-cli/chunks/beta-XLYWSKEA.js +0 -2
  119. package/dist-cli/chunks/chunk-5MVFADNH.js +0 -3
  120. package/dist-cli/chunks/chunk-7NYW73Q6.js +0 -2
  121. package/dist-cli/chunks/chunk-EMMX6RF7.js +0 -73
  122. package/dist-cli/chunks/chunk-FIIBCY5I.js +0 -3
  123. package/dist-cli/chunks/chunk-G4VWDOWB.js +0 -17
  124. package/dist-cli/chunks/chunk-GMKGJHVG.js +0 -1
  125. package/dist-cli/chunks/chunk-M3ZEZHOB.js +0 -34
  126. package/dist-cli/chunks/chunk-MWTMLNGM.js +0 -348
  127. package/dist-cli/chunks/chunk-NQKBIKUZ.js +0 -1
  128. package/dist-cli/chunks/chunk-QMRXLBPN.js +0 -11
  129. package/dist-cli/chunks/chunk-X4HQLK4V.js +0 -119
  130. package/dist-cli/chunks/chunk-XOTJSR4T.js +0 -2
  131. package/dist-cli/chunks/chunk-YSQV4D7P.js +0 -1
  132. package/dist-cli/chunks/chunk-Z6HSVZIO.js +0 -100
  133. package/dist-cli/chunks/cli-version-ESQ2S6N5.js +0 -2
  134. package/dist-cli/chunks/control-TDZXFNVT.js +0 -2
  135. package/dist-cli/chunks/demo-app-registry-JAYU7BBM.js +0 -2
  136. package/dist-cli/chunks/drivers-SIY6JBEM.js +0 -2
  137. package/dist-cli/chunks/flow-BZEWL7UQ.js +0 -2
  138. package/dist-cli/chunks/inspect-T5NC7HHB.js +0 -1025
  139. package/dist-cli/chunks/install-YTJI5RS7.js +0 -2
  140. package/dist-cli/chunks/record-DHDSXC2Y.js +0 -51
  141. package/dist-cli/chunks/runtime-AJP6V5LM.js +0 -2
  142. package/dist-cli/chunks/screenshot-4KPEEI6I.js +0 -28
  143. package/dist-cli/chunks/setup-repo-D56L3CEB.js +0 -2
  144. package/dist-cli/chunks/store-Z32KZ34K.js +0 -2
  145. package/dist-cli/chunks/telemetry-RFTX2BZK.js +0 -2
  146. package/dist-cli/chunks/upload-G5C7LJWG.js +0 -2
  147. package/dist-cli/chunks/what-happened-BUXSJ3QS.js +0 -15
@@ -1,348 +0,0 @@
1
- /*! sootsim v0.1.66 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{a as Se}from"./chunk-LVFWALS4.js";import{a as Te}from"./chunk-4LYNJPUM.js";import{a as xe}from"./chunk-EMMX6RF7.js";import{a as R,b as pe,c as fe,d as q,e as G,f as we,g as Y,i as X,j as ge}from"./chunk-XZ5SQJM2.js";import{f as be,m as ve}from"./chunk-QMRXLBPN.js";import{e as he}from"./chunk-HWCZYW6M.js";import{b as me}from"./chunk-M3ZEZHOB.js";import{a as ye}from"./chunk-GDCMTHEU.js";import{a as le,b as H}from"./chunk-DEQ7RED3.js";import{f as ae}from"./chunk-FXF2FHPI.js";import{c as z,d as ce,e as ue}from"./chunk-G4VWDOWB.js";import{c as de}from"./chunk-VRV2X4X2.js";import*as A from"fs";import{tmpdir as Me}from"os";import*as h from"path";import*as w from"fs";import*as f from"path";var V=1e4,B=393,_=852,Fe="__sootsimCliPerf",Oe="maestroCopiedText",$e=new Map;function p(o){return new Promise(e=>setTimeout(e,o))}function Ne(o){return o?f.basename(o)===".maestro"?f.dirname(o):o:process.cwd()}function Re(o,e,t){let r=e.endsWith(".png")?e:`${e}.png`;if(f.isAbsolute(r))return r;if(t.mode==="flow"&&/[\\/]/.test(r)){let i=r.startsWith("./")||r.startsWith("../")?t.flowDir??process.cwd():Ne(t.flowDir);return f.resolve(i,r)}return f.join(o,r)}function Ve(o){if(typeof o=="string")return{path:o,withFrame:!1};let e=o.path?.trim()||o.name?.trim();if(!e)throw new Error("takeScreenshot object form requires path or name");return{path:e,withFrame:o.withFrame===!0}}function Q(o){let[e,t]=o.split(",").map(i=>i.trim()),r=(i,s)=>i.endsWith("%")?Number.parseFloat(i)/100*s:Number.parseFloat(i);return{x:r(e,B),y:r(t,_)}}function Be(o){let e=o.split(/^---$/m),t=e.length>1?e[e.length-1]:o,r=fe(pe.parse(t),$e);return Array.isArray(r)?r:[]}var U=class{constructor(e,t){this.bridge=e;this.opts=t}stepDelay=0;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(a=>a.id===this.opts.simId);if(t&&(this.simRouteHint=this.normalizeSimRoute(t.url||t.origin)),e.find(a=>a.id===this.opts.simId&&a.readyState==="open")||!this.simRouteHint)return;let i=this.simRouteHint&&e.find(a=>a.readyState==="open"&&this.normalizeSimRoute(a.url||a.origin)===this.simRouteHint);if(!i)return;let s=e.find(a=>a.isPrimary&&a.readyState==="open"),n=e.find(a=>a.readyState==="open"),l=i??s??n;l&&(this.opts.simId=l.id,console.log(` [flow] sim rotated to ${l.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=V){let t=Date.now()+e,r=Date.now(),i=null,s=0,n=0;for(;Date.now()<t;){try{let a=await this.evaluate(`(async () => {
3
- const test = window.__sootsimTest
4
- if (!test) return { count: 0, loading: true }
5
- const count = (await test.getNodeCount?.()) || 0
6
- const external = globalThis.__sootsimExternalAppState
7
- if (external?.error) {
8
- return { count, loading: false, error: String(external.error) }
9
- }
10
- if (external) {
11
- return {
12
- count,
13
- loading: !external.ready,
14
- error: null,
15
- }
16
- }
17
- const loadingNode = await test.findByText?.('loading')
18
- const capturingNode = await test.findByText?.('capturing')
19
- const openingAppNode = await test.findByText?.('opening app')
20
- const isLoading = !!loadingNode || !!capturingNode || !!openingAppNode || count < 5
21
- return { count, loading: isLoading, error: null }
22
- })()`,8e3);if(s=0,a?.error)throw new Error(`app failed to load: ${a.error}`);if(a&&a.count>10&&!a.loading)return}catch(a){if(i=a instanceof Error?a:new Error(String(a)),i.message.startsWith("app failed to load:"))throw i;if(s++,s>=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 l=Date.now()-r;l-n>=5e3&&(n=l,console.log(` [flow] waiting for app to be ready\u2026 (${Math.round(l/1e3)}s)`)),await p(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 Te("flow --video",{originOverride:this.opts.billingOriginOverride,allowGitHubAuth:this.opts.allowGitHubRecording}),this.recordingAccessChecked=!0);let e=Date.now(),t=await this.evaluate(`(() => {
23
- const rec = window.__sootsimRecorder
24
- if (!rec) return { ok: false, error: 'recorder unavailable on this page' }
25
- if (rec.state() === 'recording') return { ok: true, format: 'webm' }
26
- return rec.start({ format: 'webm', fps: 24 })
27
- })()`);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 n=await this.evaluate(`window.__sootsimRecorder.getBlobBase64({ offset: ${i}, chunk: 2097152 })`);if(!n||(r.push(Buffer.from(n.data,"base64")),i=n.offset,n.done))break}if(r.length===0)throw new Error("recording requested but no video buffer was produced");w.mkdirSync(this.opts.recordingOutputDir,{recursive:!0});let s=f.join(this.opts.recordingOutputDir,`sootsim-${Date.now()}.webm`);return w.writeFileSync(s,Buffer.concat(r)),s}async findElement(e){return this.evaluate(`(async () => {
28
- const test = window.__sootsimTest
29
- if (!test) return null
30
- let node = null
31
- if (${JSON.stringify(!!e.text)}) node = await test.findByText(${JSON.stringify(e.text||"")})
32
- if (!node && ${JSON.stringify(!!e.id)}) {
33
- node = (await test.findByTestId(${JSON.stringify(e.id||"")})) || (await test.findById(${JSON.stringify(e.id||"")}))
34
- }
35
- if (!node || !node.absolutePosition || !node.layout) return null
36
- return {
37
- nodeId: typeof node.nodeId === 'number' ? node.nodeId : null,
38
- id: node.id || null,
39
- testID: node.testID || null,
40
- text: node.text || null,
41
- absolutePosition: node.absolutePosition,
42
- layout: node.layout,
43
- isTextInput: !!node.isTextInput,
44
- }
45
- })()`)}async resolveTapTarget(e){return this.evaluate(`(async () => {
46
- const test = window.__sootsimTest
47
- if (!test?.resolveTapTarget) return null
48
- return await test.resolveTapTarget(${e})
49
- })()`)}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 () => {
50
- const test = window.__sootsimTest
51
- if (!test) return null
52
- 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||"")})`}
53
- let point = null
54
- if (node?.absolutePosition && node?.layout) {
55
- point = {
56
- x: node.absolutePosition.x + node.layout.width / 2,
57
- y: node.absolutePosition.y + node.layout.height / 2,
58
- }
59
- if (typeof node.nodeId === 'number' && test.resolveTapTarget) {
60
- const resolved = await test.resolveTapTarget(node.nodeId)
61
- if (
62
- resolved &&
63
- Number.isFinite(resolved.cx) &&
64
- Number.isFinite(resolved.cy)
65
- ) {
66
- point = { x: resolved.cx, y: resolved.cy }
67
- }
68
- }
69
- }
70
- ${e.id?`const direct = await test.activatePressById?.(${JSON.stringify(e.id)})`:`const direct = await test.activatePressByText?.(${JSON.stringify(e.text||"")})`}
71
- if (direct?.ok && point) {
72
- window.dispatchEvent(
73
- new CustomEvent('sootsim:agentAction', {
74
- detail: { type: 'tap', x: point.x, y: point.y, target: ${JSON.stringify(t)} },
75
- }),
76
- )
77
- }
78
- return direct || null
79
- })()`)}async activatePressAt(e,t){return this.evaluate(`(async () => {
80
- const test = window.__sootsimTest
81
- if (!test?.activatePressAt) return null
82
- const direct = await test.activatePressAt(${e}, ${t})
83
- if (direct?.ok) {
84
- window.dispatchEvent(
85
- new CustomEvent('sootsim:agentAction', {
86
- detail: { type: 'tap', x: ${e}, y: ${t} },
87
- }),
88
- )
89
- }
90
- return direct
91
- })()`)}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 a=Q(t.point);(await this.activatePressAt(a.x,a.y))?.ok||await this.tap(a.x,a.y),await p(300);return}let r=5e3,i=150,s=Date.now()+r,n=await this.findElement({text:t.text,id:t.id});for(;!n&&Date.now()<s;)await p(i),n=await this.findElement({text:t.text,id:t.id});if(n){let a=typeof n.nodeId=="number"?await this.resolveTapTarget(n.nodeId):null,m=a?.cx??n.absolutePosition.x+n.layout.width/2,g=a?.cy??n.absolutePosition.y+n.layout.height/2;if((await this.tap(m,g,{id:t.id??a?.target?.id??n.id??null,testID:t.id??a?.target?.testID??n.testID??null,text:t.text??a?.target?.text??a?.target?.accessibilityLabel??n.text??n.accessibilityLabel??null,type:a?.target?.type??n.type??null}))?.hit===!0){await p(300);return}}if((await this.activatePressTarget(t))?.ok){await p(300);return}throw new Error(`tapOn: element not found: ${JSON.stringify(t)}`)}async tapAtCoords(e,t){await this.tap(e,t),await p(300)}async doubleTapAtCoords(e,t,r=80){let i=Math.max(0,Math.round(r));if(!await this.evaluate(`(async () => {
92
- const interact = window.__sootsimInteract
93
- if (interact?.doubleTap) {
94
- return !!(await interact.doubleTap(${e}, ${t}, ${i}))
95
- }
96
- if (!interact?.tap) return false
97
- const first = await interact.tap(${e}, ${t})
98
- if (!first || first.hit === false) return false
99
- await new Promise((resolve) => setTimeout(resolve, ${i}))
100
- const second = await interact.tap(${e}, ${t})
101
- return !!second && second.hit !== false
102
- })()`))throw new Error(`doubleTapAtCoords failed at (${e}, ${t})`);await p(300)}async assertVisible(e){let t=typeof e=="string"?{text:e}:e;for(let r=0;r<15;r++){if(await this.isElementVisible(t))return;await p(200)}throw new Error(`assertVisible: ${JSON.stringify(t)} not found or off-screen`)}async assertNotVisible(e){let t=typeof e=="string"?{text:e}:e;if(await this.isElementVisible(t))throw new Error(`assertNotVisible: ${JSON.stringify(t)} IS visible`)}async isElementVisible(e){let t=await this.findElement(e);return!!(t&&t.absolutePosition.y+t.layout.height>0&&t.absolutePosition.y<_)}async inputText(e){await this.bridge.send({type:"keyboard",simId:this.opts.simId,action:"type",text:e}),await p(200)}async pressKey(e){await this.bridge.send({type:"keyboard",simId:this.opts.simId,action:"press",text:e}),await p(120)}async dispatchKey(e){await this.bridge.send({type:"keyboard",simId:this.opts.simId,action:"dispatchKey",text:e}),await p(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(`(() => {
103
- const keyboard =
104
- window.__sootsimKeyboard ??
105
- window.SootSim?.bridges?.keyboard ??
106
- null
107
- const test = window.__sootsimTest
108
- return {
109
- visible: !!keyboard?.isVisible?.(),
110
- focused: !!test?.isTextInputFocused?.(),
111
- }
112
- })()`);if(!t?.visible&&!t?.focused){await p(80);return}await p(80)}}async eraseText(e){for(let t=0;t<e;t++)await this.pressKey("Backspace");await p(100)}async waitFor(e){let t=Date.now()+(e.timeout||V);for(;Date.now()<t;){if(await this.findElement(e))return;await p(200)}throw new Error(`waitFor: ${JSON.stringify(e)} not found after ${e.timeout||V}ms`)}async takeScreenshot(e){await p(250);let t=Ve(e),r=Re(this.opts.screenshotDir,t.path,{mode:this.opts.screenshotPathMode??"dir",flowDir:this.opts.flowDir});w.mkdirSync(f.dirname(r),{recursive:!0});let s=(await this.bridge.send({type:"screenshot",simId:this.opts.simId})).replace(/^data:image\/png;base64,/,""),n=Buffer.from(s,"base64");if(t.withFrame){let l=await this.readCurrentDeviceModel();if(!l)throw new Error("could not read current device model for framed screenshot");let a=await Se(n,l);w.writeFileSync(r,a),console.log(`[flow] screenshot: ${r} (frame: ${l})`);return}w.writeFileSync(r,n),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 ae)?null:t}async captureFailureScreenshot(e){w.mkdirSync(f.dirname(e),{recursive:!0});let r=(await this.bridge.send({type:"screenshot",simId:this.opts.simId})).replace(/^data:image\/png;base64,/,"");w.writeFileSync(e,Buffer.from(r,"base64"))}async captureFailureBundle(e,t){w.mkdirSync(e,{recursive:!0});let r=(m,g)=>{try{w.writeFileSync(f.join(e,m),g)}catch{}},i=async m=>{try{return await this.bridge.send({type:"evaluate",simId:this.opts.simId,code:m})}catch{return null}};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()},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 s=await i(`(async () => {
113
- const t = window.__sootsimTest
114
- const mainShell = window.SootSim?.bridges?.mainShell
115
- if (!t) return { error: 'no test bridge' }
116
- let shell = null
117
- try {
118
- shell = typeof mainShell?.getState === 'function' ? await mainShell.getState() : null
119
- } catch {}
120
- const all = await t.queryAll({ pruneHidden: true })
121
- return { shell, nodes: all, url: location.href, title: document.title }
122
- })()`);s&&r("describe.json",JSON.stringify(s,null,2));let n=await i("(async () => await window.__sootsimTest?.dumpAccessibilityTree?.(20))()");typeof n=="string"&&r("a11y.txt",n);let l=await i("(async () => await window.__sootsimTest?.dumpTree?.(15))()");typeof l=="string"&&r("tree.txt",l);let a=await i(`(() => {
123
- const c = window.__sootsimConsole
124
- return {
125
- errors: c?.getErrors?.() ?? [],
126
- warnings: c?.getWarnings?.() ?? [],
127
- requests: (window.__sootsimGetFailedRequests?.() ?? []),
128
- }
129
- })()`);return a&&r("console.json",JSON.stringify(a,null,2)),e}async swipe(e="UP",t=300){let r=B/2,i=_/2,s=200,n=r,l=i,a=r,m=i;switch(e.toUpperCase()){case"UP":l+=s,m-=s;break;case"DOWN":l-=s,m+=s;break;case"LEFT":n+=s,a-=s;break;case"RIGHT":n-=s,a+=s;break}let g=Math.max(10,Math.round(t/16));await this.drag(n,l,a,m,g,16)}async drag(e,t,r,i,s=12,n=16){if(!(await this.evaluate(`(async () => {
130
- const interact = window.__sootsimInteract
131
- if (!interact?.drag) return { ok: false }
132
- const value = await interact.drag(${e}, ${t}, ${r}, ${i}, ${Math.max(1,Math.round(s))}, ${Math.max(0,Math.round(n))})
133
- return { ok: !!value, value }
134
- })()`))?.ok)throw new Error("drag failed");await p(300)}async swipeCoords(e,t,r=300){let i=Q(e),s=Q(t),n=Math.max(10,Math.round(r/16));await this.drag(i.x,i.y,s.x,s.y,n,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 s=i.absolutePosition.x+i.layout.width/2,n=i.absolutePosition.y+i.layout.height/2,l=180,a=s,m=n;switch(t.toUpperCase()){case"UP":m-=l;break;case"DOWN":m+=l;break;case"LEFT":a-=l;break;case"RIGHT":a+=l;break}let g=Math.max(10,Math.round(r/16));await this.drag(s,n,a,m,g,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 p(250)}async pinch(e){let t=await this.evaluate(`(async () => {
135
- const interact = window.__sootsimInteract
136
- if (!interact?.pinch) return { ok: false, reason: 'no interact.pinch' }
137
- const ok = await interact.pinch(
138
- ${e.from[0]}, ${e.from[1]}, ${e.from[2]}, ${e.from[3]},
139
- ${e.to[0]}, ${e.to[1]}, ${e.to[2]}, ${e.to[3]},
140
- ${e.steps||12}, ${e.stepMs||16}
141
- )
142
- return { ok: !!ok, reason: ok ? null : 'pinch returned false' }
143
- })()`);if(!t?.ok)throw new Error(`pinch failed: ${t?.reason||"unknown error"}`);await p(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 p(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 s=await this.findElement({text:e.element});if(s&&s.absolutePosition.y>=0&&s.absolutePosition.y+s.layout.height>0&&s.absolutePosition.y<_-50){if(e.centerElement){let n=_/2,l=s.absolutePosition.y-n;if(Math.abs(l)>100){let a=Math.min(150,Math.abs(l)*.5),m=l>0?n-a:n+a;await this.drag(B/2,n,B/2,m,10,16)}}return}await this.swipe(i,250),await p(500)}throw new Error(`scrollUntilVisible: "${e.element}" not found`)}async extendedWaitUntil(e){let t=Date.now()+(e.timeout||V);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 p(200)}throw new Error("extendedWaitUntil timed out")}async launchApp(e){await this.refreshSimId();let t=!!(e&&typeof e=="object"&&e.clearState);if(t&&await this.evaluate(`(async () => {
144
- await (${R})
145
- try {
146
- const regs = await navigator.serviceWorker?.getRegistrations?.()
147
- await Promise.all((regs || []).map((reg) => reg.unregister()))
148
- } catch {}
149
- })()`),!this.firstLaunchDone&&!t)this.firstLaunchDone=!0,await this.waitForTree(3e4);else if(this.firstLaunchDone=!0,await this.evaluate("window.location.reload()").catch(()=>{}),await p(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) => {
150
- requestAnimationFrame(() => {
151
- requestAnimationFrame(() => {
152
- requestAnimationFrame(() => {
153
- setTimeout(resolve, 180)
154
- })
155
- })
156
- })
157
- })`)}catch{await p(180)}}async startProfile(){await this.evaluate(`((sessionKey) => {
158
- const host = window.__sootsimRenderHost
159
- if (host?.startPerfSession) {
160
- host.startPerfSession(sessionKey)
161
- window[sessionKey] = {
162
- active: true,
163
- mode: 'render-worker',
164
- startedAt: performance.now(),
165
- }
166
- return
167
- }
168
-
169
- const perf = window.__sootsimPerf
170
- const a11y = window.__sootsimA11y
171
- perf?.enableFrameStats?.()
172
- perf?.resetFrameStats?.()
173
- a11y?.resetProfile?.()
174
- window[sessionKey] = {
175
- active: true,
176
- mode: 'main-thread',
177
- startedAt: performance.now(),
178
- }
179
- })(${JSON.stringify(Fe)})`),this.profilingEnabled=!0}async stopProfile(){let e=await this.evaluate(`(async (sessionKey) => {
180
- const host = window.__sootsimRenderHost
181
- if (host?.stopPerfSession) {
182
- const stopped = await host.stopPerfSession(sessionKey)
183
- if (!stopped || !Array.isArray(stopped.samples)) {
184
- return { error: 'no render-worker perf samples available' }
185
- }
186
- const samples = stopped.samples
187
- const frameTimes = samples.map((sample) => Number(sample?.[1]) || 0).filter((value) => value > 0)
188
- const sorted = [...frameTimes].sort((a, b) => a - b)
189
- const worstFrames = samples
190
- .slice()
191
- .sort((a, b) => (Number(b?.[1]) || 0) - (Number(a?.[1]) || 0))
192
- .slice(0, 10)
193
- .map((sample) => [
194
- Number(sample?.[0]) || 0,
195
- Number(sample?.[1]) || 0,
196
- Number(sample?.[2]) || 0,
197
- Number(sample?.[3]) || 0,
198
- Number(sample?.[4]) || 0,
199
- ])
200
-
201
- return {
202
- mode: 'render-worker',
203
- frames: Number(stopped.frameCount) || frameTimes.length,
204
- totalMs: Number(stopped.totalMs) || frameTimes.reduce((sum, value) => sum + value, 0),
205
- avgMs: Number(stopped.avgMs) || (frameTimes.length ? frameTimes.reduce((sum, value) => sum + value, 0) / frameTimes.length : 0),
206
- maxMs: Number(stopped.maxMs) || (sorted[sorted.length - 1] || 0),
207
- layoutTotalMs: Number(stopped.layoutTotalMs) || samples.reduce((sum, sample) => sum + (Number(sample?.[2]) || 0), 0),
208
- renderTotalMs: Number(stopped.renderTotalMs) || samples.reduce((sum, sample) => sum + (Number(sample?.[3]) || 0), 0),
209
- copyTotalMs: Number(stopped.copyTotalMs) || samples.reduce((sum, sample) => sum + (Number(sample?.[4]) || 0), 0),
210
- layoutAvgMs: Number(stopped.layoutAvgMs) || 0,
211
- renderAvgMs: Number(stopped.renderAvgMs) || 0,
212
- copyAvgMs: Number(stopped.copyAvgMs) || 0,
213
- p50: sorted[Math.floor(sorted.length * 0.5)] || 0,
214
- p95: sorted[Math.floor(sorted.length * 0.95)] || 0,
215
- p99: sorted[Math.floor(sorted.length * 0.99)] || 0,
216
- jankFrames: frameTimes.filter((value) => value > 16.67).length,
217
- sampleCount: frameTimes.length,
218
- worstFrames,
219
- }
220
- }
221
-
222
- const perf = window.__sootsimPerf
223
- const a11y = window.__sootsimA11y
224
- if (!perf && !a11y) return { error: 'no perf globals available' }
225
-
226
- const frameStats = perf?.getFrameStats?.() || {}
227
- const profile = a11y?.profile?.() || {}
228
- const recent = Array.isArray(frameStats.recentFrames) ? frameStats.recentFrames : []
229
- const sorted = [...recent].sort((a, b) => a - b)
230
- perf?.disableFrameStats?.()
231
-
232
- return {
233
- mode: 'main-thread',
234
- frames: frameStats.frames || profile.syncCount || 0,
235
- totalMs: frameStats.totalMs || 0,
236
- avgMs: frameStats.totalMs && frameStats.frames ? frameStats.totalMs / frameStats.frames : profile.avgSyncMs || 0,
237
- maxMs: frameStats.maxMs || profile.maxSyncMs || 0,
238
- layoutTotalMs: frameStats.layoutTotalMs || 0,
239
- p50: sorted[Math.floor(sorted.length * 0.5)] || 0,
240
- p95: sorted[Math.floor(sorted.length * 0.95)] || 0,
241
- p99: sorted[Math.floor(sorted.length * 0.99)] || 0,
242
- jankFrames: recent.filter((value) => value > 16.67).length,
243
- sampleCount: recent.length,
244
- worstFrames: recent.slice().sort((a, b) => b - a).slice(0, 10),
245
- }
246
- })(${JSON.stringify(Fe)})`);if(this.profilingEnabled=!1,e?.error)throw new Error(e.error);return e}async stopApp(){await this.evaluate(`(async () => {
247
- try { await (${R}) } catch {}
248
- try {
249
- const regs = await navigator.serviceWorker?.getRegistrations?.()
250
- await Promise.all((regs || []).map((reg) => reg.unregister()))
251
- } catch {}
252
- })()`)}async clearState(){await this.evaluate(`(async () => {
253
- await (${R})
254
- })()`)}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??"";$e.set(Oe,i),console.log(`[flow] copied text: ${JSON.stringify(i)}`)}async evalScript(e){let r=await this.evaluate(`(async () => {
255
- try {
256
- return { ok: true, value: await (async () => { ${e} })() }
257
- } catch (err) {
258
- return { ok: false, error: err && err.message ? err.message : String(err) }
259
- }
260
- })()`);if(!r.ok)throw new Error(`evalScript failed: ${r.error}`);r.value!==void 0&&console.log("[flow] evalScript ->",r.value)}async openLink(e){let t=typeof e=="string"?e:e.link;if(!t)throw new Error("openLink: missing link");await this.evaluate(`window.location.href = ${JSON.stringify(t)}`),await p(300),await this.refreshSimId(),await this.waitForTree(3e4)}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()==="ios":e.true!==void 0?e.true.toLowerCase()!=="false":!0}isOptional(e){if(e.optional===!0)return!0;let r=Object.entries(e).find(([s])=>s!=="when"&&s!=="optional"),i=r?r[1]:void 0;return!!(i&&typeof i=="object"&&"optional"in i&&i.optional)}async runStep(e,t){let r=Object.keys(e).find(i=>i!=="when")||Object.keys(e)[0];if(console.log(`[flow] step ${t+1}: ${r}`),e.when&&!await this.evaluateWhen(e.when)){console.log("[flow] (when: predicate false, skipped)");return}try{let i=!!(e.extendedWaitUntil||e.waitFor||e.scrollUntilVisible||e.launchApp||e.runFlow),s=1e4,n=this.runStepInner(e);if(i)await n;else{let a=null,m=new Promise((g,y)=>{a=setTimeout(()=>{y(new Error(`step watchdog: ${r} made no progress in ${s}ms \u2014 bridge or bundle probably hung`))},s)});try{await Promise.race([n,m])}finally{a&&clearTimeout(a)}}let l=!!(e.assertVisible||e.assertNotVisible||e.extendedWaitUntil||e.waitFor);this.stepDelay>0&&!l&&await p(this.stepDelay)}catch(i){if(this.isOptional(e)){console.log(`[flow] (optional, skipped: ${i.message.slice(0,80)})`);return}throw this.lastFailedStep={index:t,kind:r,target:e[r]},i}}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 p(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)for(let t=0;t<e.repeat.times;t++)for(let r=0;r<e.repeat.commands.length;r++)await this.runStep(e.repeat.commands[r],r);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")await this.evalScript(e.evalScript);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.when;if(i&&!await this.evaluateWhen(i)){console.log(`[flow] runFlow skipped (when predicate false): ${r}`);return}let s=f.resolve(this.opts.flowDir,r),n=w.readFileSync(s,"utf8"),l=this.opts.flowDir;this.opts.flowDir=f.dirname(s),await this.runFlow(Be(n)),this.opts.flowDir=l}else throw new Error(`unsupported flow step: ${JSON.stringify(e)}`)}async runFlow(e){let t=[],r=[],i=[];for(let n of e){let l=Object.keys(n);if(l.length===1&&l[0]==="onFlowStart"&&Array.isArray(n.onFlowStart)){t.push(...n.onFlowStart);continue}if(l.length===1&&l[0]==="onFlowComplete"&&Array.isArray(n.onFlowComplete)){r.push(...n.onFlowComplete);continue}i.push(n)}if(t.length>0){console.log(`[flow] onFlowStart (${t.length} steps)`);for(let n=0;n<t.length;n++)await this.runStep(t[n],n)}let s=null;try{await this.runFlowBody(i)}catch(n){s=n instanceof Error?n:new Error(String(n))}if(r.length>0){console.log(`[flow] onFlowComplete (${r.length} steps)`);for(let n=0;n<r.length;n++)try{await this.runStep(r[n],n)}catch(l){console.warn(`[flow] onFlowComplete step ${n+1} failed: ${l instanceof Error?l.message:l}`)}}if(s)throw s}async runFlowBody(e){for(let t=0;t<e.length;t++){let r=e[t],i=typeof r.wait=="number"?r.wait:0,s=typeof r.waitFor?.timeout=="number"?r.waitFor.timeout:0,n=Math.max(6e4,i+15e3,s+15e3);if(r.runFlow){await this.runStep(r,t);continue}await Promise.race([this.runStep(r,t),new Promise((l,a)=>setTimeout(()=>a(new Error(`step ${t+1} (${Object.keys(r)[0]}) exceeded ${n}ms deadline`)),n))])}}};async function Ue(){let o=await he(),e=o.find(r=>r.patched);if(e)return`http://localhost:${e.port}/__soot/`;let t=o[0];return t?`http://localhost:${t.port}/__soot/`:null}async function Ie(o){(o.length===0||o.includes("--help")||o.includes("-h"))&&(console.log(`
261
- sootsim flow \u2014 run flows or manage a draft
262
-
263
- usage:
264
- sootsim flow <flow.yaml> [options]
265
- sootsim flow start
266
- sootsim flow keep
267
- sootsim flow end [--output <path>] [--validate] [--video]
268
- sootsim flow validate <path>
269
-
270
- options:
271
- --record record a webm artifact while the flow runs
272
- --profile capture perf stats while the flow runs
273
- --out <dir> output directory (default: /tmp/sootsim-recordings)
274
- --device <model> override the flow frontmatter device for this run
275
- --slow <ms> delay between steps for natural pacing
276
- --tail-wait <ms> hold the recording open after the last step so the
277
- final UI state is captured (default 2000ms when --record
278
- is on, 0 otherwise)
279
- --url <url> load this target before running the flow
280
- --screenshot-paths <mode>
281
- screenshot path mode: dir (default) or flow
282
- --replace <m>=<f> replace a Metro module with a local file for this run
283
- --new open a fresh sim before running the flow
284
- --driver <id> when paired with --new, launch through a specific
285
- driver from the registry (e.g. playwright for
286
- hermetic CI runs); see 'sootsim list --drivers'
287
- --headless pass headless=true to the launch driver (useful
288
- with --driver playwright)
289
- --electron prefer opening the target in the desktop companion
290
- --sim <id> target a specific current sim
291
- --validate replay the drafted flow before clearing it
292
- --video replay and record the drafted flow before clearing it
293
- --preview record events+video, upload, and print /preview/<id>
294
- --preview-open open the uploaded preview link after a successful run
295
- --preview-origin <url>
296
- upload target for --preview (default: auto)
297
- --preview-public-origin <url>
298
- public link origin for --preview (default: sootsim.com
299
- for prod uploads)
300
-
301
- frontmatter (top of flow.yaml between --- markers):
302
- app: 8081 load this target before the flow starts
303
- device: iphone-14 set the live device model for this flow run
304
- electron: true prefer the desktop companion sim for this flow
305
-
306
- default runtime:
307
- bridge-backed flow playback against the current sim
308
- if no current sim exists, flow opens the discovered target first
309
- recording and profiling both run on the same bridge-backed path
310
-
311
- examples:
312
- sootsim flow login.yaml
313
- sootsim flow demo.yaml --url 8081 --record --slow 500 --out ./recordings
314
- sootsim flow demo.yaml --sim a2
315
- sootsim flow start
316
- sootsim flow keep
317
- sootsim flow end --output ./flows/draft.yaml
318
- sootsim flow end --output ./flows/draft.yaml --validate
319
- sootsim flow end --output ./flows/draft.yaml --video
320
- sootsim flow validate ./flows/draft.yaml
321
-
322
- flow extension:
323
- takeScreenshot: hero
324
- takeScreenshot:
325
- path: marketing/hero
326
- withFrame: true
327
- `),process.exit(0));let e=o[0];A.existsSync(e)||(console.error(` error: ${e} not found`),process.exit(1));let t=u=>o.find((d,v)=>o[v-1]===u),r=o.includes("--profile"),i=o.includes("--new"),s=t("--out")||"/tmp/sootsim-recordings",n=t("--screenshots")||"/tmp/sootsim-flow",l=t("--screenshot-paths")==="flow"?"flow":"dir",a=t("--device")?.trim()||"",m=o.includes("--slow")?+(t("--slow")||"500"):0,g=o.includes("--electron"),y=o.includes("--preview"),W=await xe(t("--preview-origin")),Z=t("--preview-public-origin"),Ae=o.includes("--preview-open"),Pe=o.flatMap((u,d)=>o[d-1]==="--replace"?["--replace",u]:[]),S=o.includes("--record")||y,ee=o.includes("--tail-wait")?Math.max(0,+(t("--tail-wait")||"2000")):S?2e3:0,Ee=A.readFileSync(e,"utf8"),{frontmatter:$,steps:M}=q(Ee,{resolveEnv:!0});M.length===0&&(console.error(" error: flow file must contain a YAML array of steps"),process.exit(1));let P=a||$.device||"",C=g||$.electron===!0,L=$.app===void 0||$.app===null?"":typeof $.app=="number"?String($.app):$.app,te={stripBooleanFlags:["--record","--profile","--electron","--new","--preview","--preview-open","--headless"],stripValueFlags:["--out","--device","--slow","--tail-wait","--url","--replace","--screenshots","--screenshot-paths","--preview-origin","--preview-public-origin","--driver"]},x=z(o,te),_e=t("--url")||"";C&&!ye()&&(console.error(" error: desktop companion not found. install or build it first with `bun run build:electron`"),process.exit(1));let re=C?"desktop companion":"bridge",Ce=L?` | target: ${L}`:"";console.log(`
328
- sootsim flow \u2014 ${h.basename(e)}
329
- ${M.length} steps | ${re}${Ce}${S?" | recording":""}${r?" | profiling":""}${m?` | ${m}ms delay`:""}
330
- `),y&&le({event:"preview_flow_started",properties:{flowName:h.basename(e),stepCount:M.length,mode:re,electron:C,record:S,profile:r,previewOrigin:W}});let T=_e||L||"",j=i||C&&x.simIdSource!=="flag",ie=!1;if(!T&&!j&&x.simIdSource==="none"){let u=ue(x);try{let d=await u.listSims(),v=d.find(N=>N.isPrimary&&N.readyState==="open"),O=d.find(N=>N.readyState==="open"),se=v??O;se&&(ie=!0,console.log(` reusing active sim: ${se.id}`))}catch{}finally{u.close()}}if(!T&&!ie&&(j||x.simIdSource==="none")){let u=await Ue();u||(console.error(" error: no current sim and no sootsim target found"),await H(),process.exit(1)),T=u}if(T&&P){let u=new URL(await be(T));u.searchParams.set("device",P),T=u.toString()}if(T){let u=[T];u.push(...Pe),j&&u.push("--new"),x.simIdSource==="flag"&&x.simId&&u.push("--sim",x.simId);let d=t("--driver");d&&u.push("--driver",d),o.includes("--headless")&&u.push("--headless"),await ve(u,{port:x.wsPort,timeoutMs:x.commandTimeoutMs})}let I=z(o,te),K=I.simIdSource==="flag"?I.simId:de()||I.simId,De=I.simIdSource==="flag"?"flag":K?"saved":"none",F=ce(I.wsPort,{commandTimeoutMs:I.commandTimeoutMs,simId:K,simIdSource:De,fallbackOnMissingSimId:!1}),c,oe=async()=>{if(!P)return!1;let u=await F.send({type:"evaluate",simId:c.simId,code:"window.location.href"});if(typeof u=="string"&&u.length>0){let d=new URL(u);d.searchParams.set("device",P),c.setSimRouteHint(d.toString())}return!!await F.send({type:"call",simId:c.simId,path:"SootSim.bridges.settings.set",args:["deviceModel",P]})};c=new U(F,{screenshotDir:n,flowDir:h.dirname(h.resolve(e)),screenshotPathMode:l,simId:K,recordingOutputDir:S?s:void 0,billingOriginOverride:y?W:void 0,allowGitHubRecording:S,onAfterLaunch:async()=>{await oe()&&await c.waitForTree(12e4),y&&await F.send({type:"evaluate",simId:c.simId,code:`(() => {
331
- const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
332
- return r?.start?.() ?? false
333
- })()`})}}),m&&(c.stepDelay=m);let k=null,b=null,E=null,J=null,D=0,ne=!!M[0]?.launchApp;try{await c.waitForTree(12e4),await oe()&&await c.waitForTree(12e4),y&&!ne&&!process.env.SOOTSIM_PREVIEW_RESET_DONE&&await c.launchApp({clearState:!0}),S&&(ne?c.prepareRecording():await c.startRecording()),r&&await c.startProfile(),y&&(await F.send({type:"evaluate",simId:c.simId,code:`(() => {
334
- const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
335
- return r?.start?.() ?? false
336
- })()`})||console.warn(" warn: eventRecorder.start() returned false \u2014 preview will upload bundle without replay events")),await c.runFlow(M),r&&(k=await c.stopProfile()),S&&ee>0&&await new Promise(d=>setTimeout(d,ee)),S&&(b=await c.stopRecording(),E=c.getLastRecordingDurationMs()),y&&(J=await F.send({type:"evaluate",simId:c.simId,code:`(() => {
337
- const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
338
- return r?.stop?.() ?? []
339
- })()`}),console.log(` captured ${J.length} replay events`)),console.log(`
340
- + completed (${M.length} steps)`),k&&ke(k),b&&console.log(` video: ${b}`),console.log()}catch(u){if(r&&!k)try{k=await c.stopProfile()}catch{}if(S&&!b)try{b=await c.stopRecording(),E=c.getLastRecordingDurationMs()}catch(d){console.warn(` recording stop failed: ${d?.message||String(d)}`)}console.error(`
341
- x failed: ${u.message}
342
- `),k&&(console.log(" partial profile:"),ke(k)),b&&console.log(` partial video: ${b}`);try{let d=c.lastFailedStep,v=d?`step-${String(d.index+1).padStart(2,"0")}-${d.kind}`:"unstaged",O=h.join(n,v);await c.captureFailureBundle(O,{error:u,stepIndex:d?.index,stepKind:d?.kind,stepTarget:d?.target}),console.log(` failure bundle: ${O}`),console.log(" (contents: screenshot.png, describe.json, a11y.txt, tree.txt, console.json, error.json)")}catch(d){try{let v=h.join(n,"error.png");await c.captureFailureScreenshot(v),console.log(` error screenshot: ${v}`)}catch{}console.log(` (failure bundle capture failed: ${d instanceof Error?d.message:String(d)})`)}await me(F,{errorsCommand:`sootsim get errors 5${c.simId?` --sim ${c.simId}`:""}`,warningsCommand:`sootsim get warnings 5${c.simId?` --sim ${c.simId}`:""}`,requestsCommand:`sootsim get requests 5${c.simId?` --sim ${c.simId}`:""}`}),D=1}finally{F.close()}if(D===0&&y)try{let u=await We(J??[]),d=["--origin",W,"--events",u];Z&&d.push("--public-origin",Z),b&&d.push("--video",b),b&&E&&Number.isFinite(E)&&d.push("--video-duration-ms",String(Math.round(E))),c.simId&&d.push("--sim",c.simId),Ae&&d.push("--open"),console.log(`
343
- preparing preview upload\u2026`);let{runUpload:v}=await import("./upload-G5C7LJWG.js");await v(d,{})}catch(u){console.error(` preview upload failed: ${u?.message||u}`),D=1}return await H(),D}async function We(o){let{gzipSync:e}=await import("zlib"),t=o.map(s=>JSON.stringify(s)).join(`
344
- `)+(o.length?`
345
- `:""),r=e(Buffer.from(t,"utf8")),i=h.join(Me(),`sootsim-events-${Date.now()}.jsonl.gz`);return A.writeFileSync(i,r),console.log(` events: ${o.length} written to ${i} (${r.length} bytes gz)`),i}async function Le(o){let e=o[0],t=r=>o.find((i,s)=>o[s-1]===r);switch(e){case"start":{let{path:r,state:i}=we();console.log(" flow draft started"),console.log(` session: ${r}`),console.log(` steps: ${i.steps.length}`);return}case"keep":case"good":{let r=X();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")||(o[1]&&!o[1].startsWith("-")?o[1]:void 0),i=o.includes("--validate")||o.includes("--video"),s=o.includes("--video"),n=X();n.active&&n.kept&&console.log(` auto-kept trailing action: ${n.candidate.summary}`);let l=ge(r||(i?Ke():void 0));if(l.active||(console.error(" no active flow draft \u2014 run `sootsim flow start` first"),process.exit(1)),!l.valid){console.error(" flow draft is not valid:");for(let a of l.issues)console.error(` - ${a}`);console.error(" draft preserved \u2014 keep at least one real interaction or run `sootsim flow start` to reset"),process.exit(1)}if(i){let a=Je(o,l.outputPath),m=await Ie(a);if(m!==0){console.error(`
346
- validation failed \u2014 draft preserved so you can keep iterating`),process.exitCode=m;return}Y(),console.log(` flow draft validated (${l.stepCount} step${l.stepCount===1?"":"s"})`),l.outputPath&&console.log(` saved: ${l.outputPath}`),s&&console.log(" video: recorded during validation run");return}if(Y(),console.log(` flow draft ended (${l.stepCount} step${l.stepCount===1?"":"s"})`),l.outputPath){console.log(` saved: ${l.outputPath}`),console.log(` next: sootsim flow ${l.outputPath} --record`);return}console.log(""),process.stdout.write(l.yaml);return}case"validate":{let r=o[1];(!r||r.startsWith("-"))&&(console.error(" usage: sootsim flow validate <path>"),process.exit(1));let i=G(r);if(i.length>0){console.error(` x ${r} failed validation:`);for(let s of i)console.error(` - ${s}`);process.exit(1)}console.log(` + ${r} looks valid`);return}}}function je(o){return o[0]==="--sim"&&o.length>=2?[...o.slice(2),"--sim",o[1]]:o}async function ut(o){let e=je(o),t=e[0];if(t==="start"||t==="keep"||t==="good"||t==="end"||t==="validate")return await Le(e),0;let r=await Ie(e);return r!==0&&(process.exitCode=r),r}function ke(o){let e=o.avgMs>0?(1e3/o.avgMs).toFixed(1):"?",t=o.sampleCount>0?(o.jankFrames/o.sampleCount*100).toFixed(1):"0";console.log(`
347
- profile:`),console.log(` frames: ${o.frames}`),console.log(` total: ${o.totalMs.toFixed(1)}ms`),console.log(` avg: ${o.avgMs.toFixed(2)}ms (${e} fps)`),console.log(` max: ${o.maxMs.toFixed(2)}ms`),o.layoutAvgMs!==void 0&&console.log(` breakdown: layout ${o.layoutAvgMs.toFixed(2)}ms | render ${o.renderAvgMs?.toFixed(2)||"0.00"}ms | copy ${o.copyAvgMs?.toFixed(2)||"0.00"}ms`),console.log(` p95: ${o.p95.toFixed(2)}ms`),console.log(` p99: ${o.p99.toFixed(2)}ms`),console.log(` jank: ${o.jankFrames}/${o.sampleCount} (${t}%) >16.67ms`);let r=Array.isArray(o.worstFrames)?o.worstFrames:[];if(r.length!==0){if(console.log(`
348
- worst frames:`),o.mode==="render-worker"){console.log(" total layout render copy t+");for(let i of r){let[s,n,l,a,m]=i;console.log(` ${n.toFixed(2).padStart(7)} ${l.toFixed(2).padStart(7)} ${a.toFixed(2).padStart(7)} ${m.toFixed(2).padStart(7)} ${String(s).padStart(5)}`)}return}console.log(` ${r.map(i=>i.toFixed(2)).join(", ")}`)}}function Ke(){return h.join(Me(),`sootsim-flow-draft-${Date.now()}.yaml`)}function Je(o,e){if(!e)throw new Error("validated flow draft requires an output path");let t=[e];for(let r=1;r<o.length;r++){let i=o[r];if(!(i==="--validate"||i==="--video")){if(i==="--output"){r+=1;continue}r===1&&!i.startsWith("-")||t.push(i)}}return!t.includes("--record")&&o.includes("--video")&&t.push("--record"),t}export{Ue as a,Ie as b,je as c,ut as d};
@@ -1 +0,0 @@
1
- /*! sootsim v0.1.66 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
@@ -1,11 +0,0 @@
1
- /*! sootsim v0.1.66 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{a as _,b as z,c as le,d as ce}from"./chunk-HWCZYW6M.js";import{b as O}from"./chunk-M3ZEZHOB.js";import{j as se,k as ie,m as ae}from"./chunk-V4SZERWD.js";import{g as q}from"./chunk-Z6HSVZIO.js";import{a as C,b as j}from"./chunk-GDCMTHEU.js";import{c as de}from"./chunk-AYBGSHQK.js";import{d as ne}from"./chunk-HIN5TAAL.js";import{a as ee}from"./chunk-XOTJSR4T.js";import{b as re,c as I,d as S,e as x}from"./chunk-G4VWDOWB.js";import{c as P,d as w,e as k}from"./chunk-VRV2X4X2.js";import{E as te,F as oe}from"./chunk-BEQD2DSK.js";import Me from"node:fs";import Ue from"node:os";import G from"node:path";function Ie(t){return t.replace(/^\[|\]$/g,"").toLowerCase()}function W(t){let o=Ie(t);return o==="localhost"||o.endsWith(".localhost")||o==="0.0.0.0"||o==="::1"||/^127(?:\.\d{1,3}){3}$/.test(o)}function me(t){return new Error(`could not resolve a native bundle for ${t}. pass an explicit bundle URL or open Connect and choose the app there.`)}function xe(t,o){return t?.includes("/one/metro-entry.bundle")?"one":typeof o=="string"&&o?"expo":"unknown"}function pe(t,o,e){return`${t}//${o}:${e}`}function Pe(t){if(typeof window>"u")return!1;try{let o=new URL(t);return W(o.hostname)&&W(window.location.hostname)&&o.origin!==window.location.origin}catch{return!1}}async function ue(t,o){let e={...o,cache:o?.cache??"no-store"};return Pe(t)?fetch(`/__fetch-proxy?url=${encodeURIComponent(t)}`,e):fetch(t,e)}function ke(t){return t==="https:"?443:80}function Ce(t){let o=t.pathname||"/";return(o==="/"||o==="")&&!t.search&&!t.hash}async function fe(t,o){let e=t.replace(/\/+$/,"");try{let n=await ue(`${e}/`,{headers:{"expo-platform":"ios"}});if(n.ok){let r=await n.json(),s=r?.extra?.expoClient||r?.extra||{},a=typeof r?.launchAsset?.url=="string"?r.launchAsset.url:void 0;if(a||s.name)return{bundleUrl:le(a||`${e}${z}`),port:o,framework:xe(a,s.sdkVersion),projectName:s.name}}}catch{}try{let n=await ue(`${e}/status`);if(n.ok&&(await n.text()).includes("packager-status:running"))return{bundleUrl:`${e}${z}`,port:o,framework:"metro"}}catch{}return null}async function Be(t){return fe(pe("http:","localhost",t),t)}async function ge(t){let o=t.trim();if(/^\d+$/.test(o)){let i=parseInt(o,10),l=await Be(i);if(l)return l;throw me(`localhost:${i}`)}let e=o.startsWith("http")?o:`http://${o}`,n;try{n=new URL(e)}catch{throw new Error(`could not parse "${t}". pass a dev-server port, a dev-server base URL, or a full bundle URL.`)}let r=n.protocol||"http:",s=n.port?parseInt(n.port,10):ke(r),a=pe(r,n.hostname,s);if(Ce(n)){let i=await fe(a,s);if(i)return i;throw me(a)}return{bundleUrl:n.toString(),port:s,framework:"unknown"}}function tt(){console.error(" no sootsim desktop companion found."),console.error(""),console.error(" install the desktop app:"),console.error(" sootsim install-desktop"),console.error(""),console.error(" or wire sootsim into your own project so your dev server hosts the bridge:"),console.error(" sootsim setup-repo"),console.error("")}function he(t){let o=C();if(console.log(` note: no sootsim bridge detected on port ${t}`),o){console.log(" launch the installed companion with:"),console.log(" sootsim electron");return}console.log(""),console.log(" to get a bridge running, either:"),console.log(" sootsim install-desktop # download the electron app"),console.log(" sootsim setup-repo # wire sootsim into your own project")}function Te(t){console.error(""),console.error(` no sim is connected to the sootsim bridge on port ${t}.`),console.error(""),console.error(" start your app dev server, then open it in sootsim:"),console.error(" npx expo start --localhost --port 8081"),console.error(" sootsim open 8081"),console.error(""),console.error(" then inspect the live app:"),console.error(" sootsim describe")}async function ot(t,o,e){let n=[];try{n=await t.listSims()}catch{}if(console.error(""),n.length===0){Te(o);return}console.error(` no sim with id "${e}" is connected to the bridge on port ${o}.`),console.error(""),console.error(" connected sims:");for(let r of n){let s=[r.isPrimary?"primary":null,r.readyState].filter(Boolean).join(", ");console.error(` ${r.id} (${s})`)}console.error(""),console.error(" pass a valid --sim id, or run `sootsim list` to see all sessions.")}var Re={rn:"/rn",connectrn:"/rn","connect-rn":"/rn",clock:"/app/clock","native-ui":"/app/native-ui",tamagui:"/app/tamagui",settings:"/app/settings",photos:"/app/photos",camera:"/app/camera"};function $(t){return new Promise(o=>setTimeout(o,t))}function A(t){return t.trim()}function J(t){try{let o=new URL(t),e=o.pathname.replace(/\/+$/,"")||"/";return o.searchParams.has("open")||o.searchParams.has("port")||o.searchParams.has("bundle")||o.searchParams.has("demo")||o.pathname.includes("/sootsim/index.html")||e==="/sootsim"||o.pathname==="/__soot"||o.pathname==="/__soot/"||e==="/rn"||/^\/rn\/[^/]+$/i.test(e)||/^\/app\/[^/]+$/i.test(e)||e==="/__soot/rn"||/^\/__soot\/rn\/[^/]+$/i.test(e)||/^\/__soot\/app\/[^/]+$/i.test(e)}catch{return!1}}async function $t(t){let o=A(t);return(await be(o)).bundleUrl}function Ee(t){try{let o=new URL(t.startsWith("http")?t:`http://${t}`),e=o.pathname||"/";if(e!=="/"&&e!==""||o.search||o.hash||!/^(localhost|127\.0\.0\.1|\[::1\]|::1)$/i.test(o.hostname))return null;let n=o.port?Number(o.port):o.protocol==="https:"?443:80;return Number.isFinite(n)&&n>0?n:null}catch{return null}}async function be(t){let o=A(t),e=/^\d+$/.test(o)?Number(o):Ee(o);if(e&&e>0){let n=await ce(e);if(n)return{bundleUrl:n.bundleUrl,port:n.port,framework:n.framework,projectName:n.projectName}}return ge(o)}function V(t){let o=t.replace(/\/+$/,"")||"/";return o==="/__soot"||o.startsWith("/__soot/")?"/__soot":""}function Oe(t,o){let e=A(t),n=new URL(o),r=V(n.pathname);return n.pathname=`${r}/rn`,n.searchParams.delete("bundle"),n.searchParams.delete("demo"),n.searchParams.delete("app"),n.searchParams.delete("open"),n.searchParams.delete("port"),/^\d+$/.test(e)?n.pathname=`${r}/rn/${e}`:(n.pathname=`${r}/rn`,n.searchParams.set("open",e)),n.toString()}function _e(t){let o=A(t);return/^\d+$/.test(o)||/^https?:\/\//i.test(o)?!0:/^(localhost|127\.0\.0\.1|\[::1\]|[^/]+\.localhost):\d+(?:\/.*)?$/i.test(o)}async function Le(t,o){let e=await be(t),n=new URL(o),r=V(n.pathname);return n.pathname=`${r}/rn`,n.searchParams.delete("open"),n.searchParams.delete("port"),n.searchParams.delete("demo"),n.searchParams.delete("app"),n.searchParams.set("bundle",e.bundleUrl),n.toString()}function De(t){return t.startsWith("~/")?G.join(Ue.homedir(),t.slice(2)):G.isAbsolute(t)?t:G.resolve(process.cwd(),t)}function Ae(t){let o={};for(let e=0;e<t.length;e++){if(t[e]!=="--replace")continue;let n=t[e+1];n||(console.error(" sootsim open: --replace expects <module>=<file>"),process.exit(1));let r=n.indexOf("=");(r<=0||r===n.length-1)&&(console.error(" sootsim open: --replace expects <module>=<file>"),process.exit(1));let s=n.slice(0,r).trim(),a=De(n.slice(r+1).trim());Me.existsSync(a)||(console.error(` sootsim open: replacement file not found: ${a}`),process.exit(1)),o[s]={file:a},e++}return Object.keys(o).length>0?{modules:o}:void 0}function Se(){let t=te();return oe(t)&&t.runtimePort>0?`http://localhost:${t.runtimePort}/`:ee}async function D(t,o=Se()){if(!t)return new URL(o).toString();if(J(t))return new URL(t).toString();let e=Re[t.toLowerCase()];if(e){let n=new URL(o),r=V(n.pathname);return n.pathname=`${r}${e}`,n.toString()}return _e(t)?Le(t,o):Oe(t,o)}function we(t,o){let e=t?.url||t?.origin||o;try{let n=new URL(e);return n.searchParams.delete("bundle"),n.searchParams.delete("demo"),n.searchParams.delete("app"),n.searchParams.delete("open"),n.searchParams.delete("port"),n.searchParams.delete("inspectOpen"),n.toString()}catch{return o}}async function Ne(t,o,e){let n=new URL(await D(t,o));return n.searchParams.set("inspectOpen",e),n.toString()}async function Fe(t,o,e,n={}){let r=n.attempts??30,s=n.intervalMs??500,a=n.minNodeCount??10;for(let i=0;i<r;i++){let l=S(t,{commandTimeoutMs:o,simId:e,simIdSource:"flag"});try{let c=await l.send({type:"evaluate",code:"(async () => (await window.__sootsimTest?.getNodeCount()) || 0)()"});if(typeof c=="number"&&c>a)return{bridge:l,count:c}}catch{}l.close(),await $(s)}return null}function He(t){if(!t)return null;try{let o=new URL(t);if(o.searchParams.has("bundle")){let e=o.searchParams.get("bundle")||"";try{let n=new URL(e),r=n.pathname.length>36?`...${n.pathname.slice(-36)}`:n.pathname;return`bundle ${n.host}${r}`}catch{return"bundle"}}return o.searchParams.has("port")?`connect :${o.searchParams.get("port")||""}`:o.searchParams.has("open")?`connect ${o.searchParams.get("open")||""}`:o.searchParams.has("demo")?`demo ${o.searchParams.get("demo")||"default"}`:o.pathname.includes("/sootsim/index.html")||o.pathname==="/sootsim/"||o.pathname==="/sootsim"?"embedded sootsim":null}catch{return null}}function Ke(t,o){if(t.length===0){console.log(" no sims connected");return}console.log(` connected sims (${t.length}):
3
- `);for(let e of t){let n=e.lockedBy&&e.lockExpiresAt?`locked by ${e.lockedBy} (${Math.max(0,Math.round((e.lockExpiresAt-Date.now())/1e3))}s)`:"",r=[e.isPrimary?"primary":"",e.id===o?"selected":"",e.readyState,e.attachedCliCount&&e.attachedCliCount>0?"in use":"",e.userFocused?"focused":"",n].filter(Boolean);console.log(` ${e.id}${r.length?` [${r.join(", ")}]`:""}`);let s=He(e.url);if(s&&console.log(` loaded: ${s}`),e.url?console.log(` url: ${e.url}`):e.origin&&console.log(` origin: ${e.origin}`),e.title&&console.log(` title: ${e.title}`),console.log(` connected: ${new Date(e.connectedAt).toISOString()}`),e.lastActiveAt&&e.lastActiveAt>0){let a=Math.round((Date.now()-e.lastActiveAt)/1e3),i=a<60?`${a}s ago`:a<3600?`${Math.round(a/60)}m ago`:`${Math.round(a/3600)}h ago`;console.log(` last active: ${i}`)}}}async function L(t,o,e,n={}){let r=n.attempts??30,s=n.intervalMs??500;for(let a=0;a<r;a++){let i=S(t,{commandTimeoutMs:o});try{let c=(await i.listSims()).find(e);if(c)return c}catch{}finally{i.close()}await $(s)}return null}async function ze(t,o,e,n={}){let r=n.attempts??20,s=n.intervalMs??250;for(let a=0;a<r;a++){let i=S(t,{commandTimeoutMs:o});try{let c=(await i.listSims()).find(d=>d.id===e);if(!c||c.readyState!=="open")return!0}catch{return!0}finally{i.close()}await $(s)}return!1}function je(t){let o=t.meta;if(!o||o.sootsimHostDriver!=="playwright")return null;let e=Number(o.sootsimHostPid);return!Number.isInteger(e)||e<=1||e===process.pid?null:e}function ye(t){try{return process.kill(t,0),!0}catch(o){return o?.code==="EPERM"}}async function qe(t,o=2500){let e=Date.now()+o;for(;Date.now()<e;){if(!ye(t))return!0;await $(100)}return!ye(t)}async function Q(t,o){let e=new Set(o),n=new Set;for(let r of t){if(!e.has(r.id))continue;let s=je(r);s&&n.add(s)}for(let r of n){try{process.kill(r,"SIGTERM")}catch{}if(await qe(r)){console.log(` closed playwright host process ${r}`);continue}try{process.kill(r,"SIGKILL"),console.log(` force-closed playwright host process ${r}`)}catch{}}}function N(t,o){if(o){let r=o.trim(),s=t.find(a=>a.id===r);if(!s)throw new Error(`no sim connected with id ${r}`);return s}let e=t.find(r=>r.isPrimary&&r.readyState==="open");if(e)return e;let n=t.find(r=>r.readyState==="open");if(n)return n;throw new Error("no sim connected")}function B(t,o,e){console.log(` ${e==="current sim"?"loaded":"opened"}: ${t} [${e}]`),console.log(` current sim: ${o.id}`),console.log(JSON.stringify({simId:o.id,url:o.url},null,2))}async function T(t,o,e){if(e.includes("--no-describe"))return;let n=process.env.SOOTSIM_QUIET_TARGET_NOTICE;process.env.SOOTSIM_QUIET_TARGET_NOTICE="1";try{await We(t,o,{stableMs:150,maxMs:400});let r=S(t,{commandTimeoutMs:3e3,simId:o,cliLabel:"open --describe",simIdSource:"flag"});try{let s=null;try{s=await r.send({type:"evaluate",code:se})}catch{}if(s&&!(s.flag===!0&&!s.loadingText&&s.nodes>=ie&&ae(s))){let d=s.loadingText?`still showing "${s.loadingText}"`:s.flag!==!0?"guest ready event has not fired":s.targets<=0?"no visible app content is inspectable yet":"app tree is still stabilizing";console.log(` app still loading: ${d} (nodes: ${s.nodes}, targets: ${s.targets})`),console.log(" before interacting, run: sootsim wait ready --max-ms 120000")}let i=`(async () => {
4
- const t = window.__sootsimTest
5
- const ms = window.SootSim?.bridges?.mainShell
6
- if (!t) return null
7
- let shell = null
8
- try { shell = ms?.getState ? await ms.getState() : null } catch {}
9
- const tree = await t.dumpTree(12, ${JSON.stringify({describe:!0,verbose:!1,filter:""})})
10
- return { tree, shell }
11
- })()`,l=await r.send({type:"evaluate",code:i});if(!l?.tree)return;if(console.log(""),l.shell?.state){let c=[`state=${l.shell.state}`,l.shell.activeApp?`app=${l.shell.activeApp}`:null].filter(Boolean);console.log(` shell: ${c.join(" ")}`)}console.log(l.tree)}finally{r.close()}}catch{}finally{n===void 0?delete process.env.SOOTSIM_QUIET_TARGET_NOTICE:process.env.SOOTSIM_QUIET_TARGET_NOTICE=n}}async function We(t,o,e){let n=Date.now()+e.maxMs,r="(async () => (await window.__sootsimTest?.getNodeCount?.()) || 0)()",s=S(t,{commandTimeoutMs:2e3,simId:o,simIdSource:"flag"});try{let a=-1,i=0;for(;Date.now()<n;){let l=-1;try{let c=await s.send({type:"evaluate",code:r});typeof c=="number"&&(l=c)}catch{}if(l>=0&&l===a){if(Date.now()-i>=e.stableMs)return}else a=l,i=Date.now();await $(50)}}finally{s.close()}}async function vt(t,o={}){let e=I(t,{port:o.port,commandTimeoutMs:o.timeoutMs}),n=x(e);try{let r=await n.listSims();Ke(r,e.simId)}finally{n.close()}}async function It(t,o={}){let e=I(t,{port:o.port,commandTimeoutMs:o.timeoutMs,stripBooleanFlags:["--new","--headless","--ephemeral"],stripValueFlags:["--base-url","--replace","--driver","--profile"]}),n=t.find((m,u)=>t[u-1]==="--profile"),r=t.includes("--ephemeral");n&&r&&(console.error(" sootsim open: --profile cannot be combined with --ephemeral"),process.exit(1));let s=n?de(n).id:void 0,a=!!s||r,i=t.includes("--new")||a,l=Ae(t);i&&e.simIdSource==="flag"&&(console.error(" sootsim open: --new, --profile, and --ephemeral cannot be combined with --sim"),process.exit(1));let c=e.positional[0]||"",d=t.find((m,u)=>t[u-1]==="--driver")||"",p=t.includes("--headless"),h=t.find((m,u)=>t[u-1]==="--base-url")||Se(),M=t.includes("--base-url"),Y=P();if(!d&&!i&&(e.simIdSource==="flag"||e.simIdSource==="saved"&&!!Y)){let m=x(e),u=e.simId?` --sim ${e.simId}`:"",f=!1;try{let g=null;try{let b=await m.listSims();if(e.simIdSource==="saved"?(g=b.find(v=>v.id===Y&&v.readyState==="open")??null,g||k()):g=N(b,e.simId),!g)if(e.simIdSource==="saved")f=!0;else throw new Error("no sim connected");if(!f&&g){let v=M||J(c)?h:we(g,h),E=await D(c,_(v,l));m.send({type:"evaluate",simId:g.id,code:`window.location.href = ${JSON.stringify(E)}`}).catch(()=>{})}}catch(b){console.error(` open failed: ${b instanceof Error?b.message:String(b)}`),await O(m,{errorsCommand:`sootsim get errors 5${u}`,warningsCommand:`sootsim get warnings 5${u}`,requestsCommand:`sootsim get requests 5${u}`}),process.exit(1)}if(!f&&g){await $(1500);let b=await Fe(e.wsPort,e.commandTimeoutMs,g.id);b||(console.error(" timed out waiting for current sim to load target"),process.exit(1)),b.bridge.close(),w(g.id);let v=M||J(c)?h:we(g,h),E=await D(c,_(v,l));B(E,{...g,url:E},"current sim"),await T(e.wsPort,g.id,t);return}}finally{m.close()}}let X=_(h,l),ve=await D(c,X),Z=`cli-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,y=await Ne(c,X,Z),F={newWindow:!0},U=m=>m.url?.includes(`inspectOpen=${Z}`)??!1;if(d){let m=q(d);m||(console.error(` unknown driver "${d}" \u2014 run \`sootsim list --drivers\``),process.exit(1));let u=await m.launch({url:y,headless:p,newWindow:F.newWindow,profileId:s,ephemeralProfile:r});u.launched||(console.error(` ${m.name} driver: ${u.message}`),process.exit(1));let f=await L(e.wsPort,e.commandTimeoutMs,U,{attempts:60,intervalMs:500});if(!f){if(u.pid)try{process.kill(u.pid,"SIGTERM"),console.error(` closed ${m.name} host process ${u.pid}`)}catch{}console.error(" timed out waiting for opened sim to connect"),process.exit(1)}w(f.id),B(y,f,`${m.name} driver`),await T(e.wsPort,f.id,t);return}if(a){let m=C();m||(console.error(" profiles require electron or playwright; install the desktop companion or use `--driver playwright`"),process.exit(1));try{(await j(y,m,{profileId:s,ephemeralProfile:r})).launched||(console.error(" desktop companion failed to start"),process.exit(1))}catch(f){console.error(` desktop companion failed: ${f instanceof Error?f.message:String(f)}`),process.exit(1)}let u=await L(e.wsPort,e.commandTimeoutMs,U,{attempts:40,intervalMs:500});u||(console.error(" timed out waiting for profiled sim to connect"),process.exit(1)),w(u.id),B(y,u,"desktop companion"),await T(e.wsPort,u.id,t);return}let H=!1,K=!1;try{let m=S(e.wsPort,{commandTimeoutMs:2e3});try{await m.listSims(),H=!0}finally{m.close()}}catch{}if(H)try{let m=S(e.wsPort,{commandTimeoutMs:3e3});try{await m.openUrl(y,F),K=!0}finally{m.close()}}catch{}if(!K){let m=C();if(m)try{if((await j(y,m)).launched){let f=await L(e.wsPort,e.commandTimeoutMs,U,{attempts:20,intervalMs:500});if(f){w(f.id),B(y,f,"desktop companion"),await T(e.wsPort,f.id,t);return}}}catch{}try{await ne(y,F)}catch(u){console.error(` open failed: ${u instanceof Error?u.message:String(u)}`),q("playwright")?.availability().available?console.error(" no system browser found \u2014 retry with `sootsim open \u2026 --driver playwright` for a headless sim."):console.error(" run `sootsim list --drivers` to see available drivers."),process.exit(1)}if(!H){console.log(` opened: ${ve}`),he(e.wsPort);return}}let R=await L(e.wsPort,e.commandTimeoutMs,U,{attempts:30,intervalMs:500});R||(console.error(" timed out waiting for opened sim to connect"),process.exit(1)),w(R.id),B(y,R,K?"bridge":"direct shell open"),await T(e.wsPort,R.id,t)}async function $e(t,o={}){let e=I(t,{port:o.port,commandTimeoutMs:o.timeoutMs,stripBooleanFlags:["--force"]}),n=t.includes("--force"),r=x(e),s=e.simId?` --sim ${e.simId}`:"";try{try{let a=await r.listSims(),i=N(a,e.positional[0]||e.simId);if(i.lockedBy&&i.lockExpiresAt&&i.lockExpiresAt>Date.now()){let l=Math.max(0,Math.round((i.lockExpiresAt-Date.now())/1e3));i.lockedByKind==="user-active"&&(console.error(` refused: ${i.id} is locked by the active user (${l}s) \u2014 that's a live human tab`),console.error(" run `sootsim open --new` for a fresh investigation sim"),process.exit(1)),n||(console.error(` refused: ${i.id} is leased by ${i.lockedBy} (${l}s)`),console.error(` \`sootsim use ${i.id} --force\` to take it, or \`sootsim open --new\` for a fresh sim`),process.exit(1))}await r.focusSim(i.id),w(i.id),console.log(` using: ${i.id}`)}catch(a){console.error(` use failed: ${a instanceof Error?a.message:String(a)}`),await O(r,{errorsCommand:`sootsim get errors 5${s}`,warningsCommand:`sootsim get warnings 5${s}`,requestsCommand:`sootsim get requests 5${s}`}),process.exit(1)}}finally{r.close()}}async function xt(t,o={}){await $e(t,o)}async function Pt(t,o={}){await $e(t,o)}async function kt(t,o={}){let e=I(t,{port:o.port,commandTimeoutMs:o.timeoutMs,stripBooleanFlags:["--force"]}),n=t.includes("--force"),r=x(e);try{try{let s=await r.listSims(),a=N(s,e.positional[0]||e.simId),i=n&&a.lockedBy&&a.lockedByKind!=="user-active"?a.lockedBy:null,l=await r.claim(a.id,{force:n});w(a.id);let c=Math.max(0,Math.round((l.lockExpiresAt-Date.now())/1e3)),d=l.bootedCount>0?` (booted ${l.bootedCount})`:"";console.log(` claimed: ${l.simId} [${c}s]${d}`),i&&console.log(` took over from: ${i}`)}catch(s){if(s instanceof re){let a=Math.max(0,Math.round(s.lock.expiresInMs/1e3));console.error(` claim failed: locked by ${s.lock.by} for ${a}s more`),console.error(" use --force to take it, or `sootsim open --new` for a fresh sim"),process.exit(1)}console.error(` claim failed: ${s instanceof Error?s.message:String(s)}`),process.exit(1)}}finally{r.close()}}async function Ge(t,o,e,n){if(n.length===0)return{closed:[],remaining:[]};await Promise.all(n.map(s=>t.closeSim(s).catch(()=>{})));let r=new Set(n);for(let s=0;s<40;s++){let a=[];try{let i=S(o,{commandTimeoutMs:e});try{a=(await i.listSims()).filter(c=>r.has(c.id)&&c.readyState==="open").map(c=>c.id)}finally{i.close()}}catch{a=[]}if(a.length===0)return{closed:[...r],remaining:[]};if(s===39)return{closed:[...r].filter(i=>!a.includes(i)),remaining:a};await $(250)}return{closed:[...r],remaining:[]}}function Qe(t,o){let e=t.filter(p=>p.readyState==="open"),n=e.map(p=>p.id),r=o.explicitKeepId?.trim()||"",s=o.savedKeepId?.trim()||"",a=s?e.some(p=>p.id===s):!1,i=s&&!a?s:null,l=null,c=null,d=null;if(o.closeOthers)if(r){let p=e.find(h=>h.id===r);p?l=p.id:c=r}else if(s&&a)l=s;else{let p=e.find(h=>h.isPrimary)??e[0]??null;p&&(l=p.id,s&&!a&&(d=p.id))}return{openIds:n,keepId:l,targets:c?[]:n.filter(p=>p!==l),staleSavedId:i,missingExplicitKeepId:c,fallbackKeepId:d}}async function Ct(t,o={}){let e=I(t,{port:o.port,commandTimeoutMs:o.timeoutMs,stripBooleanFlags:["--all","--others"]}),n=x(e),r=e.simId?` --sim ${e.simId}`:"",s=t.includes("--all"),a=t.includes("--others");if(s||a){try{let i=await n.listSims(),l=P(),c=e.positional[0]||(e.simIdSource==="flag"?e.simId:void 0),d=Qe(i,{closeOthers:a,explicitKeepId:c,savedKeepId:l});if(d.staleSavedId&&k(),d.fallbackKeepId&&(w(d.fallbackKeepId),console.log(` saved sim ${d.staleSavedId} is gone \u2014 keeping primary ${d.fallbackKeepId}`)),d.missingExplicitKeepId&&(console.error(` close failed: keep sim ${d.missingExplicitKeepId} is not connected; not closing other sims`),process.exit(1)),d.targets.length===0){console.log(d.keepId?` nothing to close \u2014 only the kept sim ${d.keepId} is connected`:d.staleSavedId?` nothing to close \u2014 no sims connected (cleared stale current sim ${d.staleSavedId})`:" nothing to close \u2014 no sims connected");return}let p=await Ge(n,e.wsPort,e.commandTimeoutMs,d.targets);await Q(i,d.targets);let h=P();h&&p.closed.includes(h)&&(d.keepId?w(d.keepId):k());let M=` closed ${p.closed.length} sim(s)${d.keepId?` (kept ${d.keepId})`:""}`;console.log(M),p.remaining.length>0&&(console.error(` close failed: still connected: ${p.remaining.join(", ")}`),process.exit(1))}catch(i){console.error(` close failed: ${i instanceof Error?i.message:String(i)}`),process.exit(1)}finally{n.close()}return}try{try{let i=await n.listSims(),l=N(i,e.positional[0]||e.simId),c=i.find(p=>p.id!==l.id&&p.readyState==="open");await n.closeSim(l.id),await ze(e.wsPort,e.commandTimeoutMs,l.id)||(await Q(i,[l.id]),console.error(` close failed: ${l.id} is still connected`),process.exit(1)),await Q(i,[l.id]),P()===l.id&&(c?w(c.id):k()),console.log(` closed: ${l.id}`)}catch(i){console.error(` close failed: ${i instanceof Error?i.message:String(i)}`),await O(n,{errorsCommand:`sootsim get errors 5${r}`,warningsCommand:`sootsim get warnings 5${r}`,requestsCommand:`sootsim get requests 5${r}`}),process.exit(1)}}finally{n.close()}}export{tt as a,Te as b,ot as c,$t as d,Se as e,D as f,Ne as g,He as h,Ke as i,L as j,je as k,vt as l,It as m,xt as n,Pt as o,kt as p,Qe as q,Ct as r};