agent-device 0.19.0 → 0.19.1
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.
- package/README.md +5 -1
- package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.19.0.apk → agent-device-android-multitouch-helper-0.19.1.apk} +0 -0
- package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.19.1.apk.sha256 +1 -0
- package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.19.0.manifest.json → agent-device-android-multitouch-helper-0.19.1.manifest.json} +4 -4
- package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.19.0.apk → agent-device-android-snapshot-helper-0.19.1.apk} +0 -0
- package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.19.1.apk.sha256 +1 -0
- package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.19.0.manifest.json → agent-device-android-snapshot-helper-0.19.1.manifest.json} +6 -6
- package/dist/apple-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AXSnapshotFallback.swift +24 -7
- package/dist/apple-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +506 -119
- package/dist/apple-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +153 -48
- package/dist/apple-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Navigation.swift +172 -0
- package/dist/apple-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SequenceExecution.swift +76 -5
- package/dist/apple-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +60 -52
- package/dist/apple-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +159 -56
- package/dist/apple-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedGesturePolicy.swift +142 -0
- package/dist/apple-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +16 -14
- package/dist/src/android-adb.d.ts +1 -2
- package/dist/src/android-adb.js +1 -1
- package/dist/src/android-input-ownership.js +6 -0
- package/dist/src/android.js +1 -1
- package/dist/src/app-lifecycle.js +3 -3
- package/dist/src/apple-runner-options.js +1 -1
- package/dist/src/apps.js +5 -5
- package/dist/src/cli-help.js +131 -34
- package/dist/src/cli-runner.js +1 -1
- package/dist/src/cli.js +11 -11
- package/dist/src/client.js +2 -2
- package/dist/src/command-metadata.js +1 -1
- package/dist/src/command-schema.js +3 -3
- package/dist/src/device-input-state.js +2 -2
- package/dist/src/devices2.js +1 -1
- package/dist/src/find.js +1 -1
- package/dist/src/generic.js +1 -1
- package/dist/src/index.d.ts +199 -20
- package/dist/src/input-actions.js +3 -3
- package/dist/src/interaction-snapshot.js +1 -1
- package/dist/src/interaction.js +1 -1
- package/dist/src/interactor.js +2 -2
- package/dist/src/internal/bin.js +1 -1
- package/dist/src/internal/daemon.js +17 -15
- package/dist/src/lease.js +1 -1
- package/dist/src/linux.js +1 -1
- package/dist/src/metro.d.ts +0 -1
- package/dist/src/notifications.js +1 -1
- package/dist/src/points.js +1 -1
- package/dist/src/project-runtime.js +1 -1
- package/dist/src/providers.js +1 -1
- package/dist/src/react-native.js +1 -1
- package/dist/src/record-trace-recording.js +2 -2
- package/dist/src/record-trace.js +1 -1
- package/dist/src/registry.js +24 -23
- package/dist/src/reporting.js +3 -3
- package/dist/src/runner-client.js +1 -1
- package/dist/src/runtime.js +2 -2
- package/dist/src/sdk-android-adb.d.ts +2 -2
- package/dist/src/sdk-batch-runner.d.ts +0 -1
- package/dist/src/sdk-batch.js +2 -2
- package/dist/src/sdk-finders.d.ts +1 -2
- package/dist/src/sdk-finders.js +1 -1
- package/dist/src/sdk-io.d.ts +0 -1
- package/dist/src/sdk-remote-config.d.ts +1 -2
- package/dist/src/sdk-remote-config.js +1 -1
- package/dist/src/sdk-selectors.js +1 -1
- package/dist/src/selector-runtime.js +1 -1
- package/dist/src/selectors.d.ts +0 -1
- package/dist/src/selectors.js +1 -1
- package/dist/src/selectors2.js +1 -1
- package/dist/src/server.js +3 -3
- package/dist/src/session.js +10 -10
- package/dist/src/simctl.js +1 -1
- package/dist/src/simulator.js +1 -1
- package/dist/src/snapshot-diagnostics.js +2 -2
- package/dist/src/snapshot-helper.js +4 -4
- package/dist/src/snapshot-quality.js +1 -1
- package/dist/src/snapshot2.js +2 -2
- package/dist/src/tv-remote.js +14 -0
- package/dist/src/web.js +1 -1
- package/package.json +5 -4
- package/server.json +2 -2
- package/skills/agent-device/SKILL.md +8 -7
- package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.19.0.apk.sha256 +0 -1
- package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.19.0.apk.sha256 +0 -1
- package/dist/src/device-rotation.js +0 -14
- package/dist/src/logcat.js +0 -6
package/dist/src/session.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{B as e,F as t,I as n,S as r,b as i,f as a,h as o,m as s,p as c,t as l,v as u,y as d}from"./sdk-contracts.js";import{C as f,N as p,c as m,j as h,p as g,v as _}from"./sdk-android-adb.js";import{
|
|
2
|
-
`);function vi(e){return Ve(e)!==void 0}async function yi(e){let{device:t,appId:n,runtime:r}=e;if(Bn(t)||!n)return;let i=Ve(r);if(i){if(t.platform===`android`){await xi(t,n,i);return}c(t)&&t.kind===`simulator`&&await Ti(t,n,i)}}async function bi(e){let{device:t,appId:n}=e;if(n){if(t.platform===`android`){await Si(t,n);return}c(t)&&t.kind===`simulator`&&await Ei(t,n)}}async function xi(e,t,n){Mi(t);let r=Oi(await Ci(e,t),fi,`${n.host}:${n.port}`);r=ki(r,pi,n.scheme===`https`),await wi(e,t,r)}async function Si(e,t){Mi(t);let n=await Ci(e,t),r=ji(ji(n,fi),pi);r!==n&&await wi(e,t,r)}async function Ci(e,t){let n=await it(e,[`shell`,`run-as`,t,`cat`,di],{allowFailure:!0});return n.exitCode===0?Di(n.stdout):_i}async function wi(e,r,i){let a=[`shell`,`run-as`,r,`id`],o=await it(e,a,{allowFailure:!0});if(o.exitCode!==0){let e=Fi(o.stdout,o.stderr);throw new t(`COMMAND_FAILED`,e?`Failed to access Android app sandbox for ${r}`:`Failed to probe Android app sandbox for ${r}`,g(o,{package:r,cmd:`adb`,args:a,hint:e?gi:`adb shell run-as probe failed. Check adb connectivity and that the device is reachable. Inspect stderr/details for more information.`}))}try{await it(e,[`shell`,`run-as`,r,`mkdir`,`-p`,`shared_prefs`]),await it(e,[`shell`,`run-as`,r,`tee`,di],{stdin:i.trimEnd()})}catch(e){let i=n(e);if(i.code===`TOOL_MISSING`)throw i;let a=Fi(typeof i.details?.stdout==`string`?i.details.stdout:``,typeof i.details?.stderr==`string`?i.details.stderr:``);throw new t(`COMMAND_FAILED`,a?`Failed to access Android app sandbox for ${r}`:`Failed to write Android runtime hints for ${r}`,{...i.details??{},package:r,cmd:`adb`,phase:`write-runtime-hints`,hint:a?gi:`adb run-as succeeded, but writing ReactNativeDevPrefs.xml failed. Inspect stderr/details for the failing shell command.`},i)}}async function Ti(e,t,n){await Tt(Dt(e,[`spawn`,e.id,`defaults`,`write`,t,mi,`-string`,`${n.host}:${n.port}`])),await Tt(Dt(e,[`spawn`,e.id,`defaults`,`write`,t,hi,`-string`,n.scheme]))}async function Ei(e,t){await Tt(Dt(e,[`spawn`,e.id,`defaults`,`delete`,t,mi]),{allowFailure:!0}),await Tt(Dt(e,[`spawn`,e.id,`defaults`,`delete`,t,hi]),{allowFailure:!0})}function Di(e){let t=e.trim();return!t.includes(`<map`)||!t.includes(`</map>`)?_i:`${t}\n`}function Oi(e,t,n){let r=` <string name="${Pi(t)}">${Pi(n)}</string>`;return Ai(ji(e,t),r)}function ki(e,t,n){let r=` <boolean name="${Pi(t)}" value="${n?`true`:`false`}" />`;return Ai(ji(e,t),r)}function Ai(e,t){return Di(e).replace(`</map>`,`${t}\n</map>`)}function ji(e,t){let n=Ni(t);return Di(e).replace(RegExp(`^\\s*<string name="${n}">[\\s\\S]*?<\\/string>\\n?`,`m`),``).replace(RegExp(`^\\s*<boolean name="${n}" value="(?:true|false)"\\s*\\/?>\\n?`,`m`),``)}function Mi(e){if(Ye(e)!==`binary`)return;let n=Xe(e);throw new t(`INVALID_ARGS`,n,{package:e,hint:n})}function Ni(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Pi(e){return e.replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`).replaceAll(`"`,`"`).replaceAll(`'`,`'`)}function Fi(e,t){let n=`${e}\n${t}`.toLowerCase();return[`run-as: package not debuggable`,`run-as: permission denied`,`run-as: package is unknown`,`run-as: unknown package`,`is unknown`,`is not an application`,`could not set capabilities`].some(e=>n.includes(e))}const Ii=[`platform`,`metroHost`,`metroPort`,`bundleUrl`,`launchUrl`];function Li(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>e!==void 0&&e!==``).length:0}function Ri(e,n){if(e!==void 0){if(typeof e!=`string`)throw new t(`INVALID_ARGS`,`Invalid open runtime ${n}: expected string.`);return Be(e)}}function zi(e){if(e!==void 0){if(!Number.isInteger(e)||e<1||e>65535)throw new t(`INVALID_ARGS`,`Invalid runtime metroPort: ${String(e)}. Use an integer between 1 and 65535.`);return e}}function Bi(e){if(e!==void 0){if(typeof e!=`number`)throw new t(`INVALID_ARGS`,`Invalid open runtime metroPort: expected integer.`);return zi(e)}}function Vi(e,n,r){if(e===void 0)return r;if(e!==`ios`&&e!==`android`)throw new t(`INVALID_ARGS`,`Invalid open runtime platform: ${String(e)}. Use "ios" or "android".`);if(r&&e!==r)throw new t(`INVALID_ARGS`,`open runtime targets ${e}, but session "${n}" is bound to ${r}.`);return e}function Hi(e){if(e===`ios`||e===`android`)return e}function Ui(e,t){return{platform:t,metroHost:Be(e?.metroHost),metroPort:zi(e?.metroPort),bundleUrl:Be(e?.bundleUrl),launchUrl:Be(e?.launchUrl)}}function Wi(e,t){return{platform:t.platform??e?.platform,metroHost:t.metroHost??e?.metroHost,metroPort:t.metroPort??e?.metroPort,bundleUrl:t.bundleUrl??e?.bundleUrl,launchUrl:t.launchUrl??e?.launchUrl}}function Gi(e){let{runtime:n,sessionName:r,platform:i}=e;if(n===void 0)return;if(!n||typeof n!=`object`||Array.isArray(n))throw new t(`INVALID_ARGS`,`open runtime must be an object.`);let a=n,o=Object.keys(a).find(e=>!Ii.includes(e));if(o)throw new t(`INVALID_ARGS`,`Invalid open runtime field: ${o}. Supported fields are ${Ii.join(`, `)}.`);return{platform:Vi(a.platform,r,i),metroHost:Ri(a.metroHost,`metroHost`),metroPort:Bi(a.metroPort),bundleUrl:Ri(a.bundleUrl,`bundleUrl`),launchUrl:Ri(a.launchUrl,`launchUrl`)}}function Ki(e,t,n){if(n){if(Li(n)===0){e.clearRuntimeHints(t);return}return e.setRuntimeHints(t,n),n}}function qi(e,n,r){let a=e.getRuntimeHints(n);if(!a)return;let o=r?i(r):void 0,s=Hi(o);if(a.platform&&r&&!s)throw new t(`INVALID_ARGS`,`Session runtime hints are only supported on iOS and Android sessions, but session "${n}" is bound to ${o}.`);if(a.platform&&s&&a.platform!==s)throw new t(`INVALID_ARGS`,`Session runtime hints target ${a.platform}, but session "${n}" is bound to ${o}. Clear the runtime hints or use a different session.`);return s&&a.platform!==s?{...a,platform:s}:a}function Ji(e){let{req:t,sessionStore:n,sessionName:r,device:a}=e,o=n.getRuntimeHints(r),s=Gi({runtime:t.runtime,sessionName:r,platform:Hi(i(a))});return t.runtime===void 0?{runtime:qi(n,r,a),previousRuntime:o,replacedStoredRuntime:!1}:{runtime:s&&Li(s)>0?s:void 0,previousRuntime:o,replacedStoredRuntime:!0}}function Yi(e){try{return{ok:!0,data:Ji(e)}}catch(e){let t=n(e);return k(t.code,t.message,t.details)}}async function Xi(e){let{replacedStoredRuntime:t,previousRuntime:n,runtime:r,session:i}=e;!t||!i?.appBundleId||!vi(n)||vi(r)||await bi({device:i.device,appId:i.appBundleId})}async function Zi(e){let{req:t,sessionName:n,sessionStore:r}=e,i=(t.positionals?.[0]??`show`).toLowerCase();if($i(i))return await ia(t,i);if(!Qi(i))return k(`INVALID_ARGS`,`runtime requires set, show, clear, port-reverse, or port-reverse-remove`);let a=r.get(n),o=r.getRuntimeHints(n);return i===`clear`?await ea(n,r,a,o):i===`show`?ta(n,o):ra({req:t,sessionName:n,sessionStore:r,session:a,current:o})}function Qi(e){return e===`set`||e===`show`||e===`clear`}function $i(e){return e===`port-reverse`||e===`port-reverse-remove`}async function ea(e,t,n,r){return vi(r)&&n?.appBundleId&&await bi({device:n.device,appId:n.appBundleId}),{ok:!0,data:{session:e,cleared:t.clearRuntimeHints(e)}}}function ta(e,t){return{ok:!0,data:{session:e,configured:!!t,runtime:t}}}function na(e){return e?i(e.device):void 0}function ra(e){let{req:t,sessionName:n,sessionStore:r,session:i,current:a}=e,o=na(i),s=Hi(t.flags?.platform??a?.platform??o);if(!s)return k(`INVALID_ARGS`,`runtime set only supports iOS and Android sessions. Pass --platform ios|android or open an iOS/Android session first.`);if(o!==void 0&&o!==s)return k(`INVALID_ARGS`,`runtime set targets ${s}, but session "${n}" is already bound to ${o}.`);let c=Wi(a,Ui(t.flags,s));return Li(c)===0?k(`INVALID_ARGS`,`runtime set requires at least one hint such as --metro-host, --metro-port, --bundle-url, or --launch-url.`):(r.setRuntimeHints(n,c),{ok:!0,data:{session:n,configured:!0,runtime:c}})}async function ia(e,t){let n=aa(e);if(!n.ok)return n.response;let r=await ca(t,n.options);return r?{ok:!0,data:{action:t,...r}}:k(`UNSUPPORTED_OPERATION`,`No active provider device runtime supports port reverse for this lease.`)}function aa(e){let t=oa(e);if(!t.ok)return t;let n=sa(e);if(!n.ok)return n;let r=e.flags?.portReverseName?.trim()||`runtime`;return{ok:!0,options:{leaseId:t.leaseId,provider:t.provider,devicePort:n.devicePort,hostPort:n.hostPort,name:r}}}function oa(e){let t=e.flags?.leaseId,n=e.flags?.leaseProvider;return t?n?{ok:!0,leaseId:t,provider:n}:{ok:!1,response:k(`INVALID_ARGS`,`runtime port-reverse requires a lease provider.`)}:{ok:!1,response:k(`INVALID_ARGS`,`runtime port-reverse requires a resolved remote lease.`)}}function sa(e){let t=la(e.flags?.devicePort),n=la(e.flags?.hostPort??e.flags?.devicePort);return!t||!n?{ok:!1,response:k(`INVALID_ARGS`,`runtime port-reverse requires numeric devicePort and hostPort values from 1 to 65535.`)}:{ok:!0,devicePort:t,hostPort:n}}async function ca(e,t){return e===`port-reverse`?await Zn(t):await jn(t)}function la(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<1||e>65535))return e}const ua=`open-command-roundtrip`,da=`Not implemented for this platform in this release.`;function fa(e){let{sessionName:t,sessionStateDir:n,runnerLogPath:r,requestLogPath:a,appName:o,appBundleId:s,surface:l,startup:u,timing:d,device:f,runtime:p,runtimeHintCount:m}=e,h={session:t,surface:l,sessionStateDir:n,runnerLogPath:r,requestLogPath:a};return o&&(h.appName=o),s&&(h.appBundleId=s),u&&(h.startup=u),d&&(h.timing=d),p&&m(p)>0&&(h.runtime=p),f&&(h.platform=i(f),h.target=f.target??`mobile`,h.device=f.name,h.id=f.id,h.kind=f.kind,f.platform===`android`&&(h.serial=f.id)),f&&c(f)&&(h.device_udid=f.id,h.ios_simulator_device_set=f.simulatorSetPath??null),{...h,...Ce(`Opened: ${o??s??t}`)}}function pa(e){let{existingSession:t,sessionName:n,sessionScope:r,device:i,surface:a,appBundleId:o,appName:s,saveScript:c}=e;return t?{...t,device:i,surface:a,appBundleId:o,appName:s,recordSession:t.recordSession||c,snapshot:void 0}:{name:n,sessionScope:r,device:i,createdAt:Date.now(),surface:a,appBundleId:o,appName:s,recordSession:c,actions:[]}}const ma=new Set([`app`,`desktop`,`frontmost-app`]);function ha(e,n,r){if(e.platform===`linux`){if(!n)return`app`;let e=ue(n);if(!ma.has(e))throw new t(`INVALID_ARGS`,`Linux supports --surface app, desktop, and frontmost-app (got "${n}")`);if(e!==`app`&&r)throw new t(`INVALID_ARGS`,`open --surface ${e} does not accept an app target`);return e}if(!s(e)){if(n)throw new t(`INVALID_ARGS`,`surface is only supported on macOS and Linux`);return`app`}let i=n?ue(n):`app`;if(i!==`app`&&i!==`menubar`&&r)throw new t(`INVALID_ARGS`,`open --surface ${i} does not accept an app target`);return i}function ga(e){let{device:t,surfaceFlag:n,openTarget:r,existingSurface:i}=e;return(s(t)||t.platform===`linux`)&&!n?i??`app`:ha(t,n,r)}async function _a(e){if(e===`app`||e===`desktop`||e===`menubar`)return{};let t=await Et();return{appBundleId:t.bundleId,appName:t.appName}}async function va(e,t,n){if(!(!a(e.platform)||!t))return at(t)?s(e)?void 0:e.kind===`device`?Qe(n,t):$e(t)?void 0:n??await ya(e,t):await ba(e,t)}async function ya(e,t){try{let{resolveIosSimulatorDeepLinkBundleId:n}=await import(`./apps.js`).then(e=>e.t);return await n(e,t)}catch{return}}async function ba(e,t){try{let{resolveIosApp:n}=await import(`./apps.js`).then(e=>e.t);return await n(e,t)}catch{return}}async function xa(e,t){if(!(e.platform!==`android`||!t||at(t)))try{let{resolveAndroidApp:n}=await import(`./app-lifecycle.js`).then(e=>e.t),r=await n(e,t);return r.type===`package`?r.value:void 0}catch{return}}async function Sa(e,t,n){if(n||e.platform!==`android`||!t||!at(t))return n;try{let{getAndroidAppState:t}=await import(`./app-lifecycle.js`).then(e=>e.t);return(await t(e)).package?.trim()||n}catch{return n}}function Ca(e,t){return e.platform===`android`&&!!(t&&at(t))}async function wa(e,t,n,r){return await va(e,t,n)??await r(e,t)??(Ca(e,t)?n:void 0)}function H(e){return k(`INVALID_ARGS`,e)}function Ta(e,n,r,i){try{return ga({device:e,surfaceFlag:n,openTarget:r,existingSurface:i})}catch(e){return k(e instanceof t?e.code:`INVALID_ARGS`,String(e.message))}}function Ea(e){let{shouldRelaunch:t,openTarget:n,surface:r,device:i}=e;return t?n&&at(n)?H(`open --relaunch does not support URL targets.`):r===`app`?i.platform===`android`&&n&&Ye(n)===`binary`?H(Xe(n)):null:H(`open --relaunch is supported only for app surfaces.`):null}function Da(e){let{shouldRelaunch:t,openTarget:n,platform:r}=e;return t?n&&at(n)?H(`open --relaunch does not support URL targets.`):r===`android`&&n&&Ye(n)===`binary`?H(Xe(n)):null:null}async function Oa(e){let{req:t,sessionName:n,sessionStore:r,device:i,surface:a,openTarget:o,existingSession:s,onIosSimulatorColdBootStart:c}=e;await Dr(i,{deviceHub:t.flags?.deviceHub===!0,onIosSimulatorColdBootStart:c});let{appBundleId:l,appName:u}=await ka({device:i,surface:a,openTarget:o,existingAppBundleId:s?.appBundleId}),d=Yi({req:t,sessionStore:r,sessionName:n,device:i});if(!d.ok)return{type:`response`,response:d};if(s){let{runtime:e,previousRuntime:t,replacedStoredRuntime:n}=d.data;await Xi({replacedStoredRuntime:n,previousRuntime:t,runtime:e,session:s})}return{type:`details`,details:{appBundleId:l,appName:u,runtime:d.data.runtime}}}async function ka(e){let{device:t,surface:n,openTarget:r,existingAppBundleId:i}=e,a=await _a(n);return{appBundleId:a.appBundleId??await wa(t,r,i,xa),appName:a.appName??r}}const Aa=new Map;async function ja(e){let{device:t,closeTarget:n,outFlag:r,context:i}=e;a(t.platform)&&!z(t)&&await dt(t.id),await E(t,`close`,[n],r,i),await si(t,300)}async function Ma(e){let{runtime:t,device:n,req:r,logPath:i,appBundleId:a,traceLogPath:o,openPositionals:s}=e,c=t?.launchUrl;if(!c||s.length===0||s.length>1)return;let l=s[0]?.trim();!l||at(l)||await E(n,`open`,[c],r.flags?.out,{...Na(i,r.flags,a,o)})}function Na(e,t,n,r){let i=D(e,t,n,r);return delete i.launchConsole,delete i.launchArgs,i}function Pa(e,t,n){return{durationMs:Math.max(0,Date.now()-e),measuredAt:new Date().toISOString(),method:ua,appTarget:t,appBundleId:n}}async function Fa(e){let{req:t,sessionName:n,sessionStore:r,logPath:i,device:a,openTarget:o,openPositionals:s,appName:l,surface:u,appBundleId:d,runtime:f,existingSession:m}=e,g=t.flags?.relaunch===!0,_=m?.trace?.outPath,v=d,y=Date.now(),b={},x=c(a)&&u===`app`&&s.length>0&&!!v,S=kr({req:t,logPath:i,appBundleId:v,traceLogPath:_}),C=t.flags?.maestro?.prewarmRunnerBeforeOpen===!0,ee,te=!1,ne=!1,re=(e=S)=>{te=!0,b.runnerPrewarmKind=`session`,b.runnerPrewarmScheduled=!0,ee=_t(a,e)},ie=async()=>{if(!ee||ne)return;ne=!0;let e=Date.now();await ee,b.runnerPrewarmWaited=!0,b.runnerPrewarmDurationMs=Math.max(0,Date.now()-e)};x&&z(a)&&!C&&re();let ae=g&&!!o&&s.length===1&&z(a)&&t.flags?.clearAppState!==!0;if(g&&o&&!ae){let e=v??o,n=Date.now();await ja({device:a,closeTarget:e,outFlag:t.flags?.out,context:{...D(i,t.flags,v??m?.appBundleId,_)}}),b.relaunchCloseDurationMs=Math.max(0,Date.now()-n)}let w=Date.now();await yi({device:a,appId:v,runtime:f}),b.runtimeHintsDurationMs=Math.max(0,Date.now()-w),x&&C&&(re({...S,propagateError:!0}),await ie());let oe=Date.now(),se=await Ia({req:t,sessionName:n,sessionStore:r,device:a,surface:u,sessionAppBundleId:v,appName:l,existingSession:m});if(se.type===`response`)return se.response;let ce=se.session??m;await E(a,`open`,s,t.flags?.out,{...D(i,t.flags,v),...ae?{terminateRunningApp:!0}:{}}),b.openDispatchDurationMs=Math.max(0,Date.now()-oe);let le=Date.now();await Ma({runtime:f,device:a,req:t,logPath:i,appBundleId:v,traceLogPath:_,openPositionals:s}),b.launchUrlDurationMs=Math.max(0,Date.now()-le),x&&!te&&re(),g?await ie():ee&&!ne&&(b.runnerPrewarmWaited=!1),v=await Sa(a,o,v),a.platform===`android`&&v&&await It(a,v);let ue=o?Pa(oe,o,v):void 0,de=Date.now();if(await si(a,300),b.postOpenSettleDurationMs=Math.max(0,Date.now()-de),Ct(t.meta?.requestId)){let e=wt();return k(e.code,e.message,e.details)}m&&Xt(m,`open`,m.snapshot);let fe=pa({existingSession:ce,sessionName:m?.name??Mn(t),sessionScope:m?.sessionScope??Vn(t),device:a,surface:u,appBundleId:v,appName:l,saveScript:!!t.flags?.saveScript});fe.lease=dn({req:t,existingLease:m?.lease}),t.runtime!==void 0&&Ki(r,n,f);let pe=r.ensureSessionDir(n),me=ir(pe,t.meta?.requestId??p().requestId);b.totalDurationMs=Math.max(0,Date.now()-y),h({level:`info`,phase:`open_timing`,durationMs:b.totalDurationMs,data:b});let he=fa({sessionName:fe.name,sessionStateDir:pe,runnerLogPath:an(pe),requestLogPath:me,appName:l,appBundleId:v,surface:u,startup:ue,timing:b,device:a,runtime:f,runtimeHintCount:Li});return r.recordAction(fe,{command:`open`,positionals:s,flags:t.flags??{},runtime:t.runtime===void 0?void 0:f,result:he}),r.set(n,fe),{ok:!0,data:he}}async function Ia(e){let{req:t,sessionName:n,sessionStore:r,device:i,surface:a,sessionAppBundleId:o,appName:s,existingSession:c}=e,l=t.internal?.openLifecycle?.beforeDispatch;if(!l)return{type:`session`,session:c};let u=pa({existingSession:c,sessionName:c?.name??Mn(t),sessionScope:c?.sessionScope??Vn(t),device:i,surface:a,appBundleId:o,appName:s,saveScript:!!t.flags?.saveScript});u.lease=dn({req:t,existingLease:c?.lease}),r.set(n,u);let d=await l(u);return d&&!d.ok?{type:`response`,response:d}:{type:`session`,session:r.get(n)??u}}async function La(e){let{req:t,sessionName:n,logPath:r,sessionStore:i}=e,a=i.get(n);if(a){let e=t.flags?.relaunch===!0,o=t.positionals?.[0],s=o??(e?a.appName:void 0),c=Ta(a.device,t.flags?.surface,s,a.surface);if(typeof c!=`string`)return c;if(!s&&c===`app`)return H(e?`open --relaunch requires an app name or an active session app.`:`Session already active. Close it first or pass a new --session name.`);let l=Ea({shouldRelaunch:e,openTarget:s,surface:c,device:a.device});if(l)return l;let u=await ci(a.device),d=await Oa({req:t,sessionName:n,sessionStore:i,device:u,surface:c,openTarget:s,existingSession:a,onIosSimulatorColdBootStart:Ar({req:t,logPath:r,device:u,surface:c,openTarget:s,traceLogPath:a.trace?.outPath})});return d.type===`response`?d.response:await Fa({req:t,sessionName:n,sessionStore:i,logPath:r,device:u,openTarget:s,openPositionals:o?t.positionals??[]:s?[s]:[],appBundleId:d.details.appBundleId,appName:d.details.appName,runtime:d.details.runtime,surface:c,existingSession:a})}let o=t.flags?.relaunch===!0,s=t.positionals?.[0];if(o&&!s)return H(`open --relaunch requires an app argument.`);let c=Da({shouldRelaunch:o,openTarget:s,platform:t.flags?.platform===`android`?`android`:void 0});if(c)return c;let l=await Ln(t.flags??{}),u=Ta(l,t.flags?.surface,s);return typeof u==`string`?Ea({shouldRelaunch:o,openTarget:s,surface:u,device:l})||await gt(Aa,l.id,async()=>{let e=i.toArray().find(e=>e.device.id===l.id);if(e)return hn(t,e)?k(`DEVICE_IN_USE`,`Device is already in use by another workspace session.`,{deviceId:l.id,deviceName:l.name,hint:`Use a different device selector, wait for the other workspace to close its session, or run agent-device devices to choose another target.`}):k(`DEVICE_IN_USE`,`Device is already in use by session "${e.name}".`,{session:e.name,deviceId:l.id,deviceName:l.name,hint:$t(e,`device-in-use`)});let a=await Oa({req:t,sessionName:n,sessionStore:i,device:l,surface:u,openTarget:s,onIosSimulatorColdBootStart:Ar({req:t,logPath:r,device:l,surface:u,openTarget:s})});return a.type===`response`?a.response:await Fa({req:t,sessionName:n,sessionStore:i,logPath:r,device:l,openTarget:s,openPositionals:t.positionals??[],appBundleId:a.details.appBundleId,appName:a.details.appName,runtime:a.details.runtime,surface:u})}):u}function Ra(e){return z(e)||ai(e)}async function za(t){if(t.booted===!1)return{success:!0,exitCode:0,stdout:``,stderr:``};try{return z(t)?await Ba(t):await Ha(t)}catch(t){let n=e(t);return{success:!1,exitCode:-1,stdout:``,stderr:n.message,error:n}}}async function Ba(e){let t=await Pr(e);return t.success?t:await Va(e)===`Shutdown`?{...t,success:!0,exitCode:0}:t}async function Va(e){try{return await Fr(e)}catch{return null}}async function Ha(e){let t=await it(e,[`emu`,`kill`],{allowFailure:!0,timeoutMs:15e3});return{success:t.exitCode===0,exitCode:t.exitCode,stdout:t.stdout,stderr:t.stderr}}async function Ua(e){let{device:t,shutdownRequested:n}=e;if(n&&Ra(t))return await za(t)}function Wa(e,t){return z(t.device)&&!e.flags?.shutdown&&!t.recording&&!t.lease&&!t.device.simulatorSetPath}function Ga(e){return a(e.device.platform)&&!z(e.device)}async function Ka(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,leaseRegistry:o,leaseLifecycleProvider:s}=e,c=i.get(n);if(!c)return await Ya(t,r);let l;try{await en(c),await on(c,`session-close`),await In(c),await Un(c),await xn(c),qa(t,c)&&(Ga(c)&&await Nn(c),await E(c.device,`close`,t.positionals??[],t.flags?.out,{...D(r,t.flags,c.appBundleId,c.trace?.outPath)}),await si(c.device,300)),a(c.device.platform)&&!Wa(t,c)?await Nn(c):a(c.device.platform)&&(h({level:`debug`,phase:`ios_runner_retained_after_close`,data:{session:c.name,deviceId:c.device.id}}),vt(c.device.id)),vi(i.getRuntimeHints(n))&&c.appBundleId&&await bi({device:c.device,appId:c.appBundleId}).catch(()=>{}),Mr(i,c,t,`close`,{session:c.name,...Ce(`Closed: ${c.name}`)}),t.flags?.saveScript&&(c.recordSession=!0),i.writeSessionLog(c),await Xn(n).catch(()=>{})}finally{try{l=await Qn({session:c,leaseRegistry:o,leaseLifecycleProvider:s})}finally{i.delete(n)}}let u=await Ua({device:c.device,shutdownRequested:t.flags?.shutdown});return u?{ok:!0,data:xe({session:c.name,shutdown:u,...l?{provider:l}:{}},`Closed: ${c.name}`)}:{ok:!0,data:{session:c.name,...Ce(`Closed: ${c.name}`),...l?{provider:l}:{}}}}function qa(e,t){return Ja(e)||t.device.platform===`web`}function Ja(e){return(e.positionals?.length??0)>0}async function Ya(e,t){if(!e.positionals||e.positionals.length===0)return k(`SESSION_NOT_FOUND`,`No active session`);let n=await V({session:void 0,flags:e.flags,ensureReady:!0});return await E(n,`close`,e.positionals,e.flags?.out,{...D(t,e.flags)}),await si(n,300),{ok:!0,data:{app:e.positionals[0],...Ce(`Closed: ${e.positionals[0]}`)}}}const Xa={ios:async(e,t,n)=>{let r=await un(e,t,n,{relaunch:!0,appIdentifierHint:t});if(r)return{bundleId:r.bundleId??r.launchTarget??t};let{reinstallIosApp:i}=await import(`./apps.js`).then(e=>e.t);return await i(e,t,n)},android:async(e,t,n)=>{let r=await un(e,t,n,{relaunch:!0,packageNameHint:t});if(r)return{package:r.packageName??r.launchTarget??t};let{reinstallAndroidApp:i}=await import(`./app-lifecycle.js`).then(e=>e.t);return await i(e,t,n)}},Za={ios:async(e,t,n)=>{let r=await un(e,t,n,{appIdentifierHint:t});if(r)return{bundleId:r.bundleId,appName:r.appName,launchTarget:r.launchTarget};let{installIosApp:i}=await import(`./apps.js`).then(e=>e.t),a=await i(e,n,{appIdentifierHint:t});return{bundleId:a.bundleId,appName:a.appName,launchTarget:a.launchTarget}},android:async(e,t,n)=>{let r=await un(e,t,n,{packageNameHint:t});if(r)return{package:r.packageName,appName:r.appName,launchTarget:r.launchTarget};let{installAndroidApp:i}=await import(`./app-lifecycle.js`).then(e=>e.t),a=await i(e,n);return{package:a.packageName,appName:a.appName,launchTarget:a.launchTarget}}};async function Qa(e){let{req:t,command:n,sessionName:r,sessionStore:i,deployOps:a}=e,o=i.get(r),s=t.flags??{},l=B(n,o,s);if(l)return l;let u=no(n,t.positionals??[]);if(!u.ok)return u.response;let{app:d,appPathInput:f}=u,p=t.meta?.uploadedArtifactId;try{let e=p?Qt(p,t.meta?.tenantId):A.expandHome(f);if(!L.existsSync(e))return k(`INVALID_ARGS`,`App binary not found: ${e}`);let r=await V({session:o,flags:s,ensureReady:!1}),l=O(n,r);if(l)return l;let u=c(r)?eo(d,e,await a.ios(r,d,e)):to(d,e,await a.android(r,d,e)),m=xe(u,$a(u));return Mr(i,o,t,n,m),{ok:!0,data:m}}finally{p&&yn(p)}}function $a(e){return`Installed: ${e.appName??ye(e)}`}function eo(e,t,n){let r=n.bundleId;return{app:e||r||n.launchTarget||t,appPath:t,platform:`ios`,...r?{appId:r,bundleId:r}:{},appName:n.appName,launchTarget:n.launchTarget}}function to(e,t,n){let r=n.package;return{app:e||r||n.launchTarget||t,appPath:t,platform:`android`,...r?{appId:r,package:r,packageName:r}:{},appName:n.appName,launchTarget:n.launchTarget}}function no(e,t){let n=t[0]?.trim(),r=t[1]?.trim();if(e===`install`){let e=r??n;return e?{ok:!0,app:r?n??``:``,appPathInput:e}:{ok:!1,response:k(`INVALID_ARGS`,`install requires: install <path-to-app-binary>`)}}return!n||!r?{ok:!1,response:k(`INVALID_ARGS`,`reinstall requires: reinstall <app> <path-to-app-binary>`)}:{ok:!0,app:n,appPathInput:r}}async function ro(e,t,n){return await Le(e,t,n)}async function io(e){let{req:t,sessionName:o,sessionStore:c}=e;if(t.command===`session_list`){let e=Vn(t);return{ok:!0,data:{sessions:c.toArray().filter(t=>bn(t,e)).map(e=>{let t=c.resolveSessionDir(e.name);return{name:e.name,sessionStateDir:t,runnerLogPath:an(t),platform:i(e.device),...a(e.device.platform)&&e.device.appleOs?{appleOs:e.device.appleOs}:{},target:e.device.target??`mobile`,surface:e.surface??`app`,device:e.device.name,id:e.device.id,device_id:e.device.id,createdAt:e.createdAt,...a(e.device.platform)&&!s(e.device)&&{device_udid:e.device.id,ios_simulator_device_set:e.device.simulatorSetPath??null}}})}}}if(t.command===`devices`)try{let e=rt(t.flags?.androidDeviceAllowlist),n=t.flags?.platform,i=r({simulatorSetPath:nt(t.flags?.iosSimulatorDeviceSet),platform:n,target:t.flags?.target}),a=await tn({platform:n,target:t.flags?.target,deviceName:t.flags?.device,udid:t.flags?.udid,serial:t.flags?.serial,iosSimulatorSetPath:i,androidSerialAllowlist:e?Array.from(e).sort():void 0}),o=n?a.filter(e=>oo(e,n)):a;return{ok:!0,data:{devices:(t.flags?.target?o.filter(e=>(e.target??`mobile`)===t.flags?.target):o).map(ao)}}}catch(e){let t=n(e);return k(t.code,t.message,t.details)}if(t.command===`capabilities`){let e=c.get(o),n=t.flags??{},r=B(t.command,e,n);if(r)return r;let i=await V({session:e,flags:n,ensureReady:!1,allowStoppedAndroidAvdPlaceholders:!0});return{ok:!0,data:{device:ao(i),availableCommands:fn().filter(e=>At(e,i))}}}if(t.command===`apps`){let e=c.get(o),n=t.flags??{},r=B(t.command,e,n);if(r)return r;let i=await V({session:e,flags:n,ensureReady:!0}),s=O(`apps`,i);if(s)return s;let l=Ke(t.flags?.appsFilter);return a(i.platform)?{ok:!0,data:{apps:(await Nr(i,l)).map(e=>e.name&&e.name!==e.bundleId?`${e.name} (${e.bundleId})`:e.bundleId)}}:{ok:!0,data:{apps:(await Ze(i,l)).map(e=>e.name&&e.name!==e.package?`${e.name} (${e.package})`:e.package)}}}return null}function ao({simulatorSetPath:e,appleOs:t,...n}){return{...n,platform:i({platform:n.platform,appleOs:t}),...a(n.platform)&&t?{appleOs:t}:{}}}function oo(e,t){return d(e,t)}async function so(e){let{ensureAndroidEmulatorBooted:t}=await import(`./logcat.js`).then(e=>e.c);return await t(e)}const co=`iOS appstate requires an active session on the target device. Run open first (for example: open --session sim --platform ios --device "<name>" <app>).`,lo=`macOS appstate requires an active session on the target device. Run open first (for example: open --session macos --platform macos "System Settings").`;async function uo(e){let{req:t,sessionName:n,sessionStore:r}=e,o=r.get(n),l=t.flags??{},u=l.platform;if(!o&&oi(l))return k(`SESSION_NOT_FOUND`,u===`ios`?`No active session "${n}". Run open with --session ${n} first.`:`No active session "${n}". Run open with --session ${n} first, or omit --session to query by device selector.`);let d=B(`appstate`,o,l);if(d)return d;let f=a(o?.device.platform)&&ui(l,o),p=u===`ios`,m=u===`macos`;if(p&&!f)return k(`SESSION_NOT_FOUND`,co);if(m&&!f)return k(`SESSION_NOT_FOUND`,lo);if(f&&o){let e=o.appName??o.appBundleId;return!o.appName&&!o.appBundleId?s(o.device)&&o.surface&&o.surface!==`app`&&o.surface!==`frontmost-app`?{ok:!0,data:{platform:i(o.device),appName:o.surface,appBundleId:o.appBundleId,source:`session`,surface:o.surface}}:k(`COMMAND_FAILED`,`No foreground app is tracked for this ${s(o.device)?`macOS`:`iOS`} session. Open an app in the session, then retry appstate.`):{ok:!0,data:{platform:i(o.device),appName:e??`unknown`,appBundleId:o.appBundleId,source:`session`,surface:o.surface??`app`,...c(o.device)?{device_udid:o.device.id,ios_simulator_device_set:o.device.simulatorSetPath??null}:{}}}}let h=await V({session:o,flags:l,ensureReady:!0});if(c(h))return k(`SESSION_NOT_FOUND`,co);if(s(h))return k(`SESSION_NOT_FOUND`,lo);if(h.platform===`web`)return k(`UNSUPPORTED_OPERATION`,`appstate is not supported on web.`);let{getAndroidAppState:g}=await import(`./app-lifecycle.js`).then(e=>e.t),_=await g(h);return{ok:!0,data:{platform:`android`,package:_.package,activity:_.activity}}}async function fo(e){let{req:t,sessionName:r,logPath:o,sessionStore:s}=e;if(t.command===`boot`){let e=s.get(r),l=t.flags??{},u=B(t.command,e,l);if(u)return u;let d=(l.platform??e?.device.platform)===`android`,f=l.headless===!0;if(f&&!d)return k(`INVALID_ARGS`,`boot --headless is supported only for Android emulators.`);let p=li({flags:l,sessionDevice:e?.device}),m=d&&!!p,h,g=!1;try{h=await V({session:e,flags:l,ensureReady:!1,allowStoppedAndroidAvdPlaceholders:!0})}catch(e){let t=n(e);if(d&&f&&!p&&t.code===`DEVICE_NOT_FOUND`)return k(`INVALID_ARGS`,`boot --headless requires --device <avd-name> (or an Android emulator session target).`);if(!m||t.code!==`DEVICE_NOT_FOUND`||!p)throw e;h=await so({avdName:p,serial:l.serial,headless:f}),g=!0}if(l.target&&(h.target??`mobile`)!==l.target)return k(`DEVICE_NOT_FOUND`,`No ${h.platform} device found matching --target ${l.target}.`);if(d&&f){if(h.platform!==`android`||h.kind!==`emulator`)return k(`INVALID_ARGS`,`boot --headless is supported only for Android emulators.`);if(!g){let t=li({flags:l,sessionDevice:e?.device,resolvedDevice:h});if(!t)return k(`INVALID_ARGS`,`boot --headless requires --device <avd-name> (or an Android emulator session target).`);h=await so({avdName:t,serial:l.serial,headless:!0})}await Dr(h)}else h.platform===`android`&&h.kind===`emulator`&&h.booted!==!0?(h=await so({avdName:h.name,serial:l.serial,headless:!1}),await Dr(h)):(h.platform!==`android`||h.booted!==!0)&&await Dr(h,{onIosSimulatorColdBootStart:Or({req:t,logPath:o,device:h,enabled:!0})});return O(`boot`,h)||(c(h)&&h.kind===`simulator`&&mt(h,{}),{ok:!0,data:{platform:i(h),target:h.target??`mobile`,device:h.name,id:h.id,kind:h.kind,booted:!0,...a(h.platform)&&h.appleOs?{appleOs:h.appleOs}:{}}})}if(t.command===`shutdown`){let e=s.get(r),n=t.flags??{},o=B(t.command,e,n);if(o)return o;let c=await V({ensureReady:!1,flags:n,session:e}),l=O(`shutdown`,c,{message:`shutdown is supported only for Apple simulators and Android emulators.`});if(l)return l;if(e&&e.device.platform===c.platform&&e.device.id===c.id)return k(`DEVICE_IN_USE`,`Cannot shut down an active session device directly. Use close --shutdown to end the session and turn off the simulator/emulator.`,{hint:`Run agent-device close --shutdown --session ${r}`,session:r,platform:i(c),target:c.target??`mobile`,device:c.name,id:c.id,kind:c.kind});let u=await za(c);return u.success?{ok:!0,data:{platform:i(c),target:c.target??`mobile`,device:c.name,id:c.id,kind:c.kind,shutdown:u,...a(c.platform)&&c.appleOs?{appleOs:c.appleOs}:{}}}:k(u.error?.code??`COMMAND_FAILED`,po(u),{platform:i(c),target:c.target??`mobile`,device:c.name,id:c.id,kind:c.kind,shutdown:u})}return t.command===`appstate`?await uo({req:t,sessionName:r,sessionStore:s}):null}function po(e){let t=e.error?.message??e.stderr.trim();return t.length>0?t:`Shutdown failed`}Yn();function mo(e){let t=[];for(let n of e){if(n.command!==`open`)continue;let e=n.result?.startup;if(!e||typeof e!=`object`)continue;let r=e;typeof r.durationMs!=`number`||!Number.isFinite(r.durationMs)||typeof r.measuredAt!=`string`||r.measuredAt.trim().length===0||r.method!==`open-command-roundtrip`||t.push({durationMs:Math.max(0,Math.round(r.durationMs)),measuredAt:r.measuredAt,method:ua,appTarget:typeof r.appTarget==`string`&&r.appTarget.length>0?r.appTarget:void 0,appBundleId:typeof r.appBundleId==`string`&&r.appBundleId.length>0?r.appBundleId:void 0})}return t.slice(-20)}async function ho(e,t={}){let n=vo(e);return Oo(e)?e.appBundleId?e.device.platform===`android`?(await wo(n,e,e.appBundleId,t),n):(await To(n,e,e.appBundleId),n):(Co(n,e),n):n}async function go(e,t={}){let n=xo(e);return Oo(e)?e.appBundleId?(await Do(n,e,e.appBundleId,t),n):(n.metrics.fps={available:!1,reason:ko(e)},n):n}async function _o(e,t){let n=So(e);return Oo(e)?t.action===`sample`?(n.metrics={memory:await Io(e,t)},n):(n.artifact=await Ro(e,t),n.support=Wo(n.artifact.support)??Uo(e),n):t.action===`snapshot`?(n.artifact=Vo(e,zo(e,t.kind)),n.support=Wo(n.artifact.support)??Uo(e),n):(n.metrics={memory:{available:!1,reason:da}},n)}function vo(e){let t=mo(e.actions),n=t.at(-1),r=n?{available:!0,lastDurationMs:n.durationMs,lastMeasuredAt:n.measuredAt,method:ua,sampleCount:t.length,samples:t}:{available:!1,reason:`No startup sample captured yet. Run open <app|url> in this session first.`,method:ua};return{session:e.name,platform:i(e.device),device:e.device.name,deviceId:e.device.id,metrics:{startup:r,...yo()},sampling:{startup:{method:ua,description:`Elapsed wall-clock time around dispatching the open command for the active session app target.`,unit:`ms`},...Ao(e)}}}function yo(){return{fps:bo(),memory:{available:!1,reason:da},cpu:{available:!1,reason:da}}}function bo(){return{available:!1,reason:`Dropped-frame sampling is currently available only on Android app sessions and connected iOS device app sessions.`}}function xo(e){return{session:e.name,platform:i(e.device),device:e.device.name,deviceId:e.device.id,metrics:{fps:bo()},sampling:{fps:No(e)}}}function So(e){return{session:e.name,platform:i(e.device),device:e.device.name,deviceId:e.device.id,sampling:{memory:jo(e),snapshot:Mo(e)}}}function Co(e,t){let n=ko(t);e.metrics.fps={available:!1,reason:n},e.metrics.memory={available:!1,reason:n},e.metrics.cpu={available:!1,reason:n}}async function wo(e,t,n,r){Eo(e,t,await Po(t,n,r))}async function To(e,t,n){Eo(e,t,await Fo(t,n))}function Eo(e,t,n){e.metrics.memory=Ko(n.memory),e.metrics.cpu=Ko(n.cpu),e.metrics.fps=qo(Ko(n.fps),t)}async function Do(e,t,n,r){let i=t.device.platform===`android`?await Go(Ft(t.device,n,{adb:r.androidAdb})):await Go(ar(t.device,n));e.metrics.fps=qo(Ko(i),t)}function Oo(e){return Wn(e.device.platform)?.perf?.supportsMetrics(e.device)??!1}function ko(e){return e.device.platform===`android`?`No Android app package is associated with this session. Run open <app> first.`:`No Apple app bundle ID is associated with this session. Run open <app> first.`}function Ao(e){return e.device.platform===`android`?{memory:{method:Zt,description:gn,unit:`kB`},cpu:{method:zn,description:pn,unit:`percent`},fps:{method:Tn,description:Ut,unit:`percent`,primaryField:`droppedFramePercent`,window:`since previous Android gfxinfo reset or app process start`,resetsAfterRead:!0,relatedActionsLimit:12}}:Bt(e.device)}function jo(e){return e.device.platform===`android`?{method:Zt,description:gn,unit:`kB`,topConsumerLimit:5}:Bt(e.device).memory}function Mo(e){return e.device.platform===`android`?{method:vn,description:An,defaultKind:`android-hprof`,artifactOnly:!0}:{method:Wt,description:Ht,defaultKind:`memgraph`,artifactOnly:!0}}function No(e){return e.device.platform===`android`?{method:Tn,description:Ut,unit:`percent`,primaryField:`droppedFramePercent`,window:`since previous Android gfxinfo reset or app process start`,resetsAfterRead:!0,relatedActionsLimit:12}:Lt(e.device)}async function Po(e,t,n){let r={adb:n.androidAdb},[i,a,o]=await Promise.allSettled([rn(e.device,t,r),rr(e.device,t,r),Ft(e.device,t,r)]);return{memory:i,cpu:a,fps:o}}async function Fo(e,t){let n=await Go(ar(e.device,t)),r=await Go(Nt(e.device,t));if(r.status===`fulfilled`){let e=r.value;return{memory:{status:`fulfilled`,value:e.memory},cpu:{status:`fulfilled`,value:e.cpu},fps:n}}return{memory:{status:`rejected`,reason:r.reason},cpu:{status:`rejected`,reason:r.reason},fps:n}}async function Io(e,t){return e.appBundleId?Ko(e.device.platform===`android`?await Go(rn(e.device,e.appBundleId,{adb:t.androidAdb})):await Go(Lo(e))):{available:!1,reason:ko(e)}}async function Lo(e){if(!e.appBundleId)throw new t(`INVALID_ARGS`,ko(e));return(await Nt(e.device,e.appBundleId)).memory}async function Ro(e,n){if(!e.appBundleId)throw new t(`INVALID_ARGS`,ko(e),{hint:`Run open <app> first so perf memory snapshot can resolve the app process.`});let r=zo(e,n.kind),i=Bo(n,r);return e.device.platform===`android`?r===`android-hprof`?await $n(e.device,e.appBundleId,i,{adb:n.androidAdb}):Vo(e,r):r===`memgraph`?await Gt(e.device,e.appBundleId,i):Vo(e,r)}function zo(e,t){return t||(e.device.platform===`android`?`android-hprof`:`memgraph`)}function Bo(e,t){if(e.out)return A.expandHome(e.out,e.cwd);let n=t===`android-hprof`?`hprof`:t===`memgraph`?`memgraph`:`artifact`,r=new Date().toISOString().replace(/[:.]/g,`-`),i=e.sessionStore.ensureSessionDir(e.sessionName);return R.join(i,`artifacts`,`memory-${t}-${r}.${n}`)}function Vo(e,t){let n=Uo(e),r=Ho(e,t);return{available:!1,kind:t,reason:r.reason,hint:r.hint,support:n}}function Ho(e,t){return e.device.platform===`android`?{reason:`Android perf memory snapshot supports android-hprof, not ${t}.`,hint:`Use perf memory snapshot --kind android-hprof for Android Java heap artifacts.`}:a(e.device.platform)?{reason:`Apple perf memory snapshot supports memgraph, not ${t}.`,hint:`Use perf memory snapshot --kind memgraph for supported Apple app sessions.`}:{reason:`Memory snapshot artifacts are not supported on ${e.device.platform}.`,hint:`Use perf memory sample where supported, or run the snapshot against Android, iOS simulator, or macOS.`}}function Uo(e){return e.device.platform===`android`?{platform:e.device.platform,defaultKind:`android-hprof`,androidHprof:!0,memgraph:!1,heapprofd:!1,heapprofdDecision:`Deferred until Android Perfetto/heapprofd plumbing is available in the perf trace slice.`}:a(e.device.platform)?{...Rt(e.device),androidHprof:!1,heapprofd:!1,heapprofdDecision:`Deferred because heapprofd is Android/Perfetto-specific and outside this memory artifact slice.`}:{platform:e.device.platform,defaultKind:`memgraph`,androidHprof:!1,memgraph:!1,heapprofd:!1,reason:`Memory snapshot artifacts are available only on Android, iOS simulator, and macOS.`,hint:`Use perf memory sample where supported, or switch to a platform with memory artifact support.`,heapprofdDecision:`Deferred because heapprofd is Android/Perfetto-specific and outside this memory artifact slice.`}}function Wo(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:void 0}async function Go(e){try{return{status:`fulfilled`,value:await e}}catch(e){return{status:`rejected`,reason:e}}}function Ko(t){if(t.status===`fulfilled`)return{available:!0,...t.value};let n=e(t.reason);return{available:!1,reason:n.message,error:n}}function qo(e,t){if(e.available!==!0)return e;let n=Jo(t.actions,e);return n.length===0?e:{...e,relatedActions:n}}function Jo(e,t){let n=Yo(t.windowStartedAt),r=Yo(t.windowEndedAt)??Yo(t.measuredAt);return n===void 0||r===void 0?[]:e.filter(e=>e.ts>=n&&e.ts<=r).map(e=>({command:e.command,at:new Date(e.ts).toISOString(),offsetMs:Math.max(0,Math.round(e.ts-n)),target:Xo(e)})).slice(-12)}function Yo(e){if(typeof e!=`string`)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function Xo(e){let t=e.result;if(t)for(let e of[`refLabel`,`ref`,`appName`,`appBundleId`]){let n=t[e];if(typeof n==`string`&&n.length>0)return n}}async function Zo(t){let n=Qo(t.req,t.area);if(!n.ok)return n;let{session:r}=t;if(r.device.platform!==`android`)return k(`UNSUPPORTED_OPERATION`,`Android native perf collectors are supported only on Android sessions.`);if(!r.appBundleId)return k(`COMMAND_FAILED`,`No Android app package is associated with this session.`,{hint:`Run open <app> first so perf can resolve the package and process identity.`});try{return{ok:!0,data:n.area===`cpu`?await ss(t,r,r.appBundleId,n):await cs(t,r,r.appBundleId,n)}}catch(t){return{ok:!1,error:e(t)}}}function Qo(e,t){let n=os(e,t);return t===`cpu`?$o(e,n):es(e,n)}function $o(e,t){let n=ts(e,1),r=ts(e,2),i=ts(e,3);return ge(n)?ns(r)?i===`simpleperf`?{ok:!0,area:`cpu`,subject:n,action:r,kind:i,outPath:t}:k(`INVALID_ARGS`,`perf cpu profile requires --kind simpleperf`):k(`INVALID_ARGS`,`perf cpu profile action must be start, stop, or report`):k(`INVALID_ARGS`,pe)}function es(e,t){let n=ts(e,1),r=ts(e,2);return rs(n)?ve(r)?r===`perfetto`?{ok:!0,area:`trace`,action:n,kind:r,outPath:t}:k(`INVALID_ARGS`,`perf trace requires --kind perfetto`):k(`INVALID_ARGS`,he):k(`INVALID_ARGS`,`perf trace action must be start or stop`)}function ts(e,t){return(e.positionals?.[t]??``).toLowerCase()}function ns(e){return e===`start`||e===`stop`||e===`report`}function rs(e){return e===`start`||e===`stop`}function is(e,t){return e.sessionStore.set(e.sessionName,{...e.session,nativePerf:{android:t}}),ps(t)}function as(e,t,n){return t?A.expandHome(t,e.req.meta?.cwd):fs(e.sessionStore,e.sessionName,n)}function os(e,t){return typeof e.flags?.out==`string`&&e.flags.out.length>0?e.flags.out:(e.positionals??[])[t===`cpu`?5:4]||void 0}async function ss(e,t,n,r){if(r.action===`start`){us(t);let i=as(e,r.outPath,`cpu.perf.data`);return is(e,await tr(t.device,n,i,{adb:e.androidAdbExecutor}))}let i=ms(t,`cpu-profile`,r.kind);if(r.action===`report`){await ls(i);let n=as(e,r.outPath,`cpu-report.json`);return await Pt(t.device,i,n,{adb:e.androidAdbExecutor})}let a=ds(e,r.outPath,i);return is(e,await Kt(t.device,i,a,{adb:e.androidAdbExecutor}))}async function cs(e,t,n,r){if(r.action===`start`){us(t);let i=as(e,r.outPath,`app.perfetto-trace`);return is(e,await er(t.device,n,i,{adb:e.androidAdbExecutor}))}let i=ms(t,`trace`,r.kind),a=ds(e,r.outPath,i);return is(e,await Jt(t.device,i,a,{adb:e.androidAdbExecutor}))}function ls(e){if(e.state===`running`)throw new t(`COMMAND_FAILED`,`Stop the Android Simpleperf CPU profile before generating a report.`,{hint:`Run perf cpu profile stop --kind simpleperf, then retry perf cpu profile report --kind simpleperf.`})}function us(e){let n=e.nativePerf?.android;if(n?.state===`running`)throw new t(`COMMAND_FAILED`,`Android ${n.kind} ${n.type} is already running for this session.`,{hint:n.type===`cpu-profile`?`Run perf cpu profile stop --kind simpleperf before starting another Android native perf capture.`:`Run perf trace stop --kind perfetto before starting another Android native perf capture.`})}function ds(e,t,n){return t?as(e,t,n.outPath):n.outPath}function fs(e,t,n){let r=new Date().toISOString().replace(/[:.]/g,`-`);return R.join(e.ensureSessionDir(t),`${r}-${n}`)}function ps(e){return{action:e.action,platform:`android`,type:e.type,kind:e.kind,packageName:e.packageName,appPid:e.appPid,profilerPid:e.profilerPid,state:e.state,startedAt:new Date(e.startedAt).toISOString(),stoppedAt:typeof e.stoppedAt==`number`?new Date(e.stoppedAt).toISOString():void 0,durationMs:e.durationMs,outPath:e.outPath,sizeBytes:e.sizeBytes,remotePath:e.remotePath,method:e.method,summary:e.summary,message:e.message}}function ms(e,n,r){let i=e.nativePerf?.android;if(i?.type===n&&i.kind===r)return i;throw new t(`COMMAND_FAILED`,`No Android ${r} ${n} is active for this session.`,{hint:n===`cpu-profile`?`Run perf cpu profile start --kind simpleperf first, then stop or report in the same session.`:`Run perf trace start --kind perfetto first, then stop in the same session.`})}async function hs(e){if(!Pn(e))return;let{macOsScreenCaptureKitAudioProbeBackend:t}=await import(`./audio-probe.js`);return t}const gs=[`probe`],_s=[`start`,`status`,`stop`],vs=`audio probe requires ${_s.join(`, `)}`;async function ys(t){let n=bs(t);if(!n.ok)return n;let r=await hs(n.session.device);if(r)return await Ss(t,n,r);let i=Er();if(!i.probeAudio)return k(`UNSUPPORTED_OPERATION`,`audio is not supported by this web provider`);try{return{ok:!0,data:await i.probeAudio({action:n.probeAction,durationMs:n.durationMs,bucketMs:n.bucketMs})}}catch(t){return{ok:!1,error:e(t)}}}function bs(e){let t=xs(e);if(!t.ok)return t;let n=Cs(e.req);if(!n.ok)return n;let r=ws(e.req,n.probeAction);return r.ok?{ok:!0,session:t.session,probeAction:n.probeAction,...r.timing}:r}function xs(e){let t=e.sessionStore.get(e.sessionName);return t?At(`audio`,t.device)?{ok:!0,session:t}:k(`UNSUPPORTED_OPERATION`,`audio is supported for web browser sessions, macOS sessions, iOS simulators, and Android emulators on macOS hosts`):k(`SESSION_NOT_FOUND`,`audio requires an active session`)}async function Ss(t,n,r){try{return{ok:!0,data:await Kn({session:n.session,sessionName:t.sessionName,sessionStore:t.sessionStore,backend:r,probeAction:n.probeAction,durationMs:n.durationMs,bucketMs:n.bucketMs})}}catch(t){return{ok:!1,error:e(t)}}}function Cs(e){if(!Ts(e.positionals?.[0]))return k(`INVALID_ARGS`,`audio requires probe`);let t=Es(e.positionals?.[1]);return t?{ok:!0,probeAction:t}:k(`INVALID_ARGS`,vs)}function ws(e,t){if(t!==`start`&&e.positionals&&e.positionals.length>2)return k(`INVALID_ARGS`,`audio probe duration and bucket are only supported with audio probe start`);let n=Ds(e.positionals?.[2],{defaultValue:1e4,min:100,max:12e4,message:`audio probe duration must be an integer in range 100..120000 ms`});if(n instanceof Error)return k(`INVALID_ARGS`,n.message);let r=Ds(e.positionals?.[3],{defaultValue:1e3,min:100,max:1e4,message:`audio probe bucket must be an integer in range 100..10000 ms`});return r instanceof Error?k(`INVALID_ARGS`,r.message):{ok:!0,timing:{durationMs:n,bucketMs:r}}}function Ts(e){let t=(e??`probe`).toLowerCase();return gs.includes(t)?`probe`:void 0}function Es(e){let t=(e??`status`).toLowerCase();return _s.includes(t)?t:void 0}function Ds(e,t){if(e===void 0)return t.defaultValue;let n=Number.parseInt(e,10);return!Number.isInteger(n)||String(n)!==e||n<t.min||n>t.max?Error(t.message):n}async function Os(t,n){let r=ks(t.req);if(!r.ok)return r;if(n.device.platform===`android`)return k(`UNSUPPORTED_OPERATION`,`Android native profiling belongs to the Android perf rollout; Apple xctrace perf supports iOS and macOS sessions only.`);if(!a(n.device.platform))return k(`UNSUPPORTED_OPERATION`,`Apple xctrace perf is not supported on ${n.device.platform}.`);if(!n.appBundleId)return k(`INVALID_ARGS`,`Apple xctrace perf requires an active app session. Run open <app> first.`);try{return r.action===`start`?await Ps(t,n,r):r.action===`stop`?await Fs(t,n,r):await Bs(t,n,r)}catch(t){return{ok:!1,error:e(t)}}}function ks(e){let t=e.positionals??[],n=t[0]?.toLowerCase();return n===`cpu`?As(t):n===`trace`?js(t):k(`INVALID_ARGS`,me)}function As(e){if(e[1]?.toLowerCase()!==`profile`)return k(`INVALID_ARGS`,`perf cpu requires profile`);let t=Ms(e[2],`perf cpu profile`,!0);if(!t.ok)return t;let n=Ns(e[3]);return n.ok?{ok:!0,area:`cpu`,mode:`cpu-profile`,action:t.value,kind:`xctrace`,template:e[4]||void 0,outPath:e[5]||void 0,tracePath:e[6]||void 0}:n}function js(e){let t=Ms(e[1],`perf trace`,!1);if(!t.ok)return t;let n=Ns(e[2]);return n.ok?{ok:!0,area:`trace`,mode:`trace`,action:t.value,kind:`xctrace`,template:e[3]||void 0,outPath:e[4]||void 0,tracePath:e[5]||void 0}:n}function Ms(e,t,n){let r=e?.toLowerCase();return r===`start`||r===`stop`||n&&r===`report`?{ok:!0,value:r}:k(`INVALID_ARGS`,n?`${t} requires start, stop, or report`:`${t} requires start or stop`)}function Ns(e){return e?.toLowerCase()===`xctrace`?{ok:!0}:k(`INVALID_ARGS`,`perf native collection currently supports --kind xctrace`)}async function Ps(e,t,n){if(t.applePerf?.active)return k(`INVALID_ARGS`,`Apple xctrace perf capture already in progress`);let r=n.template??Ws(n.mode),i=Us(e,n),a=await jt({device:t.device,appBundleId:t.appBundleId,mode:n.mode,template:r,outPath:i});t.applePerf={...t.applePerf??{},active:a},e.sessionStore.set(e.sessionName,t);let o=Gs(`started`,a);return Hs(e,t,o),{ok:!0,data:o}}async function Fs(e,t,n){let r=t.applePerf?.active;if(!r)return k(`INVALID_ARGS`,`no active Apple xctrace perf capture`);let i=n.outPath?A.expandHome(n.outPath,e.req.meta?.cwd):r.outPath,a;try{a=await wn(r,i)}catch(n){throw Ls(n)&&Is(e,t),n}Rs(e,t,a);let o=Gs(`stopped`,a);return Hs(e,t,o),{ok:!0,data:o}}function Is(e,t){t.applePerf={...t.applePerf??{},active:void 0},e.sessionStore.set(e.sessionName,t)}function Ls(e){return n(e).details?.captureCleanedUp===!0}function Rs(e,t,n){t.applePerf={...t.applePerf??{},active:void 0,lastMode:n.mode,...zs(n)},e.sessionStore.set(e.sessionName,t)}function zs(e){return e.mode===`cpu-profile`?{lastProfileTracePath:e.outPath,lastProfileTemplate:e.template}:{lastTracePath:e.outPath}}async function Bs(e,t,n){if(n.mode!==`cpu-profile`)return k(`INVALID_ARGS`,`perf trace does not support report`);if(t.applePerf?.active)return k(`INVALID_ARGS`,`perf cpu profile report requires a stopped profile trace; stop the active capture first.`);let r=Us(e,n),i=Vs(t,n);if(!i.ok)return i;let a={perf:`reported`,...await Vt({tracePath:A.expandHome(i.value,e.req.meta?.cwd),outPath:r,mode:n.mode,template:t.applePerf?.lastProfileTemplate??n.template,appBundleId:t.appBundleId})};return Hs(e,t,a),{ok:!0,data:a}}function Vs(e,t){let n=t.tracePath??e.applePerf?.lastProfileTracePath??e.applePerf?.active?.outPath;return n?{ok:!0,value:n}:k(`INVALID_ARGS`,`perf cpu profile report requires a stopped profile trace or tracePath option`)}function Hs(e,t,n){Mr(e.sessionStore,t,e.req,`perf`,n)}function Us(e,t){if(t.outPath)return A.expandHome(t.outPath,e.req.meta?.cwd);let n=e.sessionStore.ensureSessionDir(e.sessionName),r=new Date().toISOString().replace(/[:.]/g,`-`),i=t.action===`report`?`json`:`trace`;return`${n}/perf-${t.mode}-${r}.${i}`}function Ws(e){return e===`cpu-profile`?`Time Profiler`:`Animation Hitches`}function Gs(e,t){return{perf:e,kind:t.kind,mode:t.mode,template:t.template,outPath:t.outPath,appBundleId:t.appBundleId,deviceId:t.deviceId,platform:t.platform,targetPids:t.targetPids,targetProcesses:t.targetProcesses,startedAt:t.startedAt,endedAt:t.endedAt}}const Ks=`logs requires ${Oe.slice(0,-1).join(`, `)}, or ${Oe.at(-1)}`,qs=[`dump`,`log`],Js=`network requires ${qs.join(` or `)}`,Ys=`network include mode must be one of: ${l.join(`, `)}`,Xs={path:({session:e,sessionName:t,sessionStore:n})=>xc(e,t,n),doctor:({session:e,sessionName:t,sessionStore:n})=>Sc(e,t,n),mark:({req:e,sessionName:t,sessionStore:n})=>Cc(e,t,n),clear:({session:e,sessionName:t,sessionStore:n,restart:r})=>wc(e,t,n,r),start:({session:e,sessionName:t,sessionStore:n})=>Tc(e,t,n),stop:({session:e,sessionName:t,sessionStore:n})=>Ec(e,t,n)};function Zs(e){if(e.appLog){let t=e.appLog.getState();return{active:t===`active`||t===`recovering`,state:t,backend:e.appLog.backend,startedAt:e.appLog.startedAt,notes:ec(t)}}return e.appLogFailure?{active:!1,state:`failed`,backend:e.appLogFailure.backend,failureCode:e.appLogFailure.code,failureMessage:e.appLogFailure.message,hint:e.appLogFailure.hint,notes:[$s(e.appLogFailure)]}:{active:!1,state:`inactive`,backend:Rn(e.device)}}function Qs(e,t){return{backend:t,code:e.code,message:e.message,hint:e.hint}}function $s(e){return e.hint?`${e.message} ${e.hint}`:e.message}function ec(e){if(e===`failed`)return[`The app log stream process exited with an error. Run logs doctor for backend diagnostics.`];if(e===`ended`)return[`The app log stream process ended. Run logs clear --restart before the next capture window.`]}function tc(e,t){return qt([...e,...t.notes??[]])}function nc(e,t,n){return{...n,platform:e.device.platform,outPath:t}}function rc(t,n,r,i){let a=e(i);return t.set(n,{...r,appLog:void 0,appLogFailure:Qs(a,Rn(r.device))}),{ok:!1,error:a}}async function ic(e){let{req:t}=e;return t.command===`perf`?ac(e):t.command===`logs`?yc(e):t.command===`network`?Dc(e):t.command===`audio`?await ys(e):null}async function ac(t){let{req:n,sessionName:r,sessionStore:i,androidAdbExecutor:a}=t,o=i.get(r);if(!o)return k(`SESSION_NOT_FOUND`,`perf requires an active session. Run open first.`);let s=(n.positionals?.[0]??`metrics`).toLowerCase();if(oc(s))return o.device.platform===`android`?await Zo({req:n,sessionName:r,sessionStore:i,session:o,androidAdbExecutor:a,area:s}):await Os(t,o);let c=sc(n);if(!c.ok)return c;if(c.native)return await Os(t,o);try{return{ok:!0,data:await cc(t,o,c)}}catch(t){return{ok:!1,error:e(t)}}}function oc(e){return e===`cpu`||e===`trace`}function sc(n){let r=lc(n.positionals?.[0]);if(!r)return k(`INVALID_ARGS`,me);if(r===`cpu`||r===`trace`)return{ok:!0,native:!0};let i=uc(n.positionals?.[1]);if(!i)return k(`INVALID_ARGS`,se);let a=dc(n.flags?.kind);return a instanceof t?{ok:!1,error:e(a)}:(fc(r,i)??hc(n,r,i,a))||{ok:!0,native:!1,area:r,action:i,kind:a,out:vc(n.flags?.out)}}async function cc(e,t,n){let{sessionName:r,sessionStore:i,androidAdbExecutor:a}=e;return n.area===`memory`?await _o(t,{action:mc(n.action),kind:n.kind,out:n.out,cwd:e.req.meta?.cwd,sessionName:r,sessionStore:i,androidAdb:a}):n.area===`frames`?await go(t,{androidAdb:a}):await ho(t,{androidAdb:a})}function lc(e){let t=(e??`metrics`).toString().toLowerCase();return le(t)?t:void 0}function uc(e){let t=(e??`sample`).toString().toLowerCase();return ke(t)?t:void 0}function dc(e){if(e!==void 0)return typeof e!=`string`||!ve(e)?new t(`INVALID_ARGS`,he):e}function fc(e,t){if(e===`memory`)return pc(t)?void 0:k(`INVALID_ARGS`,`perf memory requires sample or snapshot`);if(t!==`sample`)return k(`INVALID_ARGS`,`perf metrics and perf frames only support sample`)}function pc(e){return e===`sample`||e===`snapshot`}function mc(e){if(pc(e))return e;throw new t(`INVALID_ARGS`,`perf memory requires sample or snapshot`)}function hc(e,t,n,r){return gc(e.flags?.out,t,n)??_c(r,t,n)}function gc(e,t,n){if(!(!e||t===`memory`&&n===`snapshot`))return k(`INVALID_ARGS`,`--out is only supported with perf memory snapshot`)}function _c(e,t,n){if(e){if(t!==`memory`||n!==`snapshot`)return k(`INVALID_ARGS`,`--kind is only supported with perf memory snapshot`);if(!de(e))return k(`INVALID_ARGS`,fe)}}function vc(e){return typeof e==`string`&&e.length>0?e:void 0}async function yc(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.get(n);if(!i)return k(`SESSION_NOT_FOUND`,`logs requires an active session`);let a=O(`logs`,i.device);if(a)return a;let o=bc(t);return o.ok?await Xs[o.action]({...e,session:i,restart:o.restart}):o}function bc(e){let t=(e.positionals?.[0]??`path`).toLowerCase(),n=!!e.flags?.restart;return Oe.includes(t)?n&&t!==`clear`?k(`INVALID_ARGS`,`logs --restart is only supported with logs clear`):{ok:!0,action:t,restart:n}:k(`INVALID_ARGS`,Ks)}function xc(e,t,n){let r=n.resolveAppLogPath(t),i=Cn(r),a=Zs(e);return{ok:!0,data:{path:r,active:a.active,state:a.state,backend:a.backend,sizeBytes:i.sizeBytes,modifiedAt:i.modifiedAt,startedAt:a.startedAt?new Date(a.startedAt).toISOString():void 0,failureCode:a.failureCode,failureMessage:a.failureMessage,hint:a.hint??`Grep the file for token-efficient debugging, e.g. grep -n "Error\\|Exception" <path>`,notes:a.notes}}}async function Sc(e,t,n){let r=n.resolveAppLogPath(t),i=await kn(e.device,e.appBundleId),a=Zs(e);return{ok:!0,data:{path:r,active:a.active,state:a.state,backend:a.backend,checks:i.checks,failureCode:a.failureCode,failureMessage:a.failureMessage,hint:a.hint,notes:tc(i.notes,a)}}}function Cc(e,t,n){let r=e.positionals?.slice(1).join(` `)??``,i=n.resolveAppLogPath(t);return Fn(i,r),{ok:!0,data:{path:i,marked:!0}}}async function wc(e,t,n,r){if(e.appLog&&!r)return k(`INVALID_ARGS`,`logs clear requires logs to be stopped first; run logs stop`);let i=n.resolveAppLogPath(t);if(!r){let r=Gn(i);return n.set(t,{...e,appLogFailure:void 0}),{ok:!0,data:r}}let a=e.appBundleId;if(!a)return k(`INVALID_ARGS`,`logs clear --restart requires an app session; run open <app> first`);e.appLog&&await cn(e.appLog);let o=Gn(i),s=n.resolveAppLogPidPath(t);try{let r=await Jn(e.device,a,i,s);return n.set(t,{...e,appLog:nc(e,i,r),appLogFailure:void 0}),{ok:!0,data:{...o,restarted:!0}}}catch(r){return rc(n,t,e,r)}}async function Tc(e,t,n){if(e.appLog)return k(`INVALID_ARGS`,`app log already streaming; run logs stop first`);if(!e.appBundleId)return k(`INVALID_ARGS`,`logs start requires an app session; run open <app> first`);let r=n.resolveAppLogPath(t),i=n.resolveAppLogPidPath(t);try{let a=await Jn(e.device,e.appBundleId,r,i);return n.set(t,{...e,appLog:nc(e,r,a),appLogFailure:void 0}),{ok:!0,data:{path:r,started:!0}}}catch(r){return rc(n,t,e,r)}}async function Ec(e,t,n){if(!e.appLog)return k(`INVALID_ARGS`,`no app log stream active`);let r=e.appLog.outPath;return await cn(e.appLog),n.set(t,{...e,appLog:void 0,appLogFailure:void 0}),{ok:!0,data:{path:r,stopped:!0}}}async function Dc(e){let t=kc(e);if(!t.ok)return t;let{include:n,maxEntries:r,session:i}=t;if(i.device.platform===`web`)return await Oc({include:n,maxEntries:r});let a=await nn({device:i.device,appBundleId:i.appBundleId,appLogState:i.appLog?.getState(),appLogStartedAt:i.appLog?.startedAt,appLogPath:e.sessionStore.resolveAppLogPath(e.sessionName),maxEntries:r,include:n,maxPayloadChars:2048,maxScanLines:4e3});return{ok:!0,data:{...a.dump,active:!!i.appLog,state:i.appLog?.getState()??`inactive`,backend:a.backend,notes:a.notes}}}async function Oc(t){let n=Er();if(!n.dumpNetwork)return k(`UNSUPPORTED_OPERATION`,`network is not supported by this web provider`);try{let e=await n.dumpNetwork({include:t.include,limit:t.maxEntries});return{ok:!0,data:{entries:e.entries,active:!0,state:`active`,backend:e.backend??`agent-browser`,include:t.include,matchedLines:e.entries.length,scannedLines:e.entries.length,limits:{maxEntries:t.maxEntries,maxPayloadChars:2048,maxScanLines:e.entries.length},notes:e.notes}}}catch(t){return{ok:!1,error:e(t)}}}function kc(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.get(n);if(!i)return k(`SESSION_NOT_FOUND`,`network requires an active session`);let a=O(`network`,i.device);if(a)return a;let o=(t.positionals?.[0]??`dump`).toLowerCase();if(!qs.includes(o))return k(`INVALID_ARGS`,Js);let s=t.positionals?.[1]?Number.parseInt(t.positionals[1],10):25;if(!Number.isInteger(s)||s<1||s>200)return k(`INVALID_ARGS`,`network dump limit must be an integer in range 1..200`);let c=Ac(t);return c.ok?{ok:!0,session:i,maxEntries:s,include:c.include}:c}function Ac(e){let t=e.positionals?.[2]?.toLowerCase(),n=e.flags?.networkInclude;if(t&&n&&t!==n)return k(`INVALID_ARGS`,`network include mode was provided both positionally and via --include with different values`);let r=(n??t??`summary`).toLowerCase();return l.includes(r)?{ok:!0,include:r}:k(`INVALID_ARGS`,Ys)}function jc(e){let{artifactsDir:t,cwd:n,suiteInvocationId:r}=e,i=A.expandHome(t??`.agent-device/test-artifacts`,n);return R.join(i,r)}function Mc(e,t){let n=t?R.relative(t,e):R.basename(e);return(n.length===0||n.startsWith(`..`)?R.basename(e):n).toLowerCase().replace(/[\\/]+/g,`__`).replace(/[^a-z0-9._-]+/g,`-`).replace(/^-+|-+$/g,``)||`test`}function Nc(e,t){L.mkdirSync(t,{recursive:!0}),Lc(e,t)}function Pc(e){let{response:t,filePath:n,sessionName:r,attempts:i,maxAttempts:a,attemptArtifactsDir:o}=e,s=[...Fc(t)];!t.ok&&typeof t.error.logPath==`string`&&s.push(t.error.logPath);let c=Ic(s,o),l=[`file: ${n}`,`session: ${r}`,`attempt: ${i}/${a}`,`status: ${t.ok?`passed`:`failed`}`];if(t.ok){let e=typeof t.data?.replayed==`number`?t.data.replayed:0,n=typeof t.data?.healed==`number`?t.data.healed:0;l.push(`replayed: ${e}`,`healed: ${n}`)}else l.push(`code: ${t.error.code}`,`message: ${t.error.message}`),t.error.hint&&l.push(`hint: ${t.error.hint}`),t.error.diagnosticId&&l.push(`diagnosticId: ${t.error.diagnosticId}`),t.error.logPath&&l.push(`logPath: ${t.error.logPath}`),t.error.details?.reason===`timeout`&&l.push(`timeoutMode: cooperative`);c.length>0&&l.push(`copiedArtifacts: ${c.map(e=>R.basename(e)).join(`, `)}`);let u=R.join(o,`result.txt`),d=`${l.join(`
|
|
3
|
-
`)}\n`;L.writeFileSync(u,d),t.ok||L.writeFileSync(R.join(o,`failure.txt`),d)}function Fc(e){let t=e.ok?e.data?.artifactPaths:e.error.details?.artifactPaths;return Array.isArray(t)?[...new Set(t.filter(e=>typeof e==`string`))]:[]}function Ic(e,t){let n=[],r=new Map;for(let i of e){if(!Bc(i))continue;let e=zc(R.basename(i),r),a=R.join(t,e);R.resolve(i)!==R.resolve(a)&&L.copyFileSync(i,a),n.push(a)}return n}function Lc(e,t){let n=R.join(t,`replay.ad`);if(L.copyFileSync(e,n),!Rc(e))return;let r=R.join(t,R.basename(e));R.resolve(r)!==R.resolve(n)&&L.copyFileSync(e,r)}function Rc(e){let t=R.extname(e).toLowerCase();return t===`.yml`||t===`.yaml`}function zc(e,t){let n=R.extname(e),r=n?e.slice(0,-n.length):e,i=t.get(e)??0;return t.set(e,i+1),i===0?e:`${r}-${i+1}${n}`}function Bc(e){try{return L.statSync(e).isFile()}catch{return!1}}function Vc(e,n,r){if(e==null)return P(`open`,[I(pr(n,`launchApp`),r)]);if(typeof e==`string`)return P(`open`,[I(e,r)]);if(!F(e))throw new t(`INVALID_ARGS`,`launchApp expects a string or map.`);M(e,`launchApp`,[`appId`,`stopApp`,`clearState`,`clearKeychain`,`arguments`,`permissions`,`launchArguments`]),Kc(e,`permissions`),Kc(e,`clearKeychain`);let i=I(typeof e.appId==`string`?e.appId:pr(n,`launchApp`),r),a=Uc(e,r),o=e.clearState===!0,s=!o&&(e.stopApp===!0||a.length>0);return P(`open`,[i],{...s?{relaunch:!0}:{},...o?{clearAppState:!0}:{},...a.length>0?{launchArgs:a}:{}})}function Hc(e,n,r){if(e==null)return P(`close`,[I(pr(n,`stopApp`),r)]);if(typeof e==`string`)return P(`close`,[I(e,r)]);throw new t(`INVALID_ARGS`,`stopApp expects a string appId or no value.`)}function Uc(e,t){return[...Wc(e.arguments,`launchApp.arguments`,t),...Wc(e.launchArguments,`launchApp.launchArguments`,t)]}function Wc(e,n,r){if(e==null)return[];if(typeof e==`string`)return[I(e,r)];if(Array.isArray(e))return e.map((e,t)=>Gc(e,`${n}[${t}]`,r));if(F(e))return Object.entries(e).flatMap(([e,t])=>[I(e,r),Gc(t,`${n}.${e}`,r)]);throw new t(`INVALID_ARGS`,`${n} expects a string, list, or map.`)}function Gc(e,n,r){if(typeof e==`string`)return I(e,r);if(typeof e==`number`||typeof e==`boolean`)return String(e);throw new t(`INVALID_ARGS`,`${n} must be a string, number, or boolean.`)}function Kc(e,t){if(e[t]!==void 0)throw N(`Maestro launchApp field "${t}" is not supported yet.`)}const U={runScript:`__maestroRunScript`,assertVisible:`__maestroAssertVisible`,assertNotVisible:`__maestroAssertNotVisible`,pressEnter:`__maestroPressEnter`,waitForAnimationToEnd:`__maestroWaitForAnimationToEnd`,scrollUntilVisible:`__maestroScrollUntilVisible`,swipeScreen:`__maestroSwipeScreen`,swipeOn:`__maestroSwipeOn`,tapOn:`__maestroTapOn`,tapPointPercent:`__maestroTapPointPercent`};function qc(e,t){if(typeof e==`string`)return P(U.tapOn,[ul(I(e,t))],ml(e));if(F(e)&&typeof e.point==`string`){M(e,`tapOn`,[`point`,`repeat`,`delay`,`optional`,`label`]);let t=yr(e.point);return t.kind===`percent`?P(U.tapPointPercent,[String(t.x),String(t.y)],pl(e)):P(`click`,[String(t.x),String(t.y)],pl(e))}F(e)&&M(e,`tapOn`,[`id`,`text`,`childOf`,`enabled`,`index`,`selected`,`repeat`,`delay`,`optional`,`label`]);let n=ml(e);return P(U.tapOn,[W(e,`tapOn`,[`repeat`,`delay`,`optional`,`label`,`index`,`childOf`],t),...dl(e,t)],n)}function Jc(e,t){if(F(e)&&typeof e.point==`string`){M(e,`doubleTapOn`,[`point`,`delay`]);let t=vr(e.point);return P(`click`,[String(t.x),String(t.y)],hl(e))}return F(e)&&M(e,`doubleTapOn`,[`id`,`text`,`enabled`,`selected`,`delay`]),P(`click`,[W(e,`doubleTapOn`,[`delay`],t)],hl(e))}function Yc(e,t){if(F(e)&&typeof e.point==`string`){M(e,`longPressOn`,[`point`]);let t=vr(e.point);return P(`longpress`,[String(t.x),String(t.y),`3000`])}return F(e)&&M(e,`longPressOn`,[`id`,`text`,`enabled`,`selected`]),P(`click`,[W(e,`longPressOn`,[],t)],{holdMs:3e3})}function Xc(e){if(typeof e==`string`)return e;if(!F(e))throw new t(`INVALID_ARGS`,`inputText expects a string or map.`);if(M(e,`inputText`,[`text`,`label`]),typeof e.text!=`string`)throw new t(`INVALID_ARGS`,`inputText map requires a string text field.`);return e.text}function Zc(e){if(e==null)return P(`type`,[`\b`.repeat(50)]);if(typeof e==`number`&&Number.isInteger(e)&&e>0)return P(`type`,[`\b`.repeat(e)]);if(!F(e))throw new t(`INVALID_ARGS`,`eraseText expects empty, a positive count, or a map.`);if(M(e,`eraseText`,[`charactersToErase`]),e.charactersToErase===void 0)return P(`type`,[`\b`.repeat(50)]);if(typeof e.charactersToErase!=`number`||!Number.isInteger(e.charactersToErase)||e.charactersToErase<=0)throw new t(`INVALID_ARGS`,`eraseText.charactersToErase must be a positive integer.`);return P(`type`,[`\b`.repeat(e.charactersToErase)])}function Qc(e,n){if(!F(e))throw new t(`INVALID_ARGS`,`extendedWaitUntil expects a map.`);M(e,`extendedWaitUntil`,[`visible`,`notVisible`,`timeout`]);let r=e.visible??e.notVisible;if(r===void 0)throw N(`Only Maestro extendedWaitUntil.visible/notVisible is supported.`);let i=W(r,`extendedWaitUntil`,[],n),a=String(xr(e,17e3));return e.notVisible===void 0?[P(U.assertVisible,[i,a],{maestro:{allowAlreadyPastLoading:!0}})]:[P(U.assertNotVisible,[i,a])]}function $c(e){if(e!=null)throw N(`Maestro scroll options are not supported yet.`);return P(`scroll`,[`down`])}function el(e,n){if(typeof e==`string`)return[P(U.scrollUntilVisible,[ul(I(e,n)),`5000`,`down`])];if(!F(e))throw new t(`INVALID_ARGS`,`scrollUntilVisible expects a string or map.`);M(e,`scrollUntilVisible`,[`element`,`direction`,`timeout`]);let r=W(e.element,`scrollUntilVisible.element`,[],n),i=typeof e.direction==`string`?sl(e.direction,`scrollUntilVisible.direction`):`down`,a=String(xr(e,5e3));return[P(U.scrollUntilVisible,[r,a,i])]}function tl(e,n){if(!F(e))throw new t(`INVALID_ARGS`,`swipe expects a map.`);M(e,`swipe`,[`start`,`end`,`direction`,`duration`,`from`,`label`]);let r=e.from??(typeof e.label==`string`?e.label:void 0);return r===void 0?typeof e.direction==`string`?P(U.swipeScreen,[`direction`,cl(e.direction),...fl(e)]):rl(e):nl(e,r,n)}function nl(e,t,n){let r=cl(typeof e.direction==`string`?e.direction:`up`);return P(U.swipeOn,[W(t,`swipe.from`,[],n),r,...fl(e)])}function rl(e){let{start:t,end:n}=il(e);return ol(t,n,al(e.duration))}function il(e){if(typeof e.start==`string`&&typeof e.end==`string`)return{start:yr(e.start),end:yr(e.end)};throw N(`Only Maestro swipe start/end coordinates are supported.`)}function al(e){return typeof e==`number`&&Number.isFinite(e)?String(Math.max(16,Math.floor(e))):void 0}function ol(e,t,n){if(e.kind===`absolute`&&t.kind===`absolute`)return P(`swipe`,[String(e.x),String(e.y),String(t.x),String(t.y),...n?[n]:[]]);if(e.kind===`percent`&&t.kind===`percent`)return P(U.swipeScreen,[`percent`,String(e.x),String(e.y),String(t.x),String(t.y),...n?[n]:[]]);throw N(`Maestro swipe start/end must both be absolute pixels or both be percentages.`)}function sl(e,t){let n=e.toLowerCase();switch(n){case`up`:case`down`:case`left`:case`right`:return n;default:throw N(`Maestro ${t} must be UP, DOWN, LEFT, or RIGHT.`)}}function cl(e){return sl(e,`swipe direction`)}function ll(e){let t=mr(`pressKey`,e).toLowerCase();if(t===`back`)return P(`back`);if(t===`enter`||t===`return`)return P(U.pressEnter);if(t===`home`)return P(`home`);throw N(`Maestro pressKey "${t}" is not supported yet.`)}function W(e,n,r=[],i){if(typeof e==`string`)return ul(I(e,i));if(!F(e))throw new t(`INVALID_ARGS`,`${n} expects a string or selector map.`);M(e,n,[`id`,`text`,`enabled`,`selected`,...r]);let a=[],o=[];if(typeof e.enabled==`boolean`&&o.push(G(`enabled`,String(e.enabled))),typeof e.selected==`boolean`&&o.push(G(`selected`,String(e.selected))),typeof e.id==`string`&&a.push(G(`id`,I(e.id,i)),...o),typeof e.text==`string`&&a.length===0)return ul(I(e.text,i),o);if(typeof e.label==`string`&&a.length===0&&a.push(G(`label`,I(e.label,i)),...o),a.length===0&&o.length>0&&a.push(...o),a.length===0)throw new t(`INVALID_ARGS`,`${n} selector map must include one of id, text, label, enabled, or selected.`);return a.join(` `)}function ul(e,t=[]){return[[G(`label`,e),...t].join(` `),[G(`text`,e),...t].join(` `),[G(`id`,e),...t].join(` `)].join(` || `)}function dl(e,n){if(!F(e))return[];let r={};if(e.index!==void 0){if(typeof e.index!=`number`||!Number.isInteger(e.index)||e.index<0)throw new t(`INVALID_ARGS`,`tapOn.index must be a non-negative integer.`);r.index=e.index}return e.childOf!==void 0&&(r.childOf=W(e.childOf,`tapOn.childOf`,[],n)),Object.keys(r).length>0?[JSON.stringify(r)]:[]}function fl(e){let t=al(e.duration);return t?[t]:[]}function G(e,t){return`${e}=${JSON.stringify(t)}`}function pl(e){if(!F(e))return;let t={},n=gl(e.repeat),r=_l(e.delay);return n&&n>1&&(t.count=n),r!==void 0&&(t.intervalMs=r),e.optional===!0&&(t.maestro={optional:!0}),Object.keys(t).length>0?t:void 0}function ml(e){let t=pl(e)??{};return{...t,maestro:{...t.maestro??{},allowNonHittableCoordinateFallback:!0}}}function hl(e){let t={doubleTap:!0};return F(e)&&typeof e.delay==`number`&&Number.isInteger(e.delay)&&(t.intervalMs=Math.max(0,e.delay)),t}function gl(e){return typeof e==`number`&&Number.isInteger(e)&&e>0?e:void 0}function _l(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:void 0}const vl=1e3;function yl(e,n,r,i,a){if(typeof e==`string`)return i.parseRunFlowFile(I(e,r),r).actions;if(!F(e))throw new t(`INVALID_ARGS`,`runFlow expects a file path string or map.`);M(e,`runFlow`,[`file`,`commands`,`env`,`when`,`label`]);let o=Cl(e.when,r);return o.shouldRun?Rl(Sl(e,n,{...r,env:{...r.env,...gr(e.env,`runFlow.env`),...r.envOverrides}},i,a),o):[]}function bl(e,n,r,i,a){if(!F(e))throw new t(`INVALID_ARGS`,`repeat expects a map.`);if(M(e,`repeat`,[`times`,`commands`,`while`]),e.while!==void 0)throw N(`Maestro repeat.while is not supported yet. Only deterministic repeat.times is supported.`);let o=Bl(e.times,r);if(!Array.isArray(e.commands))throw new t(`INVALID_ARGS`,`repeat requires a commands list.`);if(o>vl)throw new t(`INVALID_ARGS`,`repeat.times must be <= ${vl} for deterministic replay expansion.`);let s=br(e.commands);return Array.from({length:o}).flatMap(()=>a(s,n,r,i))}function xl(e,n,r,i,a){if(!F(e))throw new t(`INVALID_ARGS`,`retry expects a map.`);if(M(e,`retry`,[`maxRetries`,`commands`]),!Array.isArray(e.commands))throw new t(`INVALID_ARGS`,`retry requires a commands list.`);let o=Vl(e.maxRetries,r),s=a(br(e.commands),n,r,i);return[zl(`retry`,[String(o)],{kind:`retry`,maxRetries:o,actions:s})]}function Sl(e,n,r,i,a){if(typeof e.file==`string`)return i.parseRunFlowFile(I(e.file,r),r).actions;if(Array.isArray(e.commands))return a(br(e.commands),n,r,i);throw new t(`INVALID_ARGS`,`runFlow map requires either file or commands.`)}function Cl(e,n){if(e==null)return{shouldRun:!0};if(!F(e))throw new t(`INVALID_ARGS`,`runFlow.when expects a map.`);return M(e,`runFlow.when`,[`platform`,`visible`,`notVisible`,`true`]),wl(e,n)?{shouldRun:!0,...Tl(e,n)}:{shouldRun:!1}}function wl(e,n){if(e.true!==void 0&&!Dl(e.true,n))return!1;if(e.platform===void 0)return!0;let r=El(e.platform,`runFlow.when.platform`);if(!n.platform)throw new t(`INVALID_ARGS`,`Maestro runFlow.when.platform requires replay to be run with --platform ios|android.`);return r===n.platform}function Tl(e,t){return{...e.visible===void 0?{}:{visibleSelector:W(e.visible,`runFlow.when.visible`,[],t)},...e.notVisible===void 0?{}:{notVisibleSelector:W(e.notVisible,`runFlow.when.notVisible`,[],t)}}}function El(e,n){if(typeof e!=`string`)throw new t(`INVALID_ARGS`,`${n} expects Android, iOS, or Web.`);let r=e.trim().toLowerCase();if(r===`android`||r===`ios`||r===`web`)return r;throw new t(`INVALID_ARGS`,`${n} expects Android, iOS, or Web.`)}function Dl(e,n){if(typeof e==`boolean`)return e;if(typeof e!=`string`)throw new t(`INVALID_ARGS`,`runFlow.when.true expects a boolean or expression string.`);return new Ll(kl(Ol(I(e,n))),{platform:n.platform}).parse()}function Ol(e){let t=e.trim();return t.startsWith("${")&&t.endsWith(`}`)?t.slice(2,-1).trim():t}function kl(e){let n=[],r=0;for(;r<e.length;){let i=e.slice(r),a=Al(i);if(a>0){r+=a;continue}let o=jl(i);if(o){n.push(o.token),r+=o.length;continue}throw new t(`INVALID_ARGS`,`Unsupported runFlow.when.true expression near "${i.slice(0,24)}".`)}return n}function Al(e){return/^\s+/.exec(e)?.[0].length??0}function jl(e){return Ml(e)??Nl(e)??Pl(e)??Fl(e)??Il(e)}function Ml(e){return e.startsWith(`maestro.platform`)?{token:{type:`platform`},length:16}:null}function Nl(e){let t=/^(==|!=|&&|\|\|)/.exec(e)?.[1];return t?{token:{type:`operator`,value:t},length:t.length}:null}function Pl(e){let t=e[0];return t===`(`||t===`)`?{token:{type:`paren`,value:t},length:1}:null}function Fl(e){let t=/^(['"])(.*?)\1/.exec(e);return t?{token:{type:`string`,value:t[2]??``},length:t[0].length}:null}function Il(e){let t=/^(true|false)\b/.exec(e)?.[1];return t?{token:{type:`boolean`,value:t===`true`},length:t.length}:null}var Ll=class{index=0;tokens;context;constructor(e,t){this.tokens=e,this.context=t}parse(){let e=this.parseOr();if(this.peek())throw new t(`INVALID_ARGS`,`Unsupported trailing runFlow.when.true expression.`);return e}parseOr(){let e=this.parseAnd();for(;this.consumeOperator(`||`);)e=this.parseAnd()||e;return e}parseAnd(){let e=this.parsePrimary();for(;this.consumeOperator(`&&`);)e=this.parsePrimary()&&e;return e}parsePrimary(){let e=this.peek();if(!e)throw new t(`INVALID_ARGS`,`Incomplete runFlow.when.true expression.`);if(e.type===`boolean`)return this.index+=1,e.value;if(e.type===`paren`&&e.value===`(`){this.index+=1;let e=this.parseOr();if(!this.consumeParen(`)`))throw new t(`INVALID_ARGS`,`Unclosed runFlow.when.true parenthesis.`);return e}return this.parsePlatformComparison()}parsePlatformComparison(){this.expectPlatform();let e=this.expectEqualityOperator(),t=this.expectString().toLowerCase(),n=this.context.platform;return e===`==`?n===t:n!==t}expectPlatform(){if(this.peek()?.type!==`platform`)throw new t(`INVALID_ARGS`,`runFlow.when.true supports maestro.platform comparisons.`);this.index+=1}expectEqualityOperator(){let e=this.peek();if(e?.type===`operator`&&(e.value===`==`||e.value===`!=`))return this.index+=1,e.value;throw new t(`INVALID_ARGS`,`runFlow.when.true comparison requires == or !=.`)}expectString(){let e=this.peek();if(e?.type===`string`)return this.index+=1,e.value;throw new t(`INVALID_ARGS`,`runFlow.when.true comparison requires a string literal.`)}consumeOperator(e){let t=this.peek();return t?.type!==`operator`||t.value!==e?!1:(this.index+=1,!0)}consumeParen(e){let t=this.peek();return t?.type!==`paren`||t.value!==e?!1:(this.index+=1,!0)}peek(){return this.tokens[this.index]}};function Rl(e,t){let{visibleSelector:n,notVisibleSelector:r}=t;if(!n&&!r)return e;if(n&&r)throw N(`Maestro runFlow.when cannot combine visible and notVisible yet.`);let i=n?`visible`:`notVisible`,a=n??r??``;return[zl(`runFlow.when`,[i,a],{kind:`maestroRunFlowWhen`,mode:i,selector:a,actions:e})]}function zl(e,t,n){return{...P(e,t),replayControl:n}}function Bl(e,t){return Hl(e,t,`repeat.times`)}function Vl(e,t){return e===void 0?1:Hl(e,t,`retry.maxRetries`)}function Hl(e,n,r){let i=typeof e==`string`?I(e,n):e,a=typeof i==`number`?i:typeof i==`string`&&/^\d+$/.test(i)?Number(i):void 0;if(a===void 0||!Number.isInteger(a)||a<0)throw new t(`INVALID_ARGS`,`${r} must be a non-negative integer or \${VAR} resolving to one.`);return a}const Ul=3e4;function Wl(e,t){let n=Kl(e,t),r=ql(n.file,t);return P(U.runScript,[r],{...Object.keys(n.env).length>0?{maestro:{runScriptEnv:n.env}}:{}})}function Gl(e){let{scriptPath:n,env:r}=e,i=L.readFileSync(n,`utf8`),a=Object.create(null);try{zr.runInNewContext(i,Jl(r,a),{filename:n,timeout:Ul})}catch(e){throw new t(`COMMAND_FAILED`,`Maestro runScript failed for ${n}: ${e instanceof Error?e.message:String(e)}`,{scriptPath:n},e instanceof Error?e:void 0)}return Ql(a,n),Object.fromEntries(Object.entries(a).map(([e,t])=>[`output.${e}`,$l(t)]))}function Kl(e,n){if(typeof e==`string`)return{file:I(e,n),env:{}};if(!F(e))throw new t(`INVALID_ARGS`,`runScript expects a file path string or map.`);M(e,`runScript`,[`file`,`env`]);let r=I(mr(`runScript.file`,e.file),n),i=gr(e.env,`runScript.env`);return{file:r,env:Object.fromEntries(Object.entries(i).map(([e,t])=>[e,I(t,n)]))}}function ql(e,n){if(R.isAbsolute(e))return e;if(!n.baseDir)throw new t(`INVALID_ARGS`,`runScript file paths require replay input to have a source path.`);return R.resolve(n.baseDir,e)}function Jl(e,t){return{...e,output:t,json:Yl,http:{post:(e,t)=>Zl(`POST`,e,t)}}}function Yl(e){if(typeof e!=`string`)throw new t(`COMMAND_FAILED`,`Maestro runScript json() expected a string body, received ${typeof e}.`);if(e.trim().length===0)throw new t(`COMMAND_FAILED`,`Maestro runScript json() received an empty body. Check the preceding http response status and setup server output.`);try{return JSON.parse(e,Xl)}catch(n){throw new t(`COMMAND_FAILED`,`Maestro runScript json() could not parse response body: ${n instanceof Error?n.message:String(n)}`,{bodyPreview:e.slice(0,1e3)},n instanceof Error?n:void 0)}}function Xl(e,t){return e===`__proto__`||e===`constructor`||e===`prototype`?void 0:t}function Zl(e,n,r){let i=f(process.execPath,[`-e`,`
|
|
1
|
+
import{B as e,F as t,I as n,S as r,b as i,f as a,h as o,m as s,p as c,t as l,v as u,y as d}from"./sdk-contracts.js";import{C as f,N as p,c as m,j as h,p as g,v as _}from"./sdk-android-adb.js";import{S as v,_ as y,b,x as ee}from"./sdk-batch.js";import{$t as x,Bt as S,Gt as te,Ht as ne,It as re,Jn as ie,Jt as ae,Kt as oe,Qn as C,Rn as se,Rt as ce,Tn as le,Ut as ue,Yt as de,Zn as fe,an as pe,ct as me,dt as he,f as ge,ht as _e,in as ve,q as ye,qt as be,ut as xe,wn as Se,zn as Ce}from"./tv-remote.js";import{i as we,r as Te}from"./output-path.js";import{a as Ee,n as De,t as Oe}from"./snapshot-diagnostics.js";import{n as ke}from"./version.js";import{t as w}from"./timeouts.js";import{N as Ae,d as je,g as Me,h as Ne,i as Pe,l as Fe,t as Ie}from"./sdk-selectors.js";import{n as Le,t as Re}from"./sdk-batch-runner.js";import{t as ze}from"./project-runtime.js";import{n as Be,t as Ve}from"./runtime-transport.js";import{i as He}from"./sdk-finders.js";import{a as Ue,s as We,t as Ge}from"./selectors2.js";import{n as Ke}from"./sdk-app-inventory.js";import{f as qe,h as Je}from"./runtime.js";import{f as Ye,p as Xe,s as Ze}from"./app-lifecycle.js";import{D as Qe,O as $e,S as et,b as tt,k as nt,p as rt,v as it,x as at}from"./android-input-ownership.js";import{d as ot,s as st}from"./providers.js";import{C as ct,S as lt,b as ut,c as dt,g as ft,h as pt,m as T,n as mt,o as ht,p as gt,r as _t,s as vt,t as yt,u as bt,v as xt,w as St,x as Ct,y as wt}from"./runner-client.js";import{o as Tt}from"./tool-provider.js";import{r as Et}from"./helper.js";import{n as Dt}from"./simctl.js";import{n as Ot,s as kt}from"./agent-browser-tool.js";import{$t as E,A as At,B as jt,C as Mt,Cn as Nt,D as Pt,E as Ft,F as It,Gt as D,I as Lt,Kt as Rt,L as zt,M as Bt,Mt as Vt,N as Ht,Nt as Ut,O as Wt,P as Gt,R as Kt,S as qt,Sn as Jt,St as O,T as Yt,Tn as Xt,Wt as Zt,Xt as Qt,Zt as $t,_ as en,_n as tn,_t as nn,a as rn,an,at as on,b as sn,bn as cn,c as ln,cn as un,ct as dn,d as fn,dn as pn,dt as mn,f as hn,fn as gn,g as _n,gn as vn,gt as yn,h as bn,hn as xn,ht as Sn,i as Cn,in as wn,it as Tn,j as En,k as Dn,l as On,ln as kn,lt as An,m as jn,mn as Mn,mt as Nn,n as Pn,nn as Fn,nt as In,o as Ln,on as Rn,ot as zn,p as Bn,pn as Vn,pt as Hn,r as Un,rn as Wn,rt as Gn,s as Kn,sn as qn,st as Jn,tn as k,u as Yn,un as Xn,ut as Zn,v as Qn,vn as $n,vt as er,w as tr,wn as nr,x as rr,xn as A,y as ir,z as ar,zt as j}from"./internal/daemon.js";import{C as or,D as sr,E as cr,S as lr,T as ur,a as M,b as dr,c as fr,d as pr,f as mr,g as hr,h as N,i as P,l as gr,m as _r,n as vr,o as F,p as I,r as yr,s as L,u as br,v as xr,w as Sr,x as Cr,y as wr}from"./points.js";import{n as Tr}from"./provider.js";import{a as R,i as Er,n as Dr,r as Or,t as kr}from"./apple-runner-options.js";import{t as Ar}from"./handler-utils.js";import{l as jr}from"./apps.js";import{a as Mr,n as Nr}from"./simulator.js";import{t as Pr}from"./record-trace-recording.js";import z from"node:fs";import B from"node:path";import{access as Fr}from"node:fs/promises";import{setTimeout as Ir}from"node:timers/promises";import Lr from"node:vm";function Rr(e){throw new t(`UNSUPPORTED_OPERATION`,`install_from_source ${String(e.kind)} sources require a compatible remote daemon`)}function zr(e){let n=e.meta?.installSource;if(!n)throw new t(`INVALID_ARGS`,`install_from_source requires a source payload`);switch(n.kind){case`url`:if(!n.url||n.url.trim().length===0)throw new t(`INVALID_ARGS`,`install_from_source url source requires a non-empty url`);return n;case`path`:if(!n.path||n.path.trim().length===0)throw new t(`INVALID_ARGS`,`install_from_source path source requires a non-empty path`);return n;case`github-actions-artifact`:throw new t(`UNSUPPORTED_OPERATION`,`install_from_source github-actions-artifact sources require a compatible remote daemon`);default:Rr(n)}}function Br(e){let t=zr(e),n=e.meta?.uploadedArtifactId;return!n||t.kind!==`path`?{source:t,cleanup:()=>{}}:{source:{kind:`path`,path:cn(n,e.meta?.tenantId)},cleanup:()=>{$n(n)}}}function Vr(e){return e===`ios`||e===`android`?e:void 0}function Hr(e){let n=e.meta?.retainMaterializedPaths===!0,r=e.meta?.materializedPathRetentionMs;if(!n)return{enabled:!1};if(r!==void 0&&r<=0)throw new t(`INVALID_ARGS`,`install_from_source retentionMs must be a positive integer`);return{enabled:!0,ttlMs:r}}async function Ur(e){let n=Vr(e.flags?.platform);if(e.session){if(n&&e.session.device.platform!==n)throw new t(`INVALID_ARGS`,`install_from_source requested platform ${n}, but session is bound to ${e.session.device.platform}`);return await R(e.session.device),e.session.device}if(!n)throw new t(`INVALID_ARGS`,`install_from_source requires platform "ios" or "android" when no session is provided`);let r=await kn(e.flags??{});return await R(r),r}async function Wr(e){let{prepared:t,retention:n,req:r,session:i,sessionName:a}=e;if(n.enabled)return await fn({archivePath:t.archivePath,installablePath:t.installablePath,tenantId:r.meta?.tenantId,sessionName:i?a:void 0,ttlMs:n.ttlMs})}function Gr(e){return e?{...e.archivePath?{archivePath:e.archivePath}:{},installablePath:e.installablePath,materializationId:e.materializationId,materializationExpiresAt:e.expiresAt}:{}}function Kr(e){let{session:t,sessionStore:n,req:r,data:i}=e;Ar(n,t,r,`install_source`,i,{positionals:[]})}async function qr(t){let{req:n,sessionName:r,sessionStore:i}=t,a=i.get(r);try{let e=Br(n),t=Hr(n),o=await Ur({session:a,flags:n.flags}),s=k(`install`,o,{message:`install_from_source is not supported on this device`});if(s)return s;let l=ut(n.meta?.requestId);if(c(o)){let{prepareIosInstallArtifact:s}=await import(`./apps.js`).then(e=>e.a),c=await s(e.source,{signal:l});return await Jr({prepared:c,retention:t,req:n,resolvedSourceCleanup:()=>e.cleanup(),session:a,sessionName:r,sessionStore:i,buildResult:async e=>await Yr(o,c,e)})}let{prepareAndroidInstallArtifact:u}=await import(`./android-input-ownership.js`).then(e=>e.l),d=await u(e.source,{signal:l});return await Jr({prepared:d,retention:t,req:n,resolvedSourceCleanup:()=>e.cleanup(),session:a,sessionName:r,sessionStore:i,buildResult:async e=>await Xr(o,d,e)})}catch(t){return{ok:!1,error:e(t)}}}async function Jr(e){let t;try{t=await Wr(e);let n=await e.buildResult(t),r=le(n,ti(n));return Kr({session:e.session,sessionStore:e.sessionStore,req:e.req,data:r}),{ok:!0,data:r}}catch(n){throw t&&await On(t.materializationId,e.req.meta?.tenantId).catch(()=>{}),n}finally{await e.prepared.cleanup(),e.resolvedSourceCleanup()}}async function Yr(e,t,n){let r=await xn(e,t.installablePath,{appIdentifierHint:t.bundleId});if(!r){let{installIosInstallablePath:n}=await import(`./apps.js`).then(e=>e.t);await n(e,t.installablePath)}return Zr(t,r,n)}async function Xr(e,t,n){let r=await xn(e,t.installablePath,{packageNameHint:t.packageName}),i=await ei(e,t,r),{inferAndroidAppName:a}=await import(`./app-lifecycle.js`).then(e=>e.t),o=a(i);return{...Gr(n),packageName:i,...$r(r?.appName??o),launchTarget:r?.launchTarget??i}}function Zr(e,t,n){let r=Qr(e,t),i=t?.appName??e.appName;return{...Gr(n),bundleId:r,...$r(i),launchTarget:t?.launchTarget??r}}function Qr(e,n){let r=n?.bundleId??e.bundleId;if(r)return r;throw new t(`COMMAND_FAILED`,`Installed iOS app identity could not be resolved from the artifact`)}function $r(e){return e?{appName:e}:{}}async function ei(e,n,r){let i=r?.packageName??r?.launchTarget;if(i)return i;let{installAndroidInstallablePathAndResolvePackageName:a}=await import(`./app-lifecycle.js`).then(e=>e.t),o=await a(e,n.installablePath,n.packageName);if(!o)throw new t(`COMMAND_FAILED`,`Installed Android app identity could not be resolved from the artifact or device state`);return o}function ti(e){return`Installed: ${pe(e)}`}async function ni(n){let{req:r}=n;try{let e=r.meta?.materializationId?.trim();if(!e)throw new t(`INVALID_ARGS`,`release_materialized_paths requires a materializationId`);return await On(e,r.meta?.tenantId),{ok:!0,data:{released:!0,materializationId:e}}}catch(t){return{ok:!1,error:e(t)}}}function V(e){return c(e)&&e.kind===`simulator`}function ri(e){return e.platform===`android`&&e.kind===`emulator`}function H(e,t,n){return t||$t(n)?null:E(`INVALID_ARGS`,`${e} requires an active session or an explicit device selector (e.g. --platform ios).`)}function ii(e){return typeof e?.session==`string`&&e.session.trim().length>0}async function ai(e,t){!V(e)||t<=0||await new Promise(e=>setTimeout(e,t))}async function U(e){let t=$t(e.flags)||!e.session?await kn(e.flags??{},{allowStoppedAndroidAvdPlaceholders:e.allowStoppedAndroidAvdPlaceholders}):await oi(e.session.device);return e.ensureReady!==!1&&await R(t),t}async function oi(e){if(!c(e)||e.kind!==`simulator`||process.platform!==`darwin`)return e;if(ht(e.id)?.alive)return{...e,booted:!0};let n={platform:`ios`,target:e.target,udid:e.id,...e.simulatorSetPath?{iosSimulatorDeviceSet:e.simulatorSetPath}:{}};try{return await kn(n)}catch(e){if(!(e instanceof t)||e.code!==`DEVICE_NOT_FOUND`)throw e}return await kn({platform:`ios`,target:e.target,device:e.name,...e.simulatorSetPath?{iosSimulatorDeviceSet:e.simulatorSetPath}:{}})}function si(e){let t=e.flags?.device?.trim();if(t)return t;if(e.resolvedDevice?.platform===`android`&&e.resolvedDevice.kind===`emulator`)return e.resolvedDevice.name;if(e.sessionDevice?.platform===`android`&&e.sessionDevice.kind===`emulator`)return e.sessionDevice.name}function ci(e,t){return t?nn(t,e).length===0:!1}const li=`shared_prefs/ReactNativeDevPrefs.xml`,ui=`debug_http_host`,di=`dev_server_https`,fi=`RCT_jsLocation`,pi=`RCT_packager_scheme`,mi=`React Native runtime hints require adb run-as access to the app sandbox. Verify the app is debuggable and the selected package/device are correct.`,hi=[`<?xml version="1.0" encoding="utf-8" standalone="yes" ?>`,`<map>`,`</map>`,``].join(`
|
|
2
|
+
`);function gi(e){return Ve(e)!==void 0}async function _i(e){let{device:t,appId:n,runtime:r}=e;if(vn(t)||!n)return;let i=Ve(r);if(i){if(t.platform===`android`){await yi(t,n,i);return}c(t)&&t.kind===`simulator`&&await Ci(t,n,i)}}async function vi(e){let{device:t,appId:n}=e;if(n){if(t.platform===`android`){await bi(t,n);return}c(t)&&t.kind===`simulator`&&await wi(t,n)}}async function yi(e,t,n){Ai(t);let r=Ei(await xi(e,t),ui,`${n.host}:${n.port}`);r=Di(r,di,n.scheme===`https`),await Si(e,t,r)}async function bi(e,t){Ai(t);let n=await xi(e,t),r=ki(ki(n,ui),di);r!==n&&await Si(e,t,r)}async function xi(e,t){let n=await rt(e,[`shell`,`run-as`,t,`cat`,li],{allowFailure:!0});return n.exitCode===0?Ti(n.stdout):hi}async function Si(e,r,i){let a=[`shell`,`run-as`,r,`id`],o=await rt(e,a,{allowFailure:!0});if(o.exitCode!==0){let e=Ni(o.stdout,o.stderr);throw new t(`COMMAND_FAILED`,e?`Failed to access Android app sandbox for ${r}`:`Failed to probe Android app sandbox for ${r}`,g(o,{package:r,cmd:`adb`,args:a,hint:e?mi:`adb shell run-as probe failed. Check adb connectivity and that the device is reachable. Inspect stderr/details for more information.`}))}try{await rt(e,[`shell`,`run-as`,r,`mkdir`,`-p`,`shared_prefs`]),await rt(e,[`shell`,`run-as`,r,`tee`,li],{stdin:i.trimEnd()})}catch(e){let i=n(e);if(i.code===`TOOL_MISSING`)throw i;let a=Ni(typeof i.details?.stdout==`string`?i.details.stdout:``,typeof i.details?.stderr==`string`?i.details.stderr:``);throw new t(`COMMAND_FAILED`,a?`Failed to access Android app sandbox for ${r}`:`Failed to write Android runtime hints for ${r}`,{...i.details??{},package:r,cmd:`adb`,phase:`write-runtime-hints`,hint:a?mi:`adb run-as succeeded, but writing ReactNativeDevPrefs.xml failed. Inspect stderr/details for the failing shell command.`},i)}}async function Ci(e,t,n){await Tt(Dt(e,[`spawn`,e.id,`defaults`,`write`,t,fi,`-string`,`${n.host}:${n.port}`])),await Tt(Dt(e,[`spawn`,e.id,`defaults`,`write`,t,pi,`-string`,n.scheme]))}async function wi(e,t){await Tt(Dt(e,[`spawn`,e.id,`defaults`,`delete`,t,fi]),{allowFailure:!0}),await Tt(Dt(e,[`spawn`,e.id,`defaults`,`delete`,t,pi]),{allowFailure:!0})}function Ti(e){let t=e.trim();return!t.includes(`<map`)||!t.includes(`</map>`)?hi:`${t}\n`}function Ei(e,t,n){let r=` <string name="${Mi(t)}">${Mi(n)}</string>`;return Oi(ki(e,t),r)}function Di(e,t,n){let r=` <boolean name="${Mi(t)}" value="${n?`true`:`false`}" />`;return Oi(ki(e,t),r)}function Oi(e,t){return Ti(e).replace(`</map>`,`${t}\n</map>`)}function ki(e,t){let n=ji(t);return Ti(e).replace(RegExp(`^\\s*<string name="${n}">[\\s\\S]*?<\\/string>\\n?`,`m`),``).replace(RegExp(`^\\s*<boolean name="${n}" value="(?:true|false)"\\s*\\/?>\\n?`,`m`),``)}function Ai(e){if(Ye(e)!==`binary`)return;let n=Xe(e);throw new t(`INVALID_ARGS`,n,{package:e,hint:n})}function ji(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Mi(e){return e.replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`).replaceAll(`"`,`"`).replaceAll(`'`,`'`)}function Ni(e,t){let n=`${e}\n${t}`.toLowerCase();return[`run-as: package not debuggable`,`run-as: permission denied`,`run-as: package is unknown`,`run-as: unknown package`,`is unknown`,`is not an application`,`could not set capabilities`].some(e=>n.includes(e))}const Pi=[`platform`,`metroHost`,`metroPort`,`bundleUrl`,`launchUrl`];function Fi(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>e!==void 0&&e!==``).length:0}function Ii(e,n){if(e!==void 0){if(typeof e!=`string`)throw new t(`INVALID_ARGS`,`Invalid open runtime ${n}: expected string.`);return Be(e)}}function Li(e){if(e!==void 0){if(!Number.isInteger(e)||e<1||e>65535)throw new t(`INVALID_ARGS`,`Invalid runtime metroPort: ${String(e)}. Use an integer between 1 and 65535.`);return e}}function Ri(e){if(e!==void 0){if(typeof e!=`number`)throw new t(`INVALID_ARGS`,`Invalid open runtime metroPort: expected integer.`);return Li(e)}}function zi(e,n,r){if(e===void 0)return r;if(e!==`ios`&&e!==`android`)throw new t(`INVALID_ARGS`,`Invalid open runtime platform: ${String(e)}. Use "ios" or "android".`);if(r&&e!==r)throw new t(`INVALID_ARGS`,`open runtime targets ${e}, but session "${n}" is bound to ${r}.`);return e}function Bi(e){if(e===`ios`||e===`android`)return e}function Vi(e,t){return{platform:t,metroHost:Be(e?.metroHost),metroPort:Li(e?.metroPort),bundleUrl:Be(e?.bundleUrl),launchUrl:Be(e?.launchUrl)}}function Hi(e,t){return{platform:t.platform??e?.platform,metroHost:t.metroHost??e?.metroHost,metroPort:t.metroPort??e?.metroPort,bundleUrl:t.bundleUrl??e?.bundleUrl,launchUrl:t.launchUrl??e?.launchUrl}}function Ui(e){let{runtime:n,sessionName:r,platform:i}=e;if(n===void 0)return;if(!n||typeof n!=`object`||Array.isArray(n))throw new t(`INVALID_ARGS`,`open runtime must be an object.`);let a=n,o=Object.keys(a).find(e=>!Pi.includes(e));if(o)throw new t(`INVALID_ARGS`,`Invalid open runtime field: ${o}. Supported fields are ${Pi.join(`, `)}.`);return{platform:zi(a.platform,r,i),metroHost:Ii(a.metroHost,`metroHost`),metroPort:Ri(a.metroPort),bundleUrl:Ii(a.bundleUrl,`bundleUrl`),launchUrl:Ii(a.launchUrl,`launchUrl`)}}function Wi(e,t,n){if(n){if(Fi(n)===0){e.clearRuntimeHints(t);return}return e.setRuntimeHints(t,n),n}}function Gi(e,n,r){let a=e.getRuntimeHints(n);if(!a)return;let o=r?i(r):void 0,s=Bi(o);if(a.platform&&r&&!s)throw new t(`INVALID_ARGS`,`Session runtime hints are only supported on iOS and Android sessions, but session "${n}" is bound to ${o}.`);if(a.platform&&s&&a.platform!==s)throw new t(`INVALID_ARGS`,`Session runtime hints target ${a.platform}, but session "${n}" is bound to ${o}. Clear the runtime hints or use a different session.`);return s&&a.platform!==s?{...a,platform:s}:a}function Ki(e){let{req:t,sessionStore:n,sessionName:r,device:a}=e,o=n.getRuntimeHints(r),s=Ui({runtime:t.runtime,sessionName:r,platform:Bi(i(a))});return t.runtime===void 0?{runtime:Gi(n,r,a),previousRuntime:o,replacedStoredRuntime:!1}:{runtime:s&&Fi(s)>0?s:void 0,previousRuntime:o,replacedStoredRuntime:!0}}function qi(e){try{return{ok:!0,data:Ki(e)}}catch(e){let t=n(e);return E(t.code,t.message,t.details)}}async function Ji(e){let{replacedStoredRuntime:t,previousRuntime:n,runtime:r,session:i}=e;!t||!i?.appBundleId||!gi(n)||gi(r)||await vi({device:i.device,appId:i.appBundleId})}async function Yi(e){let{req:t,sessionName:n,sessionStore:r}=e,i=(t.positionals?.[0]??`show`).toLowerCase();if(Zi(i))return await na(t,i);if(!Xi(i))return E(`INVALID_ARGS`,`runtime requires set, show, clear, port-reverse, or port-reverse-remove`);let a=r.get(n),o=r.getRuntimeHints(n);return i===`clear`?await Qi(n,r,a,o):i===`show`?$i(n,o):ta({req:t,sessionName:n,sessionStore:r,session:a,current:o})}function Xi(e){return e===`set`||e===`show`||e===`clear`}function Zi(e){return e===`port-reverse`||e===`port-reverse-remove`}async function Qi(e,t,n,r){return gi(r)&&n?.appBundleId&&await vi({device:n.device,appId:n.appBundleId}),{ok:!0,data:{session:e,cleared:t.clearRuntimeHints(e)}}}function $i(e,t){return{ok:!0,data:{session:e,configured:!!t,runtime:t}}}function ea(e){return e?i(e.device):void 0}function ta(e){let{req:t,sessionName:n,sessionStore:r,session:i,current:a}=e,o=ea(i),s=Bi(t.flags?.platform??a?.platform??o);if(!s)return E(`INVALID_ARGS`,`runtime set only supports iOS and Android sessions. Pass --platform ios|android or open an iOS/Android session first.`);if(o!==void 0&&o!==s)return E(`INVALID_ARGS`,`runtime set targets ${s}, but session "${n}" is already bound to ${o}.`);let c=Hi(a,Vi(t.flags,s));return Fi(c)===0?E(`INVALID_ARGS`,`runtime set requires at least one hint such as --metro-host, --metro-port, --bundle-url, or --launch-url.`):(r.setRuntimeHints(n,c),{ok:!0,data:{session:n,configured:!0,runtime:c}})}async function na(e,t){let n=ra(e);if(!n.ok)return n.response;let r=await oa(t,n.options);return r?{ok:!0,data:{action:t,...r}}:E(`UNSUPPORTED_OPERATION`,`No active provider device runtime supports port reverse for this lease.`)}function ra(e){let t=ia(e);if(!t.ok)return t;let n=aa(e);if(!n.ok)return n;let r=e.flags?.portReverseName?.trim()||`runtime`;return{ok:!0,options:{leaseId:t.leaseId,provider:t.provider,devicePort:n.devicePort,hostPort:n.hostPort,name:r}}}function ia(e){let t=e.flags?.leaseId,n=e.flags?.leaseProvider;return t?n?{ok:!0,leaseId:t,provider:n}:{ok:!1,response:E(`INVALID_ARGS`,`runtime port-reverse requires a lease provider.`)}:{ok:!1,response:E(`INVALID_ARGS`,`runtime port-reverse requires a resolved remote lease.`)}}function aa(e){let t=sa(e.flags?.devicePort),n=sa(e.flags?.hostPort??e.flags?.devicePort);return!t||!n?{ok:!1,response:E(`INVALID_ARGS`,`runtime port-reverse requires numeric devicePort and hostPort values from 1 to 65535.`)}:{ok:!0,devicePort:t,hostPort:n}}async function oa(e,t){return e===`port-reverse`?await Vn(t):await tn(t)}function sa(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<1||e>65535))return e}const ca=`open-command-roundtrip`,la=`Not implemented for this platform in this release.`;function ua(e){let{sessionName:t,sessionStateDir:n,runnerLogPath:r,requestLogPath:a,eventLogPath:o,appName:s,appBundleId:l,surface:u,startup:d,timing:f,device:p,runtime:m,runtimeHintCount:h}=e,g={session:t,surface:u,sessionStateDir:n,runnerLogPath:r,requestLogPath:a,eventLogPath:o};return s&&(g.appName=s),l&&(g.appBundleId=l),d&&(g.startup=d),f&&(g.timing=f),m&&h(m)>0&&(g.runtime=m),p&&(g.platform=i(p),g.target=p.target??`mobile`,g.device=p.name,g.id=p.id,g.kind=p.kind,p.platform===`android`&&(g.serial=p.id)),p&&c(p)&&(g.device_udid=p.id,g.ios_simulator_device_set=p.simulatorSetPath??null),{...g,...Se(`Opened: ${s??l??t}`)}}function da(e){let{existingSession:t,sessionName:n,sessionScope:r,device:i,surface:a,appBundleId:o,appName:s,saveScript:c}=e;return t?{...t,device:i,surface:a,appBundleId:o,appName:s,recordSession:t.recordSession||c,snapshot:void 0}:{name:n,sessionScope:r,device:i,createdAt:Date.now(),surface:a,appBundleId:o,appName:s,recordSession:c,actions:[]}}const fa=new Set([`app`,`desktop`,`frontmost-app`]);function pa(e,n,r){if(e.platform===`linux`){if(!n)return`app`;let e=x(n);if(!fa.has(e))throw new t(`INVALID_ARGS`,`Linux supports --surface app, desktop, and frontmost-app (got "${n}")`);if(e!==`app`&&r)throw new t(`INVALID_ARGS`,`open --surface ${e} does not accept an app target`);return e}if(!s(e)){if(n)throw new t(`INVALID_ARGS`,`surface is only supported on macOS and Linux`);return`app`}let i=n?x(n):`app`;if(i!==`app`&&i!==`menubar`&&r)throw new t(`INVALID_ARGS`,`open --surface ${i} does not accept an app target`);return i}function ma(e){let{device:t,surfaceFlag:n,openTarget:r,existingSurface:i}=e;return(s(t)||t.platform===`linux`)&&!n?i??`app`:pa(t,n,r)}async function ha(e){if(e===`app`||e===`desktop`||e===`menubar`)return{};let t=await Et();return{appBundleId:t.bundleId,appName:t.appName}}async function ga(e,t,n){if(!(!a(e.platform)||!t))return Qe(t)?s(e)?void 0:e.kind===`device`?nt(n,t):$e(t)?void 0:n??await _a(e,t):await va(e,t)}async function _a(e,t){try{let{resolveIosSimulatorDeepLinkBundleId:n}=await import(`./apps.js`).then(e=>e.t);return await n(e,t)}catch{return}}async function va(e,t){try{let{resolveIosApp:n}=await import(`./apps.js`).then(e=>e.t);return await n(e,t)}catch{return}}async function ya(e,t){if(!(e.platform!==`android`||!t||Qe(t)))try{let{resolveAndroidApp:n}=await import(`./app-lifecycle.js`).then(e=>e.t),r=await n(e,t);return r.type===`package`?r.value:void 0}catch{return}}async function ba(e,t,n){if(n||e.platform!==`android`||!t||!Qe(t))return n;try{let{getAndroidAppState:t}=await import(`./app-lifecycle.js`).then(e=>e.t);return(await t(e)).package?.trim()||n}catch{return n}}function xa(e,t){return e.platform===`android`&&!!(t&&Qe(t))}async function Sa(e,t,n,r){return await ga(e,t,n)??await r(e,t)??(xa(e,t)?n:void 0)}function W(e){return E(`INVALID_ARGS`,e)}function Ca(e,n,r,i){try{return ma({device:e,surfaceFlag:n,openTarget:r,existingSurface:i})}catch(e){return E(e instanceof t?e.code:`INVALID_ARGS`,String(e.message))}}function wa(e){let{shouldRelaunch:t,openTarget:n,surface:r,device:i}=e;return t?n&&Qe(n)?W(`open --relaunch does not support URL targets.`):r===`app`?i.platform===`android`&&n&&Ye(n)===`binary`?W(Xe(n)):null:W(`open --relaunch is supported only for app surfaces.`):null}function Ta(e){let{shouldRelaunch:t,openTarget:n,platform:r}=e;return t?n&&Qe(n)?W(`open --relaunch does not support URL targets.`):r===`android`&&n&&Ye(n)===`binary`?W(Xe(n)):null:null}async function Ea(e){let{req:t,sessionName:n,sessionStore:r,device:i,surface:a,openTarget:o,existingSession:s,onIosSimulatorColdBootStart:c}=e;await R(i,{deviceHub:t.flags?.deviceHub===!0,onIosSimulatorColdBootStart:c});let{appBundleId:l,appName:u}=await Da({device:i,surface:a,openTarget:o,existingAppBundleId:s?.appBundleId}),d=qi({req:t,sessionStore:r,sessionName:n,device:i});if(!d.ok)return{type:`response`,response:d};if(s){let{runtime:e,previousRuntime:t,replacedStoredRuntime:n}=d.data;await Ji({replacedStoredRuntime:n,previousRuntime:t,runtime:e,session:s})}return{type:`details`,details:{appBundleId:l,appName:u,runtime:d.data.runtime}}}async function Da(e){let{device:t,surface:n,openTarget:r,existingAppBundleId:i}=e,a=await ha(n);return{appBundleId:a.appBundleId??await Sa(t,r,i,ya),appName:a.appName??r}}const Oa=new Map;async function ka(e){let{device:t,closeTarget:n,outFlag:r,context:i}=e;a(t.platform)&&!V(t)&&await dt(t.id),await D(t,`close`,[n],r,i),await ai(t,300)}async function Aa(e){let{runtime:t,device:n,req:r,logPath:i,appBundleId:a,traceLogPath:o,openPositionals:s}=e,c=t?.launchUrl;if(!c||s.length===0||s.length>1)return;let l=s[0]?.trim();!l||Qe(l)||await D(n,`open`,[c],r.flags?.out,{...ja(i,r.flags,a,o)})}function ja(e,t,n,r){let i=j(e,t,n,r);return delete i.launchConsole,delete i.launchArgs,i}function Ma(e,t,n){return{durationMs:Math.max(0,Date.now()-e),measuredAt:new Date().toISOString(),method:ca,appTarget:t,appBundleId:n}}async function Na(e){let{req:t,sessionName:n,sessionStore:r,logPath:i,device:a,openTarget:o,openPositionals:s,appName:l,surface:u,appBundleId:d,runtime:f,existingSession:m}=e,g=t.flags?.relaunch===!0,_=m?.trace?.outPath,v=d,y=Date.now(),b={},ee=c(a)&&u===`app`&&s.length>0&&!!v,x=Dr({req:t,logPath:i,appBundleId:v,traceLogPath:_}),S=t.flags?.maestro?.prewarmRunnerBeforeOpen===!0,te,ne=!1,re=!1,ie=(e=x)=>{ne=!0,b.runnerPrewarmKind=`session`,b.runnerPrewarmScheduled=!0,te=_t(a,e)},ae=async()=>{if(!te||re)return;re=!0;let e=Date.now();await te,b.runnerPrewarmWaited=!0,b.runnerPrewarmDurationMs=Math.max(0,Date.now()-e)};ee&&V(a)&&!S&&ie();let oe=g&&!!o&&s.length===1&&V(a)&&t.flags?.clearAppState!==!0;if(g&&o&&!oe){let e=v??o,n=Date.now();await ka({device:a,closeTarget:e,outFlag:t.flags?.out,context:{...j(i,t.flags,v??m?.appBundleId,_)}}),b.relaunchCloseDurationMs=Math.max(0,Date.now()-n)}let C=Date.now();await _i({device:a,appId:v,runtime:f}),b.runtimeHintsDurationMs=Math.max(0,Date.now()-C),ee&&S&&(ie({...x,propagateError:!0}),await ae());let se=Date.now(),ce=await Pa({req:t,sessionName:n,sessionStore:r,device:a,surface:u,sessionAppBundleId:v,appName:l,existingSession:m});if(ce.type===`response`)return ce.response;let le=ce.session??m;await D(a,`open`,s,t.flags?.out,{...j(i,t.flags,v),...oe?{terminateRunningApp:!0}:{}}),b.openDispatchDurationMs=Math.max(0,Date.now()-se);let ue=Date.now();await Aa({runtime:f,device:a,req:t,logPath:i,appBundleId:v,traceLogPath:_,openPositionals:s}),b.launchUrlDurationMs=Math.max(0,Date.now()-ue),ee&&!ne&&ie(),g?await ae():te&&!re&&(b.runnerPrewarmWaited=!1),v=await ba(a,o,v),a.platform===`android`&&v&&await Ft(a,v);let de=o?Ma(se,o,v):void 0,fe=Date.now();if(await ai(a,300),b.postOpenSettleDurationMs=Math.max(0,Date.now()-fe),Ct(t.meta?.requestId)){let e=wt();return E(e.code,e.message,e.details)}m&&Zt(m,`open`,m.snapshot);let pe=da({existingSession:le,sessionName:m?.name??Sn(t),sessionScope:m?.sessionScope??Nn(t),device:a,surface:u,appBundleId:v,appName:l,saveScript:!!t.flags?.saveScript});pe.lease=mn({req:t,existingLease:m?.lease}),t.runtime!==void 0&&Wi(r,n,f);let me=r.ensureSessionDir(n),he=Jt(me,t.meta?.requestId??p().requestId);b.totalDurationMs=Math.max(0,Date.now()-y),h({level:`info`,phase:`open_timing`,durationMs:b.totalDurationMs,data:b});let ge=ua({sessionName:pe.name,sessionStateDir:me,runnerLogPath:Nt(me),requestLogPath:he,eventLogPath:r.resolveEventLogPath(n),appName:l,appBundleId:v,surface:u,startup:de,timing:b,device:a,runtime:f,runtimeHintCount:Fi});return r.set(n,pe),r.recordAction(pe,{command:`open`,positionals:s,flags:t.flags??{},runtime:t.runtime===void 0?void 0:f,result:ge}),{ok:!0,data:ge}}async function Pa(e){let{req:t,sessionName:n,sessionStore:r,device:i,surface:a,sessionAppBundleId:o,appName:s,existingSession:c}=e,l=t.internal?.openLifecycle?.beforeDispatch;if(!l)return{type:`session`,session:c};let u=da({existingSession:c,sessionName:c?.name??Sn(t),sessionScope:c?.sessionScope??Nn(t),device:i,surface:a,appBundleId:o,appName:s,saveScript:!!t.flags?.saveScript});u.lease=mn({req:t,existingLease:c?.lease}),r.set(n,u);let d=await l(u);return d&&!d.ok?{type:`response`,response:d}:{type:`session`,session:r.get(n)??u}}async function Fa(e){let{req:t,sessionName:n,logPath:r,sessionStore:i}=e,a=i.get(n);if(a){let e=t.flags?.relaunch===!0,o=t.positionals?.[0],s=o??(e?a.appName:void 0),c=Ca(a.device,t.flags?.surface,s,a.surface);if(typeof c!=`string`)return c;if(!s&&c===`app`)return W(e?`open --relaunch requires an app name or an active session app.`:`Session already active. Close it first or pass a new --session name.`);let l=wa({shouldRelaunch:e,openTarget:s,surface:c,device:a.device});if(l)return l;let u=await oi(a.device),d=await Ea({req:t,sessionName:n,sessionStore:i,device:u,surface:c,openTarget:s,existingSession:a,onIosSimulatorColdBootStart:Or({req:t,logPath:r,device:u,surface:c,openTarget:s,traceLogPath:a.trace?.outPath})});return d.type===`response`?d.response:await Na({req:t,sessionName:n,sessionStore:i,logPath:r,device:u,openTarget:s,openPositionals:o?t.positionals??[]:s?[s]:[],appBundleId:d.details.appBundleId,appName:d.details.appName,runtime:d.details.runtime,surface:c,existingSession:a})}let o=t.flags?.relaunch===!0,s=t.positionals?.[0];if(o&&!s)return W(`open --relaunch requires an app argument.`);let c=Ta({shouldRelaunch:o,openTarget:s,platform:t.flags?.platform===`android`?`android`:void 0});if(c)return c;let l=await kn(t.flags??{}),u=Ca(l,t.flags?.surface,s);return typeof u==`string`?wa({shouldRelaunch:o,openTarget:s,surface:u,device:l})||await gt(Oa,l.id,async()=>{let e=i.toArray().find(e=>e.device.id===l.id);if(e)return Hn(t,e)?E(`DEVICE_IN_USE`,`Device is already in use by another workspace session.`,{deviceId:l.id,deviceName:l.name,hint:`Use a different device selector, wait for the other workspace to close its session, or run agent-device devices to choose another target.`}):E(`DEVICE_IN_USE`,`Device is already in use by session "${e.name}".`,{session:e.name,deviceId:l.id,deviceName:l.name,hint:er(e,`device-in-use`)});let a=await Ea({req:t,sessionName:n,sessionStore:i,device:l,surface:u,openTarget:s,onIosSimulatorColdBootStart:Or({req:t,logPath:r,device:l,surface:u,openTarget:s})});return a.type===`response`?a.response:await Na({req:t,sessionName:n,sessionStore:i,logPath:r,device:l,openTarget:s,openPositionals:t.positionals??[],appBundleId:a.details.appBundleId,appName:a.details.appName,runtime:a.details.runtime,surface:u})}):u}function Ia(e){return V(e)||ri(e)}async function La(t){if(t.booted===!1)return{success:!0,exitCode:0,stdout:``,stderr:``};try{return V(t)?await Ra(t):await Ba(t)}catch(t){let n=e(t);return{success:!1,exitCode:-1,stdout:``,stderr:n.message,error:n}}}async function Ra(e){let t=await Mr(e);return t.success?t:await za(e)===`Shutdown`?{...t,success:!0,exitCode:0}:t}async function za(e){try{return await Nr(e)}catch{return null}}async function Ba(e){let t=await rt(e,[`emu`,`kill`],{allowFailure:!0,timeoutMs:15e3});return{success:t.exitCode===0,exitCode:t.exitCode,stdout:t.stdout,stderr:t.stderr}}async function Va(e){let{device:t,shutdownRequested:n}=e;if(n&&Ia(t))return await La(t)}function Ha(e,t){return V(t.device)&&!e.flags?.shutdown&&!t.recording&&!t.lease&&!t.device.simulatorSetPath}function Ua(e){return a(e.device.platform)&&!V(e.device)}async function Wa(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,leaseRegistry:o,leaseLifecycleProvider:s}=e,c=i.get(n);if(!c)return await qa(t,r);let l;try{await rn(c),await ln(c,`session-close`),await Ln(c),await Un(c),await Cn(c),Ga(t,c)&&(Ua(c)&&await Pn(c),await D(c.device,`close`,t.positionals??[],t.flags?.out,{...j(r,t.flags,c.appBundleId,c.trace?.outPath)}),await ai(c.device,300)),a(c.device.platform)&&!Ha(t,c)?await Pn(c):a(c.device.platform)&&(h({level:`debug`,phase:`ios_runner_retained_after_close`,data:{session:c.name,deviceId:c.device.id}}),vt(c.device.id)),gi(i.getRuntimeHints(n))&&c.appBundleId&&await vi({device:c.device,appId:c.appBundleId}).catch(()=>{}),Ar(i,c,t,`close`,{session:c.name,...Se(`Closed: ${c.name}`)}),t.flags?.saveScript&&(c.recordSession=!0),i.writeSessionLog(c),await Yn(n).catch(()=>{})}finally{try{l=await Zn({session:c,leaseRegistry:o,leaseLifecycleProvider:s})}finally{i.delete(n)}}let u=await Va({device:c.device,shutdownRequested:t.flags?.shutdown});return u?{ok:!0,data:le({session:c.name,shutdown:u,...l?{provider:l}:{}},`Closed: ${c.name}`)}:{ok:!0,data:{session:c.name,...Se(`Closed: ${c.name}`),...l?{provider:l}:{}}}}function Ga(e,t){return Ka(e)||t.device.platform===`web`}function Ka(e){return(e.positionals?.length??0)>0}async function qa(e,t){if(!e.positionals||e.positionals.length===0)return E(`SESSION_NOT_FOUND`,`No active session`);let n=await U({session:void 0,flags:e.flags,ensureReady:!0});return await D(n,`close`,e.positionals,e.flags?.out,{...j(t,e.flags)}),await ai(n,300),{ok:!0,data:{app:e.positionals[0],...Se(`Closed: ${e.positionals[0]}`)}}}const Ja={ios:async(e,t,n)=>{let r=await Mn(e,t,n,{relaunch:!0,appIdentifierHint:t});if(r)return{bundleId:r.bundleId??r.launchTarget??t};let{reinstallIosApp:i}=await import(`./apps.js`).then(e=>e.t);return await i(e,t,n)},android:async(e,t,n)=>{let r=await Mn(e,t,n,{relaunch:!0,packageNameHint:t});if(r)return{package:r.packageName??r.launchTarget??t};let{reinstallAndroidApp:i}=await import(`./app-lifecycle.js`).then(e=>e.t);return await i(e,t,n)}},Ya={ios:async(e,t,n)=>{let r=await Mn(e,t,n,{appIdentifierHint:t});if(r)return{bundleId:r.bundleId,appName:r.appName,launchTarget:r.launchTarget};let{installIosApp:i}=await import(`./apps.js`).then(e=>e.t),a=await i(e,n,{appIdentifierHint:t});return{bundleId:a.bundleId,appName:a.appName,launchTarget:a.launchTarget}},android:async(e,t,n)=>{let r=await Mn(e,t,n,{packageNameHint:t});if(r)return{package:r.packageName,appName:r.appName,launchTarget:r.launchTarget};let{installAndroidApp:i}=await import(`./app-lifecycle.js`).then(e=>e.t),a=await i(e,n);return{package:a.packageName,appName:a.appName,launchTarget:a.launchTarget}}};async function Xa(e){let{req:t,command:n,sessionName:r,sessionStore:i,deployOps:a}=e,o=i.get(r),s=t.flags??{},l=H(n,o,s);if(l)return l;let u=eo(n,t.positionals??[]);if(!u.ok)return u.response;let{app:d,appPathInput:f}=u,p=t.meta?.uploadedArtifactId;try{let e=p?cn(p,t.meta?.tenantId):A.expandHome(f);if(!z.existsSync(e))return E(`INVALID_ARGS`,`App binary not found: ${e}`);let r=await U({session:o,flags:s,ensureReady:!1}),l=k(n,r);if(l)return l;let u=c(r)?Qa(d,e,await a.ios(r,d,e)):$a(d,e,await a.android(r,d,e)),m=le(u,Za(u));return Ar(i,o,t,n,m),{ok:!0,data:m}}finally{p&&$n(p)}}function Za(e){return`Installed: ${e.appName??ve(e)}`}function Qa(e,t,n){let r=n.bundleId;return{app:e||r||n.launchTarget||t,appPath:t,platform:`ios`,...r?{appId:r,bundleId:r}:{},appName:n.appName,launchTarget:n.launchTarget}}function $a(e,t,n){let r=n.package;return{app:e||r||n.launchTarget||t,appPath:t,platform:`android`,...r?{appId:r,package:r,packageName:r}:{},appName:n.appName,launchTarget:n.launchTarget}}function eo(e,t){let n=t[0]?.trim(),r=t[1]?.trim();if(e===`install`){let e=r??n;return e?{ok:!0,app:r?n??``:``,appPathInput:e}:{ok:!1,response:E(`INVALID_ARGS`,`install requires: install <path-to-app-binary>`)}}return!n||!r?{ok:!1,response:E(`INVALID_ARGS`,`reinstall requires: reinstall <app> <path-to-app-binary>`)}:{ok:!0,app:n,appPathInput:r}}async function to(e,t,n){return await Le(e,t,n)}async function no(e){let{req:t,sessionName:o,sessionStore:c}=e;if(t.command===`session_list`){let e=Nn(t);return{ok:!0,data:{sessions:c.toArray().filter(t=>yn(t,e)).map(e=>{let t=c.resolveSessionDir(e.name);return{name:e.name,sessionStateDir:t,runnerLogPath:Nt(t),platform:i(e.device),...a(e.device.platform)&&e.device.appleOs?{appleOs:e.device.appleOs}:{},target:e.device.target??`mobile`,surface:e.surface??`app`,device:e.device.name,id:e.device.id,device_id:e.device.id,createdAt:e.createdAt,...a(e.device.platform)&&!s(e.device)&&{device_udid:e.device.id,ios_simulator_device_set:e.device.simulatorSetPath??null}}})}}}if(t.command===`devices`)try{let e=tt(t.flags?.androidDeviceAllowlist),n=t.flags?.platform,i=r({simulatorSetPath:at(t.flags?.iosSimulatorDeviceSet),platform:n,target:t.flags?.target}),a=await un({platform:n,target:t.flags?.target,deviceName:t.flags?.device,udid:t.flags?.udid,serial:t.flags?.serial,iosSimulatorSetPath:i,androidSerialAllowlist:e?Array.from(e).sort():void 0}),o=n?a.filter(e=>io(e,n)):a;return{ok:!0,data:{devices:(t.flags?.target?o.filter(e=>(e.target??`mobile`)===t.flags?.target):o).map(ro)}}}catch(e){let t=n(e);return E(t.code,t.message,t.details)}if(t.command===`capabilities`){let e=c.get(o),n=t.flags??{},r=H(t.command,e,n);if(r)return r;let i=await U({session:e,flags:n,ensureReady:!1,allowStoppedAndroidAvdPlaceholders:!0});return{ok:!0,data:{device:ro(i),availableCommands:Wn().filter(e=>Fn(e,i))}}}if(t.command===`apps`){let e=c.get(o),n=t.flags??{},r=H(t.command,e,n);if(r)return r;let i=await U({session:e,flags:n,ensureReady:!0}),s=k(`apps`,i);if(s)return s;let l=Ke(t.flags?.appsFilter);return a(i.platform)?{ok:!0,data:{apps:(await jr(i,l)).map(e=>e.name&&e.name!==e.bundleId?`${e.name} (${e.bundleId})`:e.bundleId)}}:{ok:!0,data:{apps:(await Ze(i,l)).map(e=>e.name&&e.name!==e.package?`${e.name} (${e.package})`:e.package)}}}return null}function ro({simulatorSetPath:e,appleOs:t,...n}){return{...n,platform:i({platform:n.platform,appleOs:t}),...a(n.platform)&&t?{appleOs:t}:{}}}function io(e,t){return d(e,t)}async function ao(e){let{ensureAndroidEmulatorBooted:t}=await import(`./android-input-ownership.js`).then(e=>e.m);return await t(e)}const oo=`iOS appstate requires an active session on the target device. Run open first (for example: open --session sim --platform ios --device "<name>" <app>).`,so=`macOS appstate requires an active session on the target device. Run open first (for example: open --session macos --platform macos "System Settings").`;async function co(e){let{req:t,sessionName:n,sessionStore:r}=e,o=r.get(n),l=t.flags??{},u=l.platform;if(!o&&ii(l))return E(`SESSION_NOT_FOUND`,u===`ios`?`No active session "${n}". Run open with --session ${n} first.`:`No active session "${n}". Run open with --session ${n} first, or omit --session to query by device selector.`);let d=H(`appstate`,o,l);if(d)return d;let f=a(o?.device.platform)&&ci(l,o),p=u===`ios`,m=u===`macos`;if(p&&!f)return E(`SESSION_NOT_FOUND`,oo);if(m&&!f)return E(`SESSION_NOT_FOUND`,so);if(f&&o){let e=o.appName??o.appBundleId;return!o.appName&&!o.appBundleId?s(o.device)&&o.surface&&o.surface!==`app`&&o.surface!==`frontmost-app`?{ok:!0,data:{platform:i(o.device),appName:o.surface,appBundleId:o.appBundleId,source:`session`,surface:o.surface}}:E(`COMMAND_FAILED`,`No foreground app is tracked for this ${s(o.device)?`macOS`:`iOS`} session. Open an app in the session, then retry appstate.`):{ok:!0,data:{platform:i(o.device),appName:e??`unknown`,appBundleId:o.appBundleId,source:`session`,surface:o.surface??`app`,...c(o.device)?{device_udid:o.device.id,ios_simulator_device_set:o.device.simulatorSetPath??null}:{}}}}let h=await U({session:o,flags:l,ensureReady:!0});if(c(h))return E(`SESSION_NOT_FOUND`,oo);if(s(h))return E(`SESSION_NOT_FOUND`,so);if(h.platform===`web`)return E(`UNSUPPORTED_OPERATION`,`appstate is not supported on web.`);let{getAndroidAppState:g}=await import(`./app-lifecycle.js`).then(e=>e.t),_=await g(h);return{ok:!0,data:{platform:`android`,package:_.package,activity:_.activity}}}async function lo(e){let{req:t,sessionName:r,logPath:o,sessionStore:s}=e;if(t.command===`boot`){let e=s.get(r),l=t.flags??{},u=H(t.command,e,l);if(u)return u;let d=(l.platform??e?.device.platform)===`android`,f=l.headless===!0;if(f&&!d)return E(`INVALID_ARGS`,`boot --headless is supported only for Android emulators.`);let p=si({flags:l,sessionDevice:e?.device}),m=d&&!!p,h,g=!1;try{h=await U({session:e,flags:l,ensureReady:!1,allowStoppedAndroidAvdPlaceholders:!0})}catch(e){let t=n(e);if(d&&f&&!p&&t.code===`DEVICE_NOT_FOUND`)return E(`INVALID_ARGS`,`boot --headless requires --device <avd-name> (or an Android emulator session target).`);if(!m||t.code!==`DEVICE_NOT_FOUND`||!p)throw e;h=await ao({avdName:p,serial:l.serial,headless:f}),g=!0}if(l.target&&(h.target??`mobile`)!==l.target)return E(`DEVICE_NOT_FOUND`,`No ${h.platform} device found matching --target ${l.target}.`);if(d&&f){if(h.platform!==`android`||h.kind!==`emulator`)return E(`INVALID_ARGS`,`boot --headless is supported only for Android emulators.`);if(!g){let t=si({flags:l,sessionDevice:e?.device,resolvedDevice:h});if(!t)return E(`INVALID_ARGS`,`boot --headless requires --device <avd-name> (or an Android emulator session target).`);h=await ao({avdName:t,serial:l.serial,headless:!0})}await R(h)}else h.platform===`android`&&h.kind===`emulator`&&h.booted!==!0?(h=await ao({avdName:h.name,serial:l.serial,headless:!1}),await R(h)):(h.platform!==`android`||h.booted!==!0)&&await R(h,{onIosSimulatorColdBootStart:Er({req:t,logPath:o,device:h,enabled:!0})});return k(`boot`,h)||(c(h)&&h.kind===`simulator`&&mt(h,{}),{ok:!0,data:{platform:i(h),target:h.target??`mobile`,device:h.name,id:h.id,kind:h.kind,booted:!0,...a(h.platform)&&h.appleOs?{appleOs:h.appleOs}:{}}})}if(t.command===`shutdown`){let e=s.get(r),n=t.flags??{},o=H(t.command,e,n);if(o)return o;let c=await U({ensureReady:!1,flags:n,session:e}),l=k(`shutdown`,c,{message:`shutdown is supported only for Apple simulators and Android emulators.`});if(l)return l;if(e&&e.device.platform===c.platform&&e.device.id===c.id)return E(`DEVICE_IN_USE`,`Cannot shut down an active session device directly. Use close --shutdown to end the session and turn off the simulator/emulator.`,{hint:`Run agent-device close --shutdown --session ${r}`,session:r,platform:i(c),target:c.target??`mobile`,device:c.name,id:c.id,kind:c.kind});let u=await La(c);return u.success?{ok:!0,data:{platform:i(c),target:c.target??`mobile`,device:c.name,id:c.id,kind:c.kind,shutdown:u,...a(c.platform)&&c.appleOs?{appleOs:c.appleOs}:{}}}:E(u.error?.code??`COMMAND_FAILED`,uo(u),{platform:i(c),target:c.target??`mobile`,device:c.name,id:c.id,kind:c.kind,shutdown:u})}return t.command===`appstate`?await co({req:t,sessionName:r,sessionStore:s}):null}function uo(e){let t=e.error?.message??e.stderr.trim();return t.length>0?t:`Shutdown failed`}wn();function fo(e){let t=[];for(let n of e){if(n.command!==`open`)continue;let e=n.result?.startup;if(!e||typeof e!=`object`)continue;let r=e;typeof r.durationMs!=`number`||!Number.isFinite(r.durationMs)||typeof r.measuredAt!=`string`||r.measuredAt.trim().length===0||r.method!==`open-command-roundtrip`||t.push({durationMs:Math.max(0,Math.round(r.durationMs)),measuredAt:r.measuredAt,method:ca,appTarget:typeof r.appTarget==`string`&&r.appTarget.length>0?r.appTarget:void 0,appBundleId:typeof r.appBundleId==`string`&&r.appBundleId.length>0?r.appBundleId:void 0})}return t.slice(-20)}async function po(e,t={}){let n=go(e);return Eo(e)?e.appBundleId?e.device.platform===`android`?(await So(n,e,e.appBundleId,t),n):(await Co(n,e,e.appBundleId),n):(xo(n,e),n):n}async function mo(e,t={}){let n=yo(e);return Eo(e)?e.appBundleId?(await To(n,e,e.appBundleId,t),n):(n.metrics.fps={available:!1,reason:Do(e)},n):n}async function ho(e,t){let n=bo(e);return Eo(e)?t.action===`sample`?(n.metrics={memory:await Po(e,t)},n):(n.artifact=await Io(e,t),n.support=Ho(n.artifact.support)??Vo(e),n):t.action===`snapshot`?(n.artifact=zo(e,Lo(e,t.kind)),n.support=Ho(n.artifact.support)??Vo(e),n):(n.metrics={memory:{available:!1,reason:la}},n)}function go(e){let t=fo(e.actions),n=t.at(-1),r=n?{available:!0,lastDurationMs:n.durationMs,lastMeasuredAt:n.measuredAt,method:ca,sampleCount:t.length,samples:t}:{available:!1,reason:`No startup sample captured yet. Run open <app|url> in this session first.`,method:ca};return{session:e.name,platform:i(e.device),device:e.device.name,deviceId:e.device.id,metrics:{startup:r,..._o()},sampling:{startup:{method:ca,description:`Elapsed wall-clock time around dispatching the open command for the active session app target.`,unit:`ms`},...Oo(e)}}}function _o(){return{fps:vo(),memory:{available:!1,reason:la},cpu:{available:!1,reason:la}}}function vo(){return{available:!1,reason:`Dropped-frame sampling is currently available only on Android app sessions and connected iOS device app sessions.`}}function yo(e){return{session:e.name,platform:i(e.device),device:e.device.name,deviceId:e.device.id,metrics:{fps:vo()},sampling:{fps:jo(e)}}}function bo(e){return{session:e.name,platform:i(e.device),device:e.device.name,deviceId:e.device.id,sampling:{memory:ko(e),snapshot:Ao(e)}}}function xo(e,t){let n=Do(t);e.metrics.fps={available:!1,reason:n},e.metrics.memory={available:!1,reason:n},e.metrics.cpu={available:!1,reason:n}}async function So(e,t,n,r){wo(e,t,await Mo(t,n,r))}async function Co(e,t,n){wo(e,t,await No(t,n))}function wo(e,t,n){e.metrics.memory=Wo(n.memory),e.metrics.cpu=Wo(n.cpu),e.metrics.fps=Go(Wo(n.fps),t)}async function To(e,t,n,r){let i=t.device.platform===`android`?await Uo(Pt(t.device,n,{adb:r.androidAdb})):await Uo(ar(t.device,n));e.metrics.fps=Go(Wo(i),t)}function Eo(e){return Rn(e.device.platform)?.perf?.supportsMetrics(e.device)??!1}function Do(e){return e.device.platform===`android`?`No Android app package is associated with this session. Run open <app> first.`:`No Apple app bundle ID is associated with this session. Run open <app> first.`}function Oo(e){return e.device.platform===`android`?{memory:{method:en,description:_n,unit:`kB`},cpu:{method:Bn,description:hn,unit:`percent`},fps:{method:Dn,description:Wt,unit:`percent`,primaryField:`droppedFramePercent`,window:`since previous Android gfxinfo reset or app process start`,resetsAfterRead:!0,relatedActionsLimit:12}}:zt(e.device)}function ko(e){return e.device.platform===`android`?{method:en,description:_n,unit:`kB`,topConsumerLimit:5}:zt(e.device).memory}function Ao(e){return e.device.platform===`android`?{method:bn,description:jn,defaultKind:`android-hprof`,artifactOnly:!0}:{method:Gt,description:Ht,defaultKind:`memgraph`,artifactOnly:!0}}function jo(e){return e.device.platform===`android`?{method:Dn,description:Wt,unit:`percent`,primaryField:`droppedFramePercent`,window:`since previous Android gfxinfo reset or app process start`,resetsAfterRead:!0,relatedActionsLimit:12}:It(e.device)}async function Mo(e,t,n){let r={adb:n.androidAdb},[i,a,o]=await Promise.allSettled([sn(e.device,t,r),ir(e.device,t,r),Pt(e.device,t,r)]);return{memory:i,cpu:a,fps:o}}async function No(e,t){let n=await Uo(ar(e.device,t)),r=await Uo(jt(e.device,t));if(r.status===`fulfilled`){let e=r.value;return{memory:{status:`fulfilled`,value:e.memory},cpu:{status:`fulfilled`,value:e.cpu},fps:n}}return{memory:{status:`rejected`,reason:r.reason},cpu:{status:`rejected`,reason:r.reason},fps:n}}async function Po(e,t){return e.appBundleId?Wo(e.device.platform===`android`?await Uo(sn(e.device,e.appBundleId,{adb:t.androidAdb})):await Uo(Fo(e))):{available:!1,reason:Do(e)}}async function Fo(e){if(!e.appBundleId)throw new t(`INVALID_ARGS`,Do(e));return(await jt(e.device,e.appBundleId)).memory}async function Io(e,n){if(!e.appBundleId)throw new t(`INVALID_ARGS`,Do(e),{hint:`Run open <app> first so perf memory snapshot can resolve the app process.`});let r=Lo(e,n.kind),i=Ro(n,r);return e.device.platform===`android`?r===`android-hprof`?await Qn(e.device,e.appBundleId,i,{adb:n.androidAdb}):zo(e,r):r===`memgraph`?await Kt(e.device,e.appBundleId,i):zo(e,r)}function Lo(e,t){return t||(e.device.platform===`android`?`android-hprof`:`memgraph`)}function Ro(e,t){if(e.out)return A.expandHome(e.out,e.cwd);let n=t===`android-hprof`?`hprof`:t===`memgraph`?`memgraph`:`artifact`,r=new Date().toISOString().replace(/[:.]/g,`-`),i=e.sessionStore.ensureSessionDir(e.sessionName);return B.join(i,`artifacts`,`memory-${t}-${r}.${n}`)}function zo(e,t){let n=Vo(e),r=Bo(e,t);return{available:!1,kind:t,reason:r.reason,hint:r.hint,support:n}}function Bo(e,t){return e.device.platform===`android`?{reason:`Android perf memory snapshot supports android-hprof, not ${t}.`,hint:`Use perf memory snapshot --kind android-hprof for Android Java heap artifacts.`}:a(e.device.platform)?{reason:`Apple perf memory snapshot supports memgraph, not ${t}.`,hint:`Use perf memory snapshot --kind memgraph for supported Apple app sessions.`}:{reason:`Memory snapshot artifacts are not supported on ${e.device.platform}.`,hint:`Use perf memory sample where supported, or run the snapshot against Android, iOS simulator, or macOS.`}}function Vo(e){return e.device.platform===`android`?{platform:e.device.platform,defaultKind:`android-hprof`,androidHprof:!0,memgraph:!1,heapprofd:!1,heapprofdDecision:`Deferred until Android Perfetto/heapprofd plumbing is available in the perf trace slice.`}:a(e.device.platform)?{...Lt(e.device),androidHprof:!1,heapprofd:!1,heapprofdDecision:`Deferred because heapprofd is Android/Perfetto-specific and outside this memory artifact slice.`}:{platform:e.device.platform,defaultKind:`memgraph`,androidHprof:!1,memgraph:!1,heapprofd:!1,reason:`Memory snapshot artifacts are available only on Android, iOS simulator, and macOS.`,hint:`Use perf memory sample where supported, or switch to a platform with memory artifact support.`,heapprofdDecision:`Deferred because heapprofd is Android/Perfetto-specific and outside this memory artifact slice.`}}function Ho(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:void 0}async function Uo(e){try{return{status:`fulfilled`,value:await e}}catch(e){return{status:`rejected`,reason:e}}}function Wo(t){if(t.status===`fulfilled`)return{available:!0,...t.value};let n=e(t.reason);return{available:!1,reason:n.message,error:n}}function Go(e,t){if(e.available!==!0)return e;let n=Ko(t.actions,e);return n.length===0?e:{...e,relatedActions:n}}function Ko(e,t){let n=qo(t.windowStartedAt),r=qo(t.windowEndedAt)??qo(t.measuredAt);return n===void 0||r===void 0?[]:e.filter(e=>e.ts>=n&&e.ts<=r).map(e=>({command:e.command,at:new Date(e.ts).toISOString(),offsetMs:Math.max(0,Math.round(e.ts-n)),target:Jo(e)})).slice(-12)}function qo(e){if(typeof e!=`string`)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function Jo(e){let t=e.result;if(t)for(let e of[`refLabel`,`ref`,`appName`,`appBundleId`]){let n=t[e];if(typeof n==`string`&&n.length>0)return n}}async function Yo(t){let n=Xo(t.req,t.area);if(!n.ok)return n;let{session:r}=t;if(r.device.platform!==`android`)return E(`UNSUPPORTED_OPERATION`,`Android native perf collectors are supported only on Android sessions.`);if(!r.appBundleId)return E(`COMMAND_FAILED`,`No Android app package is associated with this session.`,{hint:`Run open <app> first so perf can resolve the package and process identity.`});try{return{ok:!0,data:n.area===`cpu`?await as(t,r,r.appBundleId,n):await os(t,r,r.appBundleId,n)}}catch(t){return{ok:!1,error:e(t)}}}function Xo(e,t){let n=is(e,t);return t===`cpu`?Zo(e,n):Qo(e,n)}function Zo(e,t){let n=$o(e,1),r=$o(e,2),i=$o(e,3);return de(n)?es(r)?i===`simpleperf`?{ok:!0,area:`cpu`,subject:n,action:r,kind:i,outPath:t}:E(`INVALID_ARGS`,`perf cpu profile requires --kind simpleperf`):E(`INVALID_ARGS`,`perf cpu profile action must be start, stop, or report`):E(`INVALID_ARGS`,ue)}function Qo(e,t){let n=$o(e,1),r=$o(e,2);return ts(n)?be(r)?r===`perfetto`?{ok:!0,area:`trace`,action:n,kind:r,outPath:t}:E(`INVALID_ARGS`,`perf trace requires --kind perfetto`):E(`INVALID_ARGS`,S):E(`INVALID_ARGS`,`perf trace action must be start or stop`)}function $o(e,t){return(e.positionals?.[t]??``).toLowerCase()}function es(e){return e===`start`||e===`stop`||e===`report`}function ts(e){return e===`start`||e===`stop`}function ns(e,t){return e.sessionStore.set(e.sessionName,{...e.session,nativePerf:{android:t}}),ds(t)}function rs(e,t,n){return t?A.expandHome(t,e.req.meta?.cwd):us(e.sessionStore,e.sessionName,n)}function is(e,t){return typeof e.flags?.out==`string`&&e.flags.out.length>0?e.flags.out:(e.positionals??[])[t===`cpu`?5:4]||void 0}async function as(e,t,n,r){if(r.action===`start`){cs(t);let i=rs(e,r.outPath,`cpu.perf.data`);return ns(e,await rr(t.device,n,i,{adb:e.androidAdbExecutor}))}let i=fs(t,`cpu-profile`,r.kind);if(r.action===`report`){await ss(i);let n=rs(e,r.outPath,`cpu-report.json`);return await Mt(t.device,i,n,{adb:e.androidAdbExecutor})}let a=ls(e,r.outPath,i);return ns(e,await qt(t.device,i,a,{adb:e.androidAdbExecutor}))}async function os(e,t,n,r){if(r.action===`start`){cs(t);let i=rs(e,r.outPath,`app.perfetto-trace`);return ns(e,await tr(t.device,n,i,{adb:e.androidAdbExecutor}))}let i=fs(t,`trace`,r.kind),a=ls(e,r.outPath,i);return ns(e,await Yt(t.device,i,a,{adb:e.androidAdbExecutor}))}function ss(e){if(e.state===`running`)throw new t(`COMMAND_FAILED`,`Stop the Android Simpleperf CPU profile before generating a report.`,{hint:`Run perf cpu profile stop --kind simpleperf, then retry perf cpu profile report --kind simpleperf.`})}function cs(e){let n=e.nativePerf?.android;if(n?.state===`running`)throw new t(`COMMAND_FAILED`,`Android ${n.kind} ${n.type} is already running for this session.`,{hint:n.type===`cpu-profile`?`Run perf cpu profile stop --kind simpleperf before starting another Android native perf capture.`:`Run perf trace stop --kind perfetto before starting another Android native perf capture.`})}function ls(e,t,n){return t?rs(e,t,n.outPath):n.outPath}function us(e,t,n){let r=new Date().toISOString().replace(/[:.]/g,`-`);return B.join(e.ensureSessionDir(t),`${r}-${n}`)}function ds(e){return{action:e.action,platform:`android`,type:e.type,kind:e.kind,packageName:e.packageName,appPid:e.appPid,profilerPid:e.profilerPid,state:e.state,startedAt:new Date(e.startedAt).toISOString(),stoppedAt:typeof e.stoppedAt==`number`?new Date(e.stoppedAt).toISOString():void 0,durationMs:e.durationMs,outPath:e.outPath,sizeBytes:e.sizeBytes,remotePath:e.remotePath,method:e.method,summary:e.summary,message:e.message}}function fs(e,n,r){let i=e.nativePerf?.android;if(i?.type===n&&i.kind===r)return i;throw new t(`COMMAND_FAILED`,`No Android ${r} ${n} is active for this session.`,{hint:n===`cpu-profile`?`Run perf cpu profile start --kind simpleperf first, then stop or report in the same session.`:`Run perf trace start --kind perfetto first, then stop in the same session.`})}async function ps(e){if(!an(e))return;let{macOsScreenCaptureKitAudioProbeBackend:t}=await import(`./audio-probe.js`);return t}const ms=[`probe`],hs=[`start`,`status`,`stop`],gs=`audio probe requires ${hs.join(`, `)}`;async function _s(t){let n=vs(t);if(!n.ok)return n;let r=await ps(n.session.device);if(r)return await bs(t,n,r);let i=Tr();if(!i.probeAudio)return E(`UNSUPPORTED_OPERATION`,`audio is not supported by this web provider`);try{return{ok:!0,data:await i.probeAudio({action:n.probeAction,durationMs:n.durationMs,bucketMs:n.bucketMs})}}catch(t){return{ok:!1,error:e(t)}}}function vs(e){let t=ys(e);if(!t.ok)return t;let n=xs(e.req);if(!n.ok)return n;let r=Ss(e.req,n.probeAction);return r.ok?{ok:!0,session:t.session,probeAction:n.probeAction,...r.timing}:r}function ys(e){let t=e.sessionStore.get(e.sessionName);return t?Fn(`audio`,t.device)?{ok:!0,session:t}:E(`UNSUPPORTED_OPERATION`,`audio is supported for web browser sessions, macOS sessions, iOS simulators, and Android emulators on macOS hosts`):E(`SESSION_NOT_FOUND`,`audio requires an active session`)}async function bs(t,n,r){try{return{ok:!0,data:await Kn({session:n.session,sessionName:t.sessionName,sessionStore:t.sessionStore,backend:r,probeAction:n.probeAction,durationMs:n.durationMs,bucketMs:n.bucketMs})}}catch(t){return{ok:!1,error:e(t)}}}function xs(e){if(!Cs(e.positionals?.[0]))return E(`INVALID_ARGS`,`audio requires probe`);let t=ws(e.positionals?.[1]);return t?{ok:!0,probeAction:t}:E(`INVALID_ARGS`,gs)}function Ss(e,t){if(t!==`start`&&e.positionals&&e.positionals.length>2)return E(`INVALID_ARGS`,`audio probe duration and bucket are only supported with audio probe start`);let n=Ts(e.positionals?.[2],{defaultValue:1e4,min:100,max:12e4,message:`audio probe duration must be an integer in range 100..120000 ms`});if(n instanceof Error)return E(`INVALID_ARGS`,n.message);let r=Ts(e.positionals?.[3],{defaultValue:1e3,min:100,max:1e4,message:`audio probe bucket must be an integer in range 100..10000 ms`});return r instanceof Error?E(`INVALID_ARGS`,r.message):{ok:!0,timing:{durationMs:n,bucketMs:r}}}function Cs(e){let t=(e??`probe`).toLowerCase();return ms.includes(t)?`probe`:void 0}function ws(e){let t=(e??`status`).toLowerCase();return hs.includes(t)?t:void 0}function Ts(e,t){if(e===void 0)return t.defaultValue;let n=Number.parseInt(e,10);return!Number.isInteger(n)||String(n)!==e||n<t.min||n>t.max?Error(t.message):n}async function Es(t,n){let r=Ds(t.req);if(!r.ok)return r;if(n.device.platform===`android`)return E(`UNSUPPORTED_OPERATION`,`Android native profiling belongs to the Android perf rollout; Apple xctrace perf supports iOS and macOS sessions only.`);if(!a(n.device.platform))return E(`UNSUPPORTED_OPERATION`,`Apple xctrace perf is not supported on ${n.device.platform}.`);if(!n.appBundleId)return E(`INVALID_ARGS`,`Apple xctrace perf requires an active app session. Run open <app> first.`);try{return r.action===`start`?await Ms(t,n,r):r.action===`stop`?await Ns(t,n,r):await Rs(t,n,r)}catch(t){return{ok:!1,error:e(t)}}}function Ds(e){let t=e.positionals??[],n=t[0]?.toLowerCase();return n===`cpu`?Os(t):n===`trace`?ks(t):E(`INVALID_ARGS`,ce)}function Os(e){if(e[1]?.toLowerCase()!==`profile`)return E(`INVALID_ARGS`,`perf cpu requires profile`);let t=As(e[2],`perf cpu profile`,!0);if(!t.ok)return t;let n=js(e[3]);return n.ok?{ok:!0,area:`cpu`,mode:`cpu-profile`,action:t.value,kind:`xctrace`,template:e[4]||void 0,outPath:e[5]||void 0,tracePath:e[6]||void 0}:n}function ks(e){let t=As(e[1],`perf trace`,!1);if(!t.ok)return t;let n=js(e[2]);return n.ok?{ok:!0,area:`trace`,mode:`trace`,action:t.value,kind:`xctrace`,template:e[3]||void 0,outPath:e[4]||void 0,tracePath:e[5]||void 0}:n}function As(e,t,n){let r=e?.toLowerCase();return r===`start`||r===`stop`||n&&r===`report`?{ok:!0,value:r}:E(`INVALID_ARGS`,n?`${t} requires start, stop, or report`:`${t} requires start or stop`)}function js(e){return e?.toLowerCase()===`xctrace`?{ok:!0}:E(`INVALID_ARGS`,`perf native collection currently supports --kind xctrace`)}async function Ms(e,t,n){if(t.applePerf?.active)return E(`INVALID_ARGS`,`Apple xctrace perf capture already in progress`);let r=n.template??Hs(n.mode),i=Vs(e,n),a=await At({device:t.device,appBundleId:t.appBundleId,mode:n.mode,template:r,outPath:i});t.applePerf={...t.applePerf??{},active:a},e.sessionStore.set(e.sessionName,t);let o=Us(`started`,a);return Bs(e,t,o),{ok:!0,data:o}}async function Ns(e,t,n){let r=t.applePerf?.active;if(!r)return E(`INVALID_ARGS`,`no active Apple xctrace perf capture`);let i=n.outPath?A.expandHome(n.outPath,e.req.meta?.cwd):r.outPath,a;try{a=await En(r,i)}catch(n){throw Fs(n)&&Ps(e,t),n}Is(e,t,a);let o=Us(`stopped`,a);return Bs(e,t,o),{ok:!0,data:o}}function Ps(e,t){t.applePerf={...t.applePerf??{},active:void 0},e.sessionStore.set(e.sessionName,t)}function Fs(e){return n(e).details?.captureCleanedUp===!0}function Is(e,t,n){t.applePerf={...t.applePerf??{},active:void 0,lastMode:n.mode,...Ls(n)},e.sessionStore.set(e.sessionName,t)}function Ls(e){return e.mode===`cpu-profile`?{lastProfileTracePath:e.outPath,lastProfileTemplate:e.template}:{lastTracePath:e.outPath}}async function Rs(e,t,n){if(n.mode!==`cpu-profile`)return E(`INVALID_ARGS`,`perf trace does not support report`);if(t.applePerf?.active)return E(`INVALID_ARGS`,`perf cpu profile report requires a stopped profile trace; stop the active capture first.`);let r=Vs(e,n),i=zs(t,n);if(!i.ok)return i;let a={perf:`reported`,...await Bt({tracePath:A.expandHome(i.value,e.req.meta?.cwd),outPath:r,mode:n.mode,template:t.applePerf?.lastProfileTemplate??n.template,appBundleId:t.appBundleId})};return Bs(e,t,a),{ok:!0,data:a}}function zs(e,t){let n=t.tracePath??e.applePerf?.lastProfileTracePath??e.applePerf?.active?.outPath;return n?{ok:!0,value:n}:E(`INVALID_ARGS`,`perf cpu profile report requires a stopped profile trace or tracePath option`)}function Bs(e,t,n){Ar(e.sessionStore,t,e.req,`perf`,n)}function Vs(e,t){if(t.outPath)return A.expandHome(t.outPath,e.req.meta?.cwd);let n=e.sessionStore.ensureSessionDir(e.sessionName),r=new Date().toISOString().replace(/[:.]/g,`-`),i=t.action===`report`?`json`:`trace`;return`${n}/perf-${t.mode}-${r}.${i}`}function Hs(e){return e===`cpu-profile`?`Time Profiler`:`Animation Hitches`}function Us(e,t){return{perf:e,kind:t.kind,mode:t.mode,template:t.template,outPath:t.outPath,appBundleId:t.appBundleId,deviceId:t.deviceId,platform:t.platform,targetPids:t.targetPids,targetProcesses:t.targetProcesses,startedAt:t.startedAt,endedAt:t.endedAt}}const Ws=`logs requires ${ge.slice(0,-1).join(`, `)}, or ${ge.at(-1)}`,Gs=[`dump`,`log`],Ks=`network requires ${Gs.join(` or `)}`,qs=`network include mode must be one of: ${l.join(`, `)}`,Js={path:({session:e,sessionName:t,sessionStore:n})=>bc(e,t,n),doctor:({session:e,sessionName:t,sessionStore:n})=>xc(e,t,n),mark:({req:e,sessionName:t,sessionStore:n})=>Sc(e,t,n),clear:({session:e,sessionName:t,sessionStore:n,restart:r})=>Cc(e,t,n,r),start:({session:e,sessionName:t,sessionStore:n})=>wc(e,t,n),stop:({session:e,sessionName:t,sessionStore:n})=>Tc(e,t,n)};function Ys(e){if(e.appLog){let t=e.appLog.getState();return{active:t===`active`||t===`recovering`,state:t,backend:e.appLog.backend,startedAt:e.appLog.startedAt,notes:Qs(t)}}return e.appLogFailure?{active:!1,state:`failed`,backend:e.appLogFailure.backend,failureCode:e.appLogFailure.code,failureMessage:e.appLogFailure.message,hint:e.appLogFailure.hint,notes:[Zs(e.appLogFailure)]}:{active:!1,state:`inactive`,backend:zn(e.device)}}function Xs(e,t){return{backend:t,code:e.code,message:e.message,hint:e.hint}}function Zs(e){return e.hint?`${e.message} ${e.hint}`:e.message}function Qs(e){if(e===`failed`)return[`The app log stream process exited with an error. Run logs doctor for backend diagnostics.`];if(e===`ended`)return[`The app log stream process ended. Run logs clear --restart before the next capture window.`]}function $s(e,t){return Xt([...e,...t.notes??[]])}function ec(e,t,n){return{...n,platform:e.device.platform,outPath:t}}function tc(t,n,r,i){let a=e(i);return t.set(n,{...r,appLog:void 0,appLogFailure:Xs(a,zn(r.device))}),{ok:!1,error:a}}async function nc(e){let{req:t}=e;return t.command===`perf`?ic(e):t.command===`logs`?vc(e):t.command===`events`?await rc(e):t.command===`network`?Ec(e):t.command===`audio`?await _s(e):null}async function rc(t){let{req:n,sessionName:r,sessionStore:i}=t;try{return await i.flushEvents(r),{ok:!0,data:i.readEvents(r,{limit:n.positionals?.[0],cursor:n.positionals?.[1]})}}catch(t){return{ok:!1,error:e(t)}}}async function ic(t){let{req:n,sessionName:r,sessionStore:i,androidAdbExecutor:a}=t,o=i.get(r);if(!o)return E(`SESSION_NOT_FOUND`,`perf requires an active session. Run open first.`);let s=(n.positionals?.[0]??`metrics`).toLowerCase();if(ac(s))return o.device.platform===`android`?await Yo({req:n,sessionName:r,sessionStore:i,session:o,androidAdbExecutor:a,area:s}):await Es(t,o);let c=oc(n);if(!c.ok)return c;if(c.native)return await Es(t,o);try{return{ok:!0,data:await sc(t,o,c)}}catch(t){return{ok:!1,error:e(t)}}}function ac(e){return e===`cpu`||e===`trace`}function oc(n){let r=cc(n.positionals?.[0]);if(!r)return E(`INVALID_ARGS`,ce);if(r===`cpu`||r===`trace`)return{ok:!0,native:!0};let i=lc(n.positionals?.[1]);if(!i)return E(`INVALID_ARGS`,re);let a=uc(n.flags?.kind);return a instanceof t?{ok:!1,error:e(a)}:(dc(r,i)??mc(n,r,i,a))||{ok:!0,native:!1,area:r,action:i,kind:a,out:_c(n.flags?.out)}}async function sc(e,t,n){let{sessionName:r,sessionStore:i,androidAdbExecutor:a}=e;return n.area===`memory`?await ho(t,{action:pc(n.action),kind:n.kind,out:n.out,cwd:e.req.meta?.cwd,sessionName:r,sessionStore:i,androidAdb:a}):n.area===`frames`?await mo(t,{androidAdb:a}):await po(t,{androidAdb:a})}function cc(e){let t=(e??`metrics`).toString().toLowerCase();return oe(t)?t:void 0}function lc(e){let t=(e??`sample`).toString().toLowerCase();return te(t)?t:void 0}function uc(e){if(e!==void 0)return typeof e!=`string`||!be(e)?new t(`INVALID_ARGS`,S):e}function dc(e,t){if(e===`memory`)return fc(t)?void 0:E(`INVALID_ARGS`,`perf memory requires sample or snapshot`);if(t!==`sample`)return E(`INVALID_ARGS`,`perf metrics and perf frames only support sample`)}function fc(e){return e===`sample`||e===`snapshot`}function pc(e){if(fc(e))return e;throw new t(`INVALID_ARGS`,`perf memory requires sample or snapshot`)}function mc(e,t,n,r){return hc(e.flags?.out,t,n)??gc(r,t,n)}function hc(e,t,n){if(!(!e||t===`memory`&&n===`snapshot`))return E(`INVALID_ARGS`,`--out is only supported with perf memory snapshot`)}function gc(e,t,n){if(e){if(t!==`memory`||n!==`snapshot`)return E(`INVALID_ARGS`,`--kind is only supported with perf memory snapshot`);if(!ae(e))return E(`INVALID_ARGS`,ne)}}function _c(e){return typeof e==`string`&&e.length>0?e:void 0}async function vc(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.get(n);if(!i)return E(`SESSION_NOT_FOUND`,`logs requires an active session`);let a=k(`logs`,i.device);if(a)return a;let o=yc(t);return o.ok?await Js[o.action]({...e,session:i,restart:o.restart}):o}function yc(e){let t=(e.positionals?.[0]??`path`).toLowerCase(),n=!!e.flags?.restart;return ge.includes(t)?n&&t!==`clear`?E(`INVALID_ARGS`,`logs --restart is only supported with logs clear`):{ok:!0,action:t,restart:n}:E(`INVALID_ARGS`,Ws)}function bc(e,t,n){let r=n.resolveAppLogPath(t),i=Tn(r),a=Ys(e);return{ok:!0,data:{path:r,active:a.active,state:a.state,backend:a.backend,sizeBytes:i.sizeBytes,modifiedAt:i.modifiedAt,startedAt:a.startedAt?new Date(a.startedAt).toISOString():void 0,failureCode:a.failureCode,failureMessage:a.failureMessage,hint:a.hint??`Grep the file for token-efficient debugging, e.g. grep -n "Error\\|Exception" <path>`,notes:a.notes}}}async function xc(e,t,n){let r=n.resolveAppLogPath(t),i=await An(e.device,e.appBundleId),a=Ys(e);return{ok:!0,data:{path:r,active:a.active,state:a.state,backend:a.backend,checks:i.checks,failureCode:a.failureCode,failureMessage:a.failureMessage,hint:a.hint,notes:$s(i.notes,a)}}}function Sc(e,t,n){let r=e.positionals?.slice(1).join(` `)??``,i=n.resolveAppLogPath(t);return In(i,r),{ok:!0,data:{path:i,marked:!0}}}async function Cc(e,t,n,r){if(e.appLog&&!r)return E(`INVALID_ARGS`,`logs clear requires logs to be stopped first; run logs stop`);let i=n.resolveAppLogPath(t);if(!r){let r=Gn(i);return n.set(t,{...e,appLogFailure:void 0}),{ok:!0,data:r}}let a=e.appBundleId;if(!a)return E(`INVALID_ARGS`,`logs clear --restart requires an app session; run open <app> first`);e.appLog&&await dn(e.appLog);let o=Gn(i),s=n.resolveAppLogPidPath(t);try{let r=await Jn(e.device,a,i,s);return n.set(t,{...e,appLog:ec(e,i,r),appLogFailure:void 0}),{ok:!0,data:{...o,restarted:!0}}}catch(r){return tc(n,t,e,r)}}async function wc(e,t,n){if(e.appLog)return E(`INVALID_ARGS`,`app log already streaming; run logs stop first`);if(!e.appBundleId)return E(`INVALID_ARGS`,`logs start requires an app session; run open <app> first`);let r=n.resolveAppLogPath(t),i=n.resolveAppLogPidPath(t);try{let a=await Jn(e.device,e.appBundleId,r,i);return n.set(t,{...e,appLog:ec(e,r,a),appLogFailure:void 0}),{ok:!0,data:{path:r,started:!0}}}catch(r){return tc(n,t,e,r)}}async function Tc(e,t,n){if(!e.appLog)return E(`INVALID_ARGS`,`no app log stream active`);let r=e.appLog.outPath;return await dn(e.appLog),n.set(t,{...e,appLog:void 0,appLogFailure:void 0}),{ok:!0,data:{path:r,stopped:!0}}}async function Ec(e){let t=Oc(e);if(!t.ok)return t;let{include:n,maxEntries:r,session:i}=t;if(i.device.platform===`web`)return await Dc({include:n,maxEntries:r});let a=await on({device:i.device,appBundleId:i.appBundleId,appLogState:i.appLog?.getState(),appLogStartedAt:i.appLog?.startedAt,appLogPath:e.sessionStore.resolveAppLogPath(e.sessionName),maxEntries:r,include:n,maxPayloadChars:2048,maxScanLines:4e3});return{ok:!0,data:{...a.dump,active:!!i.appLog,state:i.appLog?.getState()??`inactive`,backend:a.backend,notes:a.notes}}}async function Dc(t){let n=Tr();if(!n.dumpNetwork)return E(`UNSUPPORTED_OPERATION`,`network is not supported by this web provider`);try{let e=await n.dumpNetwork({include:t.include,limit:t.maxEntries});return{ok:!0,data:{entries:e.entries,active:!0,state:`active`,backend:e.backend??`agent-browser`,include:t.include,matchedLines:e.entries.length,scannedLines:e.entries.length,limits:{maxEntries:t.maxEntries,maxPayloadChars:2048,maxScanLines:e.entries.length},notes:e.notes}}}catch(t){return{ok:!1,error:e(t)}}}function Oc(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.get(n);if(!i)return E(`SESSION_NOT_FOUND`,`network requires an active session`);let a=k(`network`,i.device);if(a)return a;let o=(t.positionals?.[0]??`dump`).toLowerCase();if(!Gs.includes(o))return E(`INVALID_ARGS`,Ks);let s=t.positionals?.[1]?Number.parseInt(t.positionals[1],10):25;if(!Number.isInteger(s)||s<1||s>200)return E(`INVALID_ARGS`,`network dump limit must be an integer in range 1..200`);let c=kc(t);return c.ok?{ok:!0,session:i,maxEntries:s,include:c.include}:c}function kc(e){let t=e.positionals?.[2]?.toLowerCase(),n=e.flags?.networkInclude;if(t&&n&&t!==n)return E(`INVALID_ARGS`,`network include mode was provided both positionally and via --include with different values`);let r=(n??t??`summary`).toLowerCase();return l.includes(r)?{ok:!0,include:r}:E(`INVALID_ARGS`,qs)}function Ac(e){let{artifactsDir:t,cwd:n,suiteInvocationId:r}=e,i=A.expandHome(t??`.agent-device/test-artifacts`,n);return B.join(i,r)}function jc(e,t){let n=t?B.relative(t,e):B.basename(e);return(n.length===0||n.startsWith(`..`)?B.basename(e):n).toLowerCase().replace(/[\\/]+/g,`__`).replace(/[^a-z0-9._-]+/g,`-`).replace(/^-+|-+$/g,``)||`test`}function Mc(e,t){z.mkdirSync(t,{recursive:!0}),Ic(e,t)}function Nc(e){let{response:t,filePath:n,sessionName:r,attempts:i,maxAttempts:a,attemptArtifactsDir:o}=e,s=[...Pc(t)];!t.ok&&typeof t.error.logPath==`string`&&s.push(t.error.logPath);let c=Fc(s,o),l=[`file: ${n}`,`session: ${r}`,`attempt: ${i}/${a}`,`status: ${t.ok?`passed`:`failed`}`];if(t.ok){let e=typeof t.data?.replayed==`number`?t.data.replayed:0,n=typeof t.data?.healed==`number`?t.data.healed:0;l.push(`replayed: ${e}`,`healed: ${n}`)}else l.push(`code: ${t.error.code}`,`message: ${t.error.message}`),t.error.hint&&l.push(`hint: ${t.error.hint}`),t.error.diagnosticId&&l.push(`diagnosticId: ${t.error.diagnosticId}`),t.error.logPath&&l.push(`logPath: ${t.error.logPath}`),t.error.details?.reason===`timeout`&&l.push(`timeoutMode: cooperative`);c.length>0&&l.push(`copiedArtifacts: ${c.map(e=>B.basename(e)).join(`, `)}`);let u=B.join(o,`result.txt`),d=`${l.join(`
|
|
3
|
+
`)}\n`;z.writeFileSync(u,d),t.ok||z.writeFileSync(B.join(o,`failure.txt`),d)}function Pc(e){let t=e.ok?e.data?.artifactPaths:e.error.details?.artifactPaths;return Array.isArray(t)?[...new Set(t.filter(e=>typeof e==`string`))]:[]}function Fc(e,t){let n=[],r=new Map;for(let i of e){if(!zc(i))continue;let e=Rc(B.basename(i),r),a=B.join(t,e);B.resolve(i)!==B.resolve(a)&&z.copyFileSync(i,a),n.push(a)}return n}function Ic(e,t){let n=B.join(t,`replay.ad`);if(z.copyFileSync(e,n),!Lc(e))return;let r=B.join(t,B.basename(e));B.resolve(r)!==B.resolve(n)&&z.copyFileSync(e,r)}function Lc(e){let t=B.extname(e).toLowerCase();return t===`.yml`||t===`.yaml`}function Rc(e,t){let n=B.extname(e),r=n?e.slice(0,-n.length):e,i=t.get(e)??0;return t.set(e,i+1),i===0?e:`${r}-${i+1}${n}`}function zc(e){try{return z.statSync(e).isFile()}catch{return!1}}function Bc(e,n,r){if(e==null)return P(`open`,[I(pr(n,`launchApp`),r)]);if(typeof e==`string`)return P(`open`,[I(e,r)]);if(!F(e))throw new t(`INVALID_ARGS`,`launchApp expects a string or map.`);M(e,`launchApp`,[`appId`,`stopApp`,`clearState`,`clearKeychain`,`arguments`,`permissions`,`launchArguments`]),Gc(e,`permissions`),Gc(e,`clearKeychain`);let i=I(typeof e.appId==`string`?e.appId:pr(n,`launchApp`),r),a=Hc(e,r),o=e.clearState===!0,s=!o&&(e.stopApp===!0||a.length>0);return P(`open`,[i],{...s?{relaunch:!0}:{},...o?{clearAppState:!0}:{},...a.length>0?{launchArgs:a}:{}})}function Vc(e,n,r){if(e==null)return P(`close`,[I(pr(n,`stopApp`),r)]);if(typeof e==`string`)return P(`close`,[I(e,r)]);throw new t(`INVALID_ARGS`,`stopApp expects a string appId or no value.`)}function Hc(e,t){return[...Uc(e.arguments,`launchApp.arguments`,t),...Uc(e.launchArguments,`launchApp.launchArguments`,t)]}function Uc(e,n,r){if(e==null)return[];if(typeof e==`string`)return[I(e,r)];if(Array.isArray(e))return e.map((e,t)=>Wc(e,`${n}[${t}]`,r));if(F(e))return Object.entries(e).flatMap(([e,t])=>[I(e,r),Wc(t,`${n}.${e}`,r)]);throw new t(`INVALID_ARGS`,`${n} expects a string, list, or map.`)}function Wc(e,n,r){if(typeof e==`string`)return I(e,r);if(typeof e==`number`||typeof e==`boolean`)return String(e);throw new t(`INVALID_ARGS`,`${n} must be a string, number, or boolean.`)}function Gc(e,t){if(e[t]!==void 0)throw N(`Maestro launchApp field "${t}" is not supported yet.`)}const G={runScript:`__maestroRunScript`,assertVisible:`__maestroAssertVisible`,assertNotVisible:`__maestroAssertNotVisible`,pressEnter:`__maestroPressEnter`,waitForAnimationToEnd:`__maestroWaitForAnimationToEnd`,scrollUntilVisible:`__maestroScrollUntilVisible`,swipeScreen:`__maestroSwipeScreen`,swipeOn:`__maestroSwipeOn`,tapOn:`__maestroTapOn`,tapPointPercent:`__maestroTapPointPercent`};function Kc(e,t){if(typeof e==`string`)return P(G.tapOn,[ll(I(e,t))],ml(e));if(F(e)&&typeof e.point==`string`){M(e,`tapOn`,[`point`,`repeat`,`delay`,`optional`,`label`]);let t=yr(e.point);return t.kind===`percent`?P(G.tapPointPercent,[String(t.x),String(t.y)],pl(e)):P(`click`,[String(t.x),String(t.y)],pl(e))}F(e)&&M(e,`tapOn`,[`id`,`text`,`childOf`,`enabled`,`index`,`selected`,`repeat`,`delay`,`optional`,`label`]);let n=ml(e);return P(G.tapOn,[K(e,`tapOn`,[`repeat`,`delay`,`optional`,`label`,`index`,`childOf`],t),...ul(e,t)],n)}function qc(e,t){if(F(e)&&typeof e.point==`string`){M(e,`doubleTapOn`,[`point`,`delay`]);let t=vr(e.point);return P(`click`,[String(t.x),String(t.y)],hl(e))}return F(e)&&M(e,`doubleTapOn`,[`id`,`text`,`enabled`,`selected`,`delay`]),P(`click`,[K(e,`doubleTapOn`,[`delay`],t)],hl(e))}function Jc(e,t){if(F(e)&&typeof e.point==`string`){M(e,`longPressOn`,[`point`]);let t=vr(e.point);return P(`longpress`,[String(t.x),String(t.y),`3000`])}return F(e)&&M(e,`longPressOn`,[`id`,`text`,`enabled`,`selected`]),P(`click`,[K(e,`longPressOn`,[],t)],{holdMs:3e3})}function Yc(e){if(typeof e==`string`)return e;if(!F(e))throw new t(`INVALID_ARGS`,`inputText expects a string or map.`);if(M(e,`inputText`,[`text`,`label`]),typeof e.text!=`string`)throw new t(`INVALID_ARGS`,`inputText map requires a string text field.`);return e.text}function Xc(e){if(e==null)return P(`type`,[`\b`.repeat(50)]);if(typeof e==`number`&&Number.isInteger(e)&&e>0)return P(`type`,[`\b`.repeat(e)]);if(!F(e))throw new t(`INVALID_ARGS`,`eraseText expects empty, a positive count, or a map.`);if(M(e,`eraseText`,[`charactersToErase`]),e.charactersToErase===void 0)return P(`type`,[`\b`.repeat(50)]);if(typeof e.charactersToErase!=`number`||!Number.isInteger(e.charactersToErase)||e.charactersToErase<=0)throw new t(`INVALID_ARGS`,`eraseText.charactersToErase must be a positive integer.`);return P(`type`,[`\b`.repeat(e.charactersToErase)])}function Zc(e,n){if(!F(e))throw new t(`INVALID_ARGS`,`extendedWaitUntil expects a map.`);M(e,`extendedWaitUntil`,[`visible`,`notVisible`,`timeout`]);let r=e.visible??e.notVisible;if(r===void 0)throw N(`Only Maestro extendedWaitUntil.visible/notVisible is supported.`);let i=K(r,`extendedWaitUntil`,[],n),a=String(br(e,17e3));return e.notVisible===void 0?[P(G.assertVisible,[i,a],{maestro:{allowAlreadyPastLoading:!0}})]:[P(G.assertNotVisible,[i,a])]}function Qc(e){if(e!=null)throw N(`Maestro scroll options are not supported yet.`);return P(`scroll`,[`down`])}function $c(e,n){if(typeof e==`string`)return[P(G.scrollUntilVisible,[ll(I(e,n)),`5000`,`down`])];if(!F(e))throw new t(`INVALID_ARGS`,`scrollUntilVisible expects a string or map.`);M(e,`scrollUntilVisible`,[`element`,`direction`,`timeout`]);let r=K(e.element,`scrollUntilVisible.element`,[],n),i=typeof e.direction==`string`?ol(e.direction,`scrollUntilVisible.direction`):`down`,a=String(br(e,5e3));return[P(G.scrollUntilVisible,[r,a,i])]}function el(e,n){if(!F(e))throw new t(`INVALID_ARGS`,`swipe expects a map.`);M(e,`swipe`,[`start`,`end`,`direction`,`duration`,`from`,`label`]);let r=e.from??(typeof e.label==`string`?e.label:void 0);return r===void 0?typeof e.direction==`string`?P(G.swipeScreen,[`direction`,sl(e.direction),...dl(e)]):nl(e):tl(e,r,n)}function tl(e,t,n){let r=sl(typeof e.direction==`string`?e.direction:`up`);return P(G.swipeOn,[K(t,`swipe.from`,[],n),r,...dl(e)])}function nl(e){let{start:t,end:n}=rl(e);return al(t,n,il(e.duration))}function rl(e){if(typeof e.start==`string`&&typeof e.end==`string`)return{start:yr(e.start),end:yr(e.end)};throw N(`Only Maestro swipe start/end coordinates are supported.`)}function il(e){return typeof e==`number`&&Number.isFinite(e)?String(Math.max(16,Math.floor(e))):void 0}function al(e,t,n){if(e.kind===`absolute`&&t.kind===`absolute`)return P(`swipe`,[String(e.x),String(e.y),String(t.x),String(t.y),...n?[n]:[]]);if(e.kind===`percent`&&t.kind===`percent`)return P(G.swipeScreen,[`percent`,String(e.x),String(e.y),String(t.x),String(t.y),...n?[n]:[]]);throw N(`Maestro swipe start/end must both be absolute pixels or both be percentages.`)}function ol(e,t){let n=e.toLowerCase();switch(n){case`up`:case`down`:case`left`:case`right`:return n;default:throw N(`Maestro ${t} must be UP, DOWN, LEFT, or RIGHT.`)}}function sl(e){return ol(e,`swipe direction`)}function cl(e){let t=mr(`pressKey`,e).toLowerCase();if(t===`back`)return P(`back`);if(t===`enter`||t===`return`)return P(G.pressEnter);if(t===`home`)return P(`home`);throw N(`Maestro pressKey "${t}" is not supported yet.`)}function K(e,n,r=[],i){if(typeof e==`string`)return ll(I(e,i));if(!F(e))throw new t(`INVALID_ARGS`,`${n} expects a string or selector map.`);M(e,n,[`id`,`text`,`enabled`,`selected`,...r]);let a=[],o=[];if(typeof e.enabled==`boolean`&&o.push(fl(`enabled`,String(e.enabled))),typeof e.selected==`boolean`&&o.push(fl(`selected`,String(e.selected))),typeof e.id==`string`&&a.push(fl(`id`,I(e.id,i)),...o),typeof e.text==`string`&&a.length===0)return ll(I(e.text,i),o);if(typeof e.label==`string`&&a.length===0&&a.push(fl(`label`,I(e.label,i)),...o),a.length===0&&o.length>0&&a.push(...o),a.length===0)throw new t(`INVALID_ARGS`,`${n} selector map must include one of id, text, label, enabled, or selected.`);return a.join(` `)}function ll(e,t=[]){return[[fl(`label`,e),...t].join(` `),[fl(`text`,e),...t].join(` `),[fl(`id`,e),...t].join(` `)].join(` || `)}function ul(e,n){if(!F(e))return[];let r={};if(e.index!==void 0){if(typeof e.index!=`number`||!Number.isInteger(e.index)||e.index<0)throw new t(`INVALID_ARGS`,`tapOn.index must be a non-negative integer.`);r.index=e.index}return e.childOf!==void 0&&(r.childOf=K(e.childOf,`tapOn.childOf`,[],n)),Object.keys(r).length>0?[JSON.stringify(r)]:[]}function dl(e){let t=il(e.duration);return t?[t]:[]}function fl(e,t){return`${e}=${JSON.stringify(t)}`}function pl(e){if(!F(e))return;let t={},n=gl(e.repeat),r=_l(e.delay);return n&&n>1&&(t.count=n),r!==void 0&&(t.intervalMs=r),e.optional===!0&&(t.maestro={optional:!0}),Object.keys(t).length>0?t:void 0}function ml(e){let t=pl(e)??{};return{...t,maestro:{...t.maestro??{},allowNonHittableCoordinateFallback:!0}}}function hl(e){let t={doubleTap:!0};return F(e)&&typeof e.delay==`number`&&Number.isInteger(e.delay)&&(t.intervalMs=Math.max(0,e.delay)),t}function gl(e){return typeof e==`number`&&Number.isInteger(e)&&e>0?e:void 0}function _l(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:void 0}const vl=1e3;function yl(e,n,r,i,a){if(typeof e==`string`)return i.parseRunFlowFile(I(e,r),r).actions;if(!F(e))throw new t(`INVALID_ARGS`,`runFlow expects a file path string or map.`);M(e,`runFlow`,[`file`,`commands`,`env`,`when`,`label`]);let o=Cl(e.when,r);return o.shouldRun?Rl(Sl(e,n,{...r,env:{...r.env,...gr(e.env,`runFlow.env`),...r.envOverrides}},i,a),o):[]}function bl(e,n,r,i,a){if(!F(e))throw new t(`INVALID_ARGS`,`repeat expects a map.`);if(M(e,`repeat`,[`times`,`commands`,`while`]),e.while!==void 0)throw N(`Maestro repeat.while is not supported yet. Only deterministic repeat.times is supported.`);let o=Bl(e.times,r);if(!Array.isArray(e.commands))throw new t(`INVALID_ARGS`,`repeat requires a commands list.`);if(o>vl)throw new t(`INVALID_ARGS`,`repeat.times must be <= ${vl} for deterministic replay expansion.`);let s=L(e.commands);return Array.from({length:o}).flatMap(()=>a(s,n,r,i))}function xl(e,n,r,i,a){if(!F(e))throw new t(`INVALID_ARGS`,`retry expects a map.`);if(M(e,`retry`,[`maxRetries`,`commands`]),!Array.isArray(e.commands))throw new t(`INVALID_ARGS`,`retry requires a commands list.`);let o=Vl(e.maxRetries,r),s=a(L(e.commands),n,r,i);return[zl(`retry`,[String(o)],{kind:`retry`,maxRetries:o,actions:s})]}function Sl(e,n,r,i,a){if(typeof e.file==`string`)return i.parseRunFlowFile(I(e.file,r),r).actions;if(Array.isArray(e.commands))return a(L(e.commands),n,r,i);throw new t(`INVALID_ARGS`,`runFlow map requires either file or commands.`)}function Cl(e,n){if(e==null)return{shouldRun:!0};if(!F(e))throw new t(`INVALID_ARGS`,`runFlow.when expects a map.`);return M(e,`runFlow.when`,[`platform`,`visible`,`notVisible`,`true`]),wl(e,n)?{shouldRun:!0,...Tl(e,n)}:{shouldRun:!1}}function wl(e,n){if(e.true!==void 0&&!Dl(e.true,n))return!1;if(e.platform===void 0)return!0;let r=El(e.platform,`runFlow.when.platform`);if(!n.platform)throw new t(`INVALID_ARGS`,`Maestro runFlow.when.platform requires replay to be run with --platform ios|android.`);return r===n.platform}function Tl(e,t){return{...e.visible===void 0?{}:{visibleSelector:K(e.visible,`runFlow.when.visible`,[],t)},...e.notVisible===void 0?{}:{notVisibleSelector:K(e.notVisible,`runFlow.when.notVisible`,[],t)}}}function El(e,n){if(typeof e!=`string`)throw new t(`INVALID_ARGS`,`${n} expects Android, iOS, or Web.`);let r=e.trim().toLowerCase();if(r===`android`||r===`ios`||r===`web`)return r;throw new t(`INVALID_ARGS`,`${n} expects Android, iOS, or Web.`)}function Dl(e,n){if(typeof e==`boolean`)return e;if(typeof e!=`string`)throw new t(`INVALID_ARGS`,`runFlow.when.true expects a boolean or expression string.`);return new Ll(kl(Ol(I(e,n))),{platform:n.platform}).parse()}function Ol(e){let t=e.trim();return t.startsWith("${")&&t.endsWith(`}`)?t.slice(2,-1).trim():t}function kl(e){let n=[],r=0;for(;r<e.length;){let i=e.slice(r),a=Al(i);if(a>0){r+=a;continue}let o=jl(i);if(o){n.push(o.token),r+=o.length;continue}throw new t(`INVALID_ARGS`,`Unsupported runFlow.when.true expression near "${i.slice(0,24)}".`)}return n}function Al(e){return/^\s+/.exec(e)?.[0].length??0}function jl(e){return Ml(e)??Nl(e)??Pl(e)??Fl(e)??Il(e)}function Ml(e){return e.startsWith(`maestro.platform`)?{token:{type:`platform`},length:16}:null}function Nl(e){let t=/^(==|!=|&&|\|\|)/.exec(e)?.[1];return t?{token:{type:`operator`,value:t},length:t.length}:null}function Pl(e){let t=e[0];return t===`(`||t===`)`?{token:{type:`paren`,value:t},length:1}:null}function Fl(e){let t=/^(['"])(.*?)\1/.exec(e);return t?{token:{type:`string`,value:t[2]??``},length:t[0].length}:null}function Il(e){let t=/^(true|false)\b/.exec(e)?.[1];return t?{token:{type:`boolean`,value:t===`true`},length:t.length}:null}var Ll=class{index=0;tokens;context;constructor(e,t){this.tokens=e,this.context=t}parse(){let e=this.parseOr();if(this.peek())throw new t(`INVALID_ARGS`,`Unsupported trailing runFlow.when.true expression.`);return e}parseOr(){let e=this.parseAnd();for(;this.consumeOperator(`||`);)e=this.parseAnd()||e;return e}parseAnd(){let e=this.parsePrimary();for(;this.consumeOperator(`&&`);)e=this.parsePrimary()&&e;return e}parsePrimary(){let e=this.peek();if(!e)throw new t(`INVALID_ARGS`,`Incomplete runFlow.when.true expression.`);if(e.type===`boolean`)return this.index+=1,e.value;if(e.type===`paren`&&e.value===`(`){this.index+=1;let e=this.parseOr();if(!this.consumeParen(`)`))throw new t(`INVALID_ARGS`,`Unclosed runFlow.when.true parenthesis.`);return e}return this.parsePlatformComparison()}parsePlatformComparison(){this.expectPlatform();let e=this.expectEqualityOperator(),t=this.expectString().toLowerCase(),n=this.context.platform;return e===`==`?n===t:n!==t}expectPlatform(){if(this.peek()?.type!==`platform`)throw new t(`INVALID_ARGS`,`runFlow.when.true supports maestro.platform comparisons.`);this.index+=1}expectEqualityOperator(){let e=this.peek();if(e?.type===`operator`&&(e.value===`==`||e.value===`!=`))return this.index+=1,e.value;throw new t(`INVALID_ARGS`,`runFlow.when.true comparison requires == or !=.`)}expectString(){let e=this.peek();if(e?.type===`string`)return this.index+=1,e.value;throw new t(`INVALID_ARGS`,`runFlow.when.true comparison requires a string literal.`)}consumeOperator(e){let t=this.peek();return t?.type!==`operator`||t.value!==e?!1:(this.index+=1,!0)}consumeParen(e){let t=this.peek();return t?.type!==`paren`||t.value!==e?!1:(this.index+=1,!0)}peek(){return this.tokens[this.index]}};function Rl(e,t){let{visibleSelector:n,notVisibleSelector:r}=t;if(!n&&!r)return e;if(n&&r)throw N(`Maestro runFlow.when cannot combine visible and notVisible yet.`);let i=n?`visible`:`notVisible`,a=n??r??``;return[zl(`runFlow.when`,[i,a],{kind:`maestroRunFlowWhen`,mode:i,selector:a,actions:e})]}function zl(e,t,n){return{...P(e,t),replayControl:n}}function Bl(e,t){return Hl(e,t,`repeat.times`)}function Vl(e,t){return e===void 0?1:Hl(e,t,`retry.maxRetries`)}function Hl(e,n,r){let i=typeof e==`string`?I(e,n):e,a=typeof i==`number`?i:typeof i==`string`&&/^\d+$/.test(i)?Number(i):void 0;if(a===void 0||!Number.isInteger(a)||a<0)throw new t(`INVALID_ARGS`,`${r} must be a non-negative integer or \${VAR} resolving to one.`);return a}const Ul=3e4;function Wl(e,t){let n=Kl(e,t),r=ql(n.file,t);return P(G.runScript,[r],{...Object.keys(n.env).length>0?{maestro:{runScriptEnv:n.env}}:{}})}function Gl(e){let{scriptPath:n,env:r}=e,i=z.readFileSync(n,`utf8`),a=Object.create(null);try{Lr.runInNewContext(i,Jl(r,a),{filename:n,timeout:Ul})}catch(e){throw new t(`COMMAND_FAILED`,`Maestro runScript failed for ${n}: ${e instanceof Error?e.message:String(e)}`,{scriptPath:n},e instanceof Error?e:void 0)}return Ql(a,n),Object.fromEntries(Object.entries(a).map(([e,t])=>[`output.${e}`,$l(t)]))}function Kl(e,n){if(typeof e==`string`)return{file:I(e,n),env:{}};if(!F(e))throw new t(`INVALID_ARGS`,`runScript expects a file path string or map.`);M(e,`runScript`,[`file`,`env`]);let r=I(mr(`runScript.file`,e.file),n),i=gr(e.env,`runScript.env`);return{file:r,env:Object.fromEntries(Object.entries(i).map(([e,t])=>[e,I(t,n)]))}}function ql(e,n){if(B.isAbsolute(e))return e;if(!n.baseDir)throw new t(`INVALID_ARGS`,`runScript file paths require replay input to have a source path.`);return B.resolve(n.baseDir,e)}function Jl(e,t){return{...e,output:t,json:Yl,http:{post:(e,t)=>Zl(`POST`,e,t)}}}function Yl(e){if(typeof e!=`string`)throw new t(`COMMAND_FAILED`,`Maestro runScript json() expected a string body, received ${typeof e}.`);if(e.trim().length===0)throw new t(`COMMAND_FAILED`,`Maestro runScript json() received an empty body. Check the preceding http response status and setup server output.`);try{return JSON.parse(e,Xl)}catch(n){throw new t(`COMMAND_FAILED`,`Maestro runScript json() could not parse response body: ${n instanceof Error?n.message:String(n)}`,{bodyPreview:e.slice(0,1e3)},n instanceof Error?n:void 0)}}function Xl(e,t){return e===`__proto__`||e===`constructor`||e===`prototype`?void 0:t}function Zl(e,n,r){let i=f(process.execPath,[`-e`,`
|
|
4
4
|
const fs = require('node:fs');
|
|
5
5
|
const input = JSON.parse(fs.readFileSync(0, 'utf8'));
|
|
6
6
|
if (typeof fetch !== 'function') {
|
|
@@ -21,10 +21,10 @@ fetch(input.url, {
|
|
|
21
21
|
console.error(error && error.stack ? error.stack : String(error));
|
|
22
22
|
process.exit(1);
|
|
23
23
|
});
|
|
24
|
-
`],{stdin:JSON.stringify({method:e,url:n,headers:r?.headers??{},body:r?.body??``}),timeoutMs:Ul,allowFailure:!0});if(i.exitCode!==0)throw new t(`COMMAND_FAILED`,`Maestro runScript http.${e.toLowerCase()} failed for ${n}: ${eu(i.stderr)}`,{exitCode:i.exitCode,stderr:i.stderr});try{return JSON.parse(i.stdout)}catch(r){throw new t(`COMMAND_FAILED`,`Maestro runScript http.${e.toLowerCase()} returned invalid JSON for ${n}`,{stdout:i.stdout.slice(0,1e3),stderr:i.stderr.slice(0,1e3)},r instanceof Error?r:void 0)}}function Ql(e,n){for(let r of Object.keys(e))if(r.includes(`.`))throw new t(`INVALID_ARGS`,`Maestro runScript output key cannot contain ".": ${r}`,{scriptPath:n,key:r})}function $l(e){return typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`?String(e):JSON.stringify(e)}function eu(e){let t=e.trim();return t.length>0?t.slice(0,1e3):`request process exited without stderr`}const tu={launchApp:({value:e,config:t,context:n})=>[Vc(e,t,n)],tapOn:({value:e,context:t})=>[qc(e,t)],doubleTapOn:({value:e,context:t})=>[Jc(e,t)],longPressOn:({value:e,context:t})=>[Yc(e,t)],inputText:({value:e,context:t})=>[P(`type`,[I(Xc(e),t)])],eraseText:({value:e})=>[Zc(e)],pasteText:({value:e,context:t,name:n})=>[P(`type`,[I(mr(n,e),t)])],openLink:({value:e,config:t,context:n,name:r})=>[ou(e,t,n,r)],assertVisible:({value:e,context:t,name:n})=>[P(U.assertVisible,[W(e,n,[],t),`17000`])],assertNotVisible:({value:e,context:t,name:n})=>[P(U.assertNotVisible,[W(e,n,[],t)])],extendedWaitUntil:({value:e,context:t})=>Qc(e,t),takeScreenshot:({value:e,context:t,name:n})=>[P(`screenshot`,[I(mr(n,e),t)])],scroll:({value:e})=>[$c(e)],scrollUntilVisible:({value:e,context:t})=>el(e,t),swipe:({value:e,context:t})=>[tl(e,t)],hideKeyboard:()=>[P(`keyboard`,[`dismiss`])],pressKey:({value:e})=>[ll(e)],back:()=>[P(`back`)],waitForAnimationToEnd:({value:e})=>[P(U.waitForAnimationToEnd,[String(xr(e,15e3))])],stopApp:({value:e,config:t,context:n})=>[Hc(e,t,n)],runScript:({value:e,context:t})=>[Wl(e,t)],runFlow:({value:e,config:t,context:n,deps:r})=>yl(e,t,n,r,cu),repeat:({value:e,config:t,context:n,deps:r})=>bl(e,t,n,r,cu),retry:({value:e,config:t,context:n,deps:r})=>xl(e,t,n,r,cu)},nu={launchApp:(e,t)=>[Vc(void 0,e,t)],scroll:()=>[P(`scroll`,[`down`])],hideKeyboard:()=>[P(`keyboard`,[`dismiss`])],eraseText:()=>[Zc(void 0)],back:()=>[P(`back`)],waitForAnimationToEnd:()=>[P(U.waitForAnimationToEnd,[`15000`])],stopApp:(e,t)=>[Hc(void 0,e,t)]};function ru(e,n,r,i,a){try{return iu(e,n,i,a)}catch(e){throw e instanceof t&&!/\bline \d+\b/.test(e.message)?new t(e.code,`${e.message} (line ${r})`,e.details):e}}function iu(e,n,r,i){if(typeof e==`string`)return au(e,n,r);let a=Object.entries(e);if(a.length!==1)throw new t(`INVALID_ARGS`,`Maestro command maps must contain exactly one command.`);let[o,s]=a[0],c=tu[o];return c?c({value:s,config:n,context:r,deps:i,name:o}):_r(o)}function au(e,t,n){let r=nu[e];return r?r(t,n):_r(e)}function ou(e,t,n,r){let i=I(su(e,r),n);return(n.platform===`ios`||n.platform===`android`)&&t.appId?P(`open`,[I(pr(t,r),n),i],n.platform===`ios`?{maestro:{prewarmRunnerBeforeOpen:!0}}:void 0):P(`open`,[i])}function su(e,t){return typeof e==`string`?e:F(e)?(M(e,t,[`link`]),mr(`${t}.link`,e.link)):mr(t,e)}function cu(e,t,n,r){return e.flatMap((e,i)=>ru(e,t,i+1,n,r))}function lu(e,t={}){return du(e,bu(t))}function uu(e){let{config:t}=Su(hr(e));return t.name}function du(e,t){let{config:n,commands:r}=Su(hr(e)),i={...t,env:{...t.env,...n.env??{},...t.envOverrides}},{actions:a,actionLines:o}=fu({config:n,commands:r,commandLines:xu(e),context:i});return{actions:a,actionLines:o,metadata:{env:n.env}}}function fu(e){let{config:t,commands:n,commandLines:r,context:i}=e,a=[...t.onFlowStart??[],...n,...t.onFlowComplete??[]],o=[...Array.from({length:t.onFlowStart?.length??0},()=>1),...r,...Array.from({length:t.onFlowComplete?.length??0},()=>r.at(-1)??1)],s=[],c=[];for(let[e,n]of a.entries()){let r=o[e]??e+1,a=ru(n,t,r,i,{parseRunFlowFile:wu});s.push(...a),a.forEach(()=>c.push(r))}return pu(s,c)}function pu(e,t){let n=[],r=[];for(let i=0;i<e.length;i+=1){let a=e[i],o=mu(e,t,i);if(o){n.push(...o.actions),r.push(...o.actionLines),i+=o.consumed-1;continue}n.push(a),r.push(t[i]??1)}return{actions:n,actionLines:r}}function mu(e,t,n){let r=hu(e,t,n);if(!r)return null;let{action:i,nextAction:a,pressEnterAction:o,tapSelector:s,typedAfterTap:c,line:l}=r;return yu(s)?{actions:[{...i,command:`wait`,positionals:[s,`30000`]},{...a,command:`fill`,positionals:[s,c],flags:i.flags},o],actionLines:[l,l,t[n+2]??l],consumed:3}:{actions:[gu(i)],actionLines:[l],consumed:1}}function hu(e,t,n){let r=e[n],i=e[n+1],a=e[n+2];if(a?.command!==U.pressEnter||r.flags?.maestro?.optional===!0)return null;let o=vu(i),s=_u(r);return!i||o===null||s===null?null:{action:r,nextAction:i,pressEnterAction:a,tapSelector:s,typedAfterTap:o,line:t[n]??1}}function gu(e){let t={...e.flags?.maestro??{}};return delete t.allowNonHittableCoordinateFallback,{...e,flags:{...e.flags??{},maestro:{...t}}}}function _u(e){if(e?.command!==U.tapOn)return null;let[t,...n]=e.positionals??[];return n.length>0||typeof t!=`string`?null:t}function vu(e){if(e?.command!==`type`||e.flags&&Object.keys(e.flags).length>0)return null;let[t,...n]=e.positionals??[];return n.length>0||typeof t!=`string`?null:t}function yu(e){return/\b(input|textfield|textarea|field|email|password|username|search|query)\b/i.test(e.replace(/([a-z])([A-Z])/g,`$1 $2`))}function bu(e){let t=e.visitedPaths??new Set;return e.sourcePath&&t.add(R.resolve(e.sourcePath)),{baseDir:e.sourcePath?R.dirname(e.sourcePath):void 0,platform:fr(e.platform),env:{},envOverrides:e.env??{},visitedPaths:t}}function xu(e){let t=e.split(/\r?\n/),n=t.findIndex(e=>e.trim()===`---`),r=n===-1?0:n+1,i=[];for(let e=r;e<t.length;e+=1)/^-\s+/.test(t[e]??``)&&i.push(e+1);return i}function Su(e){if(e.length===0)throw new t(`INVALID_ARGS`,`Maestro flow is empty.`);if(Array.isArray(e[0]))return{config:{},commands:br(e[0])};let n=Cu(e[0]),r=e[1];if(!Array.isArray(r))throw new t(`INVALID_ARGS`,`Maestro flow must contain a command list after the YAML document separator.`);return{config:n,commands:br(r)}}function Cu(e){if(!F(e))throw new t(`INVALID_ARGS`,`Maestro flow config must be a YAML map.`);return{...typeof e.name==`string`&&e.name.length>0?{name:e.name}:{},...typeof e.appId==`string`&&e.appId.length>0?{appId:e.appId}:{},...F(e.env)?{env:gr(e.env,`env`)}:{},...Array.isArray(e.onFlowStart)?{onFlowStart:br(e.onFlowStart)}:{},...Array.isArray(e.onFlowComplete)?{onFlowComplete:br(e.onFlowComplete)}:{}}}function wu(e,n){let r=Tu(e,n);if(n.visitedPaths.has(r))throw new t(`INVALID_ARGS`,`Maestro runFlow cycle detected at ${r}.`);let i=L.readFileSync(r,`utf8`),a=new Set(n.visitedPaths);return a.add(r),du(i,{...n,baseDir:R.dirname(r),visitedPaths:a})}function Tu(e,n){if(R.isAbsolute(e))return e;if(!n.baseDir)throw new t(`INVALID_ARGS`,`runFlow file paths require replay input to have a source path.`);return R.resolve(n.baseDir,e)}const Eu=/[*?[\]{}]/;function Du(e){let{inputs:n,cwd:r,platformFilter:i,replayBackend:a}=e,o=Lu(a),s=Nu(n,r??process.cwd(),o,a),c=[];for(let e of s){let t=L.readFileSync(e,`utf8`),n=Tr(t),r=Wu(t,e,a);if(!i){c.push({kind:`run`,path:e,title:r,metadata:n});continue}if(!n.platform){Uu(a)?c.push({kind:`run`,path:e,title:r,metadata:n}):c.push({kind:`skip`,path:e,reason:`skipped-by-filter`,message:`missing platform metadata for --platform ${i}`});continue}Ku(i,n.platform)&&c.push({kind:`run`,path:e,title:r,metadata:n})}if(c.filter(e=>e.kind===`run`).length===0)throw new t(`INVALID_ARGS`,`No replay tests matched${i?` for --platform ${i}`:``}.`);return c}function Ou(e,t,n,r,i=0){let a=R.basename(n,R.extname(n)).toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``);return`${e}:test:${t}:${r+1}${a?`-${a}`:``}:attempt-${i+1}`}function ku(e){return(e?.trim()||`${process.pid}-${Date.now().toString(36)}`).toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`suite`}function Au(e){let{requestId:t,suiteInvocationId:n,filePath:r,caseIndex:i,attemptIndex:a,shardIndex:o}=e,s=o===void 0?``:`:shard:${o+1}`;return St(`${t??n}${s}:test:${i+1}:${R.basename(r)}:attempt:${a+1}`,n)}function ju(e,t){return typeof e==`number`?e:t}function Mu(e,t){let n=typeof e==`number`?e:t;return typeof n==`number`?Math.max(0,Math.min(3,n)):0}function Nu(e,t,n,r){if(!Uu(r))return[...new Set(e.flatMap(e=>Iu(e,t,n).paths))].map(e=>R.normalize(e)).sort((e,t)=>e.localeCompare(t));let i=[],a=[];for(let r of e){let e=Pu(r,t,n);e.source===`file`?i.push(...e.paths):a.push(e.source===`directory`?Hu(e.paths):zu(e.paths))}return Hu([...i,...a.flat()])}function Pu(e,t,n){let r=A.expandHome(e,t);return L.existsSync(r)&&L.statSync(r).isDirectory()?{paths:Fu(r,n),source:`directory`}:Iu(e,t,n)}function Fu(e,t){let n=[],r=L.opendirSync(e);try{let i;for(;(i=r.readSync())!==null;){let r=R.join(e,i.name);i.isDirectory()?n.push(...Fu(r,t)):i.isFile()&&t.has(R.extname(i.name))&&n.push(r)}}finally{r.closeSync()}return n}function Iu(e,n,r){let i=A.expandHome(e,n);if(L.existsSync(i)){let n=L.statSync(i);if(n.isDirectory())return{paths:Ru(r).flatMap(e=>L.globSync(e,{cwd:i}).map(e=>R.join(i,e))),source:`directory`};if(n.isFile()){if(!r.has(R.extname(i)))throw new t(`INVALID_ARGS`,`test does not support this file type: ${e}`);return{paths:[i],source:`file`}}return{paths:[],source:`file`}}if(!Gu(e)&&!Gu(i))throw new t(`INVALID_ARGS`,`test input not found: ${e}`);let a=R.isAbsolute(i)?i:e;return{paths:L.globSync(a,{cwd:R.isAbsolute(i)?void 0:n}).map(e=>R.isAbsolute(e)?e:R.resolve(n,e)).filter(e=>r.has(R.extname(e))&&qu(e)),source:`glob`}}function Lu(e){return Uu(e)?new Set([`.yaml`,`.yml`,`.ad`]):new Set([`.ad`])}function Ru(e){return[...e].map(e=>`**/*${e}`)}function zu(e){return e.map(e=>R.normalize(e)).sort(Bu)}function Bu(e,t){let n=Vu(e),r=Vu(t);return n===r?e.localeCompare(t):n-r}function Vu(e){return+(R.extname(e)===`.ad`)}function Hu(e){return[...new Set(e.map(e=>R.normalize(e)))]}function Uu(e){return e===`maestro`}function Wu(e,t,n){return Uu(n)&&R.extname(t)!==`.ad`?uu(e):void 0}function Gu(e){return Eu.test(e)}function Ku(e,t){return e===`apple`?a(t):t===e}function qu(e){try{return L.statSync(e).isFile()}catch{return!1}}const Ju=[`failed to start daemon`,`runner did not accept connection`,`xcodebuild exited early`,`device is offline`,`device offline`,`device unauthorized`];function Yu(e){let t=Xu(e);return t?Zu(t.details)||Qu(t.code,t.message):!1}function Xu(e){return`ok`in e?e.ok?null:e.error:e.status===`failed`?e.error:null}function Zu(e){let t=typeof e?.reason==`string`?e.reason:``;return t===`timeout_cleanup_pending`?!0:t?et(t):!1}function Qu(e,t){let n=`${e}\n${t}`.toLowerCase();return Ju.some(e=>n.includes(e))}const $u=2e3;async function ed(t){let{filePath:n,sessionName:r,requestId:i,parentRequestId:a,timeoutMs:o,platform:s,target:c,artifactsDir:l,shard:u,progress:d,runReplay:f,cleanupSession:p,finalizeAttempt:m}=t;ct(i);let g=td(i,a),_=new Set,v,y=!1,b,x=Date.now(),S=sd({artifactsDir:l,artifactPaths:_,filePath:n,sessionName:r,requestId:i,timeoutMs:o,platform:s,target:c}),C=ft(d,async()=>await f({filePath:n,sessionName:r,platform:s,target:c,requestId:i,artifactsDir:l,artifactPaths:_,tracePath:S,shard:u})).catch(t=>({ok:!1,error:e(t)})).finally(()=>{g(),xt(i)});try{b=typeof o==`number`?await Promise.race([C,new Promise(e=>{v=setTimeout(()=>{y=!0,lt(i),e(cd(o,[..._]))},o)})]):await C,K(S,{type:`replay_test_attempt_stop`,ts:new Date().toISOString(),session:r,ok:b.ok,timedOut:y,durationMs:Date.now()-x,errorCode:b.ok?void 0:b.error.code})}finally{v&&clearTimeout(v),y&&(await nd(C)||(ad(b),h({level:`warn`,phase:`test_timeout_cleanup_race`,data:{session:r,requestId:i,graceMs:$u}}),rd({replayPromise:C,cleanupSession:p,sessionName:r,requestId:i})));let t=await id({finalizeAttempt:m,sessionName:r,artifactPaths:_,artifactsDir:l,tracePath:S});b?.ok&&t&&!t.ok&&od(b,`Replay test finalization failed: ${t.error.message}`);let n=Date.now();try{K(S,{type:`replay_test_cleanup_start`,ts:new Date().toISOString(),session:r}),await p(r),K(S,{type:`replay_test_cleanup_stop`,ts:new Date().toISOString(),session:r,ok:!0,durationMs:Date.now()-n})}catch(t){let i=e(t);K(S,{type:`replay_test_cleanup_stop`,ts:new Date().toISOString(),session:r,ok:!1,durationMs:Date.now()-n,errorCode:i.code}),h({level:`warn`,phase:`test_cleanup_failed`,data:{session:r,error:i.message}})}}return b??{ok:!1,error:{code:`COMMAND_FAILED`,message:`Unknown replay test failure`}}}function td(e,t){if(!t||t===e)return()=>{};let n=ut(t);if(!n)return()=>{};let r=()=>{lt(e)};return n.aborted?(r(),()=>{}):(n.addEventListener(`abort`,r,{once:!0}),()=>{n.removeEventListener(`abort`,r)})}async function nd(e){return await Promise.race([e.then(()=>!0),Rr($u).then(()=>!1)])}async function rd(t){let{replayPromise:n,cleanupSession:r,sessionName:i,requestId:a}=t;try{await n}finally{try{await r(i)}catch(t){h({level:`warn`,phase:`test_late_cleanup_failed`,data:{session:i,requestId:a,error:e(t).message}})}}}async function id(t){let{finalizeAttempt:n,sessionName:r,artifactPaths:i,artifactsDir:a,tracePath:o}=t;if(!n)return;let s=Date.now();K(o,{type:`replay_test_finalize_start`,ts:new Date().toISOString(),session:r});try{let e=await n({sessionName:r,artifactPaths:i,artifactsDir:a,tracePath:o});return K(o,{type:`replay_test_finalize_stop`,ts:new Date().toISOString(),session:r,ok:e?.ok??!0,durationMs:Date.now()-s,errorCode:e?.ok===!1?e.error.code:void 0}),e}catch(t){let n=e(t);return K(o,{type:`replay_test_finalize_stop`,ts:new Date().toISOString(),session:r,ok:!1,durationMs:Date.now()-s,errorCode:n.code}),h({level:`warn`,phase:`test_finalize_failed`,data:{session:r,error:n.message}}),{ok:!1,error:n}}}function ad(e){!e||e.ok||(e.error.details={...e.error.details??{},reason:`timeout_cleanup_pending`,timeoutCleanupPending:!0})}function od(e,t){let n=e.data??={};n.warnings=[...Array.isArray(n.warnings)?n.warnings.filter(e=>typeof e==`string`):[],t]}function sd(e){let{artifactsDir:t,artifactPaths:n,filePath:r,sessionName:i,requestId:a,timeoutMs:o,platform:s,target:c}=e;if(!t)return;let l=R.join(t,`replay-timing.ndjson`);return L.mkdirSync(R.dirname(l),{recursive:!0}),L.writeFileSync(l,``),n.add(l),K(l,{type:`replay_test_attempt_start`,ts:new Date().toISOString(),replayPath:r,session:i,requestId:a,timeoutMs:o,platform:s,target:c}),l}function K(e,t){e&&L.appendFileSync(e,`${JSON.stringify(t)}\n`)}function cd(e,t=[]){return{ok:!1,error:{code:`COMMAND_FAILED`,message:`TIMEOUT after ${e}ms`,hint:`Replay test timeouts are cooperative; the active command may take a short grace period to stop.`,details:{reason:`timeout`,timeoutMs:e,timeoutMode:`cooperative`,artifactPaths:t}}}}async function ld(e){let t=ud(e);return _d(e,t,await dd(e,t))}function ud(e){let{entry:t,cwd:n,retries:r,suiteArtifactsDir:i,shard:a}=e;return{testStartedAt:Date.now(),testArtifactsDir:R.join(i,...a?[`shard-${a.shardIndex+1}`]:[],Mc(t.path,n)),maxAttempts:r+1}}async function dd(e,t){pd(e,t);let n={finalSessionName:``,attempts:0,finalAttemptDurationMs:0,attemptFailures:[]};for(let r=0;r<=e.retries&&!Ct(e.requestId);r+=1){let i=await fd(e,t,r);if(md(n,i),hd(e,i.response,r))break;gd(e,t,i)}return n}async function fd(e,t,n){let{entry:r,sessionName:i,suiteInvocationId:a,caseIndex:o,suiteIndex:s,suiteTotal:c,requestId:l,timeoutMs:u,shard:d}=e,f=n+1,p=Date.now(),m=Ou(i,a,r.path,o,n),h=R.join(t.testArtifactsDir,`attempt-${f}`);Nc(r.path,h);let g=Au({requestId:l,suiteInvocationId:a,filePath:r.path,caseIndex:o,attemptIndex:n,shardIndex:d?.shardIndex}),_=await ed({filePath:r.path,sessionName:m,requestId:g,parentRequestId:l,timeoutMs:u,platform:r.metadata.platform,target:r.metadata.target,artifactsDir:h,shard:d,progress:{file:r.path,title:r.title,index:s,total:c,attempt:f,maxAttempts:t.maxAttempts,session:m,artifactsDir:t.testArtifactsDir,...Ed(d)},runReplay:e.runReplay,cleanupSession:e.cleanupSession,finalizeAttempt:e.finalizeAttempt}),v=Date.now()-p;return Pc({response:_,filePath:r.path,sessionName:m,attempts:f,maxAttempts:t.maxAttempts,attemptArtifactsDir:h}),{response:_,sessionName:m,attempt:f,durationMs:v}}function pd(e,t){let{entry:n,sessionName:r,suiteInvocationId:i,caseIndex:a,suiteIndex:o,suiteTotal:s,shard:c}=e;T({type:`replay-test`,file:n.path,title:n.title,status:`start`,index:o,total:s,maxAttempts:t.maxAttempts,session:Ou(r,i,n.path,a),artifactsDir:t.testArtifactsDir,...Ed(c)})}function md(e,t){e.finalResponse=t.response,e.finalSessionName=t.sessionName,e.attempts=t.attempt,e.finalAttemptDurationMs=t.durationMs,!t.response.ok&&e.attemptFailures.push({attempt:t.attempt,message:t.response.error.message,durationMs:t.durationMs})}function hd(e,t,n){return t.ok||Ct(e.requestId)||Yu(t)||n>=e.retries}function gd(e,t,n){n.response.ok||T({type:`replay-test`,file:e.entry.path,title:e.entry.title,status:`fail`,index:e.suiteIndex,total:e.suiteTotal,attempt:n.attempt,maxAttempts:t.maxAttempts,durationMs:n.durationMs,retrying:!0,message:n.response.error.message,hint:n.response.error.hint,session:n.sessionName,artifactsDir:t.testArtifactsDir,...Ed(e.shard)})}function _d(e,t,n){let r=Date.now()-t.testStartedAt;return n.finalResponse?.ok?vd(e,t,n,r):yd(e,t,n,r)}function vd(e,t,n,r){let{entry:i,suiteIndex:a,suiteTotal:o,shard:s}=e,c=n.finalResponse;if(!c?.ok)throw Error(`Expected passing replay test response.`);return T({type:`replay-test`,file:i.path,title:i.title,status:`pass`,index:a,total:o,attempt:n.attempts,maxAttempts:t.maxAttempts,durationMs:r,session:n.finalSessionName,artifactsDir:t.testArtifactsDir,...Ed(s)}),{file:i.path,title:i.title,session:n.finalSessionName,status:`passed`,durationMs:r,finalAttemptDurationMs:n.finalAttemptDurationMs,attempts:n.attempts,artifactsDir:t.testArtifactsDir,...xd(c),...Sd(c.data?.warnings),...Cd(c.data?.snapshotDiagnostics),...Td(s),...n.attemptFailures.length>0?{attemptFailures:n.attemptFailures}:{}}}function yd(e,t,n,r){let{entry:i,suiteIndex:a,suiteTotal:o,shard:s}=e,c=bd(n.finalResponse);return T({type:`replay-test`,file:i.path,title:i.title,status:`fail`,index:a,total:o,attempt:n.attempts,maxAttempts:t.maxAttempts,durationMs:r,session:n.finalSessionName,artifactsDir:t.testArtifactsDir,message:c.message,hint:c.hint,...Ed(s)}),{file:i.path,title:i.title,session:n.finalSessionName,status:`failed`,durationMs:r,attempts:n.attempts,artifactsDir:t.testArtifactsDir,error:c,...Cd(wd(n.finalResponse)),...Td(s)}}function bd(e){return e&&!e.ok?e.error:{code:`COMMAND_FAILED`,message:`Unknown replay test failure`}}function xd(e){return{replayed:typeof e.data?.replayed==`number`?e.data.replayed:0,healed:typeof e.data?.healed==`number`?e.data.healed:0}}function Sd(e){if(!Array.isArray(e))return{};let t=e.filter(e=>typeof e==`string`);return t.length>0?{warnings:t}:{}}function Cd(e){let t=re(e);return t?{snapshotDiagnostics:t}:{}}function wd(e){return e?.ok?e.data?.snapshotDiagnostics:e?.error.details?.snapshotDiagnostics}function Td(e){return Ed(e)}function Ed(e){return e?{shardIndex:e.shardIndex,shardCount:e.shardCount,deviceId:e.device.id,deviceName:e.device.name}:{}}async function Dd(e,t,n){let r=kd(e);if(!r||t.length===0)return;let i=await jd(e,r.count);return{mode:r.kind,shardCount:r.count,total:n+(r.kind===`all`?t.length*r.count:t.length),shards:i.map((e,n)=>({shardIndex:n,shardCount:r.count,device:e,entries:r.kind===`all`?t:t.filter((e,t)=>t%r.count===n)}))}}function Od(e,t){if(!t)return e;let n={...e??{},device:void 0,udid:void 0,serial:void 0,platform:t.device.platform,target:t.device.target,shardAll:void 0,shardSplit:void 0,shardCount:t.shardCount,shardIndex:t.shardIndex};return t.device.platform===`android`?{...n,serial:t.device.id}:{...n,udid:t.device.id}}function kd(e){let n=Ad(e?.shardAll,`--shard-all`),r=Ad(e?.shardSplit,`--shard-split`);if(n!==void 0&&r!==void 0)throw new t(`INVALID_ARGS`,`--shard-all and --shard-split are mutually exclusive`);if(n!==void 0)return{kind:`all`,count:n};if(r!==void 0)return{kind:`split`,count:r}}function Ad(e,n){if(e!==void 0){if(typeof e!=`number`||!Number.isInteger(e)||e<1)throw new t(`INVALID_ARGS`,`${n} requires a positive integer`);return e}}async function jd(e,n){let r=Fd(e),i=Nd(await tn(Md(e)),r,e);if(i.length<n)throw new t(`DEVICE_NOT_FOUND`,`test sharding requires ${Pd(n)}, but only ${i.length} matched`);return i.slice(0,n)}function Md(e){let t=rt(e?.androidDeviceAllowlist);return{platform:e?.platform,target:e?.target,iosSimulatorSetPath:r({simulatorSetPath:nt(e?.iosSimulatorDeviceSet),platform:e?.platform,target:e?.target}),androidSerialAllowlist:t?Array.from(t).sort():void 0}}function Nd(e,t,n){return t.length>0?Id(e,t,n):e.filter(e=>Ld(e,n)).sort(Bd)}function Pd(e){return`${e} device${e===1?``:`s`}`}function Fd(e){let t=e?.device;return typeof t!=`string`||t.trim().length===0?[]:t.split(`,`).map(e=>e.trim()).filter(Boolean)}function Id(e,n,r){return n.map(n=>{let i=zd(n),a=e.find(e=>Rd(e,r)&&(e.id===n||zd(e.name)===i));if(!a)throw new t(`DEVICE_NOT_FOUND`,`No shard device matched ${n}`);return a})}function Ld(e,t){return!Rd(e,t)||!o(e)?!1:e.booted!==!1}function Rd(e,t){return!(!d(e,t?.platform)||t?.target&&(e.target??`mobile`)!==t.target)}function zd(e){return e.toLowerCase().replace(/_/g,` `).replace(/\s+/g,` `).trim()}function Bd(e,t){return e.id.localeCompare(t.id)}async function Vd(e){let{req:t,sessionName:r,runReplay:i,cleanupSession:a,finalizeAttempt:o}=e;if((t.positionals?.length??0)===0)return k(`INVALID_ARGS`,`test requires at least one path or glob`);try{let e=Date.now(),n=await Hd(t);Kd(n);let s=n.shardPlan?qd({entries:n.entries,total:n.total}):[];return n.shardPlan?s.push(...await Jd({shards:n.shardPlan.shards,sessionName:r,suiteInvocationId:n.suiteInvocationId,cwd:t.meta?.cwd,requestId:t.meta?.requestId,flags:t.flags,suiteArtifactsDir:n.suiteArtifactsDir,suiteTotal:n.total,runReplay:i,cleanupSession:a,finalizeAttempt:o})):s.push(...await Qd({discoveryEntries:n.entries,sessionName:r,suiteInvocationId:n.suiteInvocationId,cwd:t.meta?.cwd,requestId:t.meta?.requestId,flags:t.flags,suiteArtifactsDir:n.suiteArtifactsDir,suiteTotal:n.total,runReplay:i,cleanupSession:a,finalizeAttempt:o})),{ok:!0,data:tf(n.total,s,Date.now()-e)}}catch(e){let t=n(e);return k(t.code,t.message)}}async function Hd(e){let t=Ud(e),n=Wd(t),r=t.length-n.length,i=ku(e.meta?.requestId),a=await Dd(e.flags,n,r);return{entries:t,runnable:n,shardPlan:a,suiteInvocationId:i,suiteArtifactsDir:Gd(e,i),total:a?.total??t.length}}function Ud(e){return Du({inputs:e.positionals??[],cwd:e.meta?.cwd,platformFilter:e.flags?.platform,replayBackend:e.flags?.replayBackend})}function Wd(e){return e.flatMap((e,t)=>e.kind===`run`?[{entry:e,suiteIndex:t+1}]:[])}function Gd(e,t){return jc({artifactsDir:typeof e.flags?.artifactsDir==`string`?e.flags.artifactsDir:void 0,cwd:e.meta?.cwd,suiteInvocationId:t})}function Kd(e){T({type:`replay-test-suite`,status:`start`,total:e.total,runnable:e.runnable.length,skipped:e.entries.length-e.runnable.length,artifactsDir:e.suiteArtifactsDir,shardMode:e.shardPlan?.mode,shardCount:e.shardPlan?.shardCount})}function qd(e){let{entries:t,total:n}=e,r=[];for(let[e,i]of t.entries())i.kind===`skip`&&(T({type:`replay-test`,file:i.path,status:`skip`,index:e+1,total:n,message:i.message}),r.push({file:i.path,status:`skipped`,durationMs:0,reason:i.reason,message:i.message}));return r}async function Jd(e){return(await Promise.allSettled(e.shards.map(async t=>await Xd({...e,shard:t})))).flatMap((t,n)=>{if(t.status===`fulfilled`)return t.value;let r=e.shards[n];return r?[Yd(r,e.sessionName,t.reason)]:[]})}function Yd(t,n,r){let i=e(r);return{file:t.entries[0]?.entry.path??`shard-${t.shardIndex+1}`,session:Zd(n,t),status:`failed`,durationMs:0,attempts:1,error:{code:i.code,message:i.message,hint:i.hint,diagnosticId:i.diagnosticId,logPath:i.logPath,details:i.details},shardIndex:t.shardIndex,shardCount:t.shardCount,deviceId:t.device.id,deviceName:t.device.name}}async function Xd(e){let{shard:t,sessionName:n}=e;return await $d({...e,entries:t.entries,sessionName:Zd(n,t),shard:t})}function Zd(e,t){return`${e}:shard-${t.shardIndex+1}`}async function Qd(e){let{discoveryEntries:t,sessionName:n,suiteInvocationId:r,cwd:i,requestId:a,flags:o,suiteArtifactsDir:s,suiteTotal:c,runReplay:l,cleanupSession:u,finalizeAttempt:d}=e,f=[],p=0;for(let[e,m]of t.entries()){if(Ct(a))break;if(m.kind===`skip`){T({type:`replay-test`,file:m.path,status:`skip`,index:e+1,total:c,message:m.message}),f.push({file:m.path,status:`skipped`,durationMs:0,reason:m.reason,message:m.message});continue}p+=1;let t=await ld({entry:m,sessionName:n,suiteInvocationId:r,caseIndex:p-1,cwd:i,requestId:a,retries:Mu(o?.retries,m.metadata.retries),timeoutMs:ju(o?.timeoutMs,m.metadata.timeoutMs),suiteArtifactsDir:s,suiteIndex:e+1,suiteTotal:c,runReplay:l,cleanupSession:u,finalizeAttempt:d});if(f.push(t),ef(t,o,a))break}return f}async function $d(e){let{entries:t,sessionName:n,suiteInvocationId:r,cwd:i,requestId:a,flags:o,suiteArtifactsDir:s,suiteTotal:c,shard:l,runReplay:u,cleanupSession:d,finalizeAttempt:f}=e,p=[];for(let[e,m]of t.entries()){if(Ct(a))break;let{entry:t,suiteIndex:h}=m,g=await ld({entry:t,sessionName:n,suiteInvocationId:r,caseIndex:e,cwd:i,requestId:a,retries:Mu(o?.retries,t.metadata.retries),timeoutMs:ju(o?.timeoutMs,t.metadata.timeoutMs),suiteArtifactsDir:s,suiteIndex:h,suiteTotal:c,shard:l,runReplay:u,cleanupSession:d,finalizeAttempt:f});if(p.push(g),ef(g,o,a))break}return p}function ef(e,t,n){return Ct(n)||t?.failFast===!0||Yu(e)}function tf(e,t,n){let r=t.filter(e=>e.status===`passed`).length,i=t.filter(e=>e.status===`failed`),a=i.length,o=t.filter(e=>e.status===`skipped`).length,s=r+a,c=ie(t.map(e=>e.status===`skipped`?void 0:e.snapshotDiagnostics));return{total:e,executed:s,passed:r,failed:a,skipped:o,notRun:Math.max(0,e-s-o),durationMs:n,failures:i,tests:t,...c?{snapshotDiagnostics:c}:{}}}const nf={maestro:{parse:lu}};function rf(e,t,n={}){let r=of(t);return r?{...r.parse(e,{...n,platform:t?.platform,env:af(t)}),updateUnsupportedMessage:`replay -u is not supported for compat flow input. Convert to .ad first, then update that replay file.`}:{...Sr(e),metadata:Tr(e)}}function af(e){return{...lr(cr(e?.replayShellEnv)),...Cr(ur(e?.replayEnv))}}function of(e){let n=e?.replayBackend;if(typeof n!=`string`)return;let r=nf[n];if(!r)throw new t(`INVALID_ARGS`,`Unsupported replay backend "${n}".`);return r}function sf(e){if(e.length===0)return{selectorExpression:null,selectorTimeout:null};let t=e[e.length-1],n=t!==void 0&&/^\d+$/.test(t)?t:null,r=x(n===null?e.slice():e.slice(0,-1));return!r||r.rest.length>0?{selectorExpression:null,selectorTimeout:null}:{selectorExpression:r.selectorExpression,selectorTimeout:n}}function cf(e){let t=[],n=Array.isArray(e.result?.selectorChain)&&e.result?.selectorChain.every(e=>typeof e==`string`)?e.result.selectorChain:[];if(t.push(...n),ot(e.command)){let n=df(e),r=n[0]??``;r&&!r.startsWith(`@`)&&t.push(n.join(` `))}if(e.command===`fill`){let n=e.positionals?.[0]??``;n&&!n.startsWith(`@`)&&Number.isNaN(Number(n))&&t.push(n)}if(e.command===`get`){let n=e.positionals?.[1]??``;n&&!n.startsWith(`@`)&&t.push(e.positionals.slice(1).join(` `))}if(e.command===`is`){let{split:n}=Ie(e.positionals);n&&t.push(n.selectorExpression)}if(e.command===`wait`){let{selectorExpression:n}=sf(e.positionals??[]);n&&t.push(n)}return qt(t).filter(e=>e.trim().length>0)}function lf(e){return cf(e).map(e=>C(e)).filter(e=>e!==null)}async function uf(e){let{action:t,sessionName:n,logPath:r,sessionStore:i}=e;if(!(ot(t.command)||[`fill`,`get`,`is`,`wait`].includes(t.command)))return null;let a=i.get(n);if(!a)return null;let o=lf(t);if(o.length===0)return null;let s=ot(t.command)||t.command===`fill`,c=ot(t.command)||t.command===`fill`||t.command===`get`&&t.positionals?.[0]===`text`,l=await hf(a,t,r,s,i);for(let e of o){let n=Ue(l.nodes,e,{platform:a.device.platform,requireRect:s,requireUnique:!0,disambiguateAmbiguous:c});if(!n)continue;let r=Ge(n.node,a.device.platform,{action:t.command===`fill`?`fill`:ot(t.command)?`click`:`get`}).join(` || `);if(ot(t.command))return{...t,positionals:t.command===`longpress`?ff(t,r):[r]};if(t.command===`fill`){let e=nr(t);if(!e)continue;return{...t,positionals:[r,e]}}if(t.command===`get`){let e=t.positionals?.[0];if(e!==`text`&&e!==`attrs`)continue;return{...t,positionals:[e,r]}}if(t.command===`is`){let{predicate:e,split:n}=Ie(t.positionals);if(!e)continue;let i=n?.rest.join(` `).trim()??``,a=[e,r];return e===`text`&&i.length>0&&a.push(i),{...t,positionals:a}}if(t.command===`wait`){let{selectorTimeout:e}=sf(t.positionals??[]),n=[r];return e&&n.push(e),{...t,positionals:n}}}return null}function df(e){let t=e.positionals??[];if(e.command!==`longpress`)return t;let n=t.at(-1);return t.length>1&&mf(n)?t.slice(0,-1):t}function ff(e,t){let n=typeof e.result?.durationMs==`number`?String(e.result.durationMs):pf(e.positionals??[]);return n?[t,n]:[t]}function pf(e){let t=e.at(-1);return e.length>1&&mf(t)?t:void 0}function mf(e){return e===void 0||e.trim()===``?!1:Number.isFinite(Number(e))}async function hf(e,t,n,r,i){let a=Mt(await E(e.device,`snapshot`,[],t.flags?.out,{...D(n,{...t.flags??{},snapshotInteractiveOnly:r},e.appBundleId,e.trace?.outPath)}),{...t.flags??{},snapshotInteractiveOnly:r});return En(e,a),i.set(e.name,e),a}const gf={swipe:{screenRatio:.35,minDistancePx:120,maxDistancePx:360,marginPx:8}};function _f(e,t){let n=_e(e.rect),r=e.frame,i=yf(r?.referenceWidth,e.rect.width),a=yf(r?.referenceHeight,e.rect.height),o=gf.swipe.marginPx,s=o,c=o,l=r?r.referenceWidth-o:n.x+i,u=r?r.referenceHeight-o:n.y+a;switch(t.toLowerCase()){case`up`:return{ok:!0,start:n,end:{x:n.x,y:Se(n.y-a,c,u)}};case`down`:return{ok:!0,start:n,end:{x:n.x,y:Se(n.y+a,c,u)}};case`left`:return{ok:!0,start:n,end:{x:Se(n.x-i,s,l),y:n.y}};case`right`:return{ok:!0,start:n,end:{x:Se(n.x+i,s,l),y:n.y}};default:return{ok:!1,message:`swipe.label direction must be up, down, left, or right.`}}}function vf(e){return _e(e.rect)}function yf(e,t){let n=typeof e==`number`?e*gf.swipe.screenRatio:0;return Math.round(Math.min(gf.swipe.maxDistancePx,Math.max(gf.swipe.minDistancePx,n,t*1.5)))}const bf=new WeakMap,xf=new WeakMap,Sf=new WeakMap;function q(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{details:n}:{}}}}async function Cf(e){let t=e.raw===!0||process.env.AGENT_DEVICE_MAESTRO_RAW_SNAPSHOTS===`1`,n=await e.invoke({...e.baseReq,command:`snapshot`,positionals:[],flags:{...e.baseReq.flags,noRecord:!0,...t?{snapshotRaw:!0}:{}}});return n.ok&&e.scope&&Mf(e.scope,n.data),n}function wf(e){return Array.isArray(e?.nodes)?e:void 0}function Tf(e){return e?bf.get(e):void 0}function Ef(e,t){e&&xf.set(e,{selector:t})}function Df(e){return e?xf.get(e):void 0}function Of(e){e&&xf.delete(e)}function kf(e,t){e&&Sf.set(e,t)}function Af(e){if(!e)return;let t=Sf.get(e);return Sf.delete(e),t}function jf(e){e&&Sf.delete(e)}function Mf(e,t){let n=j(wf(t));n&&bf.set(e,n)}const Nf=new Map([[`button`,0],[`link`,0],[`textfield`,0],[`textview`,0],[`searchfield`,0],[`switch`,0],[`slider`,0],[`cell`,1],[`statictext`,2]]);function Pf(e,t,n,r,i,a={}){let o=zf(e,t,r);if(n.childOf){let t=zf(e,n.childOf,r);if(t.length===0)return{ok:!1,message:`Maestro childOf parent did not match: ${n.childOf}`};let i=Fe(e.nodes);o=o.filter(n=>t.some(t=>Me(e.nodes,n,t,i)))}let s=Lf({nodes:e.nodes,matches:o,platform:r}),c=Xf(e.nodes,s.matches,n.index,Y(t),i,a.requireOnScreen===!0,a.promoteTapTarget,a.preferredContext);if(!c){let e=n.index??0;return{ok:!1,message:s.blockedByReactNativeOverlay?`React Native overlay is covering app content: ${t}`:o.length>0&&s.matches.length===0?`Maestro selector matched ${o.length} element(s), but none were visible: ${t}`:`Maestro selector did not match index ${e}: ${t}`}}return{ok:!0,node:c.node,rect:c.rect}}function Ff(e,t,n,r,i={}){let a=Bf(e,t),o=Lf({nodes:e.nodes,matches:a,platform:n}),s=Xf(e.nodes,o.matches,void 0,t,r,i.requireOnScreen===!0,i.promoteTapTarget,i.preferredContext);return s?{ok:!0,node:s.node,rect:s.rect}:{ok:!1,message:`Maestro fuzzy text did not match: ${t}`}}function If(e,t,n,r){let i=zf(e,t,n,{allowLeadingCompositeLabelMatch:!1}),a=Lf({nodes:e.nodes,matches:i,platform:n}),o=Xf(e.nodes,a.matches,void 0,Y(t),r,!0);return o?{ok:!0,node:o.node,rect:o.rect,matches:a.matches.length}:{ok:!1,message:a.blockedByReactNativeOverlay?`React Native overlay is covering app content: ${t}`:i.length>0?`Maestro selector matched ${i.length} element(s), but none were visible: ${t}`:`Maestro selector did not match: ${t}`}}function Lf(e){let t=e.matches.filter(t=>Pe({predicate:`visible`,node:t,nodes:e.nodes,platform:e.platform}).pass),n=Rf(e.nodes,t,e.platform);return{matches:n.matches,blockedByReactNativeOverlay:n.blockedByReactNativeOverlay}}function Rf(e,t,n){let r=qe(e);if(!r.detected||!r.redBox)return{matches:t,blockedByReactNativeOverlay:!1};let i=Je(r),a=i.filter(t=>Pe({predicate:`visible`,node:t,nodes:e,platform:n}).pass);if(a.length===0)return i.length===0?{matches:[],blockedByReactNativeOverlay:!0}:{matches:t,blockedByReactNativeOverlay:!1};let o=new Set(a.map(e=>e.index)),s=t.filter(e=>o.has(e.index));return{matches:s,blockedByReactNativeOverlay:t.length>0&&s.length===0}}function J(e){return e?.platform===`android`?`android`:`ios`}function Y(e){let t=y(e).selectors.flatMap(e=>e.terms);if(t.length===0||!t.some(e=>e.key===`label`||e.key===`text`)||!t.every(e=>[`label`,`text`,`id`].includes(e.key)))return null;let n=t.map(e=>typeof e.value==`string`?e.value:``),r=n[0];return!r||!n.every(e=>e===r)?null:r}function zf(e,t,n,r={}){let i=y(t);for(let t of i.selectors){let i=e.nodes.filter(e=>Vf(e,t,n,r));if(i.length>0)return i}return[]}function Bf(e,t){let n=He(t);if(!n)return[];let r=[],i=[];for(let t of e.nodes){let e=[t.label,je(t),t.identifier,t.value].filter(e=>!!e).map(e=>He(e));e.some(e=>e===n)?r.push(t):e.some(e=>e.includes(n))&&i.push(t)}return r.length>0?r:i}function Vf(e,t,n,r){return We(e,t,n)?!0:t.terms.every(t=>Hf(e,t,n,r))}function Hf(e,t,n,r){return typeof t.value!=`string`||!Uf(t.key)?We(e,{raw:t.key,terms:[t]},n):Gf(Wf(e,t.key),t.value,r)}function Uf(e){return e===`id`||e===`label`||e===`text`||e===`value`}function Wf(e,t){return t===`id`?e.identifier:t===`label`?e.label:t===`value`?e.value:je(e)}function Gf(e,t,n={}){let r=e??``,i=He(r),a=He(t);if(i===a||n.allowLeadingCompositeLabelMatch!==!1&&Kf(i,a))return!0;if(!qf(t))return!1;try{return new RegExp(t).test(r)}catch{return!1}}function Kf(e,t){if(!e||!t||!e.startsWith(t))return!1;let n=e.at(t.length);return n===`,`||n===`:`||n===`;`}function qf(e){return/(?:\.\*|\.\+|\[[^\]]+\]|\([^)]*\)|\||\^|\$|\\[dDsSwWbB])/.test(e)}function Jf(e,t,n){if(t.rect&&t.rect.width>0&&t.rect.height>0)return{rect:t.rect,inherited:!1};if(t.rect)return null;let r=Yf(e,t,n);return r?{rect:r,inherited:!0}:null}function Yf(e,t,n){let r=t;for(;typeof r.parentIndex==`number`;){if(r=n.get(r.parentIndex)??e[r.parentIndex],!r)return null;if(r.rect)return r.rect.width>0&&r.rect.height>0?r.rect:null}return null}function Xf(e,t,n,r,i,a=!1,o=!1,s){let c=Fe(e);return Np(e,$f(e,Zf(e,t,c,r,n,i,a),n,r,o,s),c,o,i)}function Zf(e,t,n,r,i,a,o){let s=t.map(t=>Qf(e,t,n)).filter(e=>!!e),c=s.filter(e=>!e.inheritedRect),l=c.length>0?c:s;return!r||i!==void 0?s:mp(l,a,o)}function Qf(e,t,n){let r=Jf(e,t,n);return r?{node:t,rect:r.rect,inheritedRect:r.inherited}:null}function $f(e,t,n,r,i,a){if(n!==void 0)return t[n]??null;let o=ep(e,t,r,i,a);return tp(o,r,i)?bp(e,o,r)??o:o}function ep(e,t,n,r,i){return!r||!n?np(e,t,n,i):rp(e,t,n,i)??np(e,t,n,i)}function tp(e,t,n){return!!(n&&t&&e)}function np(e,t,n,r){return ap(e,t,n,r).sort((e,t)=>gp(e,t,n))[0]??null}function rp(e,t,n,r){let i=t.filter(e=>Z(e.node,n)===0);if(i.length>=2){let t=ip(e,i,n,r);if(t)return t}let a=t.filter(e=>Z(e.node,n)===1);return i.length>0||a.length<2?null:ip(e,a,n,r)}function ip(e,t,n,r){let i=Fe(e);return np(e,t.filter(n=>fp(n)&&t.some(t=>pp(e,t,n,i))),n,r)}function ap(e,t,n,r){if(!n||t.length<2)return t;let i=t.filter(e=>Z(e.node,n)===0);if(i.length<2)return t;let a=Fe(e),o=i.map(t=>({candidate:t,container:up(e,t.node,a)})).filter(e=>!!e.container);if(o.length<2||o.length!==i.length)return t;let s=o.filter(e=>lp(e,o));if(s.length<2)return t;let c=cp(s);if(c.length>0)return c;let l=op(e,s,r,a);if(l.length>0)return l;let u=Math.max(...s.map(e=>e.container.index)),d=s.filter(e=>e.container.index===u).map(e=>e.candidate);return d.length>0?d:t}function op(e,t,n,r){if(!n)return[];let i=up(e,n.node,r),a=i&&Rp(i.rect,n.rect)?i:null,o=t.map(e=>({entry:e,score:sp(e.container,n,a)})),s=Math.min(...o.map(e=>e.score));return Number.isFinite(s)?o.filter(e=>e.score===s).map(e=>e.entry.candidate):[]}function sp(e,t,n){if(n)return e.index===n.index?0:zp(e.rect,n.rect)<.6?1/0:Math.abs(e.index-n.index);if(zp(e.rect,t.rect)>=.6)return 0;let r=e.index-t.node.index;return r>=0?r:1e5+Math.abs(r)}function cp(e){let t=e.map(e=>X(e.container.rect)),n=Math.max(...t),r=Math.min(...t);return r<=0||n<r*1.2?[]:e.filter(e=>X(e.container.rect)===n).map(e=>e.candidate)}function lp(e,t){return t.some(t=>t!==e&&e.container.index!==t.container.index&&zp(e.container.rect,t.container.rect)>=.6)}function up(e,t,n){return Ne(e,t,n,e=>!e.rect||!dp(e)||e.rect.width<240||e.rect.height<320?null:e)}function dp(e){let t=Ae(e.type??``);return t===`scrollview`||t===`scroll-area`||t===`list`}function fp(e){return e.rect.width>=16&&e.rect.width<=260&&e.rect.height>=24&&e.rect.height<=80}function pp(e,t,n,r){return t.node.index===n.node.index||!Rp(t.rect,n.rect)||X(t.rect)<X(n.rect)*2?!1:Me(e,n.node,t.node,r)}function mp(e,t,n){let r=e.filter(e=>hp(e.rect,t));return n||r.length>0?r:e}function hp(e,t){let n=t?.referenceWidth??1/0,r=t?.referenceHeight??1/0;return e.x<n&&e.y<r&&e.x+e.width>0&&e.y+e.height>0}function gp(e,t,n){let r=vp(e,t,n);if(r!==0)return r;if(!_p(e.rect,t.rect))return e.node.index-t.node.index;let i=(t.node.depth??0)-(e.node.depth??0);return i===0?t.node.index-e.node.index:i}function _p(e,t){return Math.round(e.x)===Math.round(t.x)&&Math.round(e.y)===Math.round(t.y)&&Math.round(e.width)===Math.round(t.width)&&Math.round(e.height)===Math.round(t.height)}function vp(e,t,n){if(n){let r=Z(e.node,n)-Z(t.node,n);if(r!==0)return r}let r=yp(e.node)-yp(t.node);if(r!==0)return r;let i=Number(e.inheritedRect)-Number(t.inheritedRect);if(i!==0)return i;let a=n&&yp(e.node)===yp(t.node)?X(t.rect)-X(e.rect):X(e.rect)-X(t.rect);return a===0?0:a}function X(e){return e.width*e.height}function yp(e){return Nf.get(Ae(e.type??``))??3}function bp(e,t,n){if(!Dp(t,n))return null;let r=xp(e,t,n,Fe(e));if(r.length===0)return null;let i=jp(r.map(e=>e.rect.width)),a=Sp(t,n,kp(t.rect,r.map(e=>e.rect)),i);return a?Ep(t,a):null}function xp(e,t,n,r){return e.filter(i=>i.index!==t.node.index&&!!i.rect&&Me(e,i,t.node,r)&&Op(i,t.rect,n)).sort((e,t)=>e.rect.x-t.rect.x)}function Sp(e,t,n,r){let i=n.filter(e=>Ap(e.width,r)),a=Cp(e,t,n),o=i.some(t=>Tp(e.rect,t));return a&&!o?a:i.length===1?i[0]??null:a}function Cp(e,t,n){let r=n.find(t=>Math.abs(t.x-e.rect.x)<1),i=Math.max(48,Math.min(220,t.length*8+24));return wp(e,t,r,i)?{x:e.rect.x,width:Math.min(i,r.width)}:null}function wp(e,t,n,r){return n?Ae(e.node.type??``)===`scrollview`&&Z(e.node,t)<=1&&e.rect.width>=240&&e.rect.height>=32&&e.rect.height<=80&&n.width<=e.rect.width*.55&&n.width>=r*.6:!1}function Tp(e,t){return Math.abs(t.x-e.x)<1}function Ep(e,t){return{...e,rect:{x:t.x,y:e.rect.y,width:t.width,height:e.rect.height}}}function Dp(e,t){let n=Ae(e.node.type??``);return n!==`cell`&&n!==`other`&&n!==`scrollview`&&n!==`scroll-area`||e.rect.width<120||e.rect.height<32||e.rect.height>80?!1:Z(e.node,t)<=1}function Op(e,t,n){let r=Ae(e.type??``);return r!==`button`&&r!==`cell`&&r!==`other`||Z(e,n)<=1||e.rect.width<16||e.rect.height<16||!Rp(t,e.rect)?!1:Mp(t,e.rect)>=.5}function kp(e,t){let n=[],r=e.x,i=e.x+e.width;for(let a of t){let t=Math.max(e.x,a.x),o=Math.min(i,a.x+a.width);t>r&&n.push({x:r,width:t-r}),r=Math.max(r,o)}return i>r&&n.push({x:r,width:i-r}),n}function Ap(e,t){return e<24||t<24?!1:e>=t*.4&&e<=t*1.6}function jp(e){let t=[...e].sort((e,t)=>e-t);return t[Math.floor(t.length/2)]??0}function Mp(e,t){let n=Math.max(e.y,t.y),r=Math.min(e.y+e.height,t.y+t.height);return Math.max(0,r-n)/Math.max(1,Math.min(e.height,t.height))}function Np(e,t,n,r,i){return t?r?Pp(e,t,n,i)??{node:t.node,rect:t.rect}:{node:t.node,rect:t.rect}:null}function Pp(e,t,n,r){return Fp(t.node)?null:Ne(e,t.node,n,i=>{if(!Fp(i))return null;let a=Jf(e,i,n);return!a||!Ip(t.rect,a.rect,r)?null:{node:i,rect:a.rect}})}function Fp(e){let t=Ae(e.type??``);return e.hittable===!0||t===`button`||t===`link`||t===`cell`||t===`textfield`||t===`searchfield`||t===`switch`||t===`slider`}function Ip(e,t,n){if(!Rp(t,e)||Lp(e,t))return!1;let r=X(t),i=X(e);if(i>0&&r>i*30)return!1;if(n){let e=n.referenceWidth*n.referenceHeight;if(e>0&&r>e*.5)return!1}return!0}function Lp(e,t){return t.height<32||t.height>80||e.height<t.height*.75||Mp(e,t)<.75||t.width<240?!1:t.width>=e.width*3}function Rp(e,t){return t.x>=e.x-1&&t.y>=e.y-1&&t.x+t.width<=e.x+e.width+1&&t.y+t.height<=e.y+e.height+1}function zp(e,t){let n=Math.max(e.x,t.x),r=Math.min(e.x+e.width,t.x+t.width),i=Math.max(e.y,t.y),a=Math.min(e.y+e.height,t.y+t.height);return Math.max(0,r-n)*Math.max(0,a-i)/Math.max(1,Math.min(X(e),X(t)))}function Z(e,t){let n=[e.label,je(e),e.identifier,e.value].filter(e=>!!e);return n.some(e=>e===t)?0:n.some(e=>He(e)===He(t))?1:n.some(e=>Gf(e,t))?2:3}const Q={animationPollMs:250,assertVisibleGraceMs:1e3,assertVisiblePollMs:250,assertVisibleRetryTimeoutMs:5e3,assertNotVisiblePollMs:250,defaultAssertNotVisibleTimeoutMs:3e3};async function Bp(e){let t=om(e.positionals,{command:`assertVisible`,defaultTimeoutMs:17e3});if(!t.ok)return t.response;let n=im(e.baseReq,t.selector);return n?await Vp(e,t,n):await Wp(e,t)}async function Vp(e,t,n){let r=Date.now(),i=await Up(e,t,n);if(i.ok){if(Hp(e.baseReq)){let n=await sm(e,t.selector,`assertVisible`);if(!n.visible){let i=em(e.baseReq,t,n,r);return i.kind===`return`?i.response:await Wp(e,t)}}return Ef(e.scope,t.selector),fm({ok:!0,data:{selector:t.selector,nativeWait:!0,query:n,response:i.data}},t.selector,r)}return await Gp(e,t,i,r)}function Hp(e){return e.flags?.platform===`android`}async function Up(e,t,n){return await e.invoke({...e.baseReq,command:`wait`,positionals:[n,String(t.timeoutMs)]})}async function Wp(e,t){let n=Date.now(),r=t.timeoutMs+Q.assertVisibleGraceMs,i,a,o=!1;for(;;){let s=Date.now(),c=await sm(e,t.selector,`assertVisible`);if(c.visible)return fm(c.response,t.selector,n);i=c.response,a=c.snapshot??a;let l=em(e.baseReq,t,c,n);if(l.kind===`return`)return l.response;let u=nm({captureStartedAt:s,capturedAfterDeadline:o,startedAt:n,deadlineMs:r});if(u===`capture-again`){o=!0;continue}if(u===`finish`)break;await w(Q.assertVisiblePollMs)}let s=i??q(`COMMAND_FAILED`,`Expected visible but did not match: ${t.selector}`,{selector:t.selector,timeoutMs:t.timeoutMs});return await Kp(e,t,a)||pm(s,a,e.baseReq)}async function Gp(e,t,n,r){let i=await sm(e,t.selector,`assertVisible`);if(i.visible)return fm(i.response,t.selector,r);let a=em(e.baseReq,t,i,r);return a.kind===`return`?a.response:await Kp(e,t,i.snapshot)||pm(n,i.snapshot,e.baseReq)}async function Kp(e,t,n){if(e.baseReq.flags?.platform!==`android`)return null;let r=Af(e.scope);return r?r.kind===`tap`?await qp(e,t,n,r):await Jp(e,t,r):null}async function qp(e,t,n,r){if(!n)return null;let i=Xp(e,n,r);return!i.ok||(h({level:`info`,phase:`maestro_assert_visible_retry_tap`,data:{selector:t.selector,tapSelector:r.selector,originalPoint:r.point,retryTarget:i.target,timeoutMs:Q.assertVisibleRetryTimeoutMs}}),!(await Zp(e,i.target)).ok)?null:await Yp(e,t,`retryTap`)}async function Jp(e,t,n){return h({level:`info`,phase:`maestro_assert_visible_retry_swipe`,data:{selector:t.selector,swipePositionals:n.positionals,timeoutMs:Q.assertVisibleRetryTimeoutMs}}),(await Qp(e,n)).ok?await Yp(e,t,`retrySwipe`):null}async function Yp(e,t,n){let r={...t,timeoutMs:Math.min(t.timeoutMs,Q.assertVisibleRetryTimeoutMs)},i=im(e.baseReq,r.selector);if(!i)return await Wp(e,r);let a=Date.now(),o=await Up(e,r,i);return o.ok?(Ef(e.scope,r.selector),fm({ok:!0,data:{selector:r.selector,nativeWait:!0,[n]:!0,query:i,response:o.data}},r.selector,a)):await Gp(e,r,o,a)}function Xp(e,t,n){let r=J(e.baseReq.flags),i=j(t),a=Pf(t,n.selector,n.options??{},r,i,{promoteTapTarget:!0});if(a.ok)return{ok:!0,target:{kind:`point`,point:vf(a)}};let o=Y(n.selector);return!o||!$p(t,o)?{ok:!1}:{ok:!0,target:{kind:`text`,query:o}}}async function Zp(e,t){return t.kind===`text`?await e.invoke({...e.baseReq,command:`find`,positionals:[t.query,`click`],flags:{...e.baseReq.flags,findFirst:!0,postGestureStabilization:!0}}):await e.invoke({...e.baseReq,command:`click`,positionals:[String(t.point.x),String(t.point.y)],flags:{...e.baseReq.flags,postGestureStabilization:!0}})}async function Qp(e,t){return await e.invoke({...e.baseReq,command:`swipe`,positionals:t.positionals})}function $p(e,t){let n=t.trim().toLowerCase();return n?e.nodes.some(e=>[e.label,e.value,e.identifier].some(e=>e?.trim().toLowerCase().includes(n))):!1}function em(e,t,n,r){return rm(n.response)?{kind:`return`,response:n.response}:tm(e,t.selector,n.snapshot)?{kind:`return`,response:am(t.selector,t.timeoutMs,r)}:{kind:`continue`}}function tm(e,t,n){return e.flags?.maestro?.allowAlreadyPastLoading===!0&&n!==void 0&&lm(t,n)}function nm(e){return Date.now()-e.startedAt<e.deadlineMs?`wait`:_m(e.capturedAfterDeadline,e.captureStartedAt,e.startedAt,e.deadlineMs)?`capture-again`:`finish`}function rm(e){return!e.ok&&e.error.code===`COMMAND_FAILED`&&e.error.message.includes(`React Native overlay`)}function im(e,t){return e.flags?.platform!==`ios`&&e.flags?.platform!==`android`?null:Y(t)}function am(e,t,n){return{ok:!0,data:{selector:e,alreadyPastLoading:!0,waitedMs:Date.now()-n,timeoutMs:t}}}function om(e,t){let[n,r=String(t.defaultTimeoutMs)]=e;if(!n)return{ok:!1,response:q(`INVALID_ARGS`,`${t.command} requires a selector.`)};let i=Number(r);return!Number.isFinite(i)||i<0?{ok:!1,response:q(`INVALID_ARGS`,`${t.command} timeout must be a non-negative number.`)}:{ok:!0,selector:n,timeoutMs:i}}async function sm(e,t,n){return cm(e,t,n,await Cf(e))}function cm(e,t,n,r){if(!r.ok)return{visible:!1,response:r,infrastructureFailure:!0};let i=wf(r.data);if(!i)return{visible:!1,response:q(`COMMAND_FAILED`,`Unable to read snapshot data for ${n}.`),infrastructureFailure:!0};let a=If(i,t,J(e.baseReq.flags),j(i));return a.ok?(Ef(e.scope,t),{visible:!0,response:{ok:!0,data:{selector:t,matches:a.matches,nodeIndex:a.node.index,nodeType:a.node.type,nodeLabel:a.node.label,nodeIdentifier:a.node.identifier,rect:a.rect}}}):{visible:!1,response:q(`COMMAND_FAILED`,a.message,{selector:t}),infrastructureFailure:!1,snapshot:i}}function lm(e,t){let n=um(Y(e));if(!dm(n))return!1;let r=t.nodes.flatMap(e=>[e.label,e.value,e.identifier]).filter(e=>!!e?.trim()).map(e=>um(e));return r.some(e=>e.includes(`something went wrong`))?!1:r.some(e=>e!==n&&!dm(e))}function um(e){return e?.trim().toLowerCase().replace(/\u2026/g,`...`)??``}function dm(e){return e===`loading`||e===`loading...`}function fm(e,t,n){return e.ok?{ok:!0,data:{selector:t,...e.data,waitedMs:Date.now()-n}}:e}function pm(e,t,n){if(e.ok||!t)return e;let r=typeof n.flags?.artifactsDir==`string`?n.flags.artifactsDir:void 0;if(!r)return e;let i=mm(t,r);return i.length===0?e:{ok:!1,error:{...e.error,details:{...e.error.details??{},artifactPaths:gm([...hm(e.error.details?.artifactPaths),...i])}}}}function mm(e,t){try{L.mkdirSync(t,{recursive:!0});let n=R.join(t,`failure-snapshot.json`),r=R.join(t,`failure-snapshot.txt`);L.writeFileSync(n,`${JSON.stringify(e,null,2)}\n`);let i=ce(e.nodes,{summarizeTextSurfaces:!0}).map(e=>e.text);return L.writeFileSync(r,`${i.join(`
|
|
25
|
-
`)}\n`),[n,r]}catch{return[]}}function
|
|
26
|
-
`]})}function eh(e){let[t]=e.positionals;if(!t)return q(`INVALID_ARGS`,`runScript requires a file path.`);try{return{ok:!0,data:{outputEnv:Gl({scriptPath:t,env:{...e.scope.values,...e.baseReq.flags?.maestro?.runScriptEnv??{}}})}}}catch(e){let t=n(e);return q(t.code,t.message,t.details)}}async function th(e){for(let[t,n]of e.actions.entries()){let r=await e.invokeReplayAction({action:n,line:e.line,step:e.step+t/1e3});if(!r.ok)return r}return{ok:!0,data:{ran:e.actions.length}}}async function nh(e){let t;for(let n=0;n<=e.maxRetries;n+=1){let r=await th({actions:e.actions,line:e.line,step:e.step+n,invokeReplayAction:e.invokeReplayAction});if(r.ok)return{ok:!0,data:{attempts:n+1,retried:n>0}};t=r}return t??{ok:!1,error:{code:`COMMAND_FAILED`,message:`retry commands failed.`}}}const rh={visibleTimeoutMs:3e3,visiblePollMs:250};async function ih(e){let t=await ah(e,e.control);return t.ok?t.matched?await lh(e):{ok:!0,data:{skipped:!0,condition:e.control.mode,selector:e.control.selector}}:t.response}async function ah(e,t){if(t.mode===`visible`)return await oh(e,t);let n=await sh(e,t.selector);return n.ok?{ok:!0,matched:!n.matched}:{ok:!1,response:n.response}}async function oh(e,t){let n=Date.now();for(;;){let r=await sh(e,t.selector);if(!r.ok)return{ok:!1,response:r.response};if(r.matched)return{ok:!0,matched:!0};if(Date.now()-n>=rh.visibleTimeoutMs)return{ok:!0,matched:!1};await w(rh.visiblePollMs)}}async function sh(e,t){let n=await Cf(e);return n.ok?ch(e,t,n):{ok:!1,response:n}}function ch(e,t,n){let r=wf(n.data);return r?{ok:!0,matched:If(r,t,J(e.baseReq.flags),j(r)).ok}:{ok:!1,response:q(`COMMAND_FAILED`,`Unable to read snapshot data for runFlow.when.`)}}async function lh(e){let t=await th({actions:e.control.actions,line:e.line,step:e.step,invokeReplayAction:e.invokeReplayAction});return t.ok?{ok:!0,data:{ran:t.data?.ran,condition:e.control.mode,selector:e.control.selector}}:t}async function uh(e){let{req:t,sessionName:n,action:r,scope:i,filePath:a,line:o,step:s,tracePath:c,invoke:l}=e,u=sr(r,i,{file:a,line:o}),d=e=>uh({req:t,sessionName:n,action:e.action,scope:i,filePath:a,line:e.line,step:e.step,tracePath:c,invoke:l}),f=Date.now();hh(c,{type:`replay_action_start`,ts:new Date(f).toISOString(),replayPath:a,line:o,step:s,command:u.command,positionals:u.positionals??[]});let p=await dh({req:t,sessionName:n,resolved:u,scope:i,line:o,step:s,invoke:l,invokeReplayAction:d}),m=Date.now();return hh(c,{type:`replay_action_stop`,ts:new Date(m).toISOString(),replayPath:a,line:o,step:s,command:u.command,ok:p.ok,durationMs:m-f,resultTiming:p.ok?mh(p.data):void 0,errorCode:p.ok?void 0:p.error.code}),p}async function dh(e){let{req:t,sessionName:n,resolved:r,scope:i,line:a,step:o,invoke:s,invokeReplayAction:c}=e,l=gh(t.flags,r.flags),u={token:t.token,session:n,flags:l,runtime:r.runtime,meta:t.meta,internal:t.internal},d=await fh({control:r.replayControl,baseReq:u,line:a,step:o,invoke:s,invokeReplayAction:c})??await Qm({command:r.command,baseReq:u,positionals:r.positionals??[],scope:i,line:a,step:o,invoke:s,invokeReplayAction:c})??await s({...u,command:r.command,positionals:r.positionals??[]});if(d.ok){let e=ph(d.data);e&&or(i,e)}return d}async function fh(e){let{control:t,baseReq:n,line:r,step:i,invoke:a,invokeReplayAction:o}=e;if(t){switch(t.kind){case`retry`:return await nh({actions:t.actions,maxRetries:t.maxRetries,line:r,step:i,invokeReplayAction:o});case`maestroRunFlowWhen`:return await ih({baseReq:n,control:t,line:r,step:i,invoke:a,invokeReplayAction:o})}return t}}function ph(e){if(!e||typeof e!=`object`)return null;let t=e.outputEnv;if(!t||typeof t!=`object`||Array.isArray(t))return null;let n=Object.entries(t).filter(e=>typeof e[1]==`string`);return n.length>0?Object.fromEntries(n):null}function mh(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e.timing;if(!(!t||typeof t!=`object`||Array.isArray(t)))return Object.fromEntries(Object.entries(t).filter(([,e])=>{let t=typeof e;return t===`number`||t===`string`||t===`boolean`}))}function hh(e,t){e&&L.appendFileSync(e,`${JSON.stringify(t)}\n`)}function gh(e,t){return Re(e,{...t??{}})}async function _h(e){let{req:t,sessionName:r,logPath:i,sessionStore:a,tracePath:o,invoke:s}=e,c=t.positionals?.[0];if(!c)return k(`INVALID_ARGS`,`replay requires a path`);let l=``,u=new Set;try{l=A.expandHome(c,t.meta?.cwd);let e=L.readFileSync(l,`utf8`),n=e.trimStart()[0];if(n===`{`||n===`[`)return k(`INVALID_ARGS`,`replay accepts .ad script files. JSON replay payloads are no longer supported.`);let d=rf(e,t.flags,{sourcePath:l}),f=d.metadata,p=f.platform||f.target?{...t,flags:wh(t.flags,f)}:t,m=d.actions,h=d.actionLines;if(t.flags?.replayUpdate===!0&&d.updateUnsupportedMessage)return k(`INVALID_ARGS`,d.updateUnsupportedMessage);if(t.flags?.replayUpdate===!0&&f.env&&Object.keys(f.env).length>0)return k(`INVALID_ARGS`,`replay -u does not yet preserve env directives. Temporarily remove the env lines, run replay -u, then restore them.`);if(t.flags?.replayUpdate===!0&&jh(m))return k(`INVALID_ARGS`,"replay -u does not yet preserve ${VAR} substitutions. Resolve or inline the variables before running with -u.");let g=wr({builtins:vh({req:p,sessionName:r,metadata:f,resolvedPath:l}),fileEnv:f.env,shellEnv:lr(cr(t.flags?.replayShellEnv)),cliEnv:Cr(ur(t.flags?.replayEnv))}),_=t.flags?.replayUpdate===!0,v=o??a.get(r)?.trace?.outPath,y=[],b=0;for(let e=0;e<m.length;e+=1){let t=m[e];if(!t||t.command===`replay`)continue;yh(l,e,m.length,t);let n=Oh(a,r),o=await uh({req:p,sessionName:r,action:t,scope:g,filePath:l,line:h[e]??0,step:e+1,tracePath:v,invoke:s});if(y.push(...kh(a,r,n)),o.ok){Dh(o).forEach(e=>u.add(e));continue}if(Dh(o).forEach(e=>u.add(e)),!_)return Th(o,t,e,l,[...u],y);let c=await uf({action:t,sessionName:r,logPath:i,sessionStore:a});if(!c)return Th(o,t,e,l,[...u],y);m[e]=c;let d=Oh(a,r);if(o=await uh({req:p,sessionName:r,action:c,scope:g,filePath:l,line:h[e]??0,step:e+1,tracePath:v,invoke:s}),y.push(...kh(a,r,d)),!o.ok)return Dh(o).forEach(e=>u.add(e)),Th(o,c,e,l,[...u],y);Dh(o).forEach(e=>u.add(e)),b+=1}_&&b>0&&dr(l,m,a.get(r));let x=ne(y);return{ok:!0,data:{replayed:m.length,healed:b,session:r,artifactPaths:[...u],...x?{snapshotDiagnostics:x}:{}}}}catch(e){let t=n(e);return k(t.code,t.message,u.size>0?{artifactPaths:[...u]}:void 0)}}function vh(e){let{req:t,sessionName:n,metadata:r,resolvedPath:i}=e,a=t.flags??{},o=t.meta?.cwd??process.cwd(),s={AD_SESSION:n,AD_FILENAME:R.relative(o,i)||i},c=a.platform??r.platform;c&&(s.AD_PLATFORM=c);let l=a.target??r.target;l&&(s.AD_TARGET=l);let u=a.device;typeof u==`string`&&u.length>0&&(s.AD_DEVICE=u);let d=typeof a.serial==`string`?a.serial:a.udid;typeof d==`string`&&d.length>0&&(s.AD_DEVICE_ID=d),typeof a.shardIndex==`number`&&(s.AD_SHARD_INDEX=String(a.shardIndex)),typeof a.shardCount==`number`&&(s.AD_SHARD_COUNT=String(a.shardCount));let f=a.artifactsDir;return typeof f==`string`&&f.length>0&&(s.AD_ARTIFACTS=f),s}function yh(e,t,n,r){let i=pt();i&&T({type:`replay-test`,...i,file:i.file||e,status:`progress`,stepIndex:t+1,stepTotal:n,...bh(r)})}function bh(e){return{stepCommand:xh(e.command),...Sh(e)}}function xh(e){if(!e.startsWith(`__maestro`))return e;let t=e.slice(9);return t.length>0?t[0].toLowerCase()+t.slice(1):e}function Sh(e){let t=e.positionals??[],n=Ch(t[0]);return n?{stepValue:n}:e.command===`__maestroTapPointPercent`&&t.length>=2?{stepValue:`${t[0]},${t[1]}%`}:t.length===0?{}:{stepValue:t.join(` `)}}function Ch(e){if(!e)return;let t=C(e);if(!t)return;let n=t.selectors.flatMap(e=>e.terms.flatMap(e=>(e.key===`label`||e.key===`text`||e.key===`id`)&&typeof e.value==`string`?[e.value]:[]));if(n.length===0)return;let r=n[0];return r&&n.every(e=>e===r)?r:void 0}function wh(e,t){return{...e??{},...t.platform!==void 0&&e?.platform===void 0?{platform:t.platform}:{},...t.target!==void 0&&e?.target===void 0?{target:t.target}:{}}}function Th(e,t,n,r,i,a){return Eh(e,t,n,r,i,ne(a))}function Eh(e,t,n,r,i=[],a){if(e.ok)return e;let o=n+1;return{ok:!1,error:{code:e.error.code,message:`Replay failed at step ${o} (${st(t)}): ${e.error.message}`,hint:e.error.hint,diagnosticId:e.error.diagnosticId,logPath:e.error.logPath,details:{...e.error.details??{},replayPath:r,step:o,action:t.command,positionals:t.positionals??[],artifactPaths:i,...a?{snapshotDiagnostics:a}:{}}}}}function Dh(e){if(!e.ok){let t=e.error.details?.artifactPaths;return Array.isArray(t)?[...new Set(t.filter(e=>typeof e==`string`&&Ah(e)))]:[]}if(!e.data)return[];let t=[];if(typeof e.data.path==`string`&&t.push(e.data.path),typeof e.data.outPath==`string`&&t.push(e.data.outPath),Array.isArray(e.data.artifacts))for(let n of e.data.artifacts){if(!n||typeof n!=`object`)continue;let e=n,r=typeof e.localPath==`string`?e.localPath:void 0,i=typeof e.path==`string`?e.path:void 0;r?t.push(r):i&&t.push(i)}return[...new Set(t.filter(e=>Ah(e)))]}function Oh(e,t){return e.get(t)?.snapshotDiagnostics?.samples.length??0}function kh(e,t,n){return e.get(t)?.snapshotDiagnostics?.samples.slice(n)??[]}function Ah(e){try{return L.statSync(e).isFile()}catch{return!1}}function jh(e){for(let t of e){for(let e of t.positionals??[])if(typeof e==`string`&&e.includes("${"))return!0;if(Mh(t.flags)||Mh(t.runtime))return!0}return!1}function Mh(e){return typeof e==`string`?e.includes("${"):Array.isArray(e)?e.some(Mh):e&&typeof e==`object`?Object.values(e).some(Mh):!1}const Nh=1e3,Ph=3e3;function Fh(e){if(e.req.flags?.recordVideo===!0)return{beforeDispatch:async()=>await Ih(e)}}async function Ih(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,artifactsDir:a,tracePath:o}=e;if(t.flags?.recordVideo!==!0)return;let s=i.get(n);if(!s||s.recording)return;let c=ee(s.device.platform),l=a?R.join(a,`recording${c}`):te(s.device.platform);Rh(o,{type:`video_recording_start`,session:n,videoPath:l}),h({phase:`replay_test_video_recording_start`,data:{session:n,videoPath:l}});let u=await Ir({req:{token:t.token,session:n,command:`record`,positionals:[`start`,l],flags:{},meta:t.meta},sessionName:n,sessionStore:i,logPath:r});if(!u.ok)return Rh(o,{type:`video_recording_start_failed`,session:n,videoPath:l,errorCode:u.error.code}),u;let d=Date.now();return await w(Nh),Rh(o,{type:`video_preroll_done`,session:n,durationMs:Date.now()-d,requestedDurationMs:Nh}),h({phase:`replay_test_video_recording_preroll_done`,durationMs:Date.now()-d,data:{session:n,requestedDurationMs:Nh}}),u}async function Lh(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,tracePath:a,artifactPaths:o}=e;if(t.flags?.recordVideo!==!0||!i.get(n)?.recording)return;Rh(a,{type:`video_tail_start`,session:n,requestedDurationMs:Ph});let s=Date.now();await w(Ph);let c=Date.now(),l=await Ir({req:{token:t.token,session:n,command:`record`,positionals:[`stop`],flags:{},meta:t.meta},sessionName:n,sessionStore:i,logPath:r});return Dh(l).forEach(e=>o.add(e)),Rh(a,{type:`video_recording_stop`,session:n,ok:l.ok,durationMs:Date.now()-c,tailDurationMs:c-s,errorCode:l.ok?void 0:l.error.code}),h({phase:`replay_test_video_recording_stop`,durationMs:Date.now()-c,data:{session:n,ok:l.ok,tailDurationMs:c-s}}),l}function Rh(e,t){K(e,{...t,ts:new Date().toISOString()})}function zh(e){let{platform:t,target:n,artifactsDir:r,shard:i}=e,a=Bh(e.parentFlags);return t===void 0&&n===void 0&&r===void 0&&i===void 0?a:Od({...a??{},...t===void 0?{}:{platform:t},...n===void 0?{}:{target:n},...r===void 0?{}:{artifactsDir:r}},i)}function Bh(e){if(e?.recordVideo!==!0)return e;let t={...e};return delete t.recordVideo,Object.keys(t).length>0?t:void 0}async function Vh(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,leaseRegistry:a,invoke:o}=e;return t.command===`replay`?await _h({req:t,sessionName:n,logPath:r,sessionStore:i,invoke:o}):t.command===`test`?await Vd({req:t,sessionName:n,runReplay:async({filePath:e,sessionName:n,platform:a,target:s,requestId:c,artifactsDir:l,artifactPaths:u,tracePath:d,shard:f})=>{let p=e=>(u&&Dh(e).forEach(e=>u.add(e)),e),m=zh({parentFlags:t.flags,platform:a,target:s,artifactsDir:l,shard:f}),h={req:t,sessionName:n,logPath:r,sessionStore:i,artifactsDir:l,tracePath:d},g=Fh(h);return await _h({req:{...t,command:`replay`,session:n,positionals:[e],flags:m,meta:{...t.meta??{},...c?{requestId:c}:{}},...t.internal||g?{internal:{...t.internal??{},...g?{openLifecycle:g}:{}}}:{}},sessionName:n,logPath:r,sessionStore:i,tracePath:d,invoke:async e=>{let t=await Ih(h);return t&&!t.ok?t:p(await o(e))}})},finalizeAttempt:async({sessionName:e,artifactPaths:n,artifactsDir:a,tracePath:o})=>await Lh({req:t,sessionName:e,logPath:r,sessionStore:i,artifactsDir:a,tracePath:o,artifactPaths:n}),cleanupSession:async e=>{i.get(e)&&await Ka({req:{token:t.token,session:e,command:`close`,positionals:[],flags:{},meta:t.meta},sessionName:e,logPath:r,sessionStore:i,leaseRegistry:a})}}):null}function Hh(e){return e.some(e=>e.status===`fail`)?`fail`:e.some(e=>e.status===`warn`)?`warn`:`pass`}function Uh(e){return e===`fail`?`Blockers found before the run.`:e===`warn`?`No hard blockers found, but warnings need attention.`:`No blockers found.`}function Wh(e){let t={fail:0,warn:1,pass:2,info:3};return[...e].sort((e,n)=>t[e.status]-t[n.status])}function Gh(e,...t){for(let n of t)$(e,n)}function $(e,t){e.push(t),T({type:`command`,status:`progress`,message:Kh(t)})}function Kh(e){return[Te(e),...oe(e)].join(`
|
|
27
|
-
`)}async function
|
|
28
|
-
`).map(e=>e.startsWith(`p`)?Number.parseInt(e.slice(1),10):NaN).find(e=>Number.isInteger(e)&&e>0)}async function
|
|
29
|
-
`).find(e=>e.startsWith(`n`)&&e.length>1)?.slice(1)}const
|
|
30
|
-
`).map(e=>e.trim()).find(Boolean):void 0}catch{return}}async function
|
|
24
|
+
`],{stdin:JSON.stringify({method:e,url:n,headers:r?.headers??{},body:r?.body??``}),timeoutMs:Ul,allowFailure:!0});if(i.exitCode!==0)throw new t(`COMMAND_FAILED`,`Maestro runScript http.${e.toLowerCase()} failed for ${n}: ${eu(i.stderr)}`,{exitCode:i.exitCode,stderr:i.stderr});try{return JSON.parse(i.stdout)}catch(r){throw new t(`COMMAND_FAILED`,`Maestro runScript http.${e.toLowerCase()} returned invalid JSON for ${n}`,{stdout:i.stdout.slice(0,1e3),stderr:i.stderr.slice(0,1e3)},r instanceof Error?r:void 0)}}function Ql(e,n){for(let r of Object.keys(e))if(r.includes(`.`))throw new t(`INVALID_ARGS`,`Maestro runScript output key cannot contain ".": ${r}`,{scriptPath:n,key:r})}function $l(e){return typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`?String(e):JSON.stringify(e)}function eu(e){let t=e.trim();return t.length>0?t.slice(0,1e3):`request process exited without stderr`}const tu={launchApp:({value:e,config:t,context:n})=>[Bc(e,t,n)],tapOn:({value:e,context:t})=>[Kc(e,t)],doubleTapOn:({value:e,context:t})=>[qc(e,t)],longPressOn:({value:e,context:t})=>[Jc(e,t)],inputText:({value:e,context:t})=>[P(`type`,[I(Yc(e),t)])],eraseText:({value:e})=>[Xc(e)],pasteText:({value:e,context:t,name:n})=>[P(`type`,[I(mr(n,e),t)])],openLink:({value:e,config:t,context:n,name:r})=>[ou(e,t,n,r)],assertVisible:({value:e,context:t,name:n})=>[P(G.assertVisible,[K(e,n,[],t),`17000`])],assertNotVisible:({value:e,context:t,name:n})=>[P(G.assertNotVisible,[K(e,n,[],t)])],extendedWaitUntil:({value:e,context:t})=>Zc(e,t),takeScreenshot:({value:e,context:t,name:n})=>[P(`screenshot`,[I(mr(n,e),t)])],scroll:({value:e})=>[Qc(e)],scrollUntilVisible:({value:e,context:t})=>$c(e,t),swipe:({value:e,context:t})=>[el(e,t)],hideKeyboard:()=>[P(`keyboard`,[`dismiss`])],pressKey:({value:e})=>[cl(e)],back:()=>[P(`back`)],waitForAnimationToEnd:({value:e})=>[P(G.waitForAnimationToEnd,[String(br(e,15e3))])],stopApp:({value:e,config:t,context:n})=>[Vc(e,t,n)],runScript:({value:e,context:t})=>[Wl(e,t)],runFlow:({value:e,config:t,context:n,deps:r})=>yl(e,t,n,r,cu),repeat:({value:e,config:t,context:n,deps:r})=>bl(e,t,n,r,cu),retry:({value:e,config:t,context:n,deps:r})=>xl(e,t,n,r,cu)},nu={launchApp:(e,t)=>[Bc(void 0,e,t)],scroll:()=>[P(`scroll`,[`down`])],hideKeyboard:()=>[P(`keyboard`,[`dismiss`])],eraseText:()=>[Xc(void 0)],back:()=>[P(`back`)],waitForAnimationToEnd:()=>[P(G.waitForAnimationToEnd,[`15000`])],stopApp:(e,t)=>[Vc(void 0,e,t)]};function ru(e,n,r,i,a){try{return iu(e,n,i,a)}catch(e){throw e instanceof t&&!/\bline \d+\b/.test(e.message)?new t(e.code,`${e.message} (line ${r})`,e.details):e}}function iu(e,n,r,i){if(typeof e==`string`)return au(e,n,r);let a=Object.entries(e);if(a.length!==1)throw new t(`INVALID_ARGS`,`Maestro command maps must contain exactly one command.`);let[o,s]=a[0],c=tu[o];return c?c({value:s,config:n,context:r,deps:i,name:o}):_r(o)}function au(e,t,n){let r=nu[e];return r?r(t,n):_r(e)}function ou(e,t,n,r){let i=I(su(e,r),n);return(n.platform===`ios`||n.platform===`android`)&&t.appId?P(`open`,[I(pr(t,r),n),i],n.platform===`ios`?{maestro:{prewarmRunnerBeforeOpen:!0}}:void 0):P(`open`,[i])}function su(e,t){return typeof e==`string`?e:F(e)?(M(e,t,[`link`]),mr(`${t}.link`,e.link)):mr(t,e)}function cu(e,t,n,r){return e.flatMap((e,i)=>ru(e,t,i+1,n,r))}function lu(e,t={}){return du(e,bu(t))}function uu(e){let{config:t}=Su(hr(e));return t.name}function du(e,t){let{config:n,commands:r}=Su(hr(e)),i={...t,env:{...t.env,...n.env??{},...t.envOverrides}},{actions:a,actionLines:o}=fu({config:n,commands:r,commandLines:xu(e),context:i});return{actions:a,actionLines:o,metadata:{env:n.env}}}function fu(e){let{config:t,commands:n,commandLines:r,context:i}=e,a=[...t.onFlowStart??[],...n,...t.onFlowComplete??[]],o=[...Array.from({length:t.onFlowStart?.length??0},()=>1),...r,...Array.from({length:t.onFlowComplete?.length??0},()=>r.at(-1)??1)],s=[],c=[];for(let[e,n]of a.entries()){let r=o[e]??e+1,a=ru(n,t,r,i,{parseRunFlowFile:wu});s.push(...a),a.forEach(()=>c.push(r))}return pu(s,c)}function pu(e,t){let n=[],r=[];for(let i=0;i<e.length;i+=1){let a=e[i],o=mu(e,t,i);if(o){n.push(...o.actions),r.push(...o.actionLines),i+=o.consumed-1;continue}n.push(a),r.push(t[i]??1)}return{actions:n,actionLines:r}}function mu(e,t,n){let r=hu(e,t,n);if(!r)return null;let{action:i,nextAction:a,pressEnterAction:o,tapSelector:s,typedAfterTap:c,line:l}=r;return yu(s)?{actions:[{...i,command:`wait`,positionals:[s,`30000`]},{...a,command:`fill`,positionals:[s,c],flags:i.flags},o],actionLines:[l,l,t[n+2]??l],consumed:3}:{actions:[gu(i)],actionLines:[l],consumed:1}}function hu(e,t,n){let r=e[n],i=e[n+1],a=e[n+2];if(a?.command!==G.pressEnter||r.flags?.maestro?.optional===!0)return null;let o=vu(i),s=_u(r);return!i||o===null||s===null?null:{action:r,nextAction:i,pressEnterAction:a,tapSelector:s,typedAfterTap:o,line:t[n]??1}}function gu(e){let t={...e.flags?.maestro??{}};return delete t.allowNonHittableCoordinateFallback,{...e,flags:{...e.flags??{},maestro:{...t}}}}function _u(e){if(e?.command!==G.tapOn)return null;let[t,...n]=e.positionals??[];return n.length>0||typeof t!=`string`?null:t}function vu(e){if(e?.command!==`type`||e.flags&&Object.keys(e.flags).length>0)return null;let[t,...n]=e.positionals??[];return n.length>0||typeof t!=`string`?null:t}function yu(e){return/\b(input|textfield|textarea|field|email|password|username|search|query)\b/i.test(e.replace(/([a-z])([A-Z])/g,`$1 $2`))}function bu(e){let t=e.visitedPaths??new Set;return e.sourcePath&&t.add(B.resolve(e.sourcePath)),{baseDir:e.sourcePath?B.dirname(e.sourcePath):void 0,platform:fr(e.platform),env:{},envOverrides:e.env??{},visitedPaths:t}}function xu(e){let t=e.split(/\r?\n/),n=t.findIndex(e=>e.trim()===`---`),r=n===-1?0:n+1,i=[];for(let e=r;e<t.length;e+=1)/^-\s+/.test(t[e]??``)&&i.push(e+1);return i}function Su(e){if(e.length===0)throw new t(`INVALID_ARGS`,`Maestro flow is empty.`);if(Array.isArray(e[0]))return{config:{},commands:L(e[0])};let n=Cu(e[0]),r=e[1];if(!Array.isArray(r))throw new t(`INVALID_ARGS`,`Maestro flow must contain a command list after the YAML document separator.`);return{config:n,commands:L(r)}}function Cu(e){if(!F(e))throw new t(`INVALID_ARGS`,`Maestro flow config must be a YAML map.`);return{...typeof e.name==`string`&&e.name.length>0?{name:e.name}:{},...typeof e.appId==`string`&&e.appId.length>0?{appId:e.appId}:{},...F(e.env)?{env:gr(e.env,`env`)}:{},...Array.isArray(e.onFlowStart)?{onFlowStart:L(e.onFlowStart)}:{},...Array.isArray(e.onFlowComplete)?{onFlowComplete:L(e.onFlowComplete)}:{}}}function wu(e,n){let r=Tu(e,n);if(n.visitedPaths.has(r))throw new t(`INVALID_ARGS`,`Maestro runFlow cycle detected at ${r}.`);let i=z.readFileSync(r,`utf8`),a=new Set(n.visitedPaths);return a.add(r),du(i,{...n,baseDir:B.dirname(r),visitedPaths:a})}function Tu(e,n){if(B.isAbsolute(e))return e;if(!n.baseDir)throw new t(`INVALID_ARGS`,`runFlow file paths require replay input to have a source path.`);return B.resolve(n.baseDir,e)}const Eu=/[*?[\]{}]/;function Du(e){let{inputs:n,cwd:r,platformFilter:i,replayBackend:a}=e,o=Lu(a),s=Nu(n,r??process.cwd(),o,a),c=[];for(let e of s){let t=z.readFileSync(e,`utf8`),n=wr(t),r=Wu(t,e,a);if(!i){c.push({kind:`run`,path:e,title:r,metadata:n});continue}if(!n.platform){Uu(a)?c.push({kind:`run`,path:e,title:r,metadata:n}):c.push({kind:`skip`,path:e,reason:`skipped-by-filter`,message:`missing platform metadata for --platform ${i}`});continue}Ku(i,n.platform)&&c.push({kind:`run`,path:e,title:r,metadata:n})}if(c.filter(e=>e.kind===`run`).length===0)throw new t(`INVALID_ARGS`,`No replay tests matched${i?` for --platform ${i}`:``}.`);return c}function Ou(e,t,n,r,i=0){let a=B.basename(n,B.extname(n)).toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``);return`${e}:test:${t}:${r+1}${a?`-${a}`:``}:attempt-${i+1}`}function ku(e){return(e?.trim()||`${process.pid}-${Date.now().toString(36)}`).toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`suite`}function Au(e){let{requestId:t,suiteInvocationId:n,filePath:r,caseIndex:i,attemptIndex:a,shardIndex:o}=e,s=o===void 0?``:`:shard:${o+1}`;return St(`${t??n}${s}:test:${i+1}:${B.basename(r)}:attempt:${a+1}`,n)}function ju(e,t){return typeof e==`number`?e:t}function Mu(e,t){let n=typeof e==`number`?e:t;return typeof n==`number`?Math.max(0,Math.min(3,n)):0}function Nu(e,t,n,r){if(!Uu(r))return[...new Set(e.flatMap(e=>Iu(e,t,n).paths))].map(e=>B.normalize(e)).sort((e,t)=>e.localeCompare(t));let i=[],a=[];for(let r of e){let e=Pu(r,t,n);e.source===`file`?i.push(...e.paths):a.push(e.source===`directory`?Hu(e.paths):zu(e.paths))}return Hu([...i,...a.flat()])}function Pu(e,t,n){let r=A.expandHome(e,t);return z.existsSync(r)&&z.statSync(r).isDirectory()?{paths:Fu(r,n),source:`directory`}:Iu(e,t,n)}function Fu(e,t){let n=[],r=z.opendirSync(e);try{let i;for(;(i=r.readSync())!==null;){let r=B.join(e,i.name);i.isDirectory()?n.push(...Fu(r,t)):i.isFile()&&t.has(B.extname(i.name))&&n.push(r)}}finally{r.closeSync()}return n}function Iu(e,n,r){let i=A.expandHome(e,n);if(z.existsSync(i)){let n=z.statSync(i);if(n.isDirectory())return{paths:Ru(r).flatMap(e=>z.globSync(e,{cwd:i}).map(e=>B.join(i,e))),source:`directory`};if(n.isFile()){if(!r.has(B.extname(i)))throw new t(`INVALID_ARGS`,`test does not support this file type: ${e}`);return{paths:[i],source:`file`}}return{paths:[],source:`file`}}if(!Gu(e)&&!Gu(i))throw new t(`INVALID_ARGS`,`test input not found: ${e}`);let a=B.isAbsolute(i)?i:e;return{paths:z.globSync(a,{cwd:B.isAbsolute(i)?void 0:n}).map(e=>B.isAbsolute(e)?e:B.resolve(n,e)).filter(e=>r.has(B.extname(e))&&qu(e)),source:`glob`}}function Lu(e){return Uu(e)?new Set([`.yaml`,`.yml`,`.ad`]):new Set([`.ad`])}function Ru(e){return[...e].map(e=>`**/*${e}`)}function zu(e){return e.map(e=>B.normalize(e)).sort(Bu)}function Bu(e,t){let n=Vu(e),r=Vu(t);return n===r?e.localeCompare(t):n-r}function Vu(e){return+(B.extname(e)===`.ad`)}function Hu(e){return[...new Set(e.map(e=>B.normalize(e)))]}function Uu(e){return e===`maestro`}function Wu(e,t,n){return Uu(n)&&B.extname(t)!==`.ad`?uu(e):void 0}function Gu(e){return Eu.test(e)}function Ku(e,t){return e===`apple`?a(t):t===e}function qu(e){try{return z.statSync(e).isFile()}catch{return!1}}const Ju=[`failed to start daemon`,`runner did not accept connection`,`xcodebuild exited early`,`device is offline`,`device offline`,`device unauthorized`];function Yu(e){let t=Xu(e);return t?Zu(t.details)||Qu(t.code,t.message):!1}function Xu(e){return`ok`in e?e.ok?null:e.error:e.status===`failed`?e.error:null}function Zu(e){let t=typeof e?.reason==`string`?e.reason:``;return t===`timeout_cleanup_pending`?!0:t?it(t):!1}function Qu(e,t){let n=`${e}\n${t}`.toLowerCase();return Ju.some(e=>n.includes(e))}const $u=2e3;async function ed(t){let{filePath:n,sessionName:r,requestId:i,parentRequestId:a,timeoutMs:o,platform:s,target:c,artifactsDir:l,shard:u,progress:d,runReplay:f,cleanupSession:p,finalizeAttempt:m}=t;ct(i);let g=td(i,a),_=new Set,v,y=!1,b,ee=Date.now(),x=sd({artifactsDir:l,artifactPaths:_,filePath:n,sessionName:r,requestId:i,timeoutMs:o,platform:s,target:c}),S=ft(d,async()=>await f({filePath:n,sessionName:r,platform:s,target:c,requestId:i,artifactsDir:l,artifactPaths:_,tracePath:x,shard:u})).catch(t=>({ok:!1,error:e(t)})).finally(()=>{g(),xt(i)});try{b=typeof o==`number`?await Promise.race([S,new Promise(e=>{v=setTimeout(()=>{y=!0,lt(i),e(cd(o,[..._]))},o)})]):await S,q(x,{type:`replay_test_attempt_stop`,ts:new Date().toISOString(),session:r,ok:b.ok,timedOut:y,durationMs:Date.now()-ee,errorCode:b.ok?void 0:b.error.code})}finally{v&&clearTimeout(v),y&&(await nd(S)||(ad(b),h({level:`warn`,phase:`test_timeout_cleanup_race`,data:{session:r,requestId:i,graceMs:$u}}),rd({replayPromise:S,cleanupSession:p,sessionName:r,requestId:i})));let t=await id({finalizeAttempt:m,sessionName:r,artifactPaths:_,artifactsDir:l,tracePath:x});b?.ok&&t&&!t.ok&&od(b,`Replay test finalization failed: ${t.error.message}`);let n=Date.now();try{q(x,{type:`replay_test_cleanup_start`,ts:new Date().toISOString(),session:r}),await p(r),q(x,{type:`replay_test_cleanup_stop`,ts:new Date().toISOString(),session:r,ok:!0,durationMs:Date.now()-n})}catch(t){let i=e(t);q(x,{type:`replay_test_cleanup_stop`,ts:new Date().toISOString(),session:r,ok:!1,durationMs:Date.now()-n,errorCode:i.code}),h({level:`warn`,phase:`test_cleanup_failed`,data:{session:r,error:i.message}})}}return b??{ok:!1,error:{code:`COMMAND_FAILED`,message:`Unknown replay test failure`}}}function td(e,t){if(!t||t===e)return()=>{};let n=ut(t);if(!n)return()=>{};let r=()=>{lt(e)};return n.aborted?(r(),()=>{}):(n.addEventListener(`abort`,r,{once:!0}),()=>{n.removeEventListener(`abort`,r)})}async function nd(e){return await Promise.race([e.then(()=>!0),Ir($u).then(()=>!1)])}async function rd(t){let{replayPromise:n,cleanupSession:r,sessionName:i,requestId:a}=t;try{await n}finally{try{await r(i)}catch(t){h({level:`warn`,phase:`test_late_cleanup_failed`,data:{session:i,requestId:a,error:e(t).message}})}}}async function id(t){let{finalizeAttempt:n,sessionName:r,artifactPaths:i,artifactsDir:a,tracePath:o}=t;if(!n)return;let s=Date.now();q(o,{type:`replay_test_finalize_start`,ts:new Date().toISOString(),session:r});try{let e=await n({sessionName:r,artifactPaths:i,artifactsDir:a,tracePath:o});return q(o,{type:`replay_test_finalize_stop`,ts:new Date().toISOString(),session:r,ok:e?.ok??!0,durationMs:Date.now()-s,errorCode:e?.ok===!1?e.error.code:void 0}),e}catch(t){let n=e(t);return q(o,{type:`replay_test_finalize_stop`,ts:new Date().toISOString(),session:r,ok:!1,durationMs:Date.now()-s,errorCode:n.code}),h({level:`warn`,phase:`test_finalize_failed`,data:{session:r,error:n.message}}),{ok:!1,error:n}}}function ad(e){!e||e.ok||(e.error.details={...e.error.details??{},reason:`timeout_cleanup_pending`,timeoutCleanupPending:!0})}function od(e,t){let n=e.data??={};n.warnings=[...Array.isArray(n.warnings)?n.warnings.filter(e=>typeof e==`string`):[],t]}function sd(e){let{artifactsDir:t,artifactPaths:n,filePath:r,sessionName:i,requestId:a,timeoutMs:o,platform:s,target:c}=e;if(!t)return;let l=B.join(t,`replay-timing.ndjson`);return z.mkdirSync(B.dirname(l),{recursive:!0}),z.writeFileSync(l,``),n.add(l),q(l,{type:`replay_test_attempt_start`,ts:new Date().toISOString(),replayPath:r,session:i,requestId:a,timeoutMs:o,platform:s,target:c}),l}function q(e,t){e&&z.appendFileSync(e,`${JSON.stringify(t)}\n`)}function cd(e,t=[]){return{ok:!1,error:{code:`COMMAND_FAILED`,message:`TIMEOUT after ${e}ms`,hint:`Replay test timeouts are cooperative; the active command may take a short grace period to stop.`,details:{reason:`timeout`,timeoutMs:e,timeoutMode:`cooperative`,artifactPaths:t}}}}async function ld(e){let t=ud(e);return _d(e,t,await dd(e,t))}function ud(e){let{entry:t,cwd:n,retries:r,suiteArtifactsDir:i,shard:a}=e;return{testStartedAt:Date.now(),testArtifactsDir:B.join(i,...a?[`shard-${a.shardIndex+1}`]:[],jc(t.path,n)),maxAttempts:r+1}}async function dd(e,t){pd(e,t);let n={finalSessionName:``,attempts:0,finalAttemptDurationMs:0,attemptFailures:[]};for(let r=0;r<=e.retries&&!Ct(e.requestId);r+=1){let i=await fd(e,t,r);if(md(n,i),hd(e,i.response,r))break;gd(e,t,i)}return n}async function fd(e,t,n){let{entry:r,sessionName:i,suiteInvocationId:a,caseIndex:o,suiteIndex:s,suiteTotal:c,requestId:l,timeoutMs:u,shard:d}=e,f=n+1,p=Date.now(),m=Ou(i,a,r.path,o,n),h=B.join(t.testArtifactsDir,`attempt-${f}`);Mc(r.path,h);let g=Au({requestId:l,suiteInvocationId:a,filePath:r.path,caseIndex:o,attemptIndex:n,shardIndex:d?.shardIndex}),_=await ed({filePath:r.path,sessionName:m,requestId:g,parentRequestId:l,timeoutMs:u,platform:r.metadata.platform,target:r.metadata.target,artifactsDir:h,shard:d,progress:{file:r.path,title:r.title,index:s,total:c,attempt:f,maxAttempts:t.maxAttempts,session:m,artifactsDir:t.testArtifactsDir,...Ed(d)},runReplay:e.runReplay,cleanupSession:e.cleanupSession,finalizeAttempt:e.finalizeAttempt}),v=Date.now()-p;return Nc({response:_,filePath:r.path,sessionName:m,attempts:f,maxAttempts:t.maxAttempts,attemptArtifactsDir:h}),{response:_,sessionName:m,attempt:f,durationMs:v}}function pd(e,t){let{entry:n,sessionName:r,suiteInvocationId:i,caseIndex:a,suiteIndex:o,suiteTotal:s,shard:c}=e;T({type:`replay-test`,file:n.path,title:n.title,status:`start`,index:o,total:s,maxAttempts:t.maxAttempts,session:Ou(r,i,n.path,a),artifactsDir:t.testArtifactsDir,...Ed(c)})}function md(e,t){e.finalResponse=t.response,e.finalSessionName=t.sessionName,e.attempts=t.attempt,e.finalAttemptDurationMs=t.durationMs,!t.response.ok&&e.attemptFailures.push({attempt:t.attempt,message:t.response.error.message,durationMs:t.durationMs})}function hd(e,t,n){return t.ok||Ct(e.requestId)||Yu(t)||n>=e.retries}function gd(e,t,n){n.response.ok||T({type:`replay-test`,file:e.entry.path,title:e.entry.title,status:`fail`,index:e.suiteIndex,total:e.suiteTotal,attempt:n.attempt,maxAttempts:t.maxAttempts,durationMs:n.durationMs,retrying:!0,message:n.response.error.message,hint:n.response.error.hint,session:n.sessionName,artifactsDir:t.testArtifactsDir,...Ed(e.shard)})}function _d(e,t,n){let r=Date.now()-t.testStartedAt;return n.finalResponse?.ok?vd(e,t,n,r):yd(e,t,n,r)}function vd(e,t,n,r){let{entry:i,suiteIndex:a,suiteTotal:o,shard:s}=e,c=n.finalResponse;if(!c?.ok)throw Error(`Expected passing replay test response.`);return T({type:`replay-test`,file:i.path,title:i.title,status:`pass`,index:a,total:o,attempt:n.attempts,maxAttempts:t.maxAttempts,durationMs:r,session:n.finalSessionName,artifactsDir:t.testArtifactsDir,...Ed(s)}),{file:i.path,title:i.title,session:n.finalSessionName,status:`passed`,durationMs:r,finalAttemptDurationMs:n.finalAttemptDurationMs,attempts:n.attempts,artifactsDir:t.testArtifactsDir,...xd(c),...Sd(c.data?.warnings),...Cd(c.data?.snapshotDiagnostics),...Td(s),...n.attemptFailures.length>0?{attemptFailures:n.attemptFailures}:{}}}function yd(e,t,n,r){let{entry:i,suiteIndex:a,suiteTotal:o,shard:s}=e,c=bd(n.finalResponse);return T({type:`replay-test`,file:i.path,title:i.title,status:`fail`,index:a,total:o,attempt:n.attempts,maxAttempts:t.maxAttempts,durationMs:r,session:n.finalSessionName,artifactsDir:t.testArtifactsDir,message:c.message,hint:c.hint,...Ed(s)}),{file:i.path,title:i.title,session:n.finalSessionName,status:`failed`,durationMs:r,attempts:n.attempts,artifactsDir:t.testArtifactsDir,error:c,...Cd(wd(n.finalResponse)),...Td(s)}}function bd(e){return e&&!e.ok?e.error:{code:`COMMAND_FAILED`,message:`Unknown replay test failure`}}function xd(e){return{replayed:typeof e.data?.replayed==`number`?e.data.replayed:0,healed:typeof e.data?.healed==`number`?e.data.healed:0}}function Sd(e){if(!Array.isArray(e))return{};let t=e.filter(e=>typeof e==`string`);return t.length>0?{warnings:t}:{}}function Cd(e){let t=De(e);return t?{snapshotDiagnostics:t}:{}}function wd(e){return e?.ok?e.data?.snapshotDiagnostics:e?.error.details?.snapshotDiagnostics}function Td(e){return Ed(e)}function Ed(e){return e?{shardIndex:e.shardIndex,shardCount:e.shardCount,deviceId:e.device.id,deviceName:e.device.name}:{}}async function Dd(e,t,n){let r=kd(e);if(!r||t.length===0)return;let i=await jd(e,r.count);return{mode:r.kind,shardCount:r.count,total:n+(r.kind===`all`?t.length*r.count:t.length),shards:i.map((e,n)=>({shardIndex:n,shardCount:r.count,device:e,entries:r.kind===`all`?t:t.filter((e,t)=>t%r.count===n)}))}}function Od(e,t){if(!t)return e;let n={...e??{},device:void 0,udid:void 0,serial:void 0,platform:t.device.platform,target:t.device.target,shardAll:void 0,shardSplit:void 0,shardCount:t.shardCount,shardIndex:t.shardIndex};return t.device.platform===`android`?{...n,serial:t.device.id}:{...n,udid:t.device.id}}function kd(e){let n=Ad(e?.shardAll,`--shard-all`),r=Ad(e?.shardSplit,`--shard-split`);if(n!==void 0&&r!==void 0)throw new t(`INVALID_ARGS`,`--shard-all and --shard-split are mutually exclusive`);if(n!==void 0)return{kind:`all`,count:n};if(r!==void 0)return{kind:`split`,count:r}}function Ad(e,n){if(e!==void 0){if(typeof e!=`number`||!Number.isInteger(e)||e<1)throw new t(`INVALID_ARGS`,`${n} requires a positive integer`);return e}}async function jd(e,n){let r=Fd(e),i=Nd(await un(Md(e)),r,e);if(i.length<n)throw new t(`DEVICE_NOT_FOUND`,`test sharding requires ${Pd(n)}, but only ${i.length} matched`);return i.slice(0,n)}function Md(e){let t=tt(e?.androidDeviceAllowlist);return{platform:e?.platform,target:e?.target,iosSimulatorSetPath:r({simulatorSetPath:at(e?.iosSimulatorDeviceSet),platform:e?.platform,target:e?.target}),androidSerialAllowlist:t?Array.from(t).sort():void 0}}function Nd(e,t,n){return t.length>0?Id(e,t,n):e.filter(e=>Ld(e,n)).sort(Bd)}function Pd(e){return`${e} device${e===1?``:`s`}`}function Fd(e){let t=e?.device;return typeof t!=`string`||t.trim().length===0?[]:t.split(`,`).map(e=>e.trim()).filter(Boolean)}function Id(e,n,r){return n.map(n=>{let i=zd(n),a=e.find(e=>Rd(e,r)&&(e.id===n||zd(e.name)===i));if(!a)throw new t(`DEVICE_NOT_FOUND`,`No shard device matched ${n}`);return a})}function Ld(e,t){return!Rd(e,t)||!o(e)?!1:e.booted!==!1}function Rd(e,t){return!(!d(e,t?.platform)||t?.target&&(e.target??`mobile`)!==t.target)}function zd(e){return e.toLowerCase().replace(/_/g,` `).replace(/\s+/g,` `).trim()}function Bd(e,t){return e.id.localeCompare(t.id)}async function Vd(e){let{req:t,sessionName:r,runReplay:i,cleanupSession:a,finalizeAttempt:o}=e;if((t.positionals?.length??0)===0)return E(`INVALID_ARGS`,`test requires at least one path or glob`);try{let e=Date.now(),n=await Hd(t);Kd(n);let s=n.shardPlan?qd({entries:n.entries,total:n.total}):[];return n.shardPlan?s.push(...await Jd({shards:n.shardPlan.shards,sessionName:r,suiteInvocationId:n.suiteInvocationId,cwd:t.meta?.cwd,requestId:t.meta?.requestId,flags:t.flags,suiteArtifactsDir:n.suiteArtifactsDir,suiteTotal:n.total,runReplay:i,cleanupSession:a,finalizeAttempt:o})):s.push(...await Qd({discoveryEntries:n.entries,sessionName:r,suiteInvocationId:n.suiteInvocationId,cwd:t.meta?.cwd,requestId:t.meta?.requestId,flags:t.flags,suiteArtifactsDir:n.suiteArtifactsDir,suiteTotal:n.total,runReplay:i,cleanupSession:a,finalizeAttempt:o})),{ok:!0,data:tf(n.total,s,Date.now()-e)}}catch(e){let t=n(e);return E(t.code,t.message)}}async function Hd(e){let t=Ud(e),n=Wd(t),r=t.length-n.length,i=ku(e.meta?.requestId),a=await Dd(e.flags,n,r);return{entries:t,runnable:n,shardPlan:a,suiteInvocationId:i,suiteArtifactsDir:Gd(e,i),total:a?.total??t.length}}function Ud(e){return Du({inputs:e.positionals??[],cwd:e.meta?.cwd,platformFilter:e.flags?.platform,replayBackend:e.flags?.replayBackend})}function Wd(e){return e.flatMap((e,t)=>e.kind===`run`?[{entry:e,suiteIndex:t+1}]:[])}function Gd(e,t){return Ac({artifactsDir:typeof e.flags?.artifactsDir==`string`?e.flags.artifactsDir:void 0,cwd:e.meta?.cwd,suiteInvocationId:t})}function Kd(e){T({type:`replay-test-suite`,status:`start`,total:e.total,runnable:e.runnable.length,skipped:e.entries.length-e.runnable.length,artifactsDir:e.suiteArtifactsDir,shardMode:e.shardPlan?.mode,shardCount:e.shardPlan?.shardCount})}function qd(e){let{entries:t,total:n}=e,r=[];for(let[e,i]of t.entries())i.kind===`skip`&&(T({type:`replay-test`,file:i.path,status:`skip`,index:e+1,total:n,message:i.message}),r.push({file:i.path,status:`skipped`,durationMs:0,reason:i.reason,message:i.message}));return r}async function Jd(e){return(await Promise.allSettled(e.shards.map(async t=>await Xd({...e,shard:t})))).flatMap((t,n)=>{if(t.status===`fulfilled`)return t.value;let r=e.shards[n];return r?[Yd(r,e.sessionName,t.reason)]:[]})}function Yd(t,n,r){let i=e(r);return{file:t.entries[0]?.entry.path??`shard-${t.shardIndex+1}`,session:Zd(n,t),status:`failed`,durationMs:0,attempts:1,error:{code:i.code,message:i.message,hint:i.hint,diagnosticId:i.diagnosticId,logPath:i.logPath,details:i.details},shardIndex:t.shardIndex,shardCount:t.shardCount,deviceId:t.device.id,deviceName:t.device.name}}async function Xd(e){let{shard:t,sessionName:n}=e;return await $d({...e,entries:t.entries,sessionName:Zd(n,t),shard:t})}function Zd(e,t){return`${e}:shard-${t.shardIndex+1}`}async function Qd(e){let{discoveryEntries:t,sessionName:n,suiteInvocationId:r,cwd:i,requestId:a,flags:o,suiteArtifactsDir:s,suiteTotal:c,runReplay:l,cleanupSession:u,finalizeAttempt:d}=e,f=[],p=0;for(let[e,m]of t.entries()){if(Ct(a))break;if(m.kind===`skip`){T({type:`replay-test`,file:m.path,status:`skip`,index:e+1,total:c,message:m.message}),f.push({file:m.path,status:`skipped`,durationMs:0,reason:m.reason,message:m.message});continue}p+=1;let t=await ld({entry:m,sessionName:n,suiteInvocationId:r,caseIndex:p-1,cwd:i,requestId:a,retries:Mu(o?.retries,m.metadata.retries),timeoutMs:ju(o?.timeoutMs,m.metadata.timeoutMs),suiteArtifactsDir:s,suiteIndex:e+1,suiteTotal:c,runReplay:l,cleanupSession:u,finalizeAttempt:d});if(f.push(t),ef(t,o,a))break}return f}async function $d(e){let{entries:t,sessionName:n,suiteInvocationId:r,cwd:i,requestId:a,flags:o,suiteArtifactsDir:s,suiteTotal:c,shard:l,runReplay:u,cleanupSession:d,finalizeAttempt:f}=e,p=[];for(let[e,m]of t.entries()){if(Ct(a))break;let{entry:t,suiteIndex:h}=m,g=await ld({entry:t,sessionName:n,suiteInvocationId:r,caseIndex:e,cwd:i,requestId:a,retries:Mu(o?.retries,t.metadata.retries),timeoutMs:ju(o?.timeoutMs,t.metadata.timeoutMs),suiteArtifactsDir:s,suiteIndex:h,suiteTotal:c,shard:l,runReplay:u,cleanupSession:d,finalizeAttempt:f});if(p.push(g),ef(g,o,a))break}return p}function ef(e,t,n){return Ct(n)||t?.failFast===!0||Yu(e)}function tf(e,t,n){let r=t.filter(e=>e.status===`passed`).length,i=t.filter(e=>e.status===`failed`),a=i.length,o=t.filter(e=>e.status===`skipped`).length,s=r+a,c=Oe(t.map(e=>e.status===`skipped`?void 0:e.snapshotDiagnostics));return{total:e,executed:s,passed:r,failed:a,skipped:o,notRun:Math.max(0,e-s-o),durationMs:n,failures:i,tests:t,...c?{snapshotDiagnostics:c}:{}}}const nf={maestro:{parse:lu}};function rf(e,t,n={}){let r=of(t);return r?{...r.parse(e,{...n,platform:t?.platform,env:af(t)}),updateUnsupportedMessage:`replay -u is not supported for compat flow input. Convert to .ad first, then update that replay file.`}:{...xr(e),metadata:wr(e)}}function af(e){return{...lr(cr(e?.replayShellEnv)),...Sr(ur(e?.replayEnv))}}function of(e){let n=e?.replayBackend;if(typeof n!=`string`)return;let r=nf[n];if(!r)throw new t(`INVALID_ARGS`,`Unsupported replay backend "${n}".`);return r}function sf(e){if(e.length===0)return{selectorExpression:null,selectorTimeout:null};let t=e[e.length-1],n=t!==void 0&&/^\d+$/.test(t)?t:null,r=ee(n===null?e.slice():e.slice(0,-1));return!r||r.rest.length>0?{selectorExpression:null,selectorTimeout:null}:{selectorExpression:r.selectorExpression,selectorTimeout:n}}function cf(e){let t=[],n=Array.isArray(e.result?.selectorChain)&&e.result?.selectorChain.every(e=>typeof e==`string`)?e.result.selectorChain:[];if(t.push(...n),ot(e.command)){let n=df(e),r=n[0]??``;r&&!r.startsWith(`@`)&&t.push(n.join(` `))}if(e.command===`fill`){let n=e.positionals?.[0]??``;n&&!n.startsWith(`@`)&&Number.isNaN(Number(n))&&t.push(n)}if(e.command===`get`){let n=e.positionals?.[1]??``;n&&!n.startsWith(`@`)&&t.push(e.positionals.slice(1).join(` `))}if(e.command===`is`){let{split:n}=Ie(e.positionals);n&&t.push(n.selectorExpression)}if(e.command===`wait`){let{selectorExpression:n}=sf(e.positionals??[]);n&&t.push(n)}return Xt(t).filter(e=>e.trim().length>0)}function lf(e){return cf(e).map(e=>v(e)).filter(e=>e!==null)}async function uf(e){let{action:t,sessionName:n,logPath:r,sessionStore:i}=e;if(!(ot(t.command)||[`fill`,`get`,`is`,`wait`].includes(t.command)))return null;let a=i.get(n);if(!a)return null;let o=lf(t);if(o.length===0)return null;let s=ot(t.command)||t.command===`fill`,c=ot(t.command)||t.command===`fill`||t.command===`get`&&t.positionals?.[0]===`text`,l=await hf(a,t,r,s,i);for(let e of o){let n=Ue(l.nodes,e,{platform:a.device.platform,requireRect:s,requireUnique:!0,disambiguateAmbiguous:c});if(!n)continue;let r=Ge(n.node,a.device.platform,{action:t.command===`fill`?`fill`:ot(t.command)?`click`:`get`}).join(` || `);if(ot(t.command))return{...t,positionals:t.command===`longpress`?ff(t,r):[r]};if(t.command===`fill`){let e=nr(t);if(!e)continue;return{...t,positionals:[r,e]}}if(t.command===`get`){let e=t.positionals?.[0];if(e!==`text`&&e!==`attrs`)continue;return{...t,positionals:[e,r]}}if(t.command===`is`){let{predicate:e,split:n}=Ie(t.positionals);if(!e)continue;let i=n?.rest.join(` `).trim()??``,a=[e,r];return e===`text`&&i.length>0&&a.push(i),{...t,positionals:a}}if(t.command===`wait`){let{selectorTimeout:e}=sf(t.positionals??[]),n=[r];return e&&n.push(e),{...t,positionals:n}}}return null}function df(e){let t=e.positionals??[];if(e.command!==`longpress`)return t;let n=t.at(-1);return t.length>1&&mf(n)?t.slice(0,-1):t}function ff(e,t){let n=typeof e.result?.durationMs==`number`?String(e.result.durationMs):pf(e.positionals??[]);return n?[t,n]:[t]}function pf(e){let t=e.at(-1);return e.length>1&&mf(t)?t:void 0}function mf(e){return e===void 0||e.trim()===``?!1:Number.isFinite(Number(e))}async function hf(e,t,n,r,i){let a=Ut(await D(e.device,`snapshot`,[],t.flags?.out,{...j(n,{...t.flags??{},snapshotInteractiveOnly:r},e.appBundleId,e.trace?.outPath)}),{...t.flags??{},snapshotInteractiveOnly:r});return Vt(e,a),i.set(e.name,e),a}const gf={swipe:{screenRatio:.35,minDistancePx:120,maxDistancePx:360,marginPx:8}};function _f(e,t){let n=ye(e.rect),r=e.frame,i=yf(r?.referenceWidth,e.rect.width),a=yf(r?.referenceHeight,e.rect.height),o=gf.swipe.marginPx,s=o,c=o,l=r?r.referenceWidth-o:n.x+i,u=r?r.referenceHeight-o:n.y+a;switch(t.toLowerCase()){case`up`:return{ok:!0,start:n,end:{x:n.x,y:he(n.y-a,c,u)}};case`down`:return{ok:!0,start:n,end:{x:n.x,y:he(n.y+a,c,u)}};case`left`:return{ok:!0,start:n,end:{x:he(n.x-i,s,l),y:n.y}};case`right`:return{ok:!0,start:n,end:{x:he(n.x+i,s,l),y:n.y}};default:return{ok:!1,message:`swipe.label direction must be up, down, left, or right.`}}}function vf(e){return ye(e.rect)}function yf(e,t){let n=typeof e==`number`?e*gf.swipe.screenRatio:0;return Math.round(Math.min(gf.swipe.maxDistancePx,Math.max(gf.swipe.minDistancePx,n,t*1.5)))}const bf=new WeakMap,xf=new WeakMap,Sf=new WeakMap;function J(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{details:n}:{}}}}async function Cf(e){let t=e.raw===!0||process.env.AGENT_DEVICE_MAESTRO_RAW_SNAPSHOTS===`1`,n=await e.invoke({...e.baseReq,command:`snapshot`,positionals:[],flags:{...e.baseReq.flags,noRecord:!0,...t?{snapshotRaw:!0}:{}}});return n.ok&&e.scope&&Mf(e.scope,n.data),n}function wf(e){return Array.isArray(e?.nodes)?e:void 0}function Tf(e){return e?bf.get(e):void 0}function Ef(e,t){e&&xf.set(e,{selector:t})}function Df(e){return e?xf.get(e):void 0}function Of(e){e&&xf.delete(e)}function kf(e,t){e&&Sf.set(e,t)}function Af(e){if(!e)return;let t=Sf.get(e);return Sf.delete(e),t}function jf(e){e&&Sf.delete(e)}function Mf(e,t){let n=O(wf(t));n&&bf.set(e,n)}const Nf=new Map([[`button`,0],[`link`,0],[`textfield`,0],[`textview`,0],[`searchfield`,0],[`switch`,0],[`slider`,0],[`cell`,1],[`statictext`,2]]);function Pf(e,t,n,r,i,a={}){let o=Bf(e,t,r);if(n.childOf){let t=Bf(e,n.childOf,r);if(t.length===0)return{ok:!1,message:`Maestro childOf parent did not match: ${n.childOf}`};let i=Fe(e.nodes);o=o.filter(n=>t.some(t=>Me(e.nodes,n,t,i)))}let s=Lf({nodes:e.nodes,matches:o,platform:r}),c=Zf(e.nodes,s.matches,n.index,Y(t),i,a.requireOnScreen===!0,a.promoteTapTarget,a.preferredContext);if(!c){let e=n.index??0;return{ok:!1,message:s.blockedByReactNativeOverlay?`React Native overlay is covering app content: ${t}`:o.length>0&&s.matches.length===0?`Maestro selector matched ${o.length} element(s), but none were visible: ${t}`:`Maestro selector did not match index ${e}: ${t}`}}return{ok:!0,node:c.node,rect:c.rect}}function Ff(e,t,n,r,i={}){let a=Vf(e,t),o=Lf({nodes:e.nodes,matches:a,platform:n}),s=Zf(e.nodes,o.matches,void 0,t,r,i.requireOnScreen===!0,i.promoteTapTarget,i.preferredContext);return s?{ok:!0,node:s.node,rect:s.rect}:{ok:!1,message:`Maestro fuzzy text did not match: ${t}`}}function If(e,t,n,r){let i=Bf(e,t,n,{allowLeadingCompositeLabelMatch:!1}),a=Lf({nodes:e.nodes,matches:i,platform:n}),o=Zf(e.nodes,a.matches,void 0,Y(t),r,!0);return o?{ok:!0,node:o.node,rect:o.rect,matches:a.matches.length}:{ok:!1,message:a.blockedByReactNativeOverlay?`React Native overlay is covering app content: ${t}`:i.length>0?`Maestro selector matched ${i.length} element(s), but none were visible: ${t}`:`Maestro selector did not match: ${t}`}}function Lf(e){let t=e.matches.filter(t=>Pe({predicate:`visible`,node:t,nodes:e.nodes,platform:e.platform}).pass),n=Rf(e.nodes,t,e.platform);return{matches:n.matches,blockedByReactNativeOverlay:n.blockedByReactNativeOverlay}}function Rf(e,t,n){let r=qe(e);if(!r.detected||!r.redBox)return{matches:t,blockedByReactNativeOverlay:!1};let i=Je(r),a=i.filter(t=>Pe({predicate:`visible`,node:t,nodes:e,platform:n}).pass);if(a.length===0)return i.length===0?{matches:[],blockedByReactNativeOverlay:!0}:{matches:t,blockedByReactNativeOverlay:!1};let o=new Set(a.map(e=>e.index)),s=t.filter(e=>o.has(e.index));return{matches:s,blockedByReactNativeOverlay:t.length>0&&s.length===0}}function zf(e){return e?.platform===`android`?`android`:`ios`}function Y(e){let t=b(e).selectors.flatMap(e=>e.terms);if(t.length===0||!t.some(e=>e.key===`label`||e.key===`text`)||!t.every(e=>[`label`,`text`,`id`].includes(e.key)))return null;let n=t.map(e=>typeof e.value==`string`?e.value:``),r=n[0];return!r||!n.every(e=>e===r)?null:r}function Bf(e,t,n,r={}){let i=b(t);for(let t of i.selectors){let i=e.nodes.filter(e=>Hf(e,t,n,r));if(i.length>0)return i}return[]}function Vf(e,t){let n=He(t);if(!n)return[];let r=[],i=[];for(let t of e.nodes){let e=[t.label,je(t),t.identifier,t.value].filter(e=>!!e).map(e=>He(e));e.some(e=>e===n)?r.push(t):e.some(e=>e.includes(n))&&i.push(t)}return r.length>0?r:i}function Hf(e,t,n,r){return We(e,t,n)?!0:t.terms.every(t=>Uf(e,t,n,r))}function Uf(e,t,n,r){return typeof t.value!=`string`||!Wf(t.key)?We(e,{raw:t.key,terms:[t]},n):Kf(Gf(e,t.key),t.value,r)}function Wf(e){return e===`id`||e===`label`||e===`text`||e===`value`}function Gf(e,t){return t===`id`?e.identifier:t===`label`?e.label:t===`value`?e.value:je(e)}function Kf(e,t,n={}){let r=e??``,i=He(r),a=He(t);if(i===a||n.allowLeadingCompositeLabelMatch!==!1&&qf(i,a))return!0;if(!Jf(t))return!1;try{return new RegExp(t).test(r)}catch{return!1}}function qf(e,t){if(!e||!t||!e.startsWith(t))return!1;let n=e.at(t.length);return n===`,`||n===`:`||n===`;`}function Jf(e){return/(?:\.\*|\.\+|\[[^\]]+\]|\([^)]*\)|\||\^|\$|\\[dDsSwWbB])/.test(e)}function Yf(e,t,n){if(t.rect&&t.rect.width>0&&t.rect.height>0)return{rect:t.rect,inherited:!1};if(t.rect)return null;let r=Xf(e,t,n);return r?{rect:r,inherited:!0}:null}function Xf(e,t,n){let r=t;for(;typeof r.parentIndex==`number`;){if(r=n.get(r.parentIndex)??e[r.parentIndex],!r)return null;if(r.rect)return r.rect.width>0&&r.rect.height>0?r.rect:null}return null}function Zf(e,t,n,r,i,a=!1,o=!1,s){let c=Fe(e);return Pp(e,ep(e,Qf(e,t,c,r,n,i,a),n,r,o,s),c,o,i)}function Qf(e,t,n,r,i,a,o){let s=t.map(t=>$f(e,t,n)).filter(e=>!!e),c=s.filter(e=>!e.inheritedRect),l=c.length>0?c:s;return!r||i!==void 0?s:hp(l,a,o)}function $f(e,t,n){let r=Yf(e,t,n);return r?{node:t,rect:r.rect,inheritedRect:r.inherited}:null}function ep(e,t,n,r,i,a){if(n!==void 0)return t[n]??null;let o=tp(e,t,r,i,a);return np(o,r,i)?xp(e,o,r)??o:o}function tp(e,t,n,r,i){return!r||!n?rp(e,t,n,i):ip(e,t,n,i)??rp(e,t,n,i)}function np(e,t,n){return!!(n&&t&&e)}function rp(e,t,n,r){return op(e,t,n,r).sort((e,t)=>_p(e,t,n))[0]??null}function ip(e,t,n,r){let i=t.filter(e=>Z(e.node,n)===0);if(i.length>=2){let t=ap(e,i,n,r);if(t)return t}let a=t.filter(e=>Z(e.node,n)===1);return i.length>0||a.length<2?null:ap(e,a,n,r)}function ap(e,t,n,r){let i=Fe(e);return rp(e,t.filter(n=>pp(n)&&t.some(t=>mp(e,t,n,i))),n,r)}function op(e,t,n,r){if(!n||t.length<2)return t;let i=t.filter(e=>Z(e.node,n)===0);if(i.length<2)return t;let a=Fe(e),o=i.map(t=>({candidate:t,container:dp(e,t.node,a)})).filter(e=>!!e.container);if(o.length<2||o.length!==i.length)return t;let s=o.filter(e=>up(e,o));if(s.length<2)return t;let c=lp(s);if(c.length>0)return c;let l=sp(e,s,r,a);if(l.length>0)return l;let u=Math.max(...s.map(e=>e.container.index)),d=s.filter(e=>e.container.index===u).map(e=>e.candidate);return d.length>0?d:t}function sp(e,t,n,r){if(!n)return[];let i=dp(e,n.node,r),a=i&&zp(i.rect,n.rect)?i:null,o=t.map(e=>({entry:e,score:cp(e.container,n,a)})),s=Math.min(...o.map(e=>e.score));return Number.isFinite(s)?o.filter(e=>e.score===s).map(e=>e.entry.candidate):[]}function cp(e,t,n){if(n)return e.index===n.index?0:Bp(e.rect,n.rect)<.6?1/0:Math.abs(e.index-n.index);if(Bp(e.rect,t.rect)>=.6)return 0;let r=e.index-t.node.index;return r>=0?r:1e5+Math.abs(r)}function lp(e){let t=e.map(e=>X(e.container.rect)),n=Math.max(...t),r=Math.min(...t);return r<=0||n<r*1.2?[]:e.filter(e=>X(e.container.rect)===n).map(e=>e.candidate)}function up(e,t){return t.some(t=>t!==e&&e.container.index!==t.container.index&&Bp(e.container.rect,t.container.rect)>=.6)}function dp(e,t,n){return Ne(e,t,n,e=>!e.rect||!fp(e)||e.rect.width<240||e.rect.height<320?null:e)}function fp(e){let t=Ae(e.type??``);return t===`scrollview`||t===`scroll-area`||t===`list`}function pp(e){return e.rect.width>=16&&e.rect.width<=260&&e.rect.height>=24&&e.rect.height<=80}function mp(e,t,n,r){return t.node.index===n.node.index||!zp(t.rect,n.rect)||X(t.rect)<X(n.rect)*2?!1:Me(e,n.node,t.node,r)}function hp(e,t,n){let r=e.filter(e=>gp(e.rect,t));return n||r.length>0?r:e}function gp(e,t){let n=t?.referenceWidth??1/0,r=t?.referenceHeight??1/0;return e.x<n&&e.y<r&&e.x+e.width>0&&e.y+e.height>0}function _p(e,t,n){let r=yp(e,t,n);if(r!==0)return r;if(!vp(e.rect,t.rect))return e.node.index-t.node.index;let i=(t.node.depth??0)-(e.node.depth??0);return i===0?t.node.index-e.node.index:i}function vp(e,t){return Math.round(e.x)===Math.round(t.x)&&Math.round(e.y)===Math.round(t.y)&&Math.round(e.width)===Math.round(t.width)&&Math.round(e.height)===Math.round(t.height)}function yp(e,t,n){if(n){let r=Z(e.node,n)-Z(t.node,n);if(r!==0)return r}let r=bp(e.node)-bp(t.node);if(r!==0)return r;let i=Number(e.inheritedRect)-Number(t.inheritedRect);if(i!==0)return i;let a=n&&bp(e.node)===bp(t.node)?X(t.rect)-X(e.rect):X(e.rect)-X(t.rect);return a===0?0:a}function X(e){return e.width*e.height}function bp(e){return Nf.get(Ae(e.type??``))??3}function xp(e,t,n){if(!Op(t,n))return null;let r=Sp(e,t,n,Fe(e));if(r.length===0)return null;let i=Mp(r.map(e=>e.rect.width)),a=Cp(t,n,Ap(t.rect,r.map(e=>e.rect)),i);return a?Dp(t,a):null}function Sp(e,t,n,r){return e.filter(i=>i.index!==t.node.index&&!!i.rect&&Me(e,i,t.node,r)&&kp(i,t.rect,n)).sort((e,t)=>e.rect.x-t.rect.x)}function Cp(e,t,n,r){let i=n.filter(e=>jp(e.width,r)),a=wp(e,t,n),o=i.some(t=>Ep(e.rect,t));return a&&!o?a:i.length===1?i[0]??null:a}function wp(e,t,n){let r=n.find(t=>Math.abs(t.x-e.rect.x)<1),i=Math.max(48,Math.min(220,t.length*8+24));return Tp(e,t,r,i)?{x:e.rect.x,width:Math.min(i,r.width)}:null}function Tp(e,t,n,r){return n?Ae(e.node.type??``)===`scrollview`&&Z(e.node,t)<=1&&e.rect.width>=240&&e.rect.height>=32&&e.rect.height<=80&&n.width<=e.rect.width*.55&&n.width>=r*.6:!1}function Ep(e,t){return Math.abs(t.x-e.x)<1}function Dp(e,t){return{...e,rect:{x:t.x,y:e.rect.y,width:t.width,height:e.rect.height}}}function Op(e,t){let n=Ae(e.node.type??``);return n!==`cell`&&n!==`other`&&n!==`scrollview`&&n!==`scroll-area`||e.rect.width<120||e.rect.height<32||e.rect.height>80?!1:Z(e.node,t)<=1}function kp(e,t,n){let r=Ae(e.type??``);return r!==`button`&&r!==`cell`&&r!==`other`||Z(e,n)<=1||e.rect.width<16||e.rect.height<16||!zp(t,e.rect)?!1:Np(t,e.rect)>=.5}function Ap(e,t){let n=[],r=e.x,i=e.x+e.width;for(let a of t){let t=Math.max(e.x,a.x),o=Math.min(i,a.x+a.width);t>r&&n.push({x:r,width:t-r}),r=Math.max(r,o)}return i>r&&n.push({x:r,width:i-r}),n}function jp(e,t){return e<24||t<24?!1:e>=t*.4&&e<=t*1.6}function Mp(e){let t=[...e].sort((e,t)=>e-t);return t[Math.floor(t.length/2)]??0}function Np(e,t){let n=Math.max(e.y,t.y),r=Math.min(e.y+e.height,t.y+t.height);return Math.max(0,r-n)/Math.max(1,Math.min(e.height,t.height))}function Pp(e,t,n,r,i){return t?r?Fp(e,t,n,i)??{node:t.node,rect:t.rect}:{node:t.node,rect:t.rect}:null}function Fp(e,t,n,r){return Ip(t.node)?null:Ne(e,t.node,n,i=>{if(!Ip(i))return null;let a=Yf(e,i,n);return!a||!Lp(t.rect,a.rect,r)?null:{node:i,rect:a.rect}})}function Ip(e){let t=Ae(e.type??``);return e.hittable===!0||t===`button`||t===`link`||t===`cell`||t===`textfield`||t===`searchfield`||t===`switch`||t===`slider`}function Lp(e,t,n){if(!zp(t,e)||Rp(e,t))return!1;let r=X(t),i=X(e);if(i>0&&r>i*30)return!1;if(n){let e=n.referenceWidth*n.referenceHeight;if(e>0&&r>e*.5)return!1}return!0}function Rp(e,t){return t.height<32||t.height>80||e.height<t.height*.75||Np(e,t)<.75||t.width<240?!1:t.width>=e.width*3}function zp(e,t){return t.x>=e.x-1&&t.y>=e.y-1&&t.x+t.width<=e.x+e.width+1&&t.y+t.height<=e.y+e.height+1}function Bp(e,t){let n=Math.max(e.x,t.x),r=Math.min(e.x+e.width,t.x+t.width),i=Math.max(e.y,t.y),a=Math.min(e.y+e.height,t.y+t.height);return Math.max(0,r-n)*Math.max(0,a-i)/Math.max(1,Math.min(X(e),X(t)))}function Z(e,t){let n=[e.label,je(e),e.identifier,e.value].filter(e=>!!e);return n.some(e=>e===t)?0:n.some(e=>He(e)===He(t))?1:n.some(e=>Kf(e,t))?2:3}const Q={animationPollMs:250,assertVisibleGraceMs:1e3,assertVisiblePollMs:250,assertVisibleRetryTimeoutMs:5e3,assertNotVisiblePollMs:250,defaultAssertNotVisibleTimeoutMs:3e3};async function Vp(e){let t=lm(e.positionals,{command:`assertVisible`,defaultTimeoutMs:17e3});if(!t.ok)return t.response;let n=sm(e.baseReq,t.selector);return n?await Hp(e,t,n):await Gp(e,t)}async function Hp(e,t,n){let r=Date.now(),i=await Wp(e,t,n);if(i.ok){if(Up(e.baseReq)){let n=await um(e,t.selector,`assertVisible`);if(!n.visible){let i=tm(e.baseReq,t,n,r);return i.kind===`return`?i.response:await Gp(e,im(t))}}return Ef(e.scope,t.selector),hm({ok:!0,data:{selector:t.selector,nativeWait:!0,query:n,response:i.data}},t.selector,r)}return await Kp(e,t,i,r)}function Up(e){return e.flags?.platform===`android`}async function Wp(e,t,n){return await e.invoke({...e.baseReq,command:`wait`,positionals:[n,String(t.timeoutMs)]})}async function Gp(e,t){let n=Date.now(),r=t.timeoutMs+Q.assertVisibleGraceMs,i,a,o=!1;for(;;){let s=Date.now(),c=await um(e,t.selector,`assertVisible`);if(c.visible)return hm(c.response,t.selector,n);i=c.response,a=c.snapshot??a;let l=tm(e.baseReq,t,c,n);if(l.kind===`return`)return l.response;let u=rm({captureStartedAt:s,capturedAfterDeadline:o,startedAt:n,deadlineMs:r});if(u===`capture-again`){o=!0;continue}if(u===`finish`)break;await w(Q.assertVisiblePollMs)}let s=i??J(`COMMAND_FAILED`,`Expected visible but did not match: ${t.selector}`,{selector:t.selector,timeoutMs:t.timeoutMs});return await qp(e,t,a)||gm(s,a,e.baseReq)}async function Kp(e,t,n,r){let i=await um(e,t.selector,`assertVisible`);if(i.visible)return hm(i.response,t.selector,r);let a=tm(e.baseReq,t,i,r);return a.kind===`return`?a.response:await qp(e,t,i.snapshot)||gm(n,i.snapshot,e.baseReq)}async function qp(e,t,n){if(e.baseReq.flags?.platform!==`android`)return null;let r=Af(e.scope);return r?r.kind===`tap`?await Jp(e,t,n,r):await Yp(e,t,r):null}async function Jp(e,t,n,r){if(!n)return null;let i=Zp(e,n,r);return!i.ok||(h({level:`info`,phase:`maestro_assert_visible_retry_tap`,data:{selector:t.selector,tapSelector:r.selector,originalPoint:r.point,retryTarget:i.target,timeoutMs:Q.assertVisibleRetryTimeoutMs}}),!(await Qp(e,i.target)).ok)?null:await Xp(e,t,`retryTap`)}async function Yp(e,t,n){return h({level:`info`,phase:`maestro_assert_visible_retry_swipe`,data:{selector:t.selector,swipePositionals:n.positionals,timeoutMs:Q.assertVisibleRetryTimeoutMs}}),(await $p(e,n)).ok?await Xp(e,t,`retrySwipe`):null}async function Xp(e,t,n){let r={...t,timeoutMs:am(t.timeoutMs)},i=sm(e.baseReq,r.selector);if(!i)return await Gp(e,r);let a=Date.now(),o=await Wp(e,r,i);return o.ok?(Ef(e.scope,r.selector),hm({ok:!0,data:{selector:r.selector,nativeWait:!0,[n]:!0,query:i,response:o.data}},r.selector,a)):await Kp(e,r,o,a)}function Zp(e,t,n){let r=zf(e.baseReq.flags),i=O(t),a=Pf(t,n.selector,n.options??{},r,i,{promoteTapTarget:!0});if(a.ok)return{ok:!0,target:{kind:`point`,point:vf(a)}};let o=Y(n.selector);return!o||!em(t,o)?{ok:!1}:{ok:!0,target:{kind:`text`,query:o}}}async function Qp(e,t){return t.kind===`text`?await e.invoke({...e.baseReq,command:`find`,positionals:[t.query,`click`],flags:{...e.baseReq.flags,findFirst:!0,postGestureStabilization:!0}}):await e.invoke({...e.baseReq,command:`click`,positionals:[String(t.point.x),String(t.point.y)],flags:{...e.baseReq.flags,postGestureStabilization:!0}})}async function $p(e,t){return await e.invoke({...e.baseReq,command:`swipe`,positionals:t.positionals})}function em(e,t){let n=t.trim().toLowerCase();return n?e.nodes.some(e=>[e.label,e.value,e.identifier].some(e=>e?.trim().toLowerCase().includes(n))):!1}function tm(e,t,n,r){return om(n.response)?{kind:`return`,response:n.response}:nm(e,t.selector,n.snapshot)?{kind:`return`,response:cm(t.selector,t.timeoutMs,r)}:{kind:`continue`}}function nm(e,t,n){return e.flags?.maestro?.allowAlreadyPastLoading===!0&&n!==void 0&&fm(t,n)}function rm(e){return Date.now()-e.startedAt<e.deadlineMs?`wait`:bm(e.capturedAfterDeadline,e.captureStartedAt,e.startedAt,e.deadlineMs)?`capture-again`:`finish`}function im(e){return{...e,timeoutMs:am(e.timeoutMs)}}function am(e){return Math.min(e,Q.assertVisibleRetryTimeoutMs)}function om(e){return!e.ok&&e.error.code===`COMMAND_FAILED`&&e.error.message.includes(`React Native overlay`)}function sm(e,t){return e.flags?.platform!==`ios`&&e.flags?.platform!==`android`?null:Y(t)}function cm(e,t,n){return{ok:!0,data:{selector:e,alreadyPastLoading:!0,waitedMs:Date.now()-n,timeoutMs:t}}}function lm(e,t){let[n,r=String(t.defaultTimeoutMs)]=e;if(!n)return{ok:!1,response:J(`INVALID_ARGS`,`${t.command} requires a selector.`)};let i=Number(r);return!Number.isFinite(i)||i<0?{ok:!1,response:J(`INVALID_ARGS`,`${t.command} timeout must be a non-negative number.`)}:{ok:!0,selector:n,timeoutMs:i}}async function um(e,t,n){return dm(e,t,n,await Cf(e))}function dm(e,t,n,r){if(!r.ok)return{visible:!1,response:r,infrastructureFailure:!0};let i=wf(r.data);if(!i)return{visible:!1,response:J(`COMMAND_FAILED`,`Unable to read snapshot data for ${n}.`),infrastructureFailure:!0};let a=If(i,t,zf(e.baseReq.flags),O(i));return a.ok?(Ef(e.scope,t),{visible:!0,response:{ok:!0,data:{selector:t,matches:a.matches,nodeIndex:a.node.index,nodeType:a.node.type,nodeLabel:a.node.label,nodeIdentifier:a.node.identifier,rect:a.rect}}}):{visible:!1,response:J(`COMMAND_FAILED`,a.message,{selector:t}),infrastructureFailure:!1,snapshot:i}}function fm(e,t){let n=pm(Y(e));if(!mm(n))return!1;let r=t.nodes.flatMap(e=>[e.label,e.value,e.identifier]).filter(e=>!!e?.trim()).map(e=>pm(e));return r.some(e=>e.includes(`something went wrong`))?!1:r.some(e=>e!==n&&!mm(e))}function pm(e){return e?.trim().toLowerCase().replace(/\u2026/g,`...`)??``}function mm(e){return e===`loading`||e===`loading...`}function hm(e,t,n){return e.ok?{ok:!0,data:{selector:t,...e.data,waitedMs:Date.now()-n}}:e}function gm(e,t,n){if(e.ok||!t)return e;let r=typeof n.flags?.artifactsDir==`string`?n.flags.artifactsDir:void 0;if(!r)return e;let i=_m(t,r);return i.length===0?e:{ok:!1,error:{...e.error,details:{...e.error.details??{},artifactPaths:ym([...vm(e.error.details?.artifactPaths),...i])}}}}function _m(e,t){try{z.mkdirSync(t,{recursive:!0});let n=B.join(t,`failure-snapshot.json`),r=B.join(t,`failure-snapshot.txt`);z.writeFileSync(n,`${JSON.stringify(e,null,2)}\n`);let i=ie(e.nodes,{summarizeTextSurfaces:!0}).map(e=>e.text);return z.writeFileSync(r,`${i.join(`
|
|
25
|
+
`)}\n`),[n,r]}catch{return[]}}function vm(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function ym(e){return[...new Set(e)]}function bm(e,t,n,r){return!e&&t-n<r}async function xm(e){let t=lm(e.positionals,{command:`assertNotVisible`,defaultTimeoutMs:Q.defaultAssertNotVisibleTimeoutMs});if(!t.ok)return t.response;let n=Date.now(),r=0,i;for(;Date.now()-n<=t.timeoutMs;){let a=await um(e,t.selector,`assertNotVisible`);if(!a.visible&&a.infrastructureFailure)return a.response;if(a.visible)r=0,i=a.response;else{r+=1;let e=Date.now()-n;if(r>=2||e>=t.timeoutMs)return{ok:!0,data:{pass:!0,selector:t.selector,stableSamples:r,waitedMs:e,timeoutMs:t.timeoutMs}}}await w(Q.assertNotVisiblePollMs)}return r>0?{ok:!0,data:{pass:!0,selector:t.selector,stableSamples:r,waitedMs:Date.now()-n,timeoutMs:t.timeoutMs}}:J(`COMMAND_FAILED`,`Expected not visible but matched: ${t.selector}`,{selector:t.selector,timeoutMs:t.timeoutMs,lastResponse:i})}async function Sm(e){let t=Number(e.positionals[0]??15e3);if(!Number.isFinite(t)||t<0)return J(`INVALID_ARGS`,`waitForAnimationToEnd timeout must be a number.`);let n=Date.now(),r,i;for(;Date.now()-n<t;){let n=await Cf(e),a=Cm(n,r,t);if(a.done)return a.response;r=a.signature??r,i=n,await w(Q.animationPollMs)}return i?.ok===!1?i:{ok:!0,data:{stable:!1,timeoutMs:t}}}function Cm(e,t,n){let r=wm(e);return e.ok?r?t===r?{done:!0,response:{ok:!0,data:{stable:!0,timeoutMs:n}}}:{done:!1,signature:r}:{done:!0,response:e}:{done:!1}}function wm(e){if(!e.ok)return null;let t=wf(e.data);return t?Tm(t):null}function Tm(e){return JSON.stringify(e.nodes.map(e=>({index:e.index,parentIndex:e.parentIndex,type:e.type,identifier:e.identifier,label:e.label,value:e.value,rect:e.rect?{x:Math.round(e.rect.x),y:Math.round(e.rect.y),width:Math.round(e.rect.width),height:Math.round(e.rect.height)}:void 0})))}async function Em(e){return await e.invoke({...e.baseReq,command:`click`,positionals:[String(e.point.x),String(e.point.y)],flags:{...e.baseReq.flags,postGestureStabilization:!0}})}const Dm={scrollUntilVisibleProbeMs:500,tapOnRetryMs:250,tapOnTimeoutMs:3e4,optionalTapOnTimeoutMs:3e3};async function Om(e){let[t,n=`5000`,r=`down`]=e.positionals;if(!t)return J(`INVALID_ARGS`,`scrollUntilVisible requires a selector.`);let i=Number(n);if(!Number.isFinite(i)||i<=0)return J(`INVALID_ARGS`,`scrollUntilVisible timeout must be a positive number.`);let a=Y(t),o=Math.max(1,Math.ceil(i/Dm.scrollUntilVisibleProbeMs)),s=null;for(let n=0;n<o;n+=1){let c=await Um(e,t,a,Wm(i,n));if(c.ok)return c;if(s=c,n===o-1)break;let l=await e.invoke({...e.baseReq,command:`scroll`,positionals:[r]});if(!l.ok)return l}return th(s,t,i)}async function km(e){let[t,n]=e.positionals,r=Number(t),i=Number(n);if(!Number.isFinite(r)||!Number.isFinite(i))return J(`INVALID_ARGS`,`tapOn percentage point requires numeric x/y values.`);let a=await Cf(e);if(!a.ok)return a;let o=wf(a.data);if(!o)return J(`COMMAND_FAILED`,`Unable to read snapshot data for Maestro percentage point tap.`);let s=O(o);if(!s)return J(`COMMAND_FAILED`,`Unable to resolve screen size for Maestro percentage point tap.`);let c=_e(s,r,i),l=await Em({...e,point:c});return l.ok&&jf(e.scope),l}async function Am(e){let t=await jm(e);if(t)return t;let n=await Fm(e);return n.ok?await Pm(e,n,n.durationMs):n.response}async function jm(e){let[t,n,r]=e.positionals;if(!(t!==`direction`||n!==`left`&&n!==`right`)&&zf(e.baseReq.flags)!==`android`)return await e.invoke({...e.baseReq,command:`gesture`,positionals:[`swipe`,n,...r?[r]:[]]})}async function Mm(e){let[t,n]=e.positionals;if(!t)return J(`INVALID_ARGS`,`tapOn requires a selector.`);let r=eh(n);if(!r.ok)return r.response;let i=Date.now(),a=Gm(e),o;for(;Date.now()-i<a;){let n=await qm(e,t,r.value??{});if(!n.retry)return n.response;o=n.response,await w(Dm.tapOnRetryMs)}return Km(e,t,o)}async function Nm(e){let[t,n=`up`,r]=e.positionals;if(!t)return J(`INVALID_ARGS`,`swipe.label requires a label selector.`);let i=await Zm(e,t,{},`swipe.label`,{promoteTapTarget:!1});if(!i.ok)return i.response;let a=_f(i.target,n);return a.ok?await Pm(e,a,r):J(`INVALID_ARGS`,a.message)}async function Pm(e,t,n){let r=[String(t.start.x),String(t.start.y),String(t.end.x),String(t.end.y),...n?[n]:[]],i=await e.invoke({...e.baseReq,command:`swipe`,positionals:r});return i.ok&&kf(e.scope,{kind:`swipe`,positionals:r}),i}async function Fm(e){let t=Tf(e.scope)??await Im(e);if(!t)return{ok:!1,response:J(`COMMAND_FAILED`,`Unable to resolve screen size for Maestro swipe.`)};let[n,...r]=e.positionals;return n===`direction`?Lm(r,t,zf(e.baseReq.flags)):n===`percent`?Bm(r,t,zf(e.baseReq.flags)):{ok:!1,response:J(`INVALID_ARGS`,`Maestro screen swipe requires direction or percent.`)}}async function Im(e){let t=await Cf(e);if(t.ok)return O(wf(t.data))}function Lm(e,t,n){let[r,i]=e;if(!r)return{ok:!1,response:J(`INVALID_ARGS`,`Maestro direction swipe requires a direction.`)};switch(r){case`up`:case`down`:return zm(r,t,i);case`left`:case`right`:return Rm(r,t,n,i);default:return{ok:!1,response:J(`INVALID_ARGS`,`Maestro swipe direction must be UP, DOWN, LEFT, or RIGHT.`)}}}function Rm(e,t,n,r){let i=Hm(n,85,50,15,50),[a,o]=e===`left`?[85,15]:[15,85],s=Vm(n,t,a,50,o,50);return{ok:!0,start:_e(t,a,i.startY,{marginPx:s}),end:_e(t,o,i.endY,{marginPx:s}),durationMs:r}}function zm(e,t,n){let r=me({direction:e,amount:.6,referenceWidth:t.referenceWidth,referenceHeight:t.referenceHeight});return{ok:!0,start:xe({x:r.x1,y:r.y1},t,8),end:xe({x:r.x2,y:r.y2},t,8),durationMs:n}}function Bm(e,t,n){let[r,i,a,o,s]=e,c=[r,i,a,o].map(Number);if(c.some(e=>!Number.isFinite(e)))return{ok:!1,response:J(`INVALID_ARGS`,`Maestro percentage swipe requires numeric points.`)};let[l,u,d,f]=c,p=Hm(n,l,u,d,f),m=Vm(n,t,l,u,d,f);return{ok:!0,start:_e(t,l,p.startY,{marginPx:m}),end:_e(t,d,p.endY,{marginPx:m}),durationMs:s}}function Vm(e,t,n,r,i,a){return e!==`ios`||r!==a||Math.abs(i-n)<30?1:Math.max(1,Math.round(t.referenceWidth*.15))}function Hm(e,t,n,r,i){return e!==`android`||n!==i||n!==50||Math.abs(r-t)<30?{startY:n,endY:i}:{startY:65,endY:65}}async function Um(e,t,n,r){let i=await e.invoke({...e.baseReq,command:`wait`,positionals:[t,String(r)]});return i.ok||!n?i:await e.invoke({...e.baseReq,command:`find`,positionals:[n,`wait`,String(r)]})}function Wm(e,t){return Math.min(Dm.scrollUntilVisibleProbeMs,Math.max(1,e-t*Dm.scrollUntilVisibleProbeMs))}function Gm(e){return e.baseReq.flags?.maestro?.optional===!0?Dm.optionalTapOnTimeoutMs:Dm.tapOnTimeoutMs}function Km(e,t,n){return e.baseReq.flags?.maestro?.optional===!0?{ok:!0,data:{skipped:!0,optional:!0,selector:t}}:n??J(`COMMAND_FAILED`,`tapOn timed out for selector: ${t}`)}async function qm(e,t,n){let r=Y(t),i=await Jm(e,t,n);return i.response.ok?{retry:!1,response:i.response}:i.targetResolved&&r?await Xm(e,r):{retry:!0,response:i.response}}async function Jm(e,t,n){let r=await Zm(e,t,n,`tapOn`,{promoteTapTarget:!0});return r.ok?await Ym(e,t,r.target,n):{response:r.response,targetResolved:!1}}async function Ym(e,t,n,r){let i=vf(n);h({level:`debug`,phase:`maestro_tap_target`,data:{selector:t,node:{index:n.node.index,type:n.node.type,label:n.node.label,value:n.node.value,identifier:n.node.identifier,visibleToUser:n.node.visibleToUser},rect:n.rect,point:i}});let a=await Em({...e,point:i});return a.ok&&(Of(e.scope),kf(e.scope,{kind:`tap`,selector:t,point:i,options:{...r}})),{response:a,targetResolved:!0}}async function Xm(e,t){let n=await e.invoke({...e.baseReq,command:`find`,positionals:[t,`click`],flags:{...e.baseReq.flags,findFirst:!0,postGestureStabilization:!0}});return h({level:n.ok?`info`:`debug`,phase:`maestro_fuzzy_tap_fallback`,data:{query:t,ok:n.ok}}),n.ok?(jf(e.scope),{retry:!1,response:n}):{retry:!0,response:n}}async function Zm(e,t,n,r,i){return Qm(e,t,n,r,i,await Cf({...e,raw:!0}))}function Qm(e,t,n,r,i,a){if(!a.ok)return{ok:!1,response:a};let o=wf(a.data);if(!o)return{ok:!1,response:J(`COMMAND_FAILED`,`Unable to read snapshot data for ${r}.`)};let s=O(o),c=zf(e.baseReq.flags),l=$m(e,o,c,s),u=Pf(o,t,n,c,s,{...i,preferredContext:l,requireOnScreen:!0});if(!u.ok){let e=Y(t);if(e){let t=Ff(o,e,c,s,{...i,preferredContext:l,requireOnScreen:!0});if(t.ok)return{ok:!0,target:{node:t.node,rect:t.rect,frame:s},snapshot:o}}}return u.ok?{ok:!0,target:{node:u.node,rect:u.rect,frame:s},snapshot:o}:{ok:!1,response:J(`ELEMENT_NOT_FOUND`,u.message,{selector:t,options:n,command:r})}}function $m(e,t,n,r){let i=Df(e.scope);if(!i)return;let a=If(t,i.selector,n,r);if(a.ok)return h({level:`debug`,phase:`maestro_preferred_context`,data:{selector:i.selector,node:{index:a.node.index,type:a.node.type,label:a.node.label,value:a.node.value,identifier:a.node.identifier},rect:a.rect}}),{node:a.node,rect:a.rect}}function eh(e){if(!e)return{ok:!0,value:null};try{return{ok:!0,value:JSON.parse(e)}}catch{return{ok:!1,response:J(`INVALID_ARGS`,`tapOn runtime options must be valid JSON.`)}}}function th(e,t,n){return e?{ok:!1,error:{...e.error,message:`scrollUntilVisible timed out after ${n}ms for selector: ${t}. Last wait: ${e.error.message}`}}:J(`COMMAND_FAILED`,`scrollUntilVisible timed out after ${n}ms for selector: ${t}`)}async function nh(e){switch(e.command){case G.assertVisible:return await Vp(e);case G.assertNotVisible:return await xm(e);case G.pressEnter:return await rh(e);case G.waitForAnimationToEnd:return await Sm(e);case G.scrollUntilVisible:return await Om(e);case G.swipeScreen:return await Am(e);case G.swipeOn:return await Nm(e);case G.tapOn:return await Mm(e);case G.tapPointPercent:return await km(e);case G.runScript:return ih(e);default:return}}async function rh(e){let t=await e.invoke({...e.baseReq,command:`keyboard`,positionals:[`enter`]});return t.ok?t:await e.invoke({...e.baseReq,command:`type`,positionals:[`
|
|
26
|
+
`]})}function ih(e){let[t]=e.positionals;if(!t)return J(`INVALID_ARGS`,`runScript requires a file path.`);try{return{ok:!0,data:{outputEnv:Gl({scriptPath:t,env:{...e.scope.values,...e.baseReq.flags?.maestro?.runScriptEnv??{}}})}}}catch(e){let t=n(e);return J(t.code,t.message,t.details)}}async function ah(e){for(let[t,n]of e.actions.entries()){let r=await e.invokeReplayAction({action:n,line:e.line,step:e.step+t/1e3});if(!r.ok)return r}return{ok:!0,data:{ran:e.actions.length}}}async function oh(e){let t;for(let n=0;n<=e.maxRetries;n+=1){let r=await ah({actions:e.actions,line:e.line,step:e.step+n,invokeReplayAction:e.invokeReplayAction});if(r.ok)return{ok:!0,data:{attempts:n+1,retried:n>0}};t=r}return t??{ok:!1,error:{code:`COMMAND_FAILED`,message:`retry commands failed.`}}}const sh={visibleTimeoutMs:3e3,visiblePollMs:250};async function ch(e){let t=await lh(e,e.control);return t.ok?t.matched?await ph(e):{ok:!0,data:{skipped:!0,condition:e.control.mode,selector:e.control.selector}}:t.response}async function lh(e,t){if(t.mode===`visible`)return await uh(e,t);let n=await dh(e,t.selector);return n.ok?{ok:!0,matched:!n.matched}:{ok:!1,response:n.response}}async function uh(e,t){let n=Date.now();for(;;){let r=await dh(e,t.selector);if(!r.ok)return{ok:!1,response:r.response};if(r.matched)return{ok:!0,matched:!0};if(Date.now()-n>=sh.visibleTimeoutMs)return{ok:!0,matched:!1};await w(sh.visiblePollMs)}}async function dh(e,t){let n=await Cf(e);return n.ok?fh(e,t,n):{ok:!1,response:n}}function fh(e,t,n){let r=wf(n.data);return r?{ok:!0,matched:If(r,t,zf(e.baseReq.flags),O(r)).ok}:{ok:!1,response:J(`COMMAND_FAILED`,`Unable to read snapshot data for runFlow.when.`)}}async function ph(e){let t=await ah({actions:e.control.actions,line:e.line,step:e.step,invokeReplayAction:e.invokeReplayAction});return t.ok?{ok:!0,data:{ran:t.data?.ran,condition:e.control.mode,selector:e.control.selector}}:t}async function mh(e){let{req:t,sessionName:n,action:r,scope:i,filePath:a,line:o,step:s,tracePath:c,invoke:l}=e,u=sr(r,i,{file:a,line:o}),d=e=>mh({req:t,sessionName:n,action:e.action,scope:i,filePath:a,line:e.line,step:e.step,tracePath:c,invoke:l}),f=Date.now();yh(c,{type:`replay_action_start`,ts:new Date(f).toISOString(),replayPath:a,line:o,step:s,command:u.command,positionals:u.positionals??[]});let p=await hh({req:t,sessionName:n,resolved:u,scope:i,line:o,step:s,invoke:l,invokeReplayAction:d}),m=Date.now();return yh(c,{type:`replay_action_stop`,ts:new Date(m).toISOString(),replayPath:a,line:o,step:s,command:u.command,ok:p.ok,durationMs:m-f,resultTiming:p.ok?vh(p.data):void 0,errorCode:p.ok?void 0:p.error.code}),p}async function hh(e){let{req:t,sessionName:n,resolved:r,scope:i,line:a,step:o,invoke:s,invokeReplayAction:c}=e,l=bh(t.flags,r.flags),u={token:t.token,session:n,flags:l,runtime:r.runtime,meta:t.meta,internal:t.internal},d=await gh({control:r.replayControl,baseReq:u,line:a,step:o,invoke:s,invokeReplayAction:c})??await nh({command:r.command,baseReq:u,positionals:r.positionals??[],scope:i,line:a,step:o,invoke:s,invokeReplayAction:c})??await s({...u,command:r.command,positionals:r.positionals??[]});if(d.ok){let e=_h(d.data);e&&or(i,e)}return d}async function gh(e){let{control:t,baseReq:n,line:r,step:i,invoke:a,invokeReplayAction:o}=e;if(t){switch(t.kind){case`retry`:return await oh({actions:t.actions,maxRetries:t.maxRetries,line:r,step:i,invokeReplayAction:o});case`maestroRunFlowWhen`:return await ch({baseReq:n,control:t,line:r,step:i,invoke:a,invokeReplayAction:o})}return t}}function _h(e){if(!e||typeof e!=`object`)return null;let t=e.outputEnv;if(!t||typeof t!=`object`||Array.isArray(t))return null;let n=Object.entries(t).filter(e=>typeof e[1]==`string`);return n.length>0?Object.fromEntries(n):null}function vh(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e.timing;if(!(!t||typeof t!=`object`||Array.isArray(t)))return Object.fromEntries(Object.entries(t).filter(([,e])=>{let t=typeof e;return t===`number`||t===`string`||t===`boolean`}))}function yh(e,t){e&&z.appendFileSync(e,`${JSON.stringify(t)}\n`)}function bh(e,t){return Re(e,{...t??{}})}async function xh(e){let{req:t,sessionName:r,logPath:i,sessionStore:a,tracePath:o,invoke:s}=e,c=t.positionals?.[0];if(!c)return E(`INVALID_ARGS`,`replay requires a path`);let l=``,u=new Set;try{l=A.expandHome(c,t.meta?.cwd);let e=z.readFileSync(l,`utf8`),n=e.trimStart()[0];if(n===`{`||n===`[`)return E(`INVALID_ARGS`,`replay accepts .ad script files. JSON replay payloads are no longer supported.`);let d=rf(e,t.flags,{sourcePath:l}),f=d.metadata,p=f.platform||f.target?{...t,flags:Oh(t.flags,f)}:t,m=d.actions,h=d.actionLines;if(t.flags?.replayUpdate===!0&&d.updateUnsupportedMessage)return E(`INVALID_ARGS`,d.updateUnsupportedMessage);if(t.flags?.replayUpdate===!0&&f.env&&Object.keys(f.env).length>0)return E(`INVALID_ARGS`,`replay -u does not yet preserve env directives. Temporarily remove the env lines, run replay -u, then restore them.`);if(t.flags?.replayUpdate===!0&&Fh(m))return E(`INVALID_ARGS`,"replay -u does not yet preserve ${VAR} substitutions. Resolve or inline the variables before running with -u.");let g=Cr({builtins:Sh({req:p,sessionName:r,metadata:f,resolvedPath:l}),fileEnv:f.env,shellEnv:lr(cr(t.flags?.replayShellEnv)),cliEnv:Sr(ur(t.flags?.replayEnv))}),_=t.flags?.replayUpdate===!0,v=o??a.get(r)?.trace?.outPath,y=[],b=0;for(let e=0;e<m.length;e+=1){let t=m[e];if(!t||t.command===`replay`)continue;Ch(l,e,m.length,t);let n=Mh(a,r),o=await mh({req:p,sessionName:r,action:t,scope:g,filePath:l,line:h[e]??0,step:e+1,tracePath:v,invoke:s});if(y.push(...Nh(a,r,n)),o.ok){jh(o).forEach(e=>u.add(e));continue}if(jh(o).forEach(e=>u.add(e)),!_)return kh(o,t,e,l,[...u],y);let c=await uf({action:t,sessionName:r,logPath:i,sessionStore:a});if(!c)return kh(o,t,e,l,[...u],y);m[e]=c;let d=Mh(a,r);if(o=await mh({req:p,sessionName:r,action:c,scope:g,filePath:l,line:h[e]??0,step:e+1,tracePath:v,invoke:s}),y.push(...Nh(a,r,d)),!o.ok)return jh(o).forEach(e=>u.add(e)),kh(o,c,e,l,[...u],y);jh(o).forEach(e=>u.add(e)),b+=1}_&&b>0&&dr(l,m,a.get(r));let ee=Ee(y);return{ok:!0,data:{replayed:m.length,healed:b,session:r,artifactPaths:[...u],...ee?{snapshotDiagnostics:ee}:{}}}}catch(e){let t=n(e);return E(t.code,t.message,u.size>0?{artifactPaths:[...u]}:void 0)}}function Sh(e){let{req:t,sessionName:n,metadata:r,resolvedPath:i}=e,a=t.flags??{},o=t.meta?.cwd??process.cwd(),s={AD_SESSION:n,AD_FILENAME:B.relative(o,i)||i},c=a.platform??r.platform;c&&(s.AD_PLATFORM=c);let l=a.target??r.target;l&&(s.AD_TARGET=l);let u=a.device;typeof u==`string`&&u.length>0&&(s.AD_DEVICE=u);let d=typeof a.serial==`string`?a.serial:a.udid;typeof d==`string`&&d.length>0&&(s.AD_DEVICE_ID=d),typeof a.shardIndex==`number`&&(s.AD_SHARD_INDEX=String(a.shardIndex)),typeof a.shardCount==`number`&&(s.AD_SHARD_COUNT=String(a.shardCount));let f=a.artifactsDir;return typeof f==`string`&&f.length>0&&(s.AD_ARTIFACTS=f),s}function Ch(e,t,n,r){let i=pt();i&&T({type:`replay-test`,...i,file:i.file||e,status:`progress`,stepIndex:t+1,stepTotal:n,...wh(r)})}function wh(e){return{stepCommand:Th(e.command),...Eh(e)}}function Th(e){if(!e.startsWith(`__maestro`))return e;let t=e.slice(9);return t.length>0?t[0].toLowerCase()+t.slice(1):e}function Eh(e){let t=e.positionals??[],n=Dh(t[0]);return n?{stepValue:n}:e.command===`__maestroTapPointPercent`&&t.length>=2?{stepValue:`${t[0]},${t[1]}%`}:t.length===0?{}:{stepValue:t.join(` `)}}function Dh(e){if(!e)return;let t=v(e);if(!t)return;let n=t.selectors.flatMap(e=>e.terms.flatMap(e=>(e.key===`label`||e.key===`text`||e.key===`id`)&&typeof e.value==`string`?[e.value]:[]));if(n.length===0)return;let r=n[0];return r&&n.every(e=>e===r)?r:void 0}function Oh(e,t){return{...e??{},...t.platform!==void 0&&e?.platform===void 0?{platform:t.platform}:{},...t.target!==void 0&&e?.target===void 0?{target:t.target}:{}}}function kh(e,t,n,r,i,a){return Ah(e,t,n,r,i,Ee(a))}function Ah(e,t,n,r,i=[],a){if(e.ok)return e;let o=n+1;return{ok:!1,error:{code:e.error.code,message:`Replay failed at step ${o} (${st(t)}): ${e.error.message}`,hint:e.error.hint,diagnosticId:e.error.diagnosticId,logPath:e.error.logPath,details:{...e.error.details??{},replayPath:r,step:o,action:t.command,positionals:t.positionals??[],artifactPaths:i,...a?{snapshotDiagnostics:a}:{}}}}}function jh(e){if(!e.ok){let t=e.error.details?.artifactPaths;return Array.isArray(t)?[...new Set(t.filter(e=>typeof e==`string`&&Ph(e)))]:[]}if(!e.data)return[];let t=[];if(typeof e.data.path==`string`&&t.push(e.data.path),typeof e.data.outPath==`string`&&t.push(e.data.outPath),Array.isArray(e.data.artifacts))for(let n of e.data.artifacts){if(!n||typeof n!=`object`)continue;let e=n,r=typeof e.localPath==`string`?e.localPath:void 0,i=typeof e.path==`string`?e.path:void 0;r?t.push(r):i&&t.push(i)}return[...new Set(t.filter(e=>Ph(e)))]}function Mh(e,t){return e.get(t)?.snapshotDiagnostics?.samples.length??0}function Nh(e,t,n){return e.get(t)?.snapshotDiagnostics?.samples.slice(n)??[]}function Ph(e){try{return z.statSync(e).isFile()}catch{return!1}}function Fh(e){for(let t of e){for(let e of t.positionals??[])if(typeof e==`string`&&e.includes("${"))return!0;if(Ih(t.flags)||Ih(t.runtime))return!0}return!1}function Ih(e){return typeof e==`string`?e.includes("${"):Array.isArray(e)?e.some(Ih):e&&typeof e==`object`?Object.values(e).some(Ih):!1}const Lh=1e3,Rh=3e3;function zh(e){if(e.req.flags?.recordVideo===!0)return{beforeDispatch:async()=>await Bh(e)}}async function Bh(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,artifactsDir:a,tracePath:o}=e;if(t.flags?.recordVideo!==!0)return;let s=i.get(n);if(!s||s.recording)return;let c=we(s.device.platform),l=a?B.join(a,`recording${c}`):Te(s.device.platform);Hh(o,{type:`video_recording_start`,session:n,videoPath:l}),h({phase:`replay_test_video_recording_start`,data:{session:n,videoPath:l}});let u=await Pr({req:{token:t.token,session:n,command:`record`,positionals:[`start`,l],flags:{},meta:t.meta},sessionName:n,sessionStore:i,logPath:r});if(!u.ok)return Hh(o,{type:`video_recording_start_failed`,session:n,videoPath:l,errorCode:u.error.code}),u;let d=Date.now();return await w(Lh),Hh(o,{type:`video_preroll_done`,session:n,durationMs:Date.now()-d,requestedDurationMs:Lh}),h({phase:`replay_test_video_recording_preroll_done`,durationMs:Date.now()-d,data:{session:n,requestedDurationMs:Lh}}),u}async function Vh(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,tracePath:a,artifactPaths:o}=e;if(t.flags?.recordVideo!==!0||!i.get(n)?.recording)return;Hh(a,{type:`video_tail_start`,session:n,requestedDurationMs:Rh});let s=Date.now();await w(Rh);let c=Date.now(),l=await Pr({req:{token:t.token,session:n,command:`record`,positionals:[`stop`],flags:{},meta:t.meta},sessionName:n,sessionStore:i,logPath:r});return jh(l).forEach(e=>o.add(e)),Hh(a,{type:`video_recording_stop`,session:n,ok:l.ok,durationMs:Date.now()-c,tailDurationMs:c-s,errorCode:l.ok?void 0:l.error.code}),h({phase:`replay_test_video_recording_stop`,durationMs:Date.now()-c,data:{session:n,ok:l.ok,tailDurationMs:c-s}}),l}function Hh(e,t){q(e,{...t,ts:new Date().toISOString()})}function Uh(e){let{platform:t,target:n,artifactsDir:r,shard:i}=e,a=Wh(e.parentFlags);return t===void 0&&n===void 0&&r===void 0&&i===void 0?a:Od({...a??{},...t===void 0?{}:{platform:t},...n===void 0?{}:{target:n},...r===void 0?{}:{artifactsDir:r}},i)}function Wh(e){if(e?.recordVideo!==!0)return e;let t={...e};return delete t.recordVideo,Object.keys(t).length>0?t:void 0}async function Gh(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,leaseRegistry:a,invoke:o}=e;return t.command===`replay`?await xh({req:t,sessionName:n,logPath:r,sessionStore:i,invoke:o}):t.command===`test`?await Vd({req:t,sessionName:n,runReplay:async({filePath:e,sessionName:n,platform:a,target:s,requestId:c,artifactsDir:l,artifactPaths:u,tracePath:d,shard:f})=>{let p=e=>(u&&jh(e).forEach(e=>u.add(e)),e),m=Uh({parentFlags:t.flags,platform:a,target:s,artifactsDir:l,shard:f}),h={req:t,sessionName:n,logPath:r,sessionStore:i,artifactsDir:l,tracePath:d},g=zh(h);return await xh({req:{...t,command:`replay`,session:n,positionals:[e],flags:m,meta:{...t.meta??{},...c?{requestId:c}:{}},...t.internal||g?{internal:{...t.internal??{},...g?{openLifecycle:g}:{}}}:{}},sessionName:n,logPath:r,sessionStore:i,tracePath:d,invoke:async e=>{let t=await Bh(h);return t&&!t.ok?t:p(await o(e))}})},finalizeAttempt:async({sessionName:e,artifactPaths:n,artifactsDir:a,tracePath:o})=>await Vh({req:t,sessionName:e,logPath:r,sessionStore:i,artifactsDir:a,tracePath:o,artifactPaths:n}),cleanupSession:async e=>{i.get(e)&&await Wa({req:{token:t.token,session:e,command:`close`,positionals:[],flags:{},meta:t.meta},sessionName:e,logPath:r,sessionStore:i,leaseRegistry:a})}}):null}function Kh(e){return e.some(e=>e.status===`fail`)?`fail`:e.some(e=>e.status===`warn`)?`warn`:`pass`}function qh(e){return e===`fail`?`Blockers found before the run.`:e===`warn`?`No hard blockers found, but warnings need attention.`:`No blockers found.`}function Jh(e){let t={fail:0,warn:1,pass:2,info:3};return[...e].sort((e,n)=>t[e.status]-t[n.status])}function Yh(e,...t){for(let n of t)$(e,n)}function $(e,t){e.push(t),T({type:`command`,status:`progress`,message:Xh(t)})}function Xh(e){return[Ce(e),...se(e)].join(`
|
|
27
|
+
`)}async function Zh(e,t){let{device:n,metroPort:r,shouldProbeMetro:i,androidAdbExecutor:a}=t;n.platform!==`android`||!i||$(e,await Qh(m(n,a),n.id,r))}async function Qh(t,n,r){try{let e=await t([`reverse`,`--list`],{allowFailure:!0,timeoutMs:2e3}),i=`tcp:${r} tcp:${r}`,a=e.stdout.includes(i);return{id:`android-reverse`,status:a?`pass`:`warn`,summary:a?`Android adb reverse exists for Metro port ${r}.`:`Android adb reverse is missing for Metro port ${r}.`,command:a?void 0:`adb -s ${n} reverse tcp:${r} tcp:${r}`,evidence:{stdout:e.stdout.trim()}}}catch(t){let n=e(t);return{id:`android-reverse`,status:`warn`,summary:`Could not inspect Android adb reverse mappings.`,hint:n.message,evidence:{code:n.code}}}}async function $h(t,n){let{device:r,targetApp:a,session:o}=n;if(a)try{let e=await eg(r,a);if(!e){$(t,{id:`target-app`,status:`info`,summary:`Target app installation checks are not supported for ${i(r)}.`,evidence:{requested:a,platform:i(r)}});return}$(t,{id:`target-app`,status:`pass`,summary:`Target app is launchable: ${e}`,evidence:{requested:a,resolved:e,sessionApp:o?.appBundleId}})}catch(n){let a=e(n);$(t,{id:`target-app`,status:`fail`,summary:`Target app check failed: ${a.message}`,hint:a.hint??`Install the app or pass an exact package/bundle id or app name.`,command:`agent-device apps --platform ${i(r)} --all`,evidence:{code:a.code,message:a.message}})}}async function eg(e,t){if(e.platform===`android`){let{listAndroidApps:n}=await import(`./app-lifecycle.js`).then(e=>e.t);return tg(t,(await n(e,`all`)).map(e=>({id:e.package,name:e.name})))?.id}if(c(e)||s(e)){let{listIosApps:n}=await import(`./apps.js`).then(e=>e.t);return tg(t,(await n(e,`all`)).map(e=>({id:e.bundleId,name:e.name})))?.id}}function tg(e,n){let r=e.trim().toLowerCase(),i=n.find(e=>e.id.toLowerCase()===r||e.name.toLowerCase()===r);if(i)return i;let a=n.filter(e=>e.id.toLowerCase().includes(r)||e.name.toLowerCase().includes(r));if(a.length===1)return a[0];throw a.length>1?new t(`AMBIGUOUS_MATCH`,`Multiple launchable apps matched "${e}"`,{matches:a.map(e=>e.id),hint:`Pass an exact package/bundle id from agent-device apps --all.`}):new t(`APP_NOT_INSTALLED`,`No launchable installed app matched "${e}"`)}async function ng(t,n,r){let i=ig(n,r);try{let e=await og(i),n=ag(e.devices,i);return $(t,{id:`device`,status:n.length===0?`fail`:`pass`,summary:ug(n,i,e.failures),hint:n.length===0?pg(e.failures):void 0,command:n.length===0?vg(i):void 0,evidence:yg(n,e.failures)}),n.length>0&&sg(t,e.failures),{devices:n,platform:i.platform,target:i.target}}catch(n){let r=e(n);return $(t,{id:`device`,status:`fail`,summary:r.message,hint:r.hint,command:`agent-device devices`,evidence:{code:r.code,details:r.details}}),{devices:[],platform:i.platform,target:i.target}}}function rg(e,t,n){if(!n||!t)return;let r=t.devices.filter(e=>e.booted===!0);if(r.length===1)return r[0];$(e,{id:`target-app-device`,status:`fail`,summary:r.length===0?`Target app check needs one booted device; none matched.`:`Target app check needs one booted device; ${r.length} matched.`,hint:r.length===0?`Boot a device, or adjust --platform/--target/--device/--udid/--serial.`:`Pass --platform/--target/--device/--udid/--serial so doctor checks the intended device.`,command:t.platform?`agent-device devices --platform ${t.platform}`:`agent-device devices`,evidence:{targetApp:n,booted:r.map(e=>({platform:i(e),id:e.id,name:e.name}))}})}function ig(e,t){let n=e.flags??{};return qn({platform:n.platform??t?.device.platform,target:n.target??t?.device.target,device:n.device,udid:n.udid,serial:n.serial,iosSimulatorDeviceSet:n.iosSimulatorDeviceSet,androidDeviceAllowlist:n.androidDeviceAllowlist})}function ag(e,t){return e.filter(e=>u(e,t,{includeExplicitSelectors:!0}))}async function og(e){if(e.platform)return{devices:await un(e),failures:[]};let t=[],n=[];for(let r of Xn)try{t.push(...await un({...e,platform:r}))}catch(e){n.push(lg(r,e))}return{devices:t,failures:n}}function sg(e,t){for(let n of t)$(e,cg(n))}function cg(e){return{id:`device-${e.platform}`,status:`warn`,summary:`${gg(e.platform)} device inventory could not be read: ${e.message}`,hint:e.hint??`Check the ${gg(e.platform)} toolchain, or scope with --platform to skip it.`,evidence:{platform:e.platform,code:e.code}}}function lg(t,n){let r=e(n);return{platform:t,message:r.message,hint:r.hint,code:r.code}}function ug(e,t,n){if(e.length===0)return n.length>0?`No ${dg(t)} devices found; ${fg(n)}.`:`No ${dg(t)} devices found.`;let r=e.filter(e=>e.booted===!0).length,i=`${e.length} ${dg(t)} ${_g(e.length,`device`)} available; ${r} booted`,a=mg(e,t);return a?`${i} (${a}).`:`${i}.`}function dg(e){let t=e.platform?gg(e.platform):`local`;return e.target?`${t} ${e.target}`:t}function fg(e){return e.slice(0,2).map(e=>`${gg(e.platform)} inventory failed: ${e.message}`).join(`; `)}function pg(e){return e.find(e=>e.hint)?.hint??`Start or create a simulator/emulator, connect a device, or adjust --platform/--target/--device selectors.`}function mg(e,t){if(t.platform||t.target)return;let n=pn(e),r=hg();return[`android`,`apple`,`linux`,`web`].flatMap(e=>{let t=n[e];return t.available>0?[`${r[e]} ${t.available} available, ${t.booted} booted`]:[]}).join(`; `)}function hg(){return{android:`Android`,apple:`Apple`,linux:`Linux`,web:`web`}}function gg(e){return e===`ios`?`iOS`:e===`macos`?`macOS`:e===`android`?`Android`:e===`linux`?`Linux`:e===`web`?`web`:`Apple`}function _g(e,t){return e===1?t:`${t}s`}function vg(e){return e.platform?`agent-device devices --platform ${e.platform}`:`agent-device devices`}function yg(e,t){let n=new Map;for(let t of e){let e=i(t),r=n.get(e)??{available:0,booted:0};r.available+=1,t.booted===!0&&(r.booted+=1),n.set(e,r)}return{available:e.length,booted:e.filter(e=>e.booted===!0).length,byPlatform:Object.fromEntries([...n.entries()].sort(([e],[t])=>e.localeCompare(t))),...t.length>0?{failures:t}:{}}}const bg=1500;async function xg(e,t,n,r={}){let i=`http://${e}:${t}/status`;try{let a=await fetch(i,{signal:AbortSignal.timeout(1500)}),o=await a.text(),s=a.ok&&o.toLowerCase().includes(`packager-status:running`),c=s?await Sg(e,t,r):void 0;return{id:`metro`,status:s?`pass`:`warn`,summary:s?Cg(i,c):`React Native dev server responded at ${i}, but did not report packager-status:running.`,hint:s?void 0:`Verify this is the Metro/Re.Pack instance for the target app, or restart the dev server.`,evidence:{url:i,statusCode:a.status,body:o.slice(0,120),kind:n,...c?{process:c}:{}}}}catch(e){return{id:`metro`,status:n===`auto`?`warn`:`fail`,summary:`React Native dev server is not reachable at ${i}.`,hint:`Start Metro or Re.Pack for this project. For non-default endpoints, launch with open --metro-host/--metro-port, or run metro prepare with --public-base-url/--proxy-base-url before retrying doctor.`,command:`curl -fsS ${i}`,evidence:{url:i,error:e instanceof Error?e.message:String(e),kind:n}}}}async function Sg(e,t,n){try{return await(n.resolveProcessInfo??wg)(e,t)}catch{return}}function Cg(e,t){return t?.cwd?`React Native dev server is reachable at ${e} (cwd: ${t.cwd}).`:`React Native dev server is reachable at ${e}.`}async function wg(e,t){if(!Tg(e))return;let n=await Eg(t);if(n!==void 0)return{pid:n,cwd:await Dg(n)}}function Tg(e){return e===`127.0.0.1`||e===`localhost`||e===`::1`||e===`0.0.0.0`}async function Eg(e){let t=await _(`lsof`,[`-nP`,`-iTCP:${e}`,`-sTCP:LISTEN`,`-Fp`],{allowFailure:!0,timeoutMs:bg});if(t.exitCode===0)return t.stdout.split(`
|
|
28
|
+
`).map(e=>e.startsWith(`p`)?Number.parseInt(e.slice(1),10):NaN).find(e=>Number.isInteger(e)&&e>0)}async function Dg(e){let t=await _(`lsof`,[`-nP`,`-a`,`-p`,String(e),`-d`,`cwd`,`-Fn`],{allowFailure:!0,timeoutMs:bg});if(t.exitCode===0)return t.stdout.split(`
|
|
29
|
+
`).find(e=>e.startsWith(`n`)&&e.length>1)?.slice(1)}const Og=[`daemonBaseUrl`,`tenant`,`runId`,`leaseId`,`leaseProvider`],kg=[`provider`,`providerSessionId`,`providerApp`,`providerOsVersion`,`providerProject`,`providerBuild`,`providerSessionName`,`awsProjectArn`,`awsDeviceArn`,`awsAppArn`,`awsRegion`,`awsInteractionMode`];function Ag(e,t){let n=ze(e.meta?.cwd);return{targetApp:Fg(e.flags?.targetApp)??t?.appBundleId,metroHost:Fg(e.runtime?.metroHost)??`127.0.0.1`,metroPort:Ig(e.runtime?.metroPort)??8081,kind:n,remote:e.flags?.remote===!0,shouldProbeMetro:Ng(e,n)}}function jg(e,t={}){let n=Pg(e);return n?[{id:`remote-connection`,status:t.required?`pass`:`info`,summary:`Remote daemon/session or provider scope is configured.`,evidence:n}]:t.required?[{id:`remote-connection`,status:`fail`,summary:`No remote daemon/session or provider scope is configured.`,hint:`Use connect, --remote-config <path>, or direct remote/provider flags for the command.`}]:[]}function Mg(e,t,n,r={}){let a=n?e.toArray().filter(e=>e.name!==n.name&&e.device.platform===n.device.platform&&e.device.id===n.device.id).map(e=>e.name):[];return n?[{id:`session`,status:a.length>0?`warn`:`pass`,summary:a.length>0?`Other active sessions target the same device: ${a.join(`, `)}`:`Active session ${n.name} targets ${n.device.name}`,hint:a.length>0?`Close stale sessions before a QA run if they belong to old attempts.`:void 0,command:a.length>0?`agent-device close --session ${a[0]} --platform ${i(n.device)}`:void 0,evidence:{session:n.name,sameDeviceSessions:a,sessionStateDir:e.resolveSessionDir(n.name)}}]:[{id:`session`,status:`info`,summary:r.remote?`No active session named ${t}. Remote doctor will use configured remote scope.`:`No active session named ${t}. Doctor will use device inventory only.`,hint:`This is expected before a run. Use open when app foreground state matters.`}]}function Ng(e,t){return t!==`auto`||typeof e.runtime?.metroPort==`number`||typeof e.runtime?.metroHost==`string`}function Pg(e){let t={...Object.fromEntries([...Og,...kg].flatMap(t=>typeof e.flags?.[t]==`string`?[[t,`<configured>`]]:[])),...e.flags?.sessionIsolation===`tenant`?{sessionIsolation:`tenant`}:{}};return Object.keys(t).length>0?t:void 0}function Fg(e){return typeof e==`string`&&e.trim().length>0?e.trim():void 0}function Ig(e){return typeof e==`number`&&Number.isInteger(e)&&e>0?e:void 0}async function Lg(e,t){if(t===`android`){$(e,await Rg());return}(t===`ios`||t===`macos`||t===`apple`)&&$(e,await Ug())}async function Rg(){let e=process.env.ANDROID_HOME||process.env.ANDROID_SDK_ROOT,t=await Jg(e),n=await Yg(`adb`,[`version`]);return n?zg({license:t,sdkRoot:e,versionLine:n}):Hg(e,t)}function zg(e){return{id:`toolchain`,status:Bg(e),summary:e.versionLine?`Android toolchain: ${e.versionLine}; ${Vg(e.sdkRoot)}.`:`Android toolchain: adb is present but version check failed.`,hint:e.license===`missing`?`Accept Android SDK licenses before installing/building apps.`:void 0,command:e.license===`missing`?`sdkmanager --licenses`:void 0,evidence:{adbVersion:e.versionLine??null,androidHome:e.sdkRoot??null,license:e.license}}}function Bg(e){return e.versionLine&&e.sdkRoot&&e.license!==`missing`?`pass`:`info`}function Vg(e){return e?`ANDROID_HOME/ANDROID_SDK_ROOT set`:`ANDROID_HOME unset`}function Hg(e,t){return{id:`toolchain`,status:`info`,summary:`Android toolchain: adb not found on PATH.`,hint:`Install Android platform-tools or add adb to PATH.`,evidence:{androidHome:e??null,license:t}}}async function Ug(){let e=await Yg(`xcodebuild`,[`-version`]);return e?Wg({selectedPath:await Yg(`xcode-select`,[`-p`]),versionLine:e}):qg()}function Wg(e){return{id:`toolchain`,status:Gg(e),summary:Kg(e),evidence:{selectedPath:e.selectedPath??null,xcodeVersion:e.versionLine??null}}}function Gg(e){return e.versionLine?`pass`:`info`}function Kg(e){return e.versionLine?e.selectedPath?`Apple toolchain: ${e.versionLine}; xcode-select ${e.selectedPath}.`:`Apple toolchain: ${e.versionLine}; xcode-select path unavailable.`:`Apple toolchain: xcodebuild version check failed.`}function qg(){return{id:`toolchain`,status:`info`,summary:`Apple toolchain: xcodebuild version check failed.`,hint:`Install/select Xcode and complete first launch/license setup if xcodebuild reports it.`,command:`xcodebuild -version`}}async function Jg(e){if(!e)return`unknown`;try{return await Fr(B.join(e,`licenses`,`android-sdk-license`)),`accepted`}catch{return`missing`}}async function Yg(e,t){try{let n=await _(e,t,{allowFailure:!0,timeoutMs:3e3});return n.exitCode===0?n.stdout.split(`
|
|
30
|
+
`).map(e=>e.trim()).find(Boolean):void 0}catch{return}}async function Xg(e,t){$(e,await Zg(t))}async function Zg(e){let t=Ot({stateDir:e});if(!t.installed)return{id:`web-agent-browser-processes`,status:`info`,summary:`Managed web backend is not installed; no agent-device-owned browser processes counted.`,evidence:{stateDir:e,installed:!1}};try{let n=await kt(t);return{id:`web-agent-browser-processes`,status:n.count>0?`info`:`pass`,summary:n.count>0?`${n.count} live agent-device-owned Chrome process${n.count===1?``:`es`} detected.`:`No live agent-device-owned Chrome processes detected.`,evidence:{stateDir:e,installed:!0,count:n.count,pids:n.pids,matchReasons:n.processes.map(e=>e.reason)}}}catch(t){return{id:`web-agent-browser-processes`,status:`info`,summary:`Could not inspect live agent-device-owned Chrome processes.`,hint:`Run doctor again from a shell with permission to inspect local processes.`,evidence:{stateDir:e,error:t instanceof Error?t.message:String(t)}}}}async function Qg(e){let{req:t,sessionName:n,sessionStore:r,androidAdbExecutor:i}=e;if(t.command!==C.doctor)return null;let a=r.get(n),o=Ag(t,a),s=t_(r,n),c=[];if(Yh(c,{id:`agent-device`,status:`pass`,summary:`agent-device ${ke()} using ${s}`,evidence:{version:ke(),stateDir:s}},...jg(t,{required:o.remote}),...Mg(r,n,a,{remote:o.remote})),o.remote)return i_(c,o);let l=await ng(c,t,a);await Lg(c,a?.device.platform??l?.platform);let u=await n_({androidAdbExecutor:i,checks:c,inventory:l,options:o,session:a,stateDir:s});return await e_(c,u??$g(l)),i_(c,o,{device:u,includeMetro:!0,inventory:l})}function $g(e){let t=(e?.devices??[]).filter(e=>c(e)&&e.kind===`simulator`);return t.find(e=>e.booted===!0)??t[0]}async function e_(e,t){if(!(!t||!c(t)||t.kind!==`simulator`)&&!(process.platform!==`darwin`||vn(t))){if(T({type:`command`,status:`progress`,message:`Checking iOS runner build cache (${t.name})...`}),await bt(t)){$(e,{id:`ios-runner-cache`,status:`pass`,summary:`iOS runner artifact cached; first open skips the runner build`});return}mt(t,{}),T({type:`command`,status:`progress`,message:`Warming iOS runner build cache in the background (${t.name})...`}),$(e,{id:`ios-runner-cache`,status:`pass`,summary:`iOS runner build started in the background; the first open gets faster once it completes`,hint:"Run `agent-device prepare ios-runner` to wait for a fully warmed runner instead."})}}function t_(e,t){let n=B.dirname(e.resolveSessionDir(t));return B.basename(n)===`sessions`?B.dirname(n):n}async function n_(e){let{checks:t,inventory:n,options:r,session:i,androidAdbExecutor:a,stateDir:o}=e,s=i?.device??rg(t,n,r.targetApp);return s&&await r_(t,{androidAdbExecutor:a,device:s,options:r,session:i}),r.shouldProbeMetro&&$(t,await xg(r.metroHost,r.metroPort,r.kind)),await Xg(t,o),s}async function r_(e,t){let{androidAdbExecutor:n,device:r,options:i,session:a}=t;await $h(e,{device:r,session:a,targetApp:i.targetApp}),await Zh(e,{androidAdbExecutor:n,device:r,metroPort:i.metroPort,shouldProbeMetro:i.shouldProbeMetro})}function i_(e,t,n={}){let r=Kh(e);return{ok:!0,data:{status:r,summary:qh(r),kind:t.kind,platform:n.device?i(n.device):n.inventory?.platform,target:n.device?.target??n.inventory?.target,targetApp:t.targetApp,metro:n.includeMetro&&t.shouldProbeMetro?{host:t.metroHost,port:t.metroPort}:void 0,checks:Jh(e)}}}async function a_(e){let{req:t,sessionName:n,logPath:r,sessionStore:i}=e,o=t.positionals?.[0]??``;if(o!==`ios-runner`)return E(`INVALID_ARGS`,`prepare requires a subcommand: ios-runner`);let s=i.get(n),c=t.flags??{},l=H(C.prepare,s,c);if(l)return l;let u=await U({session:s,flags:c,ensureReady:!0});if(!a(u.platform))return E(`UNSUPPORTED_OPERATION`,`prepare ios-runner is only supported on Apple runner platforms`);let d=Date.now(),f=await yt(u,o_(t,s,r,d));return{ok:!0,data:c_(o,u,Math.max(0,Date.now()-d),f)}}function o_(e,t,n,r){let i=s_(e);return{...kr({req:e,logPath:n,traceLogPath:t?.trace?.outPath}),cleanStaleBundles:!0,buildTimeoutMs:i,healthTimeoutMs:i,prepareDeadline:et.fromTimeoutMs(i,r),startupTimeoutMs:i}}function s_(e){let t=e.flags?.timeoutMs;return typeof t==`number`&&Number.isFinite(t)&&t>0?t:y}function c_(e,t,n,r){return{action:e,platform:i(t),deviceId:t.id,deviceName:t.name,kind:t.kind,durationMs:n,...r,timing:l_(n,r),message:`Prepared Apple runner: ${t.name}`}}function l_(e,t){let n=u_(t.buildMs),r=d_(t.connectMs),i=d_(t.healthCheckMs);return{totalMs:e,additiveParts:{...n===void 0?{}:{buildMs:n},connectAfterBuildMs:Math.max(0,r-(n??0)),healthCheckMs:i},containment:n===void 0?{healthCheckMs:[]}:{connectMs:[`buildMs`],healthCheckMs:[]},note:`Top-level prepare timing fields are diagnostic and may overlap; use timing.additiveParts for additive wall-clock phases.`}}function u_(e){return e===void 0?void 0:d_(e)}function d_(e){return Number.isFinite(e)?Math.max(0,Math.round(e)):0}async function f_(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,command:a,positionals:o,recordPositionals:s,deriveNextSession:c}=e,l=i.get(n),u=t.flags??{},d=H(a,l,u);if(d)return d;let f=await U({session:l,flags:u,ensureReady:!0}),p=k(a,f);if(p)return p;let m=await D(f,a,o,t.flags?.out,{...j(r,t.flags,l?.appBundleId,l?.trace?.outPath)});if(l){let e=c?await c(l,m,f):l;Ar(i,e,t,a,m??{},{positionals:s??o}),e!==l&&i.set(n,e)}return{ok:!0,data:m??{}}}async function p_(e){let{req:t,sessionName:n,logPath:r,sessionStore:a}=e,o=a.get(n),s=t.flags??{},c=H(C.clipboard,o,s);if(c)return c;let l=(t.positionals?.[0]??``).toLowerCase();if(l!==`read`&&l!==`write`)return E(`INVALID_ARGS`,`clipboard requires a subcommand: read or write`);let u=await U({session:o,flags:s,ensureReady:!0}),d=k(C.clipboard,u);if(d)return d;let f=await D(u,C.clipboard,t.positionals??[],t.flags?.out,{...j(r,t.flags,o?.appBundleId,o?.trace?.outPath)});return Ar(a,o,t,t.command,f??{}),{ok:!0,data:{platform:i(u),...f??{}}}}async function m_(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,leaseRegistry:a=new gn,leaseLifecycleProvider:o,invoke:s,invokeReplayAction:c,androidAdbExecutor:l}=e;if(t.command===C.doctor)return await Qg({req:t,sessionName:n,sessionStore:i,androidAdbExecutor:l});if(Qt(t.command)===`inventory`)return await no({req:t,sessionName:n,sessionStore:i});if(t.command===`runtime`)return await Yi({req:t,sessionName:n,sessionStore:i});if(Qt(t.command)===`state`)return await lo({req:t,sessionName:n,logPath:r,sessionStore:i});if(t.command===C.clipboard)return await p_({req:t,sessionName:n,logPath:r,sessionStore:i});if(t.command===C.keyboard){let e=i.get(n),a=t.positionals?.[0]?.trim().toLowerCase();return!e&&(a===`dismiss`||a===`enter`||a===`return`)&&(t.flags??{}).platform===`ios`?E(`SESSION_NOT_FOUND`,`iOS keyboard action requires an active session so the target app stays foregrounded. Run open first.`):await f_({req:t,sessionName:n,logPath:r,sessionStore:i,command:C.keyboard,positionals:t.positionals??[]})}if(Qt(t.command)===`observability`)return await nc({req:t,sessionName:n,sessionStore:i,androidAdbExecutor:l});if(t.command===C.prepare)return await a_({req:t,sessionName:n,logPath:r,sessionStore:i});if(t.command===C.install||t.command===C.reinstall)return await Xa({req:t,command:t.command,sessionName:n,sessionStore:i,deployOps:t.command===C.install?Ya:Ja});if(t.command===fe.installSource)return await qr({req:t,sessionName:n,sessionStore:i});if(t.command===fe.releaseMaterializedPaths)return await ni({req:t});if(t.command===C.push){let e=t.positionals?.[0]?.trim(),a=t.positionals?.[1]?.trim();return!e||!a?E(`INVALID_ARGS`,`push requires <bundle|package> <payload.json|inline-json>`):await f_({req:t,sessionName:n,logPath:r,sessionStore:i,command:C.push,positionals:[e,h_(a,t.meta?.cwd)],recordPositionals:[e,a]})}return t.command===C.triggerAppEvent?await f_({req:t,sessionName:n,logPath:r,sessionStore:i,command:C.triggerAppEvent,positionals:t.positionals??[],deriveNextSession:async(e,t)=>{let n=typeof t?.eventUrl==`string`?t.eventUrl:void 0,r=n?await Sa(e.device,n,e.appBundleId,ya)??e.appBundleId:e.appBundleId;return{...e,appBundleId:r}}}):t.command===C.open?await Fa({req:t,sessionName:n,logPath:r,sessionStore:i}):Qt(t.command)===`replay`?await Gh({req:t,sessionName:n,logPath:r,sessionStore:i,leaseRegistry:a,invoke:c??s}):t.command===C.batch?await to(t,n,s):t.command===C.close?await Wa({req:t,sessionName:n,logPath:r,sessionStore:i,leaseRegistry:a,leaseLifecycleProvider:o}):null}function h_(e,t){let n=Rt(e,{subject:`Push payload`,cwd:t,expandPath:(e,t)=>A.expandHome(e,t)});return n.kind===`file`?n.path:n.text}export{m_ as handleSessionCommands};
|