agent-device 0.19.1 → 0.19.3
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/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.19.3.apk +0 -0
- package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.19.3.apk.sha256 +1 -0
- package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.19.1.manifest.json → agent-device-android-multitouch-helper-0.19.3.manifest.json} +4 -4
- package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.19.1.apk → agent-device-android-snapshot-helper-0.19.3.apk} +0 -0
- package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.19.3.apk.sha256 +1 -0
- package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.19.1.manifest.json → agent-device-android-snapshot-helper-0.19.3.manifest.json} +6 -6
- package/dist/apple-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedGesture.h +7 -0
- package/dist/apple-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedGesture.m +99 -30
- package/dist/apple-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +9 -1
- package/dist/apple-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +21 -8
- package/dist/apple-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +10 -0
- package/dist/apple-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SequenceExecution.swift +1 -0
- package/dist/src/agent-browser-tool.js +1 -1
- package/dist/src/android-adb.js +1 -1
- package/dist/src/android-input-ownership.js +1 -1
- package/dist/src/android.js +1 -1
- package/dist/src/app-lifecycle.js +1 -1
- package/dist/src/apple-runner-options.js +1 -1
- package/dist/src/apps.js +5 -5
- package/dist/src/audio-probe.js +1 -1
- package/dist/src/cli-help.js +34 -19
- 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/contracts.js +1 -1
- package/dist/src/debug-symbols.js +1 -1
- package/dist/src/device-input-state.js +1 -1
- package/dist/src/devices2.js +1 -1
- package/dist/src/find.js +1 -1
- package/dist/src/generic.js +1 -1
- package/dist/src/helper.js +1 -1
- package/dist/src/index.d.ts +29 -0
- package/dist/src/index.js +1 -1
- package/dist/src/input-actions.js +1 -1
- package/dist/src/input-actions2.js +1 -1
- package/dist/src/install-source2.js +1 -1
- 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 +20 -16
- package/dist/src/internal/png-worker.js +1 -1
- package/dist/src/lease.js +1 -1
- package/dist/src/linux.js +1 -1
- package/dist/src/notifications.js +1 -1
- package/dist/src/png-worker-contract.js +1 -1
- package/dist/src/points.js +3 -3
- 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 -24
- package/dist/src/reporting.js +3 -3
- package/dist/src/runner-client.js +1 -1
- package/dist/src/runner-sequence.js +1 -1
- package/dist/src/runtime-transport.js +1 -1
- package/dist/src/runtime.js +2 -2
- package/dist/src/sdk-android-adb.js +3 -3
- package/dist/src/sdk-app-inventory.js +1 -1
- package/dist/src/sdk-batch-runner.js +2 -2
- package/dist/src/sdk-batch.js +2 -2
- package/dist/src/sdk-contracts.js +2 -2
- package/dist/src/sdk-device.js +1 -0
- package/dist/src/sdk-finders.js +1 -1
- package/dist/src/sdk-io.js +1 -1
- 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.js +1 -1
- package/dist/src/server.js +2 -2
- package/dist/src/session.js +10 -10
- package/dist/src/setting-state.js +1 -1
- package/dist/src/simctl.js +1 -1
- package/dist/src/simulator.js +1 -1
- package/dist/src/snapshot-diagnostics.js +1 -1
- package/dist/src/snapshot.js +1 -1
- package/dist/src/snapshot2.js +2 -2
- package/dist/src/tool-provider.js +2 -2
- package/dist/src/tool-provider2.js +1 -1
- package/dist/src/tv-remote.js +9 -9
- package/dist/src/version.js +1 -1
- package/dist/src/web.js +1 -1
- package/package.json +11 -3
- package/server.json +2 -2
- package/android-multitouch-helper/dist/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 +0 -1
- package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.19.1.apk.sha256 +0 -1
- package/dist/src/snapshot-helper.js +0 -5
package/dist/src/session.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{
|
|
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`,`
|
|
1
|
+
import{S as e,_ as t,t as n,v as r}from"./sdk-contracts.js";import{C as i,N as a,c as o,j as s,p as c,v as l}from"./sdk-android-adb.js";import{C as u,T as d,_ as f,w as p}from"./sdk-batch.js";import{Bt as m,Cn as h,Gt as g,In as _,It as v,Kn as y,Kt as b,Ln as ee,Pt as x,Rt as S,Sn as te,Ut as ne,Vt as re,Wt as ie,Xn as C,Yn as ae,Zt as oe,f as se,lt as ce,nn as le,pt as ue,q as de,qt as fe,rn as pe}from"./tv-remote.js";import{i as me,r as he}from"./output-path.js";import{a as ge,n as _e,t as ve}from"./snapshot-diagnostics.js";import{n as ye}from"./version.js";import{t as be}from"./timeouts.js";import{N as xe,d as Se,g as Ce,h as we,i as Te,l as Ee,t as De}from"./sdk-selectors.js";import{n as Oe,t as ke}from"./sdk-batch-runner.js";import{t as Ae}from"./project-runtime.js";import{n as je,t as Me}from"./runtime-transport.js";import{c as w,f as Ne,g as Pe,l as Fe,m as T,o as E,p as Ie,s as D}from"./sdk-device.js";import{i as Le}from"./sdk-finders.js";import{a as Re,s as ze,t as Be}from"./selectors2.js";import{n as Ve}from"./sdk-app-inventory.js";import{f as He,h as Ue}from"./runtime.js";import{f as We,p as Ge,s as Ke}from"./app-lifecycle.js";import{D as qe,O as Je,S as Ye,b as Xe,k as Ze,p as Qe,v as $e,x as et}from"./android-input-ownership.js";import{d as tt,s as nt}from"./providers.js";import{C as rt,S as it,b as at,c as ot,g as st,h as ct,m as O,n as lt,o as ut,p as dt,r as ft,s as pt,t as mt,u as ht,v as gt,w as _t,x as vt,y as yt}from"./runner-client.js";import{a as bt}from"./tool-provider.js";import{r as xt}from"./helper.js";import{n as St}from"./simctl.js";import{n as Ct,s as wt}from"./agent-browser-tool.js";import{A as Tt,An as Et,B as Dt,C as Ot,Cn as kt,D as At,Dn as jt,E as Mt,En as k,F as Nt,I as Pt,L as Ft,Lt as It,M as Lt,N as Rt,O as zt,On as Bt,P as Vt,R as Ht,Rt as Ut,S as Wt,Sn as Gt,St as Kt,T as qt,Tn as Jt,Wt as A,Xt as j,Yt,Zt as Xt,_ as Zt,_n as Qt,_t as $t,a as en,at as tn,b as nn,bn as rn,c as an,cn as on,ct as sn,d as cn,dn as ln,dt as un,f as dn,fn,g as pn,gn as mn,gt as hn,h as gn,hn as _n,ht as vn,i as yn,in as M,it as bn,j as xn,k as Sn,kn as Cn,l as wn,ln as Tn,lt as En,m as Dn,mn as On,mt as kn,n as An,nn as jn,nt as Mn,o as Nn,on as N,ot as Pn,p as Fn,pn as In,pt as Ln,r as Rn,rt as zn,s as Bn,sn as Vn,st as Hn,tn as Un,u as Wn,un as Gn,ut as Kn,v as qn,vn as Jn,vt as Yn,w as Xn,x as Zn,xn as Qn,y as $n,yn as er,z as tr}from"./internal/daemon.js";import{C as nr,D as rr,E as ir,S as ar,T as or,a as P,b as sr,c as cr,d as lr,f as ur,g as dr,h as F,i as I,l as fr,m as pr,n as mr,o as L,p as R,r as hr,s as z,u as gr,v as _r,w as vr,x as yr,y as br}from"./points.js";import{n as xr}from"./provider.js";import{a as Sr,i as Cr,n as wr,r as Tr,t as Er}from"./apple-runner-options.js";import{t as Dr}from"./handler-utils.js";import{l as Or}from"./apps.js";import{a as kr,n as Ar}from"./simulator.js";import{t as jr}from"./record-trace-recording.js";import B from"node:fs";import V from"node:path";import{access as Mr}from"node:fs/promises";import{setTimeout as Nr}from"node:timers/promises";import Pr from"node:vm";function Fr(e){throw new t(`UNSUPPORTED_OPERATION`,`install_from_source ${String(e.kind)} sources require a compatible remote daemon`)}function Ir(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:Fr(n)}}function Lr(e){let t=Ir(e),n=e.meta?.uploadedArtifactId;return!n||t.kind!==`path`?{source:t,cleanup:()=>{}}:{source:{kind:`path`,path:Jt(n,e.meta?.tenantId)},cleanup:()=>{kt(n)}}}function Rr(e){return e===`ios`||e===`android`?e:void 0}function zr(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 Br(e){let n=Rr(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 Sr(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 On(e.flags??{});return await Sr(r),r}async function Vr(e){let{prepared:t,retention:n,req:r,session:i,sessionName:a}=e;if(n.enabled)return await cn({archivePath:t.archivePath,installablePath:t.installablePath,tenantId:r.meta?.tenantId,sessionName:i?a:void 0,ttlMs:n.ttlMs})}function Hr(e){return e?{...e.archivePath?{archivePath:e.archivePath}:{},installablePath:e.installablePath,materializationId:e.materializationId,materializationExpiresAt:e.expiresAt}:{}}function Ur(e){let{session:t,sessionStore:n,req:r,data:i}=e;Dr(n,t,r,`install_source`,i,{positionals:[]})}async function Wr(t){let{req:n,sessionName:r,sessionStore:i}=t,a=i.get(r);try{let e=Lr(n),t=zr(n),o=await Br({session:a,flags:n.flags}),s=N(`install`,o,{message:`install_from_source is not supported on this device`});if(s)return s;let c=at(n.meta?.requestId);if(D(o)){let{prepareIosInstallArtifact:s}=await import(`./apps.js`).then(e=>e.a),l=await s(e.source,{signal:c});return await Gr({prepared:l,retention:t,req:n,resolvedSourceCleanup:()=>e.cleanup(),session:a,sessionName:r,sessionStore:i,buildResult:async e=>await Kr(o,l,e)})}let{prepareAndroidInstallArtifact:l}=await import(`./android-input-ownership.js`).then(e=>e.l),u=await l(e.source,{signal:c});return await Gr({prepared:u,retention:t,req:n,resolvedSourceCleanup:()=>e.cleanup(),session:a,sessionName:r,sessionStore:i,buildResult:async e=>await qr(o,u,e)})}catch(t){return{ok:!1,error:e(t)}}}async function Gr(e){let t;try{t=await Vr(e);let n=await e.buildResult(t),r=h(n,Qr(n));return Ur({session:e.session,sessionStore:e.sessionStore,req:e.req,data:r}),{ok:!0,data:r}}catch(n){throw t&&await wn(t.materializationId,e.req.meta?.tenantId).catch(()=>{}),n}finally{await e.prepared.cleanup(),e.resolvedSourceCleanup()}}async function Kr(e,t,n){let r=await rn(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 Jr(t,r,n)}async function qr(e,t,n){let r=await rn(e,t.installablePath,{packageNameHint:t.packageName}),i=await Zr(e,t,r),{inferAndroidAppName:a}=await import(`./app-lifecycle.js`).then(e=>e.t),o=a(i);return{...Hr(n),packageName:i,...Xr(r?.appName??o),launchTarget:r?.launchTarget??i}}function Jr(e,t,n){let r=Yr(e,t),i=t?.appName??e.appName;return{...Hr(n),bundleId:r,...Xr(i),launchTarget:t?.launchTarget??r}}function Yr(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 Xr(e){return e?{appName:e}:{}}async function Zr(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 Qr(e){return`Installed: ${pe(e)}`}async function $r(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 wn(e,r.meta?.tenantId),{ok:!0,data:{released:!0,materializationId:e}}}catch(t){return{ok:!1,error:e(t)}}}function H(e){return D(e)&&e.kind===`simulator`}function ei(e){return e.platform===`android`&&e.kind===`emulator`}function U(e,t,n){return t||jn(n)?null:M(`INVALID_ARGS`,`${e} requires an active session or an explicit device selector (e.g. --platform ios).`)}function ti(e){return typeof e?.session==`string`&&e.session.trim().length>0}async function ni(e,t){!H(e)||t<=0||await new Promise(e=>setTimeout(e,t))}async function W(e){let t=jn(e.flags)||!e.session?await On(e.flags??{},{allowStoppedAndroidAvdPlaceholders:e.allowStoppedAndroidAvdPlaceholders}):await ri(e.session.device);return e.ensureReady!==!1&&await Sr(t),t}async function ri(e){if(!D(e)||e.kind!==`simulator`||process.platform!==`darwin`)return e;if(ut(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 On(n)}catch(e){if(!(e instanceof t)||e.code!==`DEVICE_NOT_FOUND`)throw e}return await On({platform:`ios`,target:e.target,device:e.name,...e.simulatorSetPath?{iosSimulatorDeviceSet:e.simulatorSetPath}:{}})}function ii(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 ai(e,t){return t?$t(t,e).length===0:!1}const oi=`shared_prefs/ReactNativeDevPrefs.xml`,si=`debug_http_host`,ci=`dev_server_https`,li=`RCT_jsLocation`,ui=`RCT_packager_scheme`,di=`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.`,fi=[`<?xml version="1.0" encoding="utf-8" standalone="yes" ?>`,`<map>`,`</map>`,``].join(`
|
|
2
|
+
`);function pi(e){return Me(e)!==void 0}async function mi(e){let{device:t,appId:n,runtime:r}=e;if(Qn(t)||!n)return;let i=Me(r);if(i){if(t.platform===`android`){await gi(t,n,i);return}D(t)&&t.kind===`simulator`&&await bi(t,n,i)}}async function hi(e){let{device:t,appId:n}=e;if(n){if(t.platform===`android`){await _i(t,n);return}D(t)&&t.kind===`simulator`&&await xi(t,n)}}async function gi(e,t,n){Di(t);let r=Ci(await vi(e,t),si,`${n.host}:${n.port}`);r=wi(r,ci,n.scheme===`https`),await yi(e,t,r)}async function _i(e,t){Di(t);let n=await vi(e,t),r=Ei(Ei(n,si),ci);r!==n&&await yi(e,t,r)}async function vi(e,t){let n=await Qe(e,[`shell`,`run-as`,t,`cat`,oi],{allowFailure:!0});return n.exitCode===0?Si(n.stdout):fi}async function yi(e,n,i){let a=[`shell`,`run-as`,n,`id`],o=await Qe(e,a,{allowFailure:!0});if(o.exitCode!==0){let e=Ai(o.stdout,o.stderr);throw new t(`COMMAND_FAILED`,e?`Failed to access Android app sandbox for ${n}`:`Failed to probe Android app sandbox for ${n}`,c(o,{package:n,cmd:`adb`,args:a,hint:e?di:`adb shell run-as probe failed. Check adb connectivity and that the device is reachable. Inspect stderr/details for more information.`}))}try{await Qe(e,[`shell`,`run-as`,n,`mkdir`,`-p`,`shared_prefs`]),await Qe(e,[`shell`,`run-as`,n,`tee`,oi],{stdin:i.trimEnd()})}catch(e){let i=r(e);if(i.code===`TOOL_MISSING`)throw i;let a=Ai(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 ${n}`:`Failed to write Android runtime hints for ${n}`,{...i.details??{},package:n,cmd:`adb`,phase:`write-runtime-hints`,hint:a?di:`adb run-as succeeded, but writing ReactNativeDevPrefs.xml failed. Inspect stderr/details for the failing shell command.`},i)}}async function bi(e,t,n){await bt(St(e,[`spawn`,e.id,`defaults`,`write`,t,li,`-string`,`${n.host}:${n.port}`])),await bt(St(e,[`spawn`,e.id,`defaults`,`write`,t,ui,`-string`,n.scheme]))}async function xi(e,t){await bt(St(e,[`spawn`,e.id,`defaults`,`delete`,t,li]),{allowFailure:!0}),await bt(St(e,[`spawn`,e.id,`defaults`,`delete`,t,ui]),{allowFailure:!0})}function Si(e){let t=e.trim();return!t.includes(`<map`)||!t.includes(`</map>`)?fi:`${t}\n`}function Ci(e,t,n){let r=` <string name="${ki(t)}">${ki(n)}</string>`;return Ti(Ei(e,t),r)}function wi(e,t,n){let r=` <boolean name="${ki(t)}" value="${n?`true`:`false`}" />`;return Ti(Ei(e,t),r)}function Ti(e,t){return Si(e).replace(`</map>`,`${t}\n</map>`)}function Ei(e,t){let n=Oi(t);return Si(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 Di(e){if(We(e)!==`binary`)return;let n=Ge(e);throw new t(`INVALID_ARGS`,n,{package:e,hint:n})}function Oi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function ki(e){return e.replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`).replaceAll(`"`,`"`).replaceAll(`'`,`'`)}function Ai(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 ji=[`platform`,`metroHost`,`metroPort`,`bundleUrl`,`launchUrl`];function Mi(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>e!==void 0&&e!==``).length:0}function Ni(e,n){if(e!==void 0){if(typeof e!=`string`)throw new t(`INVALID_ARGS`,`Invalid open runtime ${n}: expected string.`);return je(e)}}function Pi(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 Fi(e){if(e!==void 0){if(typeof e!=`number`)throw new t(`INVALID_ARGS`,`Invalid open runtime metroPort: expected integer.`);return Pi(e)}}function Ii(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 Li(e){if(e===`ios`||e===`android`)return e}function Ri(e,t){return{platform:t,metroHost:je(e?.metroHost),metroPort:Pi(e?.metroPort),bundleUrl:je(e?.bundleUrl),launchUrl:je(e?.launchUrl)}}function zi(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 Bi(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=>!ji.includes(e));if(o)throw new t(`INVALID_ARGS`,`Invalid open runtime field: ${o}. Supported fields are ${ji.join(`, `)}.`);return{platform:Ii(a.platform,r,i),metroHost:Ni(a.metroHost,`metroHost`),metroPort:Fi(a.metroPort),bundleUrl:Ni(a.bundleUrl,`bundleUrl`),launchUrl:Ni(a.launchUrl,`launchUrl`)}}function Vi(e,t,n){if(n){if(Mi(n)===0){e.clearRuntimeHints(t);return}return e.setRuntimeHints(t,n),n}}function Hi(e,n,r){let i=e.getRuntimeHints(n);if(!i)return;let a=r?T(r):void 0,o=Li(a);if(i.platform&&r&&!o)throw new t(`INVALID_ARGS`,`Session runtime hints are only supported on iOS and Android sessions, but session "${n}" is bound to ${a}.`);if(i.platform&&o&&i.platform!==o)throw new t(`INVALID_ARGS`,`Session runtime hints target ${i.platform}, but session "${n}" is bound to ${a}. Clear the runtime hints or use a different session.`);return o&&i.platform!==o?{...i,platform:o}:i}function Ui(e){let{req:t,sessionStore:n,sessionName:r,device:i}=e,a=n.getRuntimeHints(r),o=Bi({runtime:t.runtime,sessionName:r,platform:Li(T(i))});return t.runtime===void 0?{runtime:Hi(n,r,i),previousRuntime:a,replacedStoredRuntime:!1}:{runtime:o&&Mi(o)>0?o:void 0,previousRuntime:a,replacedStoredRuntime:!0}}function Wi(e){try{return{ok:!0,data:Ui(e)}}catch(e){let t=r(e);return M(t.code,t.message,t.details)}}async function Gi(e){let{replacedStoredRuntime:t,previousRuntime:n,runtime:r,session:i}=e;!t||!i?.appBundleId||!pi(n)||pi(r)||await hi({device:i.device,appId:i.appBundleId})}async function Ki(e){let{req:t,sessionName:n,sessionStore:r}=e,i=(t.positionals?.[0]??`show`).toLowerCase();if(Ji(i))return await $i(t,i);if(!qi(i))return M(`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 Yi(n,r,a,o):i===`show`?Xi(n,o):Qi({req:t,sessionName:n,sessionStore:r,session:a,current:o})}function qi(e){return e===`set`||e===`show`||e===`clear`}function Ji(e){return e===`port-reverse`||e===`port-reverse-remove`}async function Yi(e,t,n,r){return pi(r)&&n?.appBundleId&&await hi({device:n.device,appId:n.appBundleId}),{ok:!0,data:{session:e,cleared:t.clearRuntimeHints(e)}}}function Xi(e,t){return{ok:!0,data:{session:e,configured:!!t,runtime:t}}}function Zi(e){return e?T(e.device):void 0}function Qi(e){let{req:t,sessionName:n,sessionStore:r,session:i,current:a}=e,o=Zi(i),s=Li(t.flags?.platform??a?.platform??o);if(!s)return M(`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 M(`INVALID_ARGS`,`runtime set targets ${s}, but session "${n}" is already bound to ${o}.`);let c=zi(a,Ri(t.flags,s));return Mi(c)===0?M(`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 $i(e,t){let n=ea(e);if(!n.ok)return n.response;let r=await ra(t,n.options);return r?{ok:!0,data:{action:t,...r}}:M(`UNSUPPORTED_OPERATION`,`No active provider device runtime supports port reverse for this lease.`)}function ea(e){let t=ta(e);if(!t.ok)return t;let n=na(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 ta(e){let t=e.flags?.leaseId,n=e.flags?.leaseProvider;return t?n?{ok:!0,leaseId:t,provider:n}:{ok:!1,response:M(`INVALID_ARGS`,`runtime port-reverse requires a lease provider.`)}:{ok:!1,response:M(`INVALID_ARGS`,`runtime port-reverse requires a resolved remote lease.`)}}function na(e){let t=ia(e.flags?.devicePort),n=ia(e.flags?.hostPort??e.flags?.devicePort);return!t||!n?{ok:!1,response:M(`INVALID_ARGS`,`runtime port-reverse requires numeric devicePort and hostPort values from 1 to 65535.`)}:{ok:!0,devicePort:t,hostPort:n}}async function ra(e,t){return e===`port-reverse`?await Jn(t):await Gt(t)}function ia(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<1||e>65535))return e}const aa=`open-command-roundtrip`,oa=`Not implemented for this platform in this release.`;function sa(e){let{sessionName:t,sessionStateDir:n,runnerLogPath:r,requestLogPath:i,eventLogPath:a,appName:o,appBundleId:s,surface:c,startup:l,timing:u,device:d,runtime:f,runtimeHintCount:p}=e,m={session:t,surface:c,sessionStateDir:n,runnerLogPath:r,requestLogPath:i,eventLogPath:a};return o&&(m.appName=o),s&&(m.appBundleId=s),l&&(m.startup=l),u&&(m.timing=u),f&&p(f)>0&&(m.runtime=f),d&&(m.platform=T(d),m.target=d.target??`mobile`,m.device=d.name,m.id=d.id,m.kind=d.kind,d.platform===`android`&&(m.serial=d.id)),d&&D(d)&&(m.device_udid=d.id,m.ios_simulator_device_set=d.simulatorSetPath??null),{...m,...te(`Opened: ${o??s??t}`)}}function ca(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 la=new Set([`app`,`desktop`,`frontmost-app`]);function ua(e,n,r){if(e.platform===`linux`){if(!n)return`app`;let e=oe(n);if(!la.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(!w(e)){if(n)throw new t(`INVALID_ARGS`,`surface is only supported on macOS and Linux`);return`app`}let i=n?oe(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 da(e){let{device:t,surfaceFlag:n,openTarget:r,existingSurface:i}=e;return(w(t)||t.platform===`linux`)&&!n?i??`app`:ua(t,n,r)}async function fa(e){if(e===`app`||e===`desktop`||e===`menubar`)return{};let t=await xt();return{appBundleId:t.bundleId,appName:t.appName}}async function pa(e,t,n){if(!(!E(e.platform)||!t))return qe(t)?w(e)?void 0:e.kind===`device`?Ze(n,t):Je(t)?void 0:n??await ma(e,t):await ha(e,t)}async function ma(e,t){try{let{resolveIosSimulatorDeepLinkBundleId:n}=await import(`./apps.js`).then(e=>e.t);return await n(e,t)}catch{return}}async function ha(e,t){try{let{resolveIosApp:n}=await import(`./apps.js`).then(e=>e.t);return await n(e,t)}catch{return}}async function ga(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 _a(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 va(e,t){return e.platform===`android`&&!!(t&&qe(t))}async function ya(e,t,n,r){return await pa(e,t,n)??await r(e,t)??(va(e,t)?n:void 0)}function ba(e){return M(`INVALID_ARGS`,e)}function xa(e,n,r,i){try{return da({device:e,surfaceFlag:n,openTarget:r,existingSurface:i})}catch(e){return M(e instanceof t?e.code:`INVALID_ARGS`,String(e.message))}}function Sa(e){let{shouldRelaunch:t,openTarget:n,surface:r,device:i}=e;return t?n&&qe(n)?ba(`open --relaunch does not support URL targets.`):r===`app`?i.platform===`android`&&n&&We(n)===`binary`?ba(Ge(n)):null:ba(`open --relaunch is supported only for app surfaces.`):null}function Ca(e){let{shouldRelaunch:t,openTarget:n,platform:r}=e;return t?n&&qe(n)?ba(`open --relaunch does not support URL targets.`):r===`android`&&n&&We(n)===`binary`?ba(Ge(n)):null:null}async function wa(e){let{req:t,sessionName:n,sessionStore:r,device:i,surface:a,openTarget:o,existingSession:s,onIosSimulatorColdBootStart:c}=e;await Sr(i,{deviceHub:t.flags?.deviceHub===!0,onIosSimulatorColdBootStart:c});let{appBundleId:l,appName:u}=await Ta({device:i,surface:a,openTarget:o,existingAppBundleId:s?.appBundleId}),d=Wi({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 Gi({replacedStoredRuntime:n,previousRuntime:t,runtime:e,session:s})}return{type:`details`,details:{appBundleId:l,appName:u,runtime:d.data.runtime}}}async function Ta(e){let{device:t,surface:n,openTarget:r,existingAppBundleId:i}=e,a=await fa(n);return{appBundleId:a.appBundleId??await ya(t,r,i,ga),appName:a.appName??r}}const Ea=new Map;async function Da(e){let{device:t,closeTarget:n,outFlag:r,context:i}=e;E(t.platform)&&!H(t)&&await ot(t.id),await j(t,`close`,[n],r,i),await ni(t,300)}async function Oa(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 j(n,`open`,[c],r.flags?.out,{...ka(i,r.flags,a,o)})}function ka(e,t,n,r){let i=A(e,t,n,r);return delete i.launchConsole,delete i.launchArgs,i}function Aa(e,t,n){return{durationMs:Math.max(0,Date.now()-e),measuredAt:new Date().toISOString(),method:aa,appTarget:t,appBundleId:n}}async function ja(e){let{req:t,sessionName:n,sessionStore:r,logPath:i,device:o,openTarget:c,openPositionals:l,appName:u,surface:d,appBundleId:f,runtime:p,existingSession:m}=e,h=t.flags?.relaunch===!0,g=m?.trace?.outPath,_=f,v=Date.now(),y={},b=D(o)&&d===`app`&&l.length>0&&!!_,ee=wr({req:t,logPath:i,appBundleId:_,traceLogPath:g}),x=t.flags?.maestro?.prewarmRunnerBeforeOpen===!0,S,te=!1,ne=!1,re=(e=ee)=>{te=!0,y.runnerPrewarmKind=`session`,y.runnerPrewarmScheduled=!0,S=ft(o,e)},ie=async()=>{if(!S||ne)return;ne=!0;let e=Date.now();await S,y.runnerPrewarmWaited=!0,y.runnerPrewarmDurationMs=Math.max(0,Date.now()-e)};b&&H(o)&&!x&&re();let C=h&&!!c&&l.length===1&&H(o)&&t.flags?.clearAppState!==!0;if(h&&c&&!C){let e=_??c,n=Date.now();await Da({device:o,closeTarget:e,outFlag:t.flags?.out,context:{...A(i,t.flags,_??m?.appBundleId,g)}}),y.relaunchCloseDurationMs=Math.max(0,Date.now()-n)}let ae=Date.now();await mi({device:o,appId:_,runtime:p}),y.runtimeHintsDurationMs=Math.max(0,Date.now()-ae),b&&x&&(re({...ee,propagateError:!0}),await ie());let oe=Date.now(),se=await Ma({req:t,sessionName:n,sessionStore:r,device:o,surface:d,sessionAppBundleId:_,appName:u,existingSession:m});if(se.type===`response`)return se.response;let ce=se.session??m;await j(o,`open`,l,t.flags?.out,{...A(i,t.flags,_),...C?{terminateRunningApp:!0}:{}}),y.openDispatchDurationMs=Math.max(0,Date.now()-oe);let le=Date.now();await Oa({runtime:p,device:o,req:t,logPath:i,appBundleId:_,traceLogPath:g,openPositionals:l}),y.launchUrlDurationMs=Math.max(0,Date.now()-le),b&&!te&&re(),h?await ie():S&&!ne&&(y.runnerPrewarmWaited=!1),_=await _a(o,c,_),o.platform===`android`&&_&&await Mt(o,_);let ue=c?Aa(oe,c,_):void 0,de=Date.now();if(await ni(o,300),y.postOpenSettleDurationMs=Math.max(0,Date.now()-de),vt(t.meta?.requestId)){let e=yt();return M(e.code,e.message,e.details)}m&&Yt(m,`open`,m.snapshot);let fe=ca({existingSession:ce,sessionName:m?.name??vn(t),sessionScope:m?.sessionScope??kn(t),device:o,surface:d,appBundleId:_,appName:u,saveScript:!!t.flags?.saveScript});fe.lease=un({req:t,existingLease:m?.lease}),t.runtime!==void 0&&Vi(r,n,p);let pe=r.ensureSessionDir(n),me=jt(pe,t.meta?.requestId??a().requestId);y.totalDurationMs=Math.max(0,Date.now()-v),s({level:`info`,phase:`open_timing`,durationMs:y.totalDurationMs,data:y});let he=sa({sessionName:fe.name,sessionStateDir:pe,runnerLogPath:Bt(pe),requestLogPath:me,eventLogPath:r.resolveEventLogPath(n),appName:u,appBundleId:_,surface:d,startup:ue,timing:y,device:o,runtime:p,runtimeHintCount:Mi});return r.set(n,fe),r.recordAction(fe,{command:`open`,positionals:l,flags:t.flags??{},runtime:t.runtime===void 0?void 0:p,result:he}),{ok:!0,data:he}}async function Ma(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=ca({existingSession:c,sessionName:c?.name??vn(t),sessionScope:c?.sessionScope??kn(t),device:i,surface:a,appBundleId:o,appName:s,saveScript:!!t.flags?.saveScript});u.lease=un({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 Na(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=xa(a.device,t.flags?.surface,s,a.surface);if(typeof c!=`string`)return c;if(!s&&c===`app`)return ba(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=Sa({shouldRelaunch:e,openTarget:s,surface:c,device:a.device});if(l)return l;let u=await ri(a.device),d=await wa({req:t,sessionName:n,sessionStore:i,device:u,surface:c,openTarget:s,existingSession:a,onIosSimulatorColdBootStart:Tr({req:t,logPath:r,device:u,surface:c,openTarget:s,traceLogPath:a.trace?.outPath})});return d.type===`response`?d.response:await ja({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 ba(`open --relaunch requires an app argument.`);let c=Ca({shouldRelaunch:o,openTarget:s,platform:t.flags?.platform===`android`?`android`:void 0});if(c)return c;let l=await On(t.flags??{}),u=xa(l,t.flags?.surface,s);return typeof u==`string`?Sa({shouldRelaunch:o,openTarget:s,surface:u,device:l})||await dt(Ea,l.id,async()=>{let e=i.toArray().find(e=>e.device.id===l.id);if(e)return Ln(t,e)?M(`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.`}):M(`DEVICE_IN_USE`,`Device is already in use by session "${e.name}".`,{session:e.name,deviceId:l.id,deviceName:l.name,hint:Yn(e,`device-in-use`)});let a=await wa({req:t,sessionName:n,sessionStore:i,device:l,surface:u,openTarget:s,onIosSimulatorColdBootStart:Tr({req:t,logPath:r,device:l,surface:u,openTarget:s})});return a.type===`response`?a.response:await ja({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 Pa(e){return H(e)||ei(e)}async function Fa(t){if(t.booted===!1)return{success:!0,exitCode:0,stdout:``,stderr:``};try{return H(t)?await Ia(t):await Ra(t)}catch(t){let n=e(t);return{success:!1,exitCode:-1,stdout:``,stderr:n.message,error:n}}}async function Ia(e){let t=await kr(e);return t.success?t:await La(e)===`Shutdown`?{...t,success:!0,exitCode:0}:t}async function La(e){try{return await Ar(e)}catch{return null}}async function Ra(e){let t=await Qe(e,[`emu`,`kill`],{allowFailure:!0,timeoutMs:15e3});return{success:t.exitCode===0,exitCode:t.exitCode,stdout:t.stdout,stderr:t.stderr}}async function za(e){let{device:t,shutdownRequested:n}=e;if(n&&Pa(t))return await Fa(t)}function Ba(e,t){return H(t.device)&&!e.flags?.shutdown&&!t.recording&&!t.lease&&!t.device.simulatorSetPath}function Va(e){return E(e.device.platform)&&!H(e.device)}async function Ha(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,leaseRegistry:a,leaseLifecycleProvider:o}=e,c=i.get(n);if(!c)return await Ga(t,r);let l;try{await en(c),await an(c,`session-close`),await Nn(c),await Rn(c),await yn(c),Ua(t,c)&&(Va(c)&&await An(c),await j(c.device,`close`,t.positionals??[],t.flags?.out,{...A(r,t.flags,c.appBundleId,c.trace?.outPath)}),await ni(c.device,300)),E(c.device.platform)&&!Ba(t,c)?await An(c):E(c.device.platform)&&(s({level:`debug`,phase:`ios_runner_retained_after_close`,data:{session:c.name,deviceId:c.device.id}}),pt(c.device.id)),pi(i.getRuntimeHints(n))&&c.appBundleId&&await hi({device:c.device,appId:c.appBundleId}).catch(()=>{}),Dr(i,c,t,`close`,{session:c.name,...te(`Closed: ${c.name}`)}),t.flags?.saveScript&&(c.recordSession=!0),i.writeSessionLog(c),await Wn(n).catch(()=>{})}finally{try{l=await Kn({session:c,leaseRegistry:a,leaseLifecycleProvider:o})}finally{i.delete(n)}}let u=await za({device:c.device,shutdownRequested:t.flags?.shutdown});return u?{ok:!0,data:h({session:c.name,shutdown:u,...l?{provider:l}:{}},`Closed: ${c.name}`)}:{ok:!0,data:{session:c.name,...te(`Closed: ${c.name}`),...l?{provider:l}:{}}}}function Ua(e,t){return Wa(e)||t.device.platform===`web`}function Wa(e){return(e.positionals?.length??0)>0}async function Ga(e,t){if(!e.positionals||e.positionals.length===0)return M(`SESSION_NOT_FOUND`,`No active session`);let n=await W({session:void 0,flags:e.flags,ensureReady:!0});return await j(n,`close`,e.positionals,e.flags?.out,{...A(t,e.flags)}),await ni(n,300),{ok:!0,data:{app:e.positionals[0],...te(`Closed: ${e.positionals[0]}`)}}}const Ka={ios:async(e,t,n)=>{let r=await er(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 er(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)}},qa={ios:async(e,t,n)=>{let r=await er(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 er(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 Ja(e){let{req:t,command:n,sessionName:r,sessionStore:i,deployOps:a}=e,o=i.get(r),s=t.flags??{},c=U(n,o,s);if(c)return c;let l=Qa(n,t.positionals??[]);if(!l.ok)return l.response;let{app:u,appPathInput:d}=l,f=t.meta?.uploadedArtifactId;try{let e=f?Jt(f,t.meta?.tenantId):k.expandHome(d);if(!B.existsSync(e))return M(`INVALID_ARGS`,`App binary not found: ${e}`);let r=await W({session:o,flags:s,ensureReady:!1}),c=N(n,r);if(c)return c;let l=D(r)?Xa(u,e,await a.ios(r,u,e)):Za(u,e,await a.android(r,u,e)),p=h(l,Ya(l));return Dr(i,o,t,n,p),{ok:!0,data:p}}finally{f&&kt(f)}}function Ya(e){return`Installed: ${e.appName??le(e)}`}function Xa(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 Za(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 Qa(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:M(`INVALID_ARGS`,`install requires: install <path-to-app-binary>`)}}return!n||!r?{ok:!1,response:M(`INVALID_ARGS`,`reinstall requires: reinstall <app> <path-to-app-binary>`)}:{ok:!0,app:n,appPathInput:r}}async function $a(e,t,n){return await Oe(e,t,n)}async function eo(e){let{req:t,sessionName:n,sessionStore:i}=e;if(t.command===`session_list`){let e=kn(t);return{ok:!0,data:{sessions:i.toArray().filter(t=>hn(t,e)).map(e=>{let t=i.resolveSessionDir(e.name);return{name:e.name,sessionStateDir:t,runnerLogPath:Bt(t),platform:T(e.device),...E(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,...E(e.device.platform)&&!w(e.device)&&{device_udid:e.device.id,ios_simulator_device_set:e.device.simulatorSetPath??null}}})}}}if(t.command===`devices`)try{let e=Xe(t.flags?.androidDeviceAllowlist),n=t.flags?.platform,r=Pe({simulatorSetPath:et(t.flags?.iosSimulatorDeviceSet),platform:n,target:t.flags?.target}),i=await In({platform:n,target:t.flags?.target,deviceName:t.flags?.device,udid:t.flags?.udid,serial:t.flags?.serial,iosSimulatorSetPath:r,androidSerialAllowlist:e?Array.from(e).sort():void 0}),a=n?i.filter(e=>no(e,n)):i;return{ok:!0,data:{devices:(t.flags?.target?a.filter(e=>(e.target??`mobile`)===t.flags?.target):a).map(to)}}}catch(e){let t=r(e);return M(t.code,t.message,t.details)}if(t.command===`capabilities`){let e=i.get(n),r=t.flags??{},a=U(t.command,e,r);if(a)return a;let o=await W({session:e,flags:r,ensureReady:!1,allowStoppedAndroidAvdPlaceholders:!0});return{ok:!0,data:{device:to(o),availableCommands:on().filter(e=>Vn(e,o))}}}if(t.command===`apps`){let e=i.get(n),r=t.flags??{},a=U(t.command,e,r);if(a)return a;let o=await W({session:e,flags:r,ensureReady:!0}),s=N(`apps`,o);if(s)return s;let c=Ve(t.flags?.appsFilter);return E(o.platform)?{ok:!0,data:{apps:(await Or(o,c)).map(e=>e.name&&e.name!==e.bundleId?`${e.name} (${e.bundleId})`:e.bundleId)}}:{ok:!0,data:{apps:(await Ke(o,c)).map(e=>e.name&&e.name!==e.package?`${e.name} (${e.package})`:e.package)}}}return null}function to({simulatorSetPath:e,appleOs:t,...n}){return{...n,platform:T({platform:n.platform,appleOs:t}),...E(n.platform)&&t?{appleOs:t}:{}}}function no(e,t){return Ie(e,t)}async function ro(e){let{ensureAndroidEmulatorBooted:t}=await import(`./android-input-ownership.js`).then(e=>e.m);return await t(e)}const io=`iOS appstate requires an active session on the target device. Run open first (for example: open --session sim --platform ios --device "<name>" <app>).`,ao=`macOS appstate requires an active session on the target device. Run open first (for example: open --session macos --platform macos "System Settings").`;async function oo(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.get(n),a=t.flags??{},o=a.platform;if(!i&&ti(a))return M(`SESSION_NOT_FOUND`,o===`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 s=U(`appstate`,i,a);if(s)return s;let c=E(i?.device.platform)&&ai(a,i),l=o===`ios`,u=o===`macos`;if(l&&!c)return M(`SESSION_NOT_FOUND`,io);if(u&&!c)return M(`SESSION_NOT_FOUND`,ao);if(c&&i){let e=i.appName??i.appBundleId;return!i.appName&&!i.appBundleId?w(i.device)&&i.surface&&i.surface!==`app`&&i.surface!==`frontmost-app`?{ok:!0,data:{platform:T(i.device),appName:i.surface,appBundleId:i.appBundleId,source:`session`,surface:i.surface}}:M(`COMMAND_FAILED`,`No foreground app is tracked for this ${w(i.device)?`macOS`:`iOS`} session. Open an app in the session, then retry appstate.`):{ok:!0,data:{platform:T(i.device),appName:e??`unknown`,appBundleId:i.appBundleId,source:`session`,surface:i.surface??`app`,...D(i.device)?{device_udid:i.device.id,ios_simulator_device_set:i.device.simulatorSetPath??null}:{}}}}let d=await W({session:i,flags:a,ensureReady:!0});if(D(d))return M(`SESSION_NOT_FOUND`,io);if(w(d))return M(`SESSION_NOT_FOUND`,ao);if(d.platform===`web`)return M(`UNSUPPORTED_OPERATION`,`appstate is not supported on web.`);let{getAndroidAppState:f}=await import(`./app-lifecycle.js`).then(e=>e.t),p=await f(d);return{ok:!0,data:{platform:`android`,package:p.package,activity:p.activity}}}async function so(e){let{req:t,sessionName:n,logPath:i,sessionStore:a}=e;if(t.command===`boot`){let e=a.get(n),o=t.flags??{},s=U(t.command,e,o);if(s)return s;let c=(o.platform??e?.device.platform)===`android`,l=o.headless===!0;if(l&&!c)return M(`INVALID_ARGS`,`boot --headless is supported only for Android emulators.`);let u=ii({flags:o,sessionDevice:e?.device}),d=c&&!!u,f,p=!1;try{f=await W({session:e,flags:o,ensureReady:!1,allowStoppedAndroidAvdPlaceholders:!0})}catch(e){let t=r(e);if(c&&l&&!u&&t.code===`DEVICE_NOT_FOUND`)return M(`INVALID_ARGS`,`boot --headless requires --device <avd-name> (or an Android emulator session target).`);if(!d||t.code!==`DEVICE_NOT_FOUND`||!u)throw e;f=await ro({avdName:u,serial:o.serial,headless:l}),p=!0}if(o.target&&(f.target??`mobile`)!==o.target)return M(`DEVICE_NOT_FOUND`,`No ${f.platform} device found matching --target ${o.target}.`);if(c&&l){if(f.platform!==`android`||f.kind!==`emulator`)return M(`INVALID_ARGS`,`boot --headless is supported only for Android emulators.`);if(!p){let t=ii({flags:o,sessionDevice:e?.device,resolvedDevice:f});if(!t)return M(`INVALID_ARGS`,`boot --headless requires --device <avd-name> (or an Android emulator session target).`);f=await ro({avdName:t,serial:o.serial,headless:!0})}await Sr(f)}else f.platform===`android`&&f.kind===`emulator`&&f.booted!==!0?(f=await ro({avdName:f.name,serial:o.serial,headless:!1}),await Sr(f)):(f.platform!==`android`||f.booted!==!0)&&await Sr(f,{onIosSimulatorColdBootStart:Cr({req:t,logPath:i,device:f,enabled:!0})});return N(`boot`,f)||(D(f)&&f.kind===`simulator`&<(f,{}),{ok:!0,data:{platform:T(f),target:f.target??`mobile`,device:f.name,id:f.id,kind:f.kind,booted:!0,...E(f.platform)&&f.appleOs?{appleOs:f.appleOs}:{}}})}if(t.command===`shutdown`){let e=a.get(n),r=t.flags??{},i=U(t.command,e,r);if(i)return i;let o=await W({ensureReady:!1,flags:r,session:e}),s=N(`shutdown`,o,{message:`shutdown is supported only for Apple simulators and Android emulators.`});if(s)return s;if(e&&e.device.platform===o.platform&&e.device.id===o.id)return M(`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 ${n}`,session:n,platform:T(o),target:o.target??`mobile`,device:o.name,id:o.id,kind:o.kind});let c=await Fa(o);return c.success?{ok:!0,data:{platform:T(o),target:o.target??`mobile`,device:o.name,id:o.id,kind:o.kind,shutdown:c,...E(o.platform)&&o.appleOs?{appleOs:o.appleOs}:{}}}:M(c.error?.code??`COMMAND_FAILED`,co(c),{platform:T(o),target:o.target??`mobile`,device:o.name,id:o.id,kind:o.kind,shutdown:c})}return t.command===`appstate`?await oo({req:t,sessionName:n,sessionStore:a}):null}function co(e){let t=e.error?.message??e.stderr.trim();return t.length>0?t:`Shutdown failed`}Tn();function lo(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:aa,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 uo(e,t={}){let n=ho(e);if(!Co(e))return n;if(!e.appBundleId)return bo(n,e),n;let r=fo(e.device);return r&&xo(n,e,await r(e,e.appBundleId,t)),n}function fo(e){let t=ln(e.platform)?.perf?.metricsSamplerTag(e);return t?jo[t]:void 0}async function po(e,t={}){let n=vo(e);return Co(e)?e.appBundleId?(await So(n,e,e.appBundleId,t),n):(n.metrics.fps={available:!1,reason:wo(e)},n):n}async function mo(e,t){let n=yo(e);return Co(e)?t.action===`sample`?(n.metrics={memory:await Mo(e,t)},n):(n.artifact=await Po(e,t),n.support=Bo(n.artifact.support)??zo(e),n):t.action===`snapshot`?(n.artifact=Lo(e,Fo(e,t.kind)),n.support=Bo(n.artifact.support)??zo(e),n):(n.metrics={memory:{available:!1,reason:oa}},n)}function ho(e){let t=lo(e.actions),n=t.at(-1),r=n?{available:!0,lastDurationMs:n.durationMs,lastMeasuredAt:n.measuredAt,method:aa,sampleCount:t.length,samples:t}:{available:!1,reason:`No startup sample captured yet. Run open <app|url> in this session first.`,method:aa};return{session:e.name,platform:T(e.device),device:e.device.name,deviceId:e.device.id,metrics:{startup:r,...go()},sampling:{startup:{method:aa,description:`Elapsed wall-clock time around dispatching the open command for the active session app target.`,unit:`ms`},...To(e)}}}function go(){return{fps:_o(),memory:{available:!1,reason:oa},cpu:{available:!1,reason:oa}}}function _o(){return{available:!1,reason:`Dropped-frame sampling is currently available only on Android app sessions and connected iOS device app sessions.`}}function vo(e){return{session:e.name,platform:T(e.device),device:e.device.name,deviceId:e.device.id,metrics:{fps:_o()},sampling:{fps:Oo(e)}}}function yo(e){return{session:e.name,platform:T(e.device),device:e.device.name,deviceId:e.device.id,sampling:{memory:Eo(e),snapshot:Do(e)}}}function bo(e,t){let n=wo(t);e.metrics.fps={available:!1,reason:n},e.metrics.memory={available:!1,reason:n},e.metrics.cpu={available:!1,reason:n}}function xo(e,t,n){e.metrics.memory=Ho(n.memory),e.metrics.cpu=Ho(n.cpu),e.metrics.fps=Uo(Ho(n.fps),t)}async function So(e,t,n,r){let i=t.device.platform===`android`?await Vo(At(t.device,n,{adb:r.androidAdb})):await Vo(tr(t.device,n));e.metrics.fps=Uo(Ho(i),t)}function Co(e){return ln(e.device.platform)?.perf?.supportsMetrics(e.device)??!1}function wo(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 To(e){return e.device.platform===`android`?{memory:{method:Zt,description:pn,unit:`kB`},cpu:{method:Fn,description:dn,unit:`percent`},fps:{method:Sn,description:zt,unit:`percent`,primaryField:`droppedFramePercent`,window:`since previous Android gfxinfo reset or app process start`,resetsAfterRead:!0,relatedActionsLimit:12}}:Ft(e.device)}function Eo(e){return e.device.platform===`android`?{method:Zt,description:pn,unit:`kB`,topConsumerLimit:5}:Ft(e.device).memory}function Do(e){return e.device.platform===`android`?{method:gn,description:Dn,defaultKind:`android-hprof`,artifactOnly:!0}:{method:Vt,description:Rt,defaultKind:`memgraph`,artifactOnly:!0}}function Oo(e){return e.device.platform===`android`?{method:Sn,description:zt,unit:`percent`,primaryField:`droppedFramePercent`,window:`since previous Android gfxinfo reset or app process start`,resetsAfterRead:!0,relatedActionsLimit:12}:Nt(e.device)}async function ko(e,t,n){let r={adb:n.androidAdb},[i,a,o]=await Promise.allSettled([nn(e.device,t,r),$n(e.device,t,r),At(e.device,t,r)]);return{memory:i,cpu:a,fps:o}}async function Ao(e,t){let n=await Vo(tr(e.device,t)),r=await Vo(Dt(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}}const jo={android:ko,apple:Ao};async function Mo(e,t){return e.appBundleId?Ho(e.device.platform===`android`?await Vo(nn(e.device,e.appBundleId,{adb:t.androidAdb})):await Vo(No(e))):{available:!1,reason:wo(e)}}async function No(e){if(!e.appBundleId)throw new t(`INVALID_ARGS`,wo(e));return(await Dt(e.device,e.appBundleId)).memory}async function Po(e,n){if(!e.appBundleId)throw new t(`INVALID_ARGS`,wo(e),{hint:`Run open <app> first so perf memory snapshot can resolve the app process.`});let r=Fo(e,n.kind),i=Io(n,r);return e.device.platform===`android`?r===`android-hprof`?await qn(e.device,e.appBundleId,i,{adb:n.androidAdb}):Lo(e,r):r===`memgraph`?await Ht(e.device,e.appBundleId,i):Lo(e,r)}function Fo(e,t){return t||(e.device.platform===`android`?`android-hprof`:`memgraph`)}function Io(e,t){if(e.out)return k.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 V.join(i,`artifacts`,`memory-${t}-${r}.${n}`)}function Lo(e,t){let n=zo(e),r=Ro(e,t);return{available:!1,kind:t,reason:r.reason,hint:r.hint,support:n}}function Ro(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.`}:E(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 zo(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.`}:E(e.device.platform)?{...Pt(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 Bo(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:void 0}async function Vo(e){try{return{status:`fulfilled`,value:await e}}catch(e){return{status:`rejected`,reason:e}}}function Ho(t){if(t.status===`fulfilled`)return{available:!0,...t.value};let n=e(t.reason);return{available:!1,reason:n.message,error:n}}function Uo(e,t){if(e.available!==!0)return e;let n=Wo(t.actions,e);return n.length===0?e:{...e,relatedActions:n}}function Wo(e,t){let n=Go(t.windowStartedAt),r=Go(t.windowEndedAt)??Go(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:Ko(e)})).slice(-12)}function Go(e){if(typeof e!=`string`)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function Ko(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 qo(t){let n=Jo(t.req,t.area);if(!n.ok)return n;let{session:r}=t;if(r.device.platform!==`android`)return M(`UNSUPPORTED_OPERATION`,`Android native perf collectors are supported only on Android sessions.`);if(!r.appBundleId)return M(`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 rs(t,r,r.appBundleId,n):await is(t,r,r.appBundleId,n)}}catch(t){return{ok:!1,error:e(t)}}}function Jo(e,t){let n=ns(e,t);return t===`cpu`?Yo(e,n):Xo(e,n)}function Yo(e,t){let n=Zo(e,1),r=Zo(e,2),i=Zo(e,3);return fe(n)?Qo(r)?i===`simpleperf`?{ok:!0,area:`cpu`,subject:n,action:r,kind:i,outPath:t}:M(`INVALID_ARGS`,`perf cpu profile requires --kind simpleperf`):M(`INVALID_ARGS`,`perf cpu profile action must be start, stop, or report`):M(`INVALID_ARGS`,re)}function Xo(e,t){let n=Zo(e,1),r=Zo(e,2);return $o(n)?g(r)?r===`perfetto`?{ok:!0,area:`trace`,action:n,kind:r,outPath:t}:M(`INVALID_ARGS`,`perf trace requires --kind perfetto`):M(`INVALID_ARGS`,S):M(`INVALID_ARGS`,`perf trace action must be start or stop`)}function Zo(e,t){return(e.positionals?.[t]??``).toLowerCase()}function Qo(e){return e===`start`||e===`stop`||e===`report`}function $o(e){return e===`start`||e===`stop`}function es(e,t){return e.sessionStore.set(e.sessionName,{...e.session,nativePerf:{android:t}}),ls(t)}function ts(e,t,n){return t?k.expandHome(t,e.req.meta?.cwd):cs(e.sessionStore,e.sessionName,n)}function ns(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 rs(e,t,n,r){if(r.action===`start`){os(t);let i=ts(e,r.outPath,`cpu.perf.data`);return es(e,await Zn(t.device,n,i,{adb:e.androidAdbExecutor}))}let i=us(t,`cpu-profile`,r.kind);if(r.action===`report`){await as(i);let n=ts(e,r.outPath,`cpu-report.json`);return await Ot(t.device,i,n,{adb:e.androidAdbExecutor})}let a=ss(e,r.outPath,i);return es(e,await Wt(t.device,i,a,{adb:e.androidAdbExecutor}))}async function is(e,t,n,r){if(r.action===`start`){os(t);let i=ts(e,r.outPath,`app.perfetto-trace`);return es(e,await Xn(t.device,n,i,{adb:e.androidAdbExecutor}))}let i=us(t,`trace`,r.kind),a=ss(e,r.outPath,i);return es(e,await qt(t.device,i,a,{adb:e.androidAdbExecutor}))}function as(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 os(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 ss(e,t,n){return t?ts(e,t,n.outPath):n.outPath}function cs(e,t,n){let r=new Date().toISOString().replace(/[:.]/g,`-`);return V.join(e.ensureSessionDir(t),`${r}-${n}`)}function ls(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 us(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 ds(e){if(!Gn(e))return;let{macOsScreenCaptureKitAudioProbeBackend:t}=await import(`./audio-probe.js`);return t}const fs=[`probe`],ps=[`start`,`status`,`stop`],ms=`audio probe requires ${ps.join(`, `)}`;async function hs(t){let n=gs(t);if(!n.ok)return n;let r=await ds(n.session.device);if(r)return await vs(t,n,r);let i=xr();if(!i.probeAudio)return M(`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 gs(e){let t=_s(e);if(!t.ok)return t;let n=ys(e.req);if(!n.ok)return n;let r=bs(e.req,n.probeAction);return r.ok?{ok:!0,session:t.session,probeAction:n.probeAction,...r.timing}:r}function _s(e){let t=e.sessionStore.get(e.sessionName);return t?Vn(`audio`,t.device)?{ok:!0,session:t}:M(`UNSUPPORTED_OPERATION`,`audio is supported for web browser sessions, macOS sessions, iOS simulators, and Android emulators on macOS hosts`):M(`SESSION_NOT_FOUND`,`audio requires an active session`)}async function vs(t,n,r){try{return{ok:!0,data:await Bn({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 ys(e){if(!xs(e.positionals?.[0]))return M(`INVALID_ARGS`,`audio requires probe`);let t=Ss(e.positionals?.[1]);return t?{ok:!0,probeAction:t}:M(`INVALID_ARGS`,ms)}function bs(e,t){if(t!==`start`&&e.positionals&&e.positionals.length>2)return M(`INVALID_ARGS`,`audio probe duration and bucket are only supported with audio probe start`);let n=Cs(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 M(`INVALID_ARGS`,n.message);let r=Cs(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?M(`INVALID_ARGS`,r.message):{ok:!0,timing:{durationMs:n,bucketMs:r}}}function xs(e){let t=(e??`probe`).toLowerCase();return fs.includes(t)?`probe`:void 0}function Ss(e){let t=(e??`status`).toLowerCase();return ps.includes(t)?t:void 0}function Cs(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 ws(t,n){let r=Ts(t.req);if(!r.ok)return r;if(n.device.platform===`android`)return M(`UNSUPPORTED_OPERATION`,`Android native profiling belongs to the Android perf rollout; Apple xctrace perf supports iOS and macOS sessions only.`);if(!E(n.device.platform))return M(`UNSUPPORTED_OPERATION`,`Apple xctrace perf is not supported on ${n.device.platform}.`);if(!n.appBundleId)return M(`INVALID_ARGS`,`Apple xctrace perf requires an active app session. Run open <app> first.`);try{return r.action===`start`?await As(t,n,r):r.action===`stop`?await js(t,n,r):await Is(t,n,r)}catch(t){return{ok:!1,error:e(t)}}}function Ts(e){let t=e.positionals??[],n=t[0]?.toLowerCase();return n===`cpu`?Es(t):n===`trace`?Ds(t):M(`INVALID_ARGS`,v)}function Es(e){if(e[1]?.toLowerCase()!==`profile`)return M(`INVALID_ARGS`,`perf cpu requires profile`);let t=Os(e[2],`perf cpu profile`,!0);if(!t.ok)return t;let n=ks(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 Ds(e){let t=Os(e[1],`perf trace`,!1);if(!t.ok)return t;let n=ks(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 Os(e,t,n){let r=e?.toLowerCase();return r===`start`||r===`stop`||n&&r===`report`?{ok:!0,value:r}:M(`INVALID_ARGS`,n?`${t} requires start, stop, or report`:`${t} requires start or stop`)}function ks(e){return e?.toLowerCase()===`xctrace`?{ok:!0}:M(`INVALID_ARGS`,`perf native collection currently supports --kind xctrace`)}async function As(e,t,n){if(t.applePerf?.active)return M(`INVALID_ARGS`,`Apple xctrace perf capture already in progress`);let r=n.template??Bs(n.mode),i=zs(e,n),a=await Tt({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=Vs(`started`,a);return Rs(e,t,o),{ok:!0,data:o}}async function js(e,t,n){let r=t.applePerf?.active;if(!r)return M(`INVALID_ARGS`,`no active Apple xctrace perf capture`);let i=n.outPath?k.expandHome(n.outPath,e.req.meta?.cwd):r.outPath,a;try{a=await xn(r,i)}catch(n){throw Ns(n)&&Ms(e,t),n}Ps(e,t,a);let o=Vs(`stopped`,a);return Rs(e,t,o),{ok:!0,data:o}}function Ms(e,t){t.applePerf={...t.applePerf??{},active:void 0},e.sessionStore.set(e.sessionName,t)}function Ns(e){return r(e).details?.captureCleanedUp===!0}function Ps(e,t,n){t.applePerf={...t.applePerf??{},active:void 0,lastMode:n.mode,...Fs(n)},e.sessionStore.set(e.sessionName,t)}function Fs(e){return e.mode===`cpu-profile`?{lastProfileTracePath:e.outPath,lastProfileTemplate:e.template}:{lastTracePath:e.outPath}}async function Is(e,t,n){if(n.mode!==`cpu-profile`)return M(`INVALID_ARGS`,`perf trace does not support report`);if(t.applePerf?.active)return M(`INVALID_ARGS`,`perf cpu profile report requires a stopped profile trace; stop the active capture first.`);let r=zs(e,n),i=Ls(t,n);if(!i.ok)return i;let a={perf:`reported`,...await Lt({tracePath:k.expandHome(i.value,e.req.meta?.cwd),outPath:r,mode:n.mode,template:t.applePerf?.lastProfileTemplate??n.template,appBundleId:t.appBundleId})};return Rs(e,t,a),{ok:!0,data:a}}function Ls(e,t){let n=t.tracePath??e.applePerf?.lastProfileTracePath??e.applePerf?.active?.outPath;return n?{ok:!0,value:n}:M(`INVALID_ARGS`,`perf cpu profile report requires a stopped profile trace or tracePath option`)}function Rs(e,t,n){Dr(e.sessionStore,t,e.req,`perf`,n)}function zs(e,t){if(t.outPath)return k.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 Bs(e){return e===`cpu-profile`?`Time Profiler`:`Animation Hitches`}function Vs(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 Hs=`logs requires ${se.slice(0,-1).join(`, `)}, or ${se.at(-1)}`,Us=[`dump`,`log`],Ws=`network requires ${Us.join(` or `)}`,Gs=`network include mode must be one of: ${n.join(`, `)}`,Ks={path:({session:e,sessionName:t,sessionStore:n})=>vc(e,t,n),doctor:({session:e,sessionName:t,sessionStore:n})=>yc(e,t,n),mark:({req:e,sessionName:t,sessionStore:n})=>bc(e,t,n),clear:({session:e,sessionName:t,sessionStore:n,restart:r})=>xc(e,t,n,r),start:({session:e,sessionName:t,sessionStore:n})=>Sc(e,t,n),stop:({session:e,sessionName:t,sessionStore:n})=>Cc(e,t,n)};function qs(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:Xs(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:[Ys(e.appLogFailure)]}:{active:!1,state:`inactive`,backend:Pn(e.device)}}function Js(e,t){return{backend:t,code:e.code,message:e.message,hint:e.hint}}function Ys(e){return e.hint?`${e.message} ${e.hint}`:e.message}function Xs(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 Zs(e,t){return Et([...e,...t.notes??[]])}function Qs(e,t,n){return{...n,platform:e.device.platform,outPath:t}}function $s(t,n,r,i){let a=e(i);return t.set(n,{...r,appLog:void 0,appLogFailure:Js(a,Pn(r.device))}),{ok:!1,error:a}}async function ec(e){let{req:t}=e;return t.command===`perf`?nc(e):t.command===`logs`?gc(e):t.command===`events`?await tc(e):t.command===`network`?wc(e):t.command===`audio`?await hs(e):null}async function tc(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 nc(t){let{req:n,sessionName:r,sessionStore:i,androidAdbExecutor:a}=t,o=i.get(r);if(!o)return M(`SESSION_NOT_FOUND`,`perf requires an active session. Run open first.`);let s=(n.positionals?.[0]??`metrics`).toLowerCase();if(rc(s))return o.device.platform===`android`?await qo({req:n,sessionName:r,sessionStore:i,session:o,androidAdbExecutor:a,area:s}):await ws(t,o);let c=ic(n);if(!c.ok)return c;if(c.native)return await ws(t,o);try{return{ok:!0,data:await ac(t,o,c)}}catch(t){return{ok:!1,error:e(t)}}}function rc(e){return e===`cpu`||e===`trace`}function ic(n){let r=oc(n.positionals?.[0]);if(!r)return M(`INVALID_ARGS`,v);if(r===`cpu`||r===`trace`)return{ok:!0,native:!0};let i=sc(n.positionals?.[1]);if(!i)return M(`INVALID_ARGS`,x);let a=cc(n.flags?.kind);return a instanceof t?{ok:!1,error:e(a)}:(lc(r,i)??fc(n,r,i,a))||{ok:!0,native:!1,area:r,action:i,kind:a,out:hc(n.flags?.out)}}async function ac(e,t,n){let{sessionName:r,sessionStore:i,androidAdbExecutor:a}=e;return n.area===`memory`?await mo(t,{action:dc(n.action),kind:n.kind,out:n.out,cwd:e.req.meta?.cwd,sessionName:r,sessionStore:i,androidAdb:a}):n.area===`frames`?await po(t,{androidAdb:a}):await uo(t,{androidAdb:a})}function oc(e){let t=(e??`metrics`).toString().toLowerCase();return ie(t)?t:void 0}function sc(e){let t=(e??`sample`).toString().toLowerCase();return ne(t)?t:void 0}function cc(e){if(e!==void 0)return typeof e!=`string`||!g(e)?new t(`INVALID_ARGS`,S):e}function lc(e,t){if(e===`memory`)return uc(t)?void 0:M(`INVALID_ARGS`,`perf memory requires sample or snapshot`);if(t!==`sample`)return M(`INVALID_ARGS`,`perf metrics and perf frames only support sample`)}function uc(e){return e===`sample`||e===`snapshot`}function dc(e){if(uc(e))return e;throw new t(`INVALID_ARGS`,`perf memory requires sample or snapshot`)}function fc(e,t,n,r){return pc(e.flags?.out,t,n)??mc(r,t,n)}function pc(e,t,n){if(!(!e||t===`memory`&&n===`snapshot`))return M(`INVALID_ARGS`,`--out is only supported with perf memory snapshot`)}function mc(e,t,n){if(e){if(t!==`memory`||n!==`snapshot`)return M(`INVALID_ARGS`,`--kind is only supported with perf memory snapshot`);if(!b(e))return M(`INVALID_ARGS`,m)}}function hc(e){return typeof e==`string`&&e.length>0?e:void 0}async function gc(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.get(n);if(!i)return M(`SESSION_NOT_FOUND`,`logs requires an active session`);let a=N(`logs`,i.device);if(a)return a;let o=_c(t);return o.ok?await Ks[o.action]({...e,session:i,restart:o.restart}):o}function _c(e){let t=(e.positionals?.[0]??`path`).toLowerCase(),n=!!e.flags?.restart;return se.includes(t)?n&&t!==`clear`?M(`INVALID_ARGS`,`logs --restart is only supported with logs clear`):{ok:!0,action:t,restart:n}:M(`INVALID_ARGS`,Hs)}function vc(e,t,n){let r=n.resolveAppLogPath(t),i=bn(r),a=qs(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 yc(e,t,n){let r=n.resolveAppLogPath(t),i=await En(e.device,e.appBundleId),a=qs(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:Zs(i.notes,a)}}}function bc(e,t,n){let r=e.positionals?.slice(1).join(` `)??``,i=n.resolveAppLogPath(t);return Mn(i,r),{ok:!0,data:{path:i,marked:!0}}}async function xc(e,t,n,r){if(e.appLog&&!r)return M(`INVALID_ARGS`,`logs clear requires logs to be stopped first; run logs stop`);let i=n.resolveAppLogPath(t);if(!r){let r=zn(i);return n.set(t,{...e,appLogFailure:void 0}),{ok:!0,data:r}}let a=e.appBundleId;if(!a)return M(`INVALID_ARGS`,`logs clear --restart requires an app session; run open <app> first`);e.appLog&&await sn(e.appLog);let o=zn(i),s=n.resolveAppLogPidPath(t);try{let r=await Hn(e.device,a,i,s);return n.set(t,{...e,appLog:Qs(e,i,r),appLogFailure:void 0}),{ok:!0,data:{...o,restarted:!0}}}catch(r){return $s(n,t,e,r)}}async function Sc(e,t,n){if(e.appLog)return M(`INVALID_ARGS`,`app log already streaming; run logs stop first`);if(!e.appBundleId)return M(`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 Hn(e.device,e.appBundleId,r,i);return n.set(t,{...e,appLog:Qs(e,r,a),appLogFailure:void 0}),{ok:!0,data:{path:r,started:!0}}}catch(r){return $s(n,t,e,r)}}async function Cc(e,t,n){if(!e.appLog)return M(`INVALID_ARGS`,`no app log stream active`);let r=e.appLog.outPath;return await sn(e.appLog),n.set(t,{...e,appLog:void 0,appLogFailure:void 0}),{ok:!0,data:{path:r,stopped:!0}}}async function wc(e){let t=Ec(e);if(!t.ok)return t;let{include:n,maxEntries:r,session:i}=t;if(i.device.platform===`web`)return await Tc({include:n,maxEntries:r});let a=await tn({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 Tc(t){let n=xr();if(!n.dumpNetwork)return M(`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 Ec(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.get(n);if(!i)return M(`SESSION_NOT_FOUND`,`network requires an active session`);let a=N(`network`,i.device);if(a)return a;let o=(t.positionals?.[0]??`dump`).toLowerCase();if(!Us.includes(o))return M(`INVALID_ARGS`,Ws);let s=t.positionals?.[1]?Number.parseInt(t.positionals[1],10):25;if(!Number.isInteger(s)||s<1||s>200)return M(`INVALID_ARGS`,`network dump limit must be an integer in range 1..200`);let c=Dc(t);return c.ok?{ok:!0,session:i,maxEntries:s,include:c.include}:c}function Dc(e){let t=e.positionals?.[2]?.toLowerCase(),r=e.flags?.networkInclude;if(t&&r&&t!==r)return M(`INVALID_ARGS`,`network include mode was provided both positionally and via --include with different values`);let i=(r??t??`summary`).toLowerCase();return n.includes(i)?{ok:!0,include:i}:M(`INVALID_ARGS`,Gs)}function Oc(e){let{artifactsDir:t,cwd:n,suiteInvocationId:r}=e,i=k.expandHome(t??`.agent-device/test-artifacts`,n);return V.join(i,r)}function kc(e,t){let n=t?V.relative(t,e):V.basename(e);return(n.length===0||n.startsWith(`..`)?V.basename(e):n).toLowerCase().replace(/[\\/]+/g,`__`).replace(/[^a-z0-9._-]+/g,`-`).replace(/^-+|-+$/g,``)||`test`}function Ac(e,t){B.mkdirSync(t,{recursive:!0}),Pc(e,t)}function jc(e){let{response:t,filePath:n,sessionName:r,attempts:i,maxAttempts:a,attemptArtifactsDir:o}=e,s=[...Mc(t)];!t.ok&&typeof t.error.logPath==`string`&&s.push(t.error.logPath);let c=Nc(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=>V.basename(e)).join(`, `)}`);let u=V.join(o,`result.txt`),d=`${l.join(`
|
|
3
|
+
`)}\n`;B.writeFileSync(u,d),t.ok||B.writeFileSync(V.join(o,`failure.txt`),d)}function Mc(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 Nc(e,t){let n=[],r=new Map;for(let i of e){if(!Lc(i))continue;let e=Ic(V.basename(i),r),a=V.join(t,e);V.resolve(i)!==V.resolve(a)&&B.copyFileSync(i,a),n.push(a)}return n}function Pc(e,t){let n=V.join(t,`replay.ad`);if(B.copyFileSync(e,n),!Fc(e))return;let r=V.join(t,V.basename(e));V.resolve(r)!==V.resolve(n)&&B.copyFileSync(e,r)}function Fc(e){let t=V.extname(e).toLowerCase();return t===`.yml`||t===`.yaml`}function Ic(e,t){let n=V.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 Lc(e){try{return B.statSync(e).isFile()}catch{return!1}}function Rc(e,n,r){if(e==null)return I(`open`,[R(lr(n,`launchApp`),r)]);if(typeof e==`string`)return I(`open`,[R(e,r)]);if(!L(e))throw new t(`INVALID_ARGS`,`launchApp expects a string or map.`);P(e,`launchApp`,[`appId`,`stopApp`,`clearState`,`clearKeychain`,`arguments`,`permissions`,`launchArguments`]),Uc(e,`permissions`),Uc(e,`clearKeychain`);let i=R(typeof e.appId==`string`?e.appId:lr(n,`launchApp`),r),a=Bc(e,r),o=e.clearState===!0,s=!o&&(e.stopApp===!0||a.length>0);return I(`open`,[i],{...s?{relaunch:!0}:{},...o?{clearAppState:!0}:{},...a.length>0?{launchArgs:a}:{}})}function zc(e,n,r){if(e==null)return I(`close`,[R(lr(n,`stopApp`),r)]);if(typeof e==`string`)return I(`close`,[R(e,r)]);throw new t(`INVALID_ARGS`,`stopApp expects a string appId or no value.`)}function Bc(e,t){return[...Vc(e.arguments,`launchApp.arguments`,t),...Vc(e.launchArguments,`launchApp.launchArguments`,t)]}function Vc(e,n,r){if(e==null)return[];if(typeof e==`string`)return[R(e,r)];if(Array.isArray(e))return e.map((e,t)=>Hc(e,`${n}[${t}]`,r));if(L(e))return Object.entries(e).flatMap(([e,t])=>[R(e,r),Hc(t,`${n}.${e}`,r)]);throw new t(`INVALID_ARGS`,`${n} expects a string, list, or map.`)}function Hc(e,n,r){if(typeof e==`string`)return R(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 Uc(e,t){if(e[t]!==void 0)throw F(`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 Wc(e,t){if(typeof e==`string`)return I(G.tapOn,[sl(R(e,t))],fl(e));if(L(e)&&typeof e.point==`string`){P(e,`tapOn`,[`point`,`repeat`,`delay`,`optional`,`label`]);let t=hr(e.point);return t.kind===`percent`?I(G.tapPointPercent,[String(t.x),String(t.y)],dl(e)):I(`click`,[String(t.x),String(t.y)],dl(e))}L(e)&&P(e,`tapOn`,[`id`,`text`,`childOf`,`enabled`,`index`,`selected`,`repeat`,`delay`,`optional`,`label`]);let n=fl(e);return I(G.tapOn,[K(e,`tapOn`,[`repeat`,`delay`,`optional`,`label`,`index`,`childOf`],t),...cl(e,t)],n)}function Gc(e,t){if(L(e)&&typeof e.point==`string`){P(e,`doubleTapOn`,[`point`,`delay`]);let t=mr(e.point);return I(`click`,[String(t.x),String(t.y)],pl(e))}return L(e)&&P(e,`doubleTapOn`,[`id`,`text`,`enabled`,`selected`,`delay`]),I(`click`,[K(e,`doubleTapOn`,[`delay`],t)],pl(e))}function Kc(e,t){if(L(e)&&typeof e.point==`string`){P(e,`longPressOn`,[`point`]);let t=mr(e.point);return I(`longpress`,[String(t.x),String(t.y),`3000`])}return L(e)&&P(e,`longPressOn`,[`id`,`text`,`enabled`,`selected`]),I(`click`,[K(e,`longPressOn`,[],t)],{holdMs:3e3})}function qc(e){if(typeof e==`string`)return e;if(!L(e))throw new t(`INVALID_ARGS`,`inputText expects a string or map.`);if(P(e,`inputText`,[`text`,`label`]),typeof e.text!=`string`)throw new t(`INVALID_ARGS`,`inputText map requires a string text field.`);return e.text}function Jc(e){if(e==null)return I(`type`,[`\b`.repeat(50)]);if(typeof e==`number`&&Number.isInteger(e)&&e>0)return I(`type`,[`\b`.repeat(e)]);if(!L(e))throw new t(`INVALID_ARGS`,`eraseText expects empty, a positive count, or a map.`);if(P(e,`eraseText`,[`charactersToErase`]),e.charactersToErase===void 0)return I(`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 I(`type`,[`\b`.repeat(e.charactersToErase)])}function Yc(e,n){if(!L(e))throw new t(`INVALID_ARGS`,`extendedWaitUntil expects a map.`);P(e,`extendedWaitUntil`,[`visible`,`notVisible`,`timeout`]);let r=e.visible??e.notVisible;if(r===void 0)throw F(`Only Maestro extendedWaitUntil.visible/notVisible is supported.`);let i=K(r,`extendedWaitUntil`,[],n),a=String(gr(e,17e3));return e.notVisible===void 0?[I(G.assertVisible,[i,a],{maestro:{allowAlreadyPastLoading:!0}})]:[I(G.assertNotVisible,[i,a])]}function Xc(e){if(e!=null)throw F(`Maestro scroll options are not supported yet.`);return I(`scroll`,[`down`])}function Zc(e,n){if(typeof e==`string`)return[I(G.scrollUntilVisible,[sl(R(e,n)),`5000`,`down`])];if(!L(e))throw new t(`INVALID_ARGS`,`scrollUntilVisible expects a string or map.`);P(e,`scrollUntilVisible`,[`element`,`direction`,`timeout`]);let r=K(e.element,`scrollUntilVisible.element`,[],n),i=typeof e.direction==`string`?il(e.direction,`scrollUntilVisible.direction`):`down`,a=String(gr(e,5e3));return[I(G.scrollUntilVisible,[r,a,i])]}function Qc(e,n){if(!L(e))throw new t(`INVALID_ARGS`,`swipe expects a map.`);P(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`?I(G.swipeScreen,[`direction`,al(e.direction),...ll(e)]):el(e):$c(e,r,n)}function $c(e,t,n){let r=al(typeof e.direction==`string`?e.direction:`up`);return I(G.swipeOn,[K(t,`swipe.from`,[],n),r,...ll(e)])}function el(e){let{start:t,end:n}=tl(e);return rl(t,n,nl(e.duration))}function tl(e){if(typeof e.start==`string`&&typeof e.end==`string`)return{start:hr(e.start),end:hr(e.end)};throw F(`Only Maestro swipe start/end coordinates are supported.`)}function nl(e){return typeof e==`number`&&Number.isFinite(e)?String(Math.max(16,Math.floor(e))):void 0}function rl(e,t,n){if(e.kind===`absolute`&&t.kind===`absolute`)return I(`swipe`,[String(e.x),String(e.y),String(t.x),String(t.y),...n?[n]:[]]);if(e.kind===`percent`&&t.kind===`percent`)return I(G.swipeScreen,[`percent`,String(e.x),String(e.y),String(t.x),String(t.y),...n?[n]:[]]);throw F(`Maestro swipe start/end must both be absolute pixels or both be percentages.`)}function il(e,t){let n=e.toLowerCase();switch(n){case`up`:case`down`:case`left`:case`right`:return n;default:throw F(`Maestro ${t} must be UP, DOWN, LEFT, or RIGHT.`)}}function al(e){return il(e,`swipe direction`)}function ol(e){let t=ur(`pressKey`,e).toLowerCase();if(t===`back`)return I(`back`);if(t===`enter`||t===`return`)return I(G.pressEnter);if(t===`home`)return I(`home`);throw F(`Maestro pressKey "${t}" is not supported yet.`)}function K(e,n,r=[],i){if(typeof e==`string`)return sl(R(e,i));if(!L(e))throw new t(`INVALID_ARGS`,`${n} expects a string or selector map.`);P(e,n,[`id`,`text`,`enabled`,`selected`,...r]);let a=[],o=[];if(typeof e.enabled==`boolean`&&o.push(ul(`enabled`,String(e.enabled))),typeof e.selected==`boolean`&&o.push(ul(`selected`,String(e.selected))),typeof e.id==`string`&&a.push(ul(`id`,R(e.id,i)),...o),typeof e.text==`string`&&a.length===0)return sl(R(e.text,i),o);if(typeof e.label==`string`&&a.length===0&&a.push(ul(`label`,R(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 sl(e,t=[]){return[[ul(`label`,e),...t].join(` `),[ul(`text`,e),...t].join(` `),[ul(`id`,e),...t].join(` `)].join(` || `)}function cl(e,n){if(!L(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 ll(e){let t=nl(e.duration);return t?[t]:[]}function ul(e,t){return`${e}=${JSON.stringify(t)}`}function dl(e){if(!L(e))return;let t={},n=ml(e.repeat),r=hl(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 fl(e){let t=dl(e)??{};return{...t,maestro:{...t.maestro??{},allowNonHittableCoordinateFallback:!0}}}function pl(e){let t={doubleTap:!0};return L(e)&&typeof e.delay==`number`&&Number.isInteger(e.delay)&&(t.intervalMs=Math.max(0,e.delay)),t}function ml(e){return typeof e==`number`&&Number.isInteger(e)&&e>0?e:void 0}function hl(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:void 0}const gl=1e3;function _l(e,n,r,i,a){if(typeof e==`string`)return i.parseRunFlowFile(R(e,r),r).actions;if(!L(e))throw new t(`INVALID_ARGS`,`runFlow expects a file path string or map.`);P(e,`runFlow`,[`file`,`commands`,`env`,`when`,`label`]);let o=xl(e.when,r);return o.shouldRun?Il(bl(e,n,{...r,env:{...r.env,...fr(e.env,`runFlow.env`),...r.envOverrides}},i,a),o):[]}function vl(e,n,r,i,a){if(!L(e))throw new t(`INVALID_ARGS`,`repeat expects a map.`);if(P(e,`repeat`,[`times`,`commands`,`while`]),e.while!==void 0)throw F(`Maestro repeat.while is not supported yet. Only deterministic repeat.times is supported.`);let o=Rl(e.times,r);if(!Array.isArray(e.commands))throw new t(`INVALID_ARGS`,`repeat requires a commands list.`);if(o>gl)throw new t(`INVALID_ARGS`,`repeat.times must be <= ${gl} for deterministic replay expansion.`);let s=z(e.commands);return Array.from({length:o}).flatMap(()=>a(s,n,r,i))}function yl(e,n,r,i,a){if(!L(e))throw new t(`INVALID_ARGS`,`retry expects a map.`);if(P(e,`retry`,[`maxRetries`,`commands`]),!Array.isArray(e.commands))throw new t(`INVALID_ARGS`,`retry requires a commands list.`);let o=zl(e.maxRetries,r),s=a(z(e.commands),n,r,i);return[Ll(`retry`,[String(o)],{kind:`retry`,maxRetries:o,actions:s})]}function bl(e,n,r,i,a){if(typeof e.file==`string`)return i.parseRunFlowFile(R(e.file,r),r).actions;if(Array.isArray(e.commands))return a(z(e.commands),n,r,i);throw new t(`INVALID_ARGS`,`runFlow map requires either file or commands.`)}function xl(e,n){if(e==null)return{shouldRun:!0};if(!L(e))throw new t(`INVALID_ARGS`,`runFlow.when expects a map.`);return P(e,`runFlow.when`,[`platform`,`visible`,`notVisible`,`true`]),Sl(e,n)?{shouldRun:!0,...Cl(e,n)}:{shouldRun:!1}}function Sl(e,n){if(e.true!==void 0&&!Tl(e.true,n))return!1;if(e.platform===void 0)return!0;let r=wl(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 Cl(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 wl(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 Tl(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 Fl(Dl(El(R(e,n))),{platform:n.platform}).parse()}function El(e){let t=e.trim();return t.startsWith("${")&&t.endsWith(`}`)?t.slice(2,-1).trim():t}function Dl(e){let n=[],r=0;for(;r<e.length;){let i=e.slice(r),a=Ol(i);if(a>0){r+=a;continue}let o=kl(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 Ol(e){return/^\s+/.exec(e)?.[0].length??0}function kl(e){return Al(e)??jl(e)??Ml(e)??Nl(e)??Pl(e)}function Al(e){return e.startsWith(`maestro.platform`)?{token:{type:`platform`},length:16}:null}function jl(e){let t=/^(==|!=|&&|\|\|)/.exec(e)?.[1];return t?{token:{type:`operator`,value:t},length:t.length}:null}function Ml(e){let t=e[0];return t===`(`||t===`)`?{token:{type:`paren`,value:t},length:1}:null}function Nl(e){let t=/^(['"])(.*?)\1/.exec(e);return t?{token:{type:`string`,value:t[2]??``},length:t[0].length}:null}function Pl(e){let t=/^(true|false)\b/.exec(e)?.[1];return t?{token:{type:`boolean`,value:t===`true`},length:t.length}:null}var Fl=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 Il(e,t){let{visibleSelector:n,notVisibleSelector:r}=t;if(!n&&!r)return e;if(n&&r)throw F(`Maestro runFlow.when cannot combine visible and notVisible yet.`);let i=n?`visible`:`notVisible`,a=n??r??``;return[Ll(`runFlow.when`,[i,a],{kind:`maestroRunFlowWhen`,mode:i,selector:a,actions:e})]}function Ll(e,t,n){return{...I(e,t),replayControl:n}}function Rl(e,t){return Bl(e,t,`repeat.times`)}function zl(e,t){return e===void 0?1:Bl(e,t,`retry.maxRetries`)}function Bl(e,n,r){let i=typeof e==`string`?R(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 Vl=3e4;function Hl(e,t){let n=Wl(e,t),r=Gl(n.file,t);return I(G.runScript,[r],{...Object.keys(n.env).length>0?{maestro:{runScriptEnv:n.env}}:{}})}function Ul(e){let{scriptPath:n,env:r}=e,i=B.readFileSync(n,`utf8`),a=Object.create(null);try{Pr.runInNewContext(i,Kl(r,a),{filename:n,timeout:Vl})}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 Xl(a,n),Object.fromEntries(Object.entries(a).map(([e,t])=>[`output.${e}`,Zl(t)]))}function Wl(e,n){if(typeof e==`string`)return{file:R(e,n),env:{}};if(!L(e))throw new t(`INVALID_ARGS`,`runScript expects a file path string or map.`);P(e,`runScript`,[`file`,`env`]);let r=R(ur(`runScript.file`,e.file),n),i=fr(e.env,`runScript.env`);return{file:r,env:Object.fromEntries(Object.entries(i).map(([e,t])=>[e,R(t,n)]))}}function Gl(e,n){if(V.isAbsolute(e))return e;if(!n.baseDir)throw new t(`INVALID_ARGS`,`runScript file paths require replay input to have a source path.`);return V.resolve(n.baseDir,e)}function Kl(e,t){return{...e,output:t,json:ql,http:{post:(e,t)=>Yl(`POST`,e,t)}}}function ql(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,Jl)}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 Jl(e,t){return e===`__proto__`||e===`constructor`||e===`prototype`?void 0:t}function Yl(e,n,r){let a=i(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})=>[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
|
|
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
|
|
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:Vl,allowFailure:!0});if(a.exitCode!==0)throw new t(`COMMAND_FAILED`,`Maestro runScript http.${e.toLowerCase()} failed for ${n}: ${Ql(a.stderr)}`,{exitCode:a.exitCode,stderr:a.stderr});try{return JSON.parse(a.stdout)}catch(r){throw new t(`COMMAND_FAILED`,`Maestro runScript http.${e.toLowerCase()} returned invalid JSON for ${n}`,{stdout:a.stdout.slice(0,1e3),stderr:a.stderr.slice(0,1e3)},r instanceof Error?r:void 0)}}function Xl(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 Zl(e){return typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`?String(e):JSON.stringify(e)}function Ql(e){let t=e.trim();return t.length>0?t.slice(0,1e3):`request process exited without stderr`}const $l={launchApp:({value:e,config:t,context:n})=>[Rc(e,t,n)],tapOn:({value:e,context:t})=>[Wc(e,t)],doubleTapOn:({value:e,context:t})=>[Gc(e,t)],longPressOn:({value:e,context:t})=>[Kc(e,t)],inputText:({value:e,context:t})=>[I(`type`,[R(qc(e),t)])],eraseText:({value:e})=>[Jc(e)],pasteText:({value:e,context:t,name:n})=>[I(`type`,[R(ur(n,e),t)])],openLink:({value:e,config:t,context:n,name:r})=>[iu(e,t,n,r)],assertVisible:({value:e,context:t,name:n})=>[I(G.assertVisible,[K(e,n,[],t),`17000`])],assertNotVisible:({value:e,context:t,name:n})=>[I(G.assertNotVisible,[K(e,n,[],t)])],extendedWaitUntil:({value:e,context:t})=>Yc(e,t),takeScreenshot:({value:e,context:t,name:n})=>[I(`screenshot`,[R(ur(n,e),t)])],scroll:({value:e})=>[Xc(e)],scrollUntilVisible:({value:e,context:t})=>Zc(e,t),swipe:({value:e,context:t})=>[Qc(e,t)],hideKeyboard:()=>[I(`keyboard`,[`dismiss`])],pressKey:({value:e})=>[ol(e)],back:()=>[I(`back`)],waitForAnimationToEnd:({value:e})=>[I(G.waitForAnimationToEnd,[String(gr(e,15e3))])],stopApp:({value:e,config:t,context:n})=>[zc(e,t,n)],runScript:({value:e,context:t})=>[Hl(e,t)],runFlow:({value:e,config:t,context:n,deps:r})=>_l(e,t,n,r,ou),repeat:({value:e,config:t,context:n,deps:r})=>vl(e,t,n,r,ou),retry:({value:e,config:t,context:n,deps:r})=>yl(e,t,n,r,ou)},eu={launchApp:(e,t)=>[Rc(void 0,e,t)],scroll:()=>[I(`scroll`,[`down`])],hideKeyboard:()=>[I(`keyboard`,[`dismiss`])],eraseText:()=>[Jc(void 0)],back:()=>[I(`back`)],waitForAnimationToEnd:()=>[I(G.waitForAnimationToEnd,[`15000`])],stopApp:(e,t)=>[zc(void 0,e,t)]};function tu(e,n,r,i,a){try{return nu(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 nu(e,n,r,i){if(typeof e==`string`)return ru(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=$l[o];return c?c({value:s,config:n,context:r,deps:i,name:o}):pr(o)}function ru(e,t,n){let r=eu[e];return r?r(t,n):pr(e)}function iu(e,t,n,r){let i=R(au(e,r),n);return(n.platform===`ios`||n.platform===`android`)&&t.appId?I(`open`,[R(lr(t,r),n),i],n.platform===`ios`?{maestro:{prewarmRunnerBeforeOpen:!0}}:void 0):I(`open`,[i])}function au(e,t){return typeof e==`string`?e:L(e)?(P(e,t,[`link`]),ur(`${t}.link`,e.link)):ur(t,e)}function ou(e,t,n,r){return e.flatMap((e,i)=>tu(e,t,i+1,n,r))}function su(e,t={}){return lu(e,vu(t))}function cu(e){let{config:t}=bu(dr(e));return t.name}function lu(e,t){let{config:n,commands:r}=bu(dr(e)),i={...t,env:{...t.env,...n.env??{},...t.envOverrides}},{actions:a,actionLines:o}=uu({config:n,commands:r,commandLines:yu(e),context:i});return{actions:a,actionLines:o,metadata:{env:n.env}}}function uu(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=tu(n,t,r,i,{parseRunFlowFile:Su});s.push(...a),a.forEach(()=>c.push(r))}return du(s,c)}function du(e,t){let n=[],r=[];for(let i=0;i<e.length;i+=1){let a=e[i],o=fu(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 fu(e,t,n){let r=pu(e,t,n);if(!r)return null;let{action:i,nextAction:a,pressEnterAction:o,tapSelector:s,typedAfterTap:c,line:l}=r;return _u(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:[mu(i)],actionLines:[l],consumed:1}}function pu(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=gu(i),s=hu(r);return!i||o===null||s===null?null:{action:r,nextAction:i,pressEnterAction:a,tapSelector:s,typedAfterTap:o,line:t[n]??1}}function mu(e){let t={...e.flags?.maestro??{}};return delete t.allowNonHittableCoordinateFallback,{...e,flags:{...e.flags??{},maestro:{...t}}}}function hu(e){if(e?.command!==G.tapOn)return null;let[t,...n]=e.positionals??[];return n.length>0||typeof t!=`string`?null:t}function gu(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 _u(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 vu(e){let t=e.visitedPaths??new Set;return e.sourcePath&&t.add(V.resolve(e.sourcePath)),{baseDir:e.sourcePath?V.dirname(e.sourcePath):void 0,platform:cr(e.platform),env:{},envOverrides:e.env??{},visitedPaths:t}}function yu(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 bu(e){if(e.length===0)throw new t(`INVALID_ARGS`,`Maestro flow is empty.`);if(Array.isArray(e[0]))return{config:{},commands:z(e[0])};let n=xu(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:z(r)}}function xu(e){if(!L(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}:{},...L(e.env)?{env:fr(e.env,`env`)}:{},...Array.isArray(e.onFlowStart)?{onFlowStart:z(e.onFlowStart)}:{},...Array.isArray(e.onFlowComplete)?{onFlowComplete:z(e.onFlowComplete)}:{}}}function Su(e,n){let r=Cu(e,n);if(n.visitedPaths.has(r))throw new t(`INVALID_ARGS`,`Maestro runFlow cycle detected at ${r}.`);let i=B.readFileSync(r,`utf8`),a=new Set(n.visitedPaths);return a.add(r),lu(i,{...n,baseDir:V.dirname(r),visitedPaths:a})}function Cu(e,n){if(V.isAbsolute(e))return e;if(!n.baseDir)throw new t(`INVALID_ARGS`,`runFlow file paths require replay input to have a source path.`);return V.resolve(n.baseDir,e)}const wu=/[*?[\]{}]/;function Tu(e){let{inputs:n,cwd:r,platformFilter:i,replayBackend:a}=e,o=Fu(a),s=ju(n,r??process.cwd(),o,a),c=[];for(let e of s){let t=B.readFileSync(e,`utf8`),n=br(t),r=Hu(t,e,a);if(!i){c.push({kind:`run`,path:e,title:r,metadata:n});continue}if(!n.platform){Vu(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}Wu(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 Eu(e,t,n,r,i=0){let a=V.basename(n,V.extname(n)).toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``);return`${e}:test:${t}:${r+1}${a?`-${a}`:``}:attempt-${i+1}`}function Du(e){return(e?.trim()||`${process.pid}-${Date.now().toString(36)}`).toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`suite`}function Ou(e){let{requestId:t,suiteInvocationId:n,filePath:r,caseIndex:i,attemptIndex:a,shardIndex:o}=e,s=o===void 0?``:`:shard:${o+1}`;return _t(`${t??n}${s}:test:${i+1}:${V.basename(r)}:attempt:${a+1}`,n)}function ku(e,t){return typeof e==`number`?e:t}function Au(e,t){let n=typeof e==`number`?e:t;return typeof n==`number`?Math.max(0,Math.min(3,n)):0}function ju(e,t,n,r){if(!Vu(r))return[...new Set(e.flatMap(e=>Pu(e,t,n).paths))].map(e=>V.normalize(e)).sort((e,t)=>e.localeCompare(t));let i=[],a=[];for(let r of e){let e=Mu(r,t,n);e.source===`file`?i.push(...e.paths):a.push(e.source===`directory`?Bu(e.paths):Lu(e.paths))}return Bu([...i,...a.flat()])}function Mu(e,t,n){let r=k.expandHome(e,t);return B.existsSync(r)&&B.statSync(r).isDirectory()?{paths:Nu(r,n),source:`directory`}:Pu(e,t,n)}function Nu(e,t){let n=[],r=B.opendirSync(e);try{let i;for(;(i=r.readSync())!==null;){let r=V.join(e,i.name);i.isDirectory()?n.push(...Nu(r,t)):i.isFile()&&t.has(V.extname(i.name))&&n.push(r)}}finally{r.closeSync()}return n}function Pu(e,n,r){let i=k.expandHome(e,n);if(B.existsSync(i)){let n=B.statSync(i);if(n.isDirectory())return{paths:Iu(r).flatMap(e=>B.globSync(e,{cwd:i}).map(e=>V.join(i,e))),source:`directory`};if(n.isFile()){if(!r.has(V.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(!Uu(e)&&!Uu(i))throw new t(`INVALID_ARGS`,`test input not found: ${e}`);let a=V.isAbsolute(i)?i:e;return{paths:B.globSync(a,{cwd:V.isAbsolute(i)?void 0:n}).map(e=>V.isAbsolute(e)?e:V.resolve(n,e)).filter(e=>r.has(V.extname(e))&&Gu(e)),source:`glob`}}function Fu(e){return Vu(e)?new Set([`.yaml`,`.yml`,`.ad`]):new Set([`.ad`])}function Iu(e){return[...e].map(e=>`**/*${e}`)}function Lu(e){return e.map(e=>V.normalize(e)).sort(Ru)}function Ru(e,t){let n=zu(e),r=zu(t);return n===r?e.localeCompare(t):n-r}function zu(e){return+(V.extname(e)===`.ad`)}function Bu(e){return[...new Set(e.map(e=>V.normalize(e)))]}function Vu(e){return e===`maestro`}function Hu(e,t,n){return Vu(n)&&V.extname(t)!==`.ad`?cu(e):void 0}function Uu(e){return wu.test(e)}function Wu(e,t){return e===`apple`?E(t):t===e}function Gu(e){try{return B.statSync(e).isFile()}catch{return!1}}const Ku=[`failed to start daemon`,`runner did not accept connection`,`xcodebuild exited early`,`device is offline`,`device offline`,`device unauthorized`];function qu(e){let t=Ju(e);return t?Yu(t.details)||Xu(t.code,t.message):!1}function Ju(e){return`ok`in e?e.ok?null:e.error:e.status===`failed`?e.error:null}function Yu(e){let t=typeof e?.reason==`string`?e.reason:``;return t===`timeout_cleanup_pending`?!0:t?$e(t):!1}function Xu(e,t){let n=`${e}\n${t}`.toLowerCase();return Ku.some(e=>n.includes(e))}const Zu=2e3;async function Qu(t){let{filePath:n,sessionName:r,requestId:i,parentRequestId:a,timeoutMs:o,platform:c,target:l,artifactsDir:u,shard:d,progress:f,runReplay:p,cleanupSession:m,finalizeAttempt:h}=t;rt(i);let g=$u(i,a),_=new Set,v,y=!1,b,ee=Date.now(),x=ad({artifactsDir:u,artifactPaths:_,filePath:n,sessionName:r,requestId:i,timeoutMs:o,platform:c,target:l}),S=st(f,async()=>await p({filePath:n,sessionName:r,platform:c,target:l,requestId:i,artifactsDir:u,artifactPaths:_,tracePath:x,shard:d})).catch(t=>({ok:!1,error:e(t)})).finally(()=>{g(),gt(i)});try{b=typeof o==`number`?await Promise.race([S,new Promise(e=>{v=setTimeout(()=>{y=!0,it(i),e(od(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 ed(S)||(rd(b),s({level:`warn`,phase:`test_timeout_cleanup_race`,data:{session:r,requestId:i,graceMs:Zu}}),td({replayPromise:S,cleanupSession:m,sessionName:r,requestId:i})));let t=await nd({finalizeAttempt:h,sessionName:r,artifactPaths:_,artifactsDir:u,tracePath:x});b?.ok&&t&&!t.ok&&id(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 m(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}),s({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 $u(e,t){if(!t||t===e)return()=>{};let n=at(t);if(!n)return()=>{};let r=()=>{it(e)};return n.aborted?(r(),()=>{}):(n.addEventListener(`abort`,r,{once:!0}),()=>{n.removeEventListener(`abort`,r)})}async function ed(e){return await Promise.race([e.then(()=>!0),Nr(Zu).then(()=>!1)])}async function td(t){let{replayPromise:n,cleanupSession:r,sessionName:i,requestId:a}=t;try{await n}finally{try{await r(i)}catch(t){s({level:`warn`,phase:`test_late_cleanup_failed`,data:{session:i,requestId:a,error:e(t).message}})}}}async function nd(t){let{finalizeAttempt:n,sessionName:r,artifactPaths:i,artifactsDir:a,tracePath:o}=t;if(!n)return;let c=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()-c,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()-c,errorCode:n.code}),s({level:`warn`,phase:`test_finalize_failed`,data:{session:r,error:n.message}}),{ok:!1,error:n}}}function rd(e){!e||e.ok||(e.error.details={...e.error.details??{},reason:`timeout_cleanup_pending`,timeoutCleanupPending:!0})}function id(e,t){let n=e.data??={};n.warnings=[...Array.isArray(n.warnings)?n.warnings.filter(e=>typeof e==`string`):[],t]}function ad(e){let{artifactsDir:t,artifactPaths:n,filePath:r,sessionName:i,requestId:a,timeoutMs:o,platform:s,target:c}=e;if(!t)return;let l=V.join(t,`replay-timing.ndjson`);return B.mkdirSync(V.dirname(l),{recursive:!0}),B.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&&B.appendFileSync(e,`${JSON.stringify(t)}\n`)}function od(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 sd(e){let t=cd(e);return hd(e,t,await ld(e,t))}function cd(e){let{entry:t,cwd:n,retries:r,suiteArtifactsDir:i,shard:a}=e;return{testStartedAt:Date.now(),testArtifactsDir:V.join(i,...a?[`shard-${a.shardIndex+1}`]:[],kc(t.path,n)),maxAttempts:r+1}}async function ld(e,t){dd(e,t);let n={finalSessionName:``,attempts:0,finalAttemptDurationMs:0,attemptFailures:[]};for(let r=0;r<=e.retries&&!vt(e.requestId);r+=1){let i=await ud(e,t,r);if(fd(n,i),pd(e,i.response,r))break;md(e,t,i)}return n}async function ud(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=Eu(i,a,r.path,o,n),h=V.join(t.testArtifactsDir,`attempt-${f}`);Ac(r.path,h);let g=Ou({requestId:l,suiteInvocationId:a,filePath:r.path,caseIndex:o,attemptIndex:n,shardIndex:d?.shardIndex}),_=await Qu({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,...wd(d)},runReplay:e.runReplay,cleanupSession:e.cleanupSession,finalizeAttempt:e.finalizeAttempt}),v=Date.now()-p;return jc({response:_,filePath:r.path,sessionName:m,attempts:f,maxAttempts:t.maxAttempts,attemptArtifactsDir:h}),{response:_,sessionName:m,attempt:f,durationMs:v}}function dd(e,t){let{entry:n,sessionName:r,suiteInvocationId:i,caseIndex:a,suiteIndex:o,suiteTotal:s,shard:c}=e;O({type:`replay-test`,file:n.path,title:n.title,status:`start`,index:o,total:s,maxAttempts:t.maxAttempts,session:Eu(r,i,n.path,a),artifactsDir:t.testArtifactsDir,...wd(c)})}function fd(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 pd(e,t,n){return t.ok||vt(e.requestId)||qu(t)||n>=e.retries}function md(e,t,n){n.response.ok||O({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,...wd(e.shard)})}function hd(e,t,n){let r=Date.now()-t.testStartedAt;return n.finalResponse?.ok?gd(e,t,n,r):_d(e,t,n,r)}function gd(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 O({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,...wd(s)}),{file:i.path,title:i.title,session:n.finalSessionName,status:`passed`,durationMs:r,finalAttemptDurationMs:n.finalAttemptDurationMs,attempts:n.attempts,artifactsDir:t.testArtifactsDir,...yd(c),...bd(c.data?.warnings),...xd(c.data?.snapshotDiagnostics),...Cd(s),...n.attemptFailures.length>0?{attemptFailures:n.attemptFailures}:{}}}function _d(e,t,n,r){let{entry:i,suiteIndex:a,suiteTotal:o,shard:s}=e,c=vd(n.finalResponse);return O({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,...wd(s)}),{file:i.path,title:i.title,session:n.finalSessionName,status:`failed`,durationMs:r,attempts:n.attempts,artifactsDir:t.testArtifactsDir,error:c,...xd(Sd(n.finalResponse)),...Cd(s)}}function vd(e){return e&&!e.ok?e.error:{code:`COMMAND_FAILED`,message:`Unknown replay test failure`}}function yd(e){return{replayed:typeof e.data?.replayed==`number`?e.data.replayed:0,healed:typeof e.data?.healed==`number`?e.data.healed:0}}function bd(e){if(!Array.isArray(e))return{};let t=e.filter(e=>typeof e==`string`);return t.length>0?{warnings:t}:{}}function xd(e){let t=_e(e);return t?{snapshotDiagnostics:t}:{}}function Sd(e){return e?.ok?e.data?.snapshotDiagnostics:e?.error.details?.snapshotDiagnostics}function Cd(e){return wd(e)}function wd(e){return e?{shardIndex:e.shardIndex,shardCount:e.shardCount,deviceId:e.device.id,deviceName:e.device.name}:{}}async function Td(e,t,n){let r=Dd(e);if(!r||t.length===0)return;let i=await kd(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 Ed(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 Dd(e){let n=Od(e?.shardAll,`--shard-all`),r=Od(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 Od(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 kd(e,n){let r=Nd(e),i=jd(await In(Ad(e)),r,e);if(i.length<n)throw new t(`DEVICE_NOT_FOUND`,`test sharding requires ${Md(n)}, but only ${i.length} matched`);return i.slice(0,n)}function Ad(e){let t=Xe(e?.androidDeviceAllowlist);return{platform:e?.platform,target:e?.target,iosSimulatorSetPath:Pe({simulatorSetPath:et(e?.iosSimulatorDeviceSet),platform:e?.platform,target:e?.target}),androidSerialAllowlist:t?Array.from(t).sort():void 0}}function jd(e,t,n){return t.length>0?Pd(e,t,n):e.filter(e=>Fd(e,n)).sort(Rd)}function Md(e){return`${e} device${e===1?``:`s`}`}function Nd(e){let t=e?.device;return typeof t!=`string`||t.trim().length===0?[]:t.split(`,`).map(e=>e.trim()).filter(Boolean)}function Pd(e,n,r){return n.map(n=>{let i=Ld(n),a=e.find(e=>Id(e,r)&&(e.id===n||Ld(e.name)===i));if(!a)throw new t(`DEVICE_NOT_FOUND`,`No shard device matched ${n}`);return a})}function Fd(e,t){return!Id(e,t)||!Fe(e)?!1:e.booted!==!1}function Id(e,t){return!(!Ie(e,t?.platform)||t?.target&&(e.target??`mobile`)!==t.target)}function Ld(e){return e.toLowerCase().replace(/_/g,` `).replace(/\s+/g,` `).trim()}function Rd(e,t){return e.id.localeCompare(t.id)}async function zd(e){let{req:t,sessionName:n,runReplay:i,cleanupSession:a,finalizeAttempt:o}=e;if((t.positionals?.length??0)===0)return M(`INVALID_ARGS`,`test requires at least one path or glob`);try{let e=Date.now(),r=await Bd(t);Wd(r);let s=r.shardPlan?Gd({entries:r.entries,total:r.total}):[];return r.shardPlan?s.push(...await Kd({shards:r.shardPlan.shards,sessionName:n,suiteInvocationId:r.suiteInvocationId,cwd:t.meta?.cwd,requestId:t.meta?.requestId,flags:t.flags,suiteArtifactsDir:r.suiteArtifactsDir,suiteTotal:r.total,runReplay:i,cleanupSession:a,finalizeAttempt:o})):s.push(...await Xd({discoveryEntries:r.entries,sessionName:n,suiteInvocationId:r.suiteInvocationId,cwd:t.meta?.cwd,requestId:t.meta?.requestId,flags:t.flags,suiteArtifactsDir:r.suiteArtifactsDir,suiteTotal:r.total,runReplay:i,cleanupSession:a,finalizeAttempt:o})),{ok:!0,data:$d(r.total,s,Date.now()-e)}}catch(e){let t=r(e);return M(t.code,t.message)}}async function Bd(e){let t=Vd(e),n=Hd(t),r=t.length-n.length,i=Du(e.meta?.requestId),a=await Td(e.flags,n,r);return{entries:t,runnable:n,shardPlan:a,suiteInvocationId:i,suiteArtifactsDir:Ud(e,i),total:a?.total??t.length}}function Vd(e){return Tu({inputs:e.positionals??[],cwd:e.meta?.cwd,platformFilter:e.flags?.platform,replayBackend:e.flags?.replayBackend})}function Hd(e){return e.flatMap((e,t)=>e.kind===`run`?[{entry:e,suiteIndex:t+1}]:[])}function Ud(e,t){return Oc({artifactsDir:typeof e.flags?.artifactsDir==`string`?e.flags.artifactsDir:void 0,cwd:e.meta?.cwd,suiteInvocationId:t})}function Wd(e){O({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 Gd(e){let{entries:t,total:n}=e,r=[];for(let[e,i]of t.entries())i.kind===`skip`&&(O({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 Kd(e){return(await Promise.allSettled(e.shards.map(async t=>await Jd({...e,shard:t})))).flatMap((t,n)=>{if(t.status===`fulfilled`)return t.value;let r=e.shards[n];return r?[qd(r,e.sessionName,t.reason)]:[]})}function qd(t,n,r){let i=e(r);return{file:t.entries[0]?.entry.path??`shard-${t.shardIndex+1}`,session:Yd(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 Jd(e){let{shard:t,sessionName:n}=e;return await Zd({...e,entries:t.entries,sessionName:Yd(n,t),shard:t})}function Yd(e,t){return`${e}:shard-${t.shardIndex+1}`}async function Xd(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(vt(a))break;if(m.kind===`skip`){O({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 sd({entry:m,sessionName:n,suiteInvocationId:r,caseIndex:p-1,cwd:i,requestId:a,retries:Au(o?.retries,m.metadata.retries),timeoutMs:ku(o?.timeoutMs,m.metadata.timeoutMs),suiteArtifactsDir:s,suiteIndex:e+1,suiteTotal:c,runReplay:l,cleanupSession:u,finalizeAttempt:d});if(f.push(t),Qd(t,o,a))break}return f}async function Zd(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(vt(a))break;let{entry:t,suiteIndex:h}=m,g=await sd({entry:t,sessionName:n,suiteInvocationId:r,caseIndex:e,cwd:i,requestId:a,retries:Au(o?.retries,t.metadata.retries),timeoutMs:ku(o?.timeoutMs,t.metadata.timeoutMs),suiteArtifactsDir:s,suiteIndex:h,suiteTotal:c,shard:l,runReplay:u,cleanupSession:d,finalizeAttempt:f});if(p.push(g),Qd(g,o,a))break}return p}function Qd(e,t,n){return vt(n)||t?.failFast===!0||qu(e)}function $d(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=ve(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 ef={maestro:{parse:su}};function tf(e,t,n={}){let r=rf(t);return r?{...r.parse(e,{...n,platform:t?.platform,env:nf(t)}),updateUnsupportedMessage:`replay -u is not supported for compat flow input. Convert to .ad first, then update that replay file.`}:{..._r(e),metadata:br(e)}}function nf(e){return{...ar(ir(e?.replayShellEnv)),...vr(or(e?.replayEnv))}}function rf(e){let n=e?.replayBackend;if(typeof n!=`string`)return;let r=ef[n];if(!r)throw new t(`INVALID_ARGS`,`Unsupported replay backend "${n}".`);return r}function af(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=p(n===null?e.slice():e.slice(0,-1));return!r||r.rest.length>0?{selectorExpression:null,selectorTimeout:null}:{selectorExpression:r.selectorExpression,selectorTimeout:n}}function of(e){let t=[],n=Array.isArray(e.result?.selectorChain)&&e.result?.selectorChain.every(e=>typeof e==`string`)?e.result.selectorChain:[];if(t.push(...n),tt(e.command)){let n=lf(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}=De(e.positionals);n&&t.push(n.selectorExpression)}if(e.command===`wait`){let{selectorExpression:n}=af(e.positionals??[]);n&&t.push(n)}return Et(t).filter(e=>e.trim().length>0)}function sf(e){return of(e).map(e=>d(e)).filter(e=>e!==null)}async function cf(e){let{action:t,sessionName:n,logPath:r,sessionStore:i}=e;if(!(tt(t.command)||[`fill`,`get`,`is`,`wait`].includes(t.command)))return null;let a=i.get(n);if(!a)return null;let o=sf(t);if(o.length===0)return null;let s=tt(t.command)||t.command===`fill`,c=tt(t.command)||t.command===`fill`||t.command===`get`&&t.positionals?.[0]===`text`,l=await pf(a,t,r,s,i);for(let e of o){let n=Re(l.nodes,e,{platform:a.device.platform,requireRect:s,requireUnique:!0,disambiguateAmbiguous:c});if(!n)continue;let r=Be(n.node,a.device.platform,{action:t.command===`fill`?`fill`:tt(t.command)?`click`:`get`}).join(` || `);if(tt(t.command))return{...t,positionals:t.command===`longpress`?uf(t,r):[r]};if(t.command===`fill`){let e=Cn(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}=De(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}=af(t.positionals??[]),n=[r];return e&&n.push(e),{...t,positionals:n}}}return null}function lf(e){let t=e.positionals??[];if(e.command!==`longpress`)return t;let n=t.at(-1);return t.length>1&&ff(n)?t.slice(0,-1):t}function uf(e,t){let n=typeof e.result?.durationMs==`number`?String(e.result.durationMs):df(e.positionals??[]);return n?[t,n]:[t]}function df(e){let t=e.at(-1);return e.length>1&&ff(t)?t:void 0}function ff(e){return e===void 0||e.trim()===``?!1:Number.isFinite(Number(e))}async function pf(e,t,n,r,i){let a=Ut(await j(e.device,`snapshot`,[],t.flags?.out,{...A(n,{...t.flags??{},snapshotInteractiveOnly:r},e.appBundleId,e.trace?.outPath)}),{...t.flags??{},snapshotInteractiveOnly:r});return It(e,a),i.set(e.name,e),a}const mf={swipe:{screenRatio:.35,minDistancePx:120,maxDistancePx:360,marginPx:8}};function hf(e,t){let n=de(e.rect),r=e.frame,i=_f(r?.referenceWidth,e.rect.width),a=_f(r?.referenceHeight,e.rect.height),o=mf.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:ce(n.y-a,c,u)}};case`down`:return{ok:!0,start:n,end:{x:n.x,y:ce(n.y+a,c,u)}};case`left`:return{ok:!0,start:n,end:{x:ce(n.x-i,s,l),y:n.y}};case`right`:return{ok:!0,start:n,end:{x:ce(n.x+i,s,l),y:n.y}};default:return{ok:!1,message:`swipe.label direction must be up, down, left, or right.`}}}function gf(e){return de(e.rect)}function _f(e,t){let n=typeof e==`number`?e*mf.swipe.screenRatio:0;return Math.round(Math.min(mf.swipe.maxDistancePx,Math.max(mf.swipe.minDistancePx,n,t*1.5)))}const vf=new WeakMap,yf=new WeakMap,bf=new WeakMap;function J(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{details:n}:{}}}}async function xf(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&&Af(e.scope,n.data),n}function Sf(e){return Array.isArray(e?.nodes)?e:void 0}function Cf(e){return e?vf.get(e):void 0}function wf(e,t){e&&yf.set(e,{selector:t})}function Tf(e){return e?yf.get(e):void 0}function Ef(e){e&&yf.delete(e)}function Df(e,t){e&&bf.set(e,t)}function Of(e){if(!e)return;let t=bf.get(e);return bf.delete(e),t}function kf(e){e&&bf.delete(e)}function Af(e,t){let n=Kt(Sf(t));n&&vf.set(e,n)}const jf=new Map([[`button`,0],[`link`,0],[`textfield`,0],[`textview`,0],[`searchfield`,0],[`switch`,0],[`slider`,0],[`cell`,1],[`statictext`,2]]);function Mf(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=Ee(e.nodes);o=o.filter(n=>t.some(t=>Ce(e.nodes,n,t,i)))}let s=If({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 Nf(e,t,n,r,i={}){let a=Bf(e,t),o=If({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 Pf(e,t,n,r){let i=zf(e,t,n,{allowLeadingCompositeLabelMatch:!1}),a=If({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 Ff(e,t,n){return zf(e,t,n,{allowLeadingCompositeLabelMatch:!1}).length>0}function If(e){let t=e.matches.filter(t=>Te({predicate:`visible`,node:t,nodes:e.nodes,platform:e.platform}).pass),n=Lf(e.nodes,t,e.platform);return{matches:n.matches,blockedByReactNativeOverlay:n.blockedByReactNativeOverlay}}function Lf(e,t,n){let r=He(e);if(!r.detected||!r.redBox)return{matches:t,blockedByReactNativeOverlay:!1};let i=Ue(r),a=i.filter(t=>Te({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 Rf(e){return e?.platform===`android`?`android`:`ios`}function Y(e){let t=u(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=u(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=Le(t);if(!n)return[];let r=[],i=[];for(let t of e.nodes){let e=[t.label,Se(t),t.identifier,t.value].filter(e=>!!e).map(e=>Le(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 ze(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)?ze(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:Se(e)}function Gf(e,t,n={}){let r=e??``,i=Le(r),a=Le(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=Ee(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=Ee(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=Ee(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 we(e,t,n,e=>!e.rect||!dp(e)||e.rect.width<240||e.rect.height<320?null:e)}function dp(e){let t=xe(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:Ce(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 jf.get(xe(e.type??``))??3}function bp(e,t,n){if(!Dp(t,n))return null;let r=xp(e,t,n,Ee(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&&Ce(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?xe(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=xe(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=xe(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:we(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=xe(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,Se(e),e.identifier,e.value].filter(e=>!!e);return n.some(e=>e===t)?0:n.some(e=>Le(e)===Le(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=cm(e.positionals,{command:`assertVisible`,defaultTimeoutMs:17e3});if(!t.ok)return t.response;let n=om(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 lm(e,t.selector,`assertVisible`);if(!n.visible){let i=em(e.baseReq,t,n,r);return i.kind===`return`?i.response:await Wp(e,rm(t))}}return wf(e.scope,t.selector),_m({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 lm(e,t.selector,`assertVisible`);if(c.visible)return _m(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 be(Q.assertVisiblePollMs)}let s=i??J(`COMMAND_FAILED`,`Expected visible but did not match: ${t.selector}`,{selector:t.selector,timeoutMs:t.timeoutMs});return await Kp(e,t,a)||vm(s,a,e.baseReq)}async function Gp(e,t,n,r){let i=await lm(e,t.selector,`assertVisible`);if(i.visible)return _m(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)||vm(n,i.snapshot,e.baseReq)}async function Kp(e,t,n){if(e.baseReq.flags?.platform!==`android`)return null;let r=Of(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||(s({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 s({level:`info`,phase:`maestro_assert_visible_retry_swipe`,data:{selector:t.selector,swipeCommand:n.command,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:im(t.timeoutMs)},i=om(e.baseReq,r.selector);if(!i)return await Wp(e,r);let a=Date.now(),o=await Up(e,r,i);return o.ok?(wf(e.scope,r.selector),_m({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=Rf(e.baseReq.flags),i=Kt(t),a=Mf(t,n.selector,n.options??{},r,i,{promoteTapTarget:!0});if(a.ok)return{ok:!0,target:{kind:`point`,point:gf(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:t.command,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 am(n.response)?{kind:`return`,response:n.response}:tm(e,t.selector,n.snapshot)?{kind:`return`,response:sm(t.selector,t.timeoutMs,r)}:{kind:`continue`}}function tm(e,t,n){return e.flags?.maestro?.allowAlreadyPastLoading===!0&&n!==void 0&&mm(t,n)}function nm(e){return Date.now()-e.startedAt<e.deadlineMs?`wait`:Sm(e.capturedAfterDeadline,e.captureStartedAt,e.startedAt,e.deadlineMs)?`capture-again`:`finish`}function rm(e){return{...e,timeoutMs:im(e.timeoutMs)}}function im(e){return Math.min(e,Q.assertVisibleRetryTimeoutMs)}function am(e){return!e.ok&&e.error.code===`COMMAND_FAILED`&&e.error.message.includes(`React Native overlay`)}function om(e,t){return e.flags?.platform!==`ios`&&e.flags?.platform!==`android`?null:Y(t)}function sm(e,t,n){return{ok:!0,data:{selector:e,alreadyPastLoading:!0,waitedMs:Date.now()-n,timeoutMs:t}}}function cm(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 lm(e,t,n){let r=um(e,t,n,await xf(e));return dm(e.baseReq,t,n,r)?um(e,t,n,await xf({...e,raw:!0})):r}function um(e,t,n,r){if(!r.ok)return{visible:!1,response:r,infrastructureFailure:!0};let i=Sf(r.data);if(!i)return{visible:!1,response:J(`COMMAND_FAILED`,`Unable to read snapshot data for ${n}.`),infrastructureFailure:!0};let a=Rf(e.baseReq.flags),o=Pf(i,t,a,Kt(i));if(!o.ok){let e=pm(i,t,a);return{visible:!1,response:J(`COMMAND_FAILED`,o.message,{selector:t}),infrastructureFailure:!1,...e?{missKind:e}:{},snapshot:i}}return wf(e.scope,t),{visible:!0,response:{ok:!0,data:{selector:t,matches:o.matches,nodeIndex:o.node.index,nodeType:o.node.type,nodeLabel:o.node.label,nodeIdentifier:o.node.identifier,rect:o.rect}}}}function dm(e,t,n,r){return n===`assertVisible`&&e.flags?.platform===`android`&&!r.visible&&!r.infrastructureFailure&&r.missKind===`missing`&&fm(t)}function fm(e){let t=d(e);return t?t.selectors.length>0&&t.selectors.every(e=>e.terms.length>0&&e.terms.every(e=>e.key===`id`&&typeof e.value==`string`)):!1}function pm(e,t,n){if(n===`android`)return Ff(e,t,n)?`notVisible`:`missing`}function mm(e,t){let n=hm(Y(e));if(!gm(n))return!1;let r=t.nodes.flatMap(e=>[e.label,e.value,e.identifier]).filter(e=>!!e?.trim()).map(e=>hm(e));return r.some(e=>e.includes(`something went wrong`))?!1:r.some(e=>e!==n&&!gm(e))}function hm(e){return e?.trim().toLowerCase().replace(/\u2026/g,`...`)??``}function gm(e){return e===`loading`||e===`loading...`}function _m(e,t,n){return e.ok?{ok:!0,data:{selector:t,...e.data,waitedMs:Date.now()-n}}:e}function vm(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=ym(t,r);return i.length===0?e:{ok:!1,error:{...e.error,details:{...e.error.details??{},artifactPaths:xm([...bm(e.error.details?.artifactPaths),...i])}}}}function ym(e,t){try{B.mkdirSync(t,{recursive:!0});let n=V.join(t,`failure-snapshot.json`),r=V.join(t,`failure-snapshot.txt`);B.writeFileSync(n,`${JSON.stringify(e,null,2)}\n`);let i=y(e.nodes,{summarizeTextSurfaces:!0}).map(e=>e.text);return B.writeFileSync(r,`${i.join(`
|
|
25
|
+
`)}\n`),[n,r]}catch{return[]}}function bm(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function xm(e){return[...new Set(e)]}function Sm(e,t,n,r){return!e&&t-n<r}async function Cm(e){let t=cm(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 lm(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 be(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 wm(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 xf(e),a=Tm(n,r,t);if(a.done)return a.response;r=a.signature??r,i=n,await be(Q.animationPollMs)}return i?.ok===!1?i:{ok:!0,data:{stable:!1,timeoutMs:t}}}function Tm(e,t,n){let r=Em(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 Em(e){if(!e.ok)return null;let t=Sf(e.data);return t?Dm(t):null}function Dm(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 Om(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 km={scrollUntilVisibleProbeMs:500,tapOnRetryMs:250,tapOnTimeoutMs:3e4,optionalTapOnTimeoutMs:3e3};async function Am(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/km.scrollUntilVisibleProbeMs)),s=null;for(let n=0;n<o;n+=1){let c=await Vm(e,t,a,Hm(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 $m(s,t,i)}async function jm(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 xf(e);if(!a.ok)return a;let o=Sf(a.data);if(!o)return J(`COMMAND_FAILED`,`Unable to read snapshot data for Maestro percentage point tap.`);let s=Kt(o);if(!s)return J(`COMMAND_FAILED`,`Unable to resolve screen size for Maestro percentage point tap.`);let c=ue(s,r,i),l=await Om({...e,point:c});return l.ok&&kf(e.scope),l}async function Mm(e){let t=await Nm(e);if(t)return t;let n=await Lm(e);return n.ok?await Im(e,n,n.durationMs):n.response}async function Nm(e){let[t,n,r]=e.positionals;if(t!==`direction`)return;if(!zm(n))return J(`INVALID_ARGS`,`Maestro swipe direction must be UP, DOWN, LEFT, or RIGHT.`);let i=[`swipe`,n,...r?[r]:[]],a=await e.invoke({...e.baseReq,command:`gesture`,positionals:i});return a.ok&&Df(e.scope,{kind:`swipe`,command:`gesture`,positionals:i}),a}async function Pm(e){let[t,n]=e.positionals;if(!t)return J(`INVALID_ARGS`,`tapOn requires a selector.`);let r=Qm(n);if(!r.ok)return r.response;let i=Date.now(),a=Um(e),o;for(;Date.now()-i<a;){let n=await Gm(e,t,r.value??{});if(!n.retry)return n.response;o=n.response,await be(km.tapOnRetryMs)}return Wm(e,t,o)}async function Fm(e){let[t,n=`up`,r]=e.positionals;if(!t)return J(`INVALID_ARGS`,`swipe.label requires a label selector.`);let i=await Ym(e,t,{},`swipe.label`,{promoteTapTarget:!1});if(!i.ok)return i.response;let a=hf(i.target,n);return a.ok?await Im(e,a,r):J(`INVALID_ARGS`,a.message)}async function Im(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&&Df(e.scope,{kind:`swipe`,command:`swipe`,positionals:r}),i}async function Lm(e){let t=Cf(e.scope)??await Rm(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===`percent`?Bm(r,t):{ok:!1,response:J(`INVALID_ARGS`,`Maestro screen swipe requires direction or percent.`)}}async function Rm(e){let t=await xf(e);if(t.ok)return Kt(Sf(t.data))}function zm(e){return e===`up`||e===`down`||e===`left`||e===`right`}function Bm(e,t){let[n,r,i,a,o]=e,s=[n,r,i,a].map(Number);if(s.some(e=>!Number.isFinite(e)))return{ok:!1,response:J(`INVALID_ARGS`,`Maestro percentage swipe requires numeric points.`)};let[c,l,u,d]=s;return{ok:!0,start:ue(t,c,l),end:ue(t,u,d),durationMs:o}}async function Vm(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 Hm(e,t){return Math.min(km.scrollUntilVisibleProbeMs,Math.max(1,e-t*km.scrollUntilVisibleProbeMs))}function Um(e){return e.baseReq.flags?.maestro?.optional===!0?km.optionalTapOnTimeoutMs:km.tapOnTimeoutMs}function Wm(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 Gm(e,t,n){let r=Y(t),i=await Km(e,t,n);return i.response.ok?{retry:!1,response:i.response}:i.targetResolved&&r?await Jm(e,r):{retry:!0,response:i.response}}async function Km(e,t,n){let r=await Ym(e,t,n,`tapOn`,{promoteTapTarget:!0});return r.ok?await qm(e,t,r.target,n):{response:r.response,targetResolved:!1}}async function qm(e,t,n,r){let i=gf(n);s({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 Om({...e,point:i});return a.ok&&(Ef(e.scope),Df(e.scope,{kind:`tap`,selector:t,point:i,options:{...r}})),{response:a,targetResolved:!0}}async function Jm(e,t){let n=await e.invoke({...e.baseReq,command:`find`,positionals:[t,`click`],flags:{...e.baseReq.flags,findFirst:!0,postGestureStabilization:!0}});return s({level:n.ok?`info`:`debug`,phase:`maestro_fuzzy_tap_fallback`,data:{query:t,ok:n.ok}}),n.ok?(kf(e.scope),{retry:!1,response:n}):{retry:!0,response:n}}async function Ym(e,t,n,r,i){return Xm(e,t,n,r,i,await xf({...e,raw:!0}))}function Xm(e,t,n,r,i,a){if(!a.ok)return{ok:!1,response:a};let o=Sf(a.data);if(!o)return{ok:!1,response:J(`COMMAND_FAILED`,`Unable to read snapshot data for ${r}.`)};let s=Kt(o),c=Rf(e.baseReq.flags),l=Zm(e,o,c,s),u=Mf(o,t,n,c,s,{...i,preferredContext:l,requireOnScreen:!0});if(!u.ok){let e=Y(t);if(e){let t=Nf(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 Zm(e,t,n,r){let i=Tf(e.scope);if(!i)return;let a=Pf(t,i.selector,n,r);if(a.ok)return s({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 Qm(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 $m(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 eh(e){switch(e.command){case G.assertVisible:return await Bp(e);case G.assertNotVisible:return await Cm(e);case G.pressEnter:return await th(e);case G.waitForAnimationToEnd:return await wm(e);case G.scrollUntilVisible:return await Am(e);case G.swipeScreen:return await Mm(e);case G.swipeOn:return await Fm(e);case G.tapOn:return await Pm(e);case G.tapPointPercent:return await jm(e);case G.runScript:return nh(e);default:return}}async function th(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 nh(e){let[t]=e.positionals;if(!t)return J(`INVALID_ARGS`,`runScript requires a file path.`);try{return{ok:!0,data:{outputEnv:Ul({scriptPath:t,env:{...e.scope.values,...e.baseReq.flags?.maestro?.runScriptEnv??{}}})}}}catch(e){let t=r(e);return J(t.code,t.message,t.details)}}async function rh(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 ih(e){let t;for(let n=0;n<=e.maxRetries;n+=1){let r=await rh({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 ah={visibleTimeoutMs:3e3,visiblePollMs:250};async function oh(e){let t=await sh(e,e.control);return t.ok?t.matched?await dh(e):{ok:!0,data:{skipped:!0,condition:e.control.mode,selector:e.control.selector}}:t.response}async function sh(e,t){if(t.mode===`visible`)return await ch(e,t);let n=await lh(e,t.selector);return n.ok?{ok:!0,matched:!n.matched}:{ok:!1,response:n.response}}async function ch(e,t){let n=Date.now();for(;;){let r=await lh(e,t.selector);if(!r.ok)return{ok:!1,response:r.response};if(r.matched)return{ok:!0,matched:!0};if(Date.now()-n>=ah.visibleTimeoutMs)return{ok:!0,matched:!1};await be(ah.visiblePollMs)}}async function lh(e,t){let n=await xf(e);return n.ok?uh(e,t,n):{ok:!1,response:n}}function uh(e,t,n){let r=Sf(n.data);return r?{ok:!0,matched:Pf(r,t,Rf(e.baseReq.flags),Kt(r)).ok}:{ok:!1,response:J(`COMMAND_FAILED`,`Unable to read snapshot data for runFlow.when.`)}}async function dh(e){let t=await rh({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 fh(e){let{req:t,sessionName:n,action:r,scope:i,filePath:a,line:o,step:s,tracePath:c,invoke:l}=e,u=rr(r,i,{file:a,line:o}),d=e=>fh({req:t,sessionName:n,action:e.action,scope:i,filePath:a,line:e.line,step:e.step,tracePath:c,invoke:l}),f=Date.now();_h(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 ph({req:t,sessionName:n,resolved:u,scope:i,line:o,step:s,invoke:l,invokeReplayAction:d}),m=Date.now();return _h(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?gh(p.data):void 0,errorCode:p.ok?void 0:p.error.code}),p}async function ph(e){let{req:t,sessionName:n,resolved:r,scope:i,line:a,step:o,invoke:s,invokeReplayAction:c}=e,l=vh(t.flags,r.flags),u={token:t.token,session:n,flags:l,runtime:r.runtime,meta:t.meta,internal:t.internal},d=await mh({control:r.replayControl,baseReq:u,line:a,step:o,invoke:s,invokeReplayAction:c})??await eh({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=hh(d.data);e&&nr(i,e)}return d}async function mh(e){let{control:t,baseReq:n,line:r,step:i,invoke:a,invokeReplayAction:o}=e;if(t){switch(t.kind){case`retry`:return await ih({actions:t.actions,maxRetries:t.maxRetries,line:r,step:i,invokeReplayAction:o});case`maestroRunFlowWhen`:return await oh({baseReq:n,control:t,line:r,step:i,invoke:a,invokeReplayAction:o})}return t}}function hh(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 gh(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 _h(e,t){e&&B.appendFileSync(e,`${JSON.stringify(t)}\n`)}function vh(e,t){return ke(e,{...t??{}})}async function yh(e){let{req:t,sessionName:n,logPath:i,sessionStore:a,tracePath:o,invoke:s}=e,c=t.positionals?.[0];if(!c)return M(`INVALID_ARGS`,`replay requires a path`);let l=``,u=new Set;try{l=k.expandHome(c,t.meta?.cwd);let e=B.readFileSync(l,`utf8`),r=e.trimStart()[0];if(r===`{`||r===`[`)return M(`INVALID_ARGS`,`replay accepts .ad script files. JSON replay payloads are no longer supported.`);let d=tf(e,t.flags,{sourcePath:l}),f=d.metadata,p=f.platform||f.target?{...t,flags:Eh(t.flags,f)}:t,m=d.actions,h=d.actionLines;if(t.flags?.replayUpdate===!0&&d.updateUnsupportedMessage)return M(`INVALID_ARGS`,d.updateUnsupportedMessage);if(t.flags?.replayUpdate===!0&&f.env&&Object.keys(f.env).length>0)return M(`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&&Nh(m))return M(`INVALID_ARGS`,"replay -u does not yet preserve ${VAR} substitutions. Resolve or inline the variables before running with -u.");let g=yr({builtins:bh({req:p,sessionName:n,metadata:f,resolvedPath:l}),fileEnv:f.env,shellEnv:ar(ir(t.flags?.replayShellEnv)),cliEnv:vr(or(t.flags?.replayEnv))}),_=t.flags?.replayUpdate===!0,v=o??a.get(n)?.trace?.outPath,y=[],b=0;for(let e=0;e<m.length;e+=1){let t=m[e];if(!t||t.command===`replay`)continue;xh(l,e,m.length,t);let r=Ah(a,n),o=await fh({req:p,sessionName:n,action:t,scope:g,filePath:l,line:h[e]??0,step:e+1,tracePath:v,invoke:s});if(y.push(...jh(a,n,r)),o.ok){kh(o).forEach(e=>u.add(e));continue}if(kh(o).forEach(e=>u.add(e)),!_)return Dh(o,t,e,l,[...u],y);let c=await cf({action:t,sessionName:n,logPath:i,sessionStore:a});if(!c)return Dh(o,t,e,l,[...u],y);m[e]=c;let d=Ah(a,n);if(o=await fh({req:p,sessionName:n,action:c,scope:g,filePath:l,line:h[e]??0,step:e+1,tracePath:v,invoke:s}),y.push(...jh(a,n,d)),!o.ok)return kh(o).forEach(e=>u.add(e)),Dh(o,c,e,l,[...u],y);kh(o).forEach(e=>u.add(e)),b+=1}_&&b>0&&sr(l,m,a.get(n));let ee=ge(y);return{ok:!0,data:{replayed:m.length,healed:b,session:n,artifactPaths:[...u],...ee?{snapshotDiagnostics:ee}:{}}}}catch(e){let t=r(e);return M(t.code,t.message,u.size>0?{artifactPaths:[...u]}:void 0)}}function bh(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:V.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 xh(e,t,n,r){let i=ct();i&&O({type:`replay-test`,...i,file:i.file||e,status:`progress`,stepIndex:t+1,stepTotal:n,...Sh(r)})}function Sh(e){return{stepCommand:Ch(e.command),...wh(e)}}function Ch(e){if(!e.startsWith(`__maestro`))return e;let t=e.slice(9);return t.length>0?t[0].toLowerCase()+t.slice(1):e}function wh(e){let t=e.positionals??[],n=Th(t[0]);return n?{stepValue:n}:e.command===`__maestroTapPointPercent`&&t.length>=2?{stepValue:`${t[0]},${t[1]}%`}:t.length===0?{}:{stepValue:t.join(` `)}}function Th(e){if(!e)return;let t=d(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 Eh(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 Dh(e,t,n,r,i,a){return Oh(e,t,n,r,i,ge(a))}function Oh(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} (${nt(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 kh(e){if(!e.ok){let t=e.error.details?.artifactPaths;return Array.isArray(t)?[...new Set(t.filter(e=>typeof e==`string`&&Mh(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=>Mh(e)))]}function Ah(e,t){return e.get(t)?.snapshotDiagnostics?.samples.length??0}function jh(e,t,n){return e.get(t)?.snapshotDiagnostics?.samples.slice(n)??[]}function Mh(e){try{return B.statSync(e).isFile()}catch{return!1}}function Nh(e){for(let t of e){for(let e of t.positionals??[])if(typeof e==`string`&&e.includes("${"))return!0;if(Ph(t.flags)||Ph(t.runtime))return!0}return!1}function Ph(e){return typeof e==`string`?e.includes("${"):Array.isArray(e)?e.some(Ph):e&&typeof e==`object`?Object.values(e).some(Ph):!1}const Fh=1e3,Ih=3e3;function Lh(e){if(e.req.flags?.recordVideo===!0)return{beforeDispatch:async()=>await Rh(e)}}async function Rh(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,artifactsDir:a,tracePath:o}=e;if(t.flags?.recordVideo!==!0)return;let c=i.get(n);if(!c||c.recording)return;let l=me(c.device.platform),u=a?V.join(a,`recording${l}`):he(c.device.platform);Bh(o,{type:`video_recording_start`,session:n,videoPath:u}),s({phase:`replay_test_video_recording_start`,data:{session:n,videoPath:u}});let d=await jr({req:{token:t.token,session:n,command:`record`,positionals:[`start`,u],flags:{},meta:t.meta},sessionName:n,sessionStore:i,logPath:r});if(!d.ok)return Bh(o,{type:`video_recording_start_failed`,session:n,videoPath:u,errorCode:d.error.code}),d;let f=Date.now();return await be(Fh),Bh(o,{type:`video_preroll_done`,session:n,durationMs:Date.now()-f,requestedDurationMs:Fh}),s({phase:`replay_test_video_recording_preroll_done`,durationMs:Date.now()-f,data:{session:n,requestedDurationMs:Fh}}),d}async function zh(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;Bh(a,{type:`video_tail_start`,session:n,requestedDurationMs:Ih});let c=Date.now();await be(Ih);let l=Date.now(),u=await jr({req:{token:t.token,session:n,command:`record`,positionals:[`stop`],flags:{},meta:t.meta},sessionName:n,sessionStore:i,logPath:r});return kh(u).forEach(e=>o.add(e)),Bh(a,{type:`video_recording_stop`,session:n,ok:u.ok,durationMs:Date.now()-l,tailDurationMs:l-c,errorCode:u.ok?void 0:u.error.code}),s({phase:`replay_test_video_recording_stop`,durationMs:Date.now()-l,data:{session:n,ok:u.ok,tailDurationMs:l-c}}),u}function Bh(e,t){q(e,{...t,ts:new Date().toISOString()})}function Vh(e){let{platform:t,target:n,artifactsDir:r,shard:i}=e,a=Hh(e.parentFlags);return t===void 0&&n===void 0&&r===void 0&&i===void 0?a:Ed({...a??{},...t===void 0?{}:{platform:t},...n===void 0?{}:{target:n},...r===void 0?{}:{artifactsDir:r}},i)}function Hh(e){if(e?.recordVideo!==!0)return e;let t={...e};return delete t.recordVideo,Object.keys(t).length>0?t:void 0}async function Uh(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,leaseRegistry:a,invoke:o}=e;return t.command===`replay`?await yh({req:t,sessionName:n,logPath:r,sessionStore:i,invoke:o}):t.command===`test`?await zd({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&&kh(e).forEach(e=>u.add(e)),e),m=Vh({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=Lh(h);return await yh({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 Rh(h);return t&&!t.ok?t:p(await o(e))}})},finalizeAttempt:async({sessionName:e,artifactPaths:n,artifactsDir:a,tracePath:o})=>await zh({req:t,sessionName:e,logPath:r,sessionStore:i,artifactsDir:a,tracePath:o,artifactPaths:n}),cleanupSession:async e=>{i.get(e)&&await Ha({req:{token:t.token,session:e,command:`close`,positionals:[],flags:{},meta:t.meta},sessionName:e,logPath:r,sessionStore:i,leaseRegistry:a})}}):null}function Wh(e){return e.some(e=>e.status===`fail`)?`fail`:e.some(e=>e.status===`warn`)?`warn`:`pass`}function Gh(e){return e===`fail`?`Blockers found before the run.`:e===`warn`?`No hard blockers found, but warnings need attention.`:`No blockers found.`}function Kh(e){let t={fail:0,warn:1,pass:2,info:3};return[...e].sort((e,n)=>t[e.status]-t[n.status])}function qh(e,...t){for(let n of t)$(e,n)}function $(e,t){e.push(t),O({type:`command`,status:`progress`,message:Jh(t)})}function Jh(e){return[ee(e),..._(e)].join(`
|
|
27
|
+
`)}async function Yh(e,t){let{device:n,metroPort:r,shouldProbeMetro:i,androidAdbExecutor:a}=t;n.platform!==`android`||!i||$(e,await Xh(o(n,a),n.id,r))}async function Xh(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 Zh(t,n){let{device:r,targetApp:i,session:a}=n;if(i)try{let e=await Qh(r,i);if(!e){$(t,{id:`target-app`,status:`info`,summary:`Target app installation checks are not supported for ${T(r)}.`,evidence:{requested:i,platform:T(r)}});return}$(t,{id:`target-app`,status:`pass`,summary:`Target app is launchable: ${e}`,evidence:{requested:i,resolved:e,sessionApp:a?.appBundleId}})}catch(n){let i=e(n);$(t,{id:`target-app`,status:`fail`,summary:`Target app check failed: ${i.message}`,hint:i.hint??`Install the app or pass an exact package/bundle id or app name.`,command:`agent-device apps --platform ${T(r)} --all`,evidence:{code:i.code,message:i.message}})}}async function Qh(e,t){if(e.platform===`android`){let{listAndroidApps:n}=await import(`./app-lifecycle.js`).then(e=>e.t);return $h(t,(await n(e,`all`)).map(e=>({id:e.package,name:e.name})))?.id}if(D(e)||w(e)){let{listIosApps:n}=await import(`./apps.js`).then(e=>e.t);return $h(t,(await n(e,`all`)).map(e=>({id:e.bundleId,name:e.name})))?.id}}function $h(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 eg(t,n,r){let i=ng(n,r);try{let e=await ig(i),n=rg(e.devices,i);return $(t,{id:`device`,status:n.length===0?`fail`:`pass`,summary:cg(n,i,e.failures),hint:n.length===0?dg(e.failures):void 0,command:n.length===0?gg(i):void 0,evidence:_g(n,e.failures)}),n.length>0&&ag(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 tg(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:T(e),id:e.id,name:e.name}))}})}function ng(e,t){let n=e.flags??{};return fn({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 rg(e,t){return e.filter(e=>Ne(e,t,{includeExplicitSelectors:!0}))}async function ig(e){if(e.platform)return{devices:await In(e),failures:[]};let t=[],n=[];for(let r of _n)try{t.push(...await In({...e,platform:r}))}catch(e){n.push(sg(r,e))}return{devices:t,failures:n}}function ag(e,t){for(let n of t)$(e,og(n))}function og(e){return{id:`device-${e.platform}`,status:`warn`,summary:`${mg(e.platform)} device inventory could not be read: ${e.message}`,hint:e.hint??`Check the ${mg(e.platform)} toolchain, or scope with --platform to skip it.`,evidence:{platform:e.platform,code:e.code}}}function sg(t,n){let r=e(n);return{platform:t,message:r.message,hint:r.hint,code:r.code}}function cg(e,t,n){if(e.length===0)return n.length>0?`No ${lg(t)} devices found; ${ug(n)}.`:`No ${lg(t)} devices found.`;let r=e.filter(e=>e.booted===!0).length,i=`${e.length} ${lg(t)} ${hg(e.length,`device`)} available; ${r} booted`,a=fg(e,t);return a?`${i} (${a}).`:`${i}.`}function lg(e){let t=e.platform?mg(e.platform):`local`;return e.target?`${t} ${e.target}`:t}function ug(e){return e.slice(0,2).map(e=>`${mg(e.platform)} inventory failed: ${e.message}`).join(`; `)}function dg(e){return e.find(e=>e.hint)?.hint??`Start or create a simulator/emulator, connect a device, or adjust --platform/--target/--device selectors.`}function fg(e,t){if(t.platform||t.target)return;let n=mn(e),r=pg();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 pg(){return{android:`Android`,apple:`Apple`,linux:`Linux`,web:`web`}}function mg(e){return e===`ios`?`iOS`:e===`macos`?`macOS`:e===`android`?`Android`:e===`linux`?`Linux`:e===`web`?`web`:`Apple`}function hg(e,t){return e===1?t:`${t}s`}function gg(e){return e.platform?`agent-device devices --platform ${e.platform}`:`agent-device devices`}function _g(e,t){let n=new Map;for(let t of e){let e=T(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 vg=1500;async function yg(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 bg(e,t,r):void 0;return{id:`metro`,status:s?`pass`:`warn`,summary:s?xg(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 bg(e,t,n){try{return await(n.resolveProcessInfo??Sg)(e,t)}catch{return}}function xg(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 Sg(e,t){if(!Cg(e))return;let n=await wg(t);if(n!==void 0)return{pid:n,cwd:await Tg(n)}}function Cg(e){return e===`127.0.0.1`||e===`localhost`||e===`::1`||e===`0.0.0.0`}async function wg(e){let t=await l(`lsof`,[`-nP`,`-iTCP:${e}`,`-sTCP:LISTEN`,`-Fp`],{allowFailure:!0,timeoutMs:vg});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 Tg(e){let t=await l(`lsof`,[`-nP`,`-a`,`-p`,String(e),`-d`,`cwd`,`-Fn`],{allowFailure:!0,timeoutMs:vg});if(t.exitCode===0)return t.stdout.split(`
|
|
29
|
+
`).find(e=>e.startsWith(`n`)&&e.length>1)?.slice(1)}const Eg=[`daemonBaseUrl`,`tenant`,`runId`,`leaseId`,`leaseProvider`],Dg=[`provider`,`providerSessionId`,`providerApp`,`providerOsVersion`,`providerProject`,`providerBuild`,`providerSessionName`,`awsProjectArn`,`awsDeviceArn`,`awsAppArn`,`awsRegion`,`awsInteractionMode`];function Og(e,t){let n=Ae(e.meta?.cwd);return{targetApp:Ng(e.flags?.targetApp)??t?.appBundleId,metroHost:Ng(e.runtime?.metroHost)??`127.0.0.1`,metroPort:Pg(e.runtime?.metroPort)??8081,kind:n,remote:e.flags?.remote===!0,shouldProbeMetro:jg(e,n)}}function kg(e,t={}){let n=Mg(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 Ag(e,t,n,r={}){let i=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:i.length>0?`warn`:`pass`,summary:i.length>0?`Other active sessions target the same device: ${i.join(`, `)}`:`Active session ${n.name} targets ${n.device.name}`,hint:i.length>0?`Close stale sessions before a QA run if they belong to old attempts.`:void 0,command:i.length>0?`agent-device close --session ${i[0]} --platform ${T(n.device)}`:void 0,evidence:{session:n.name,sameDeviceSessions:i,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 jg(e,t){return t!==`auto`||typeof e.runtime?.metroPort==`number`||typeof e.runtime?.metroHost==`string`}function Mg(e){let t={...Object.fromEntries([...Eg,...Dg].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 Ng(e){return typeof e==`string`&&e.trim().length>0?e.trim():void 0}function Pg(e){return typeof e==`number`&&Number.isInteger(e)&&e>0?e:void 0}async function Fg(e,t){if(t===`android`){$(e,await Ig());return}(t===`ios`||t===`macos`||t===`apple`)&&$(e,await Vg())}async function Ig(){let e=process.env.ANDROID_HOME||process.env.ANDROID_SDK_ROOT,t=await Kg(e),n=await qg(`adb`,[`version`]);return n?Lg({license:t,sdkRoot:e,versionLine:n}):Bg(e,t)}function Lg(e){return{id:`toolchain`,status:Rg(e),summary:e.versionLine?`Android toolchain: ${e.versionLine}; ${zg(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 Rg(e){return e.versionLine&&e.sdkRoot&&e.license!==`missing`?`pass`:`info`}function zg(e){return e?`ANDROID_HOME/ANDROID_SDK_ROOT set`:`ANDROID_HOME unset`}function Bg(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 Vg(){let e=await qg(`xcodebuild`,[`-version`]);return e?Hg({selectedPath:await qg(`xcode-select`,[`-p`]),versionLine:e}):Gg()}function Hg(e){return{id:`toolchain`,status:Ug(e),summary:Wg(e),evidence:{selectedPath:e.selectedPath??null,xcodeVersion:e.versionLine??null}}}function Ug(e){return e.versionLine?`pass`:`info`}function Wg(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 Gg(){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 Kg(e){if(!e)return`unknown`;try{return await Mr(V.join(e,`licenses`,`android-sdk-license`)),`accepted`}catch{return`missing`}}async function qg(e,t){try{let n=await l(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 Jg(e,t){$(e,await Yg(t))}async function Yg(e){let t=Ct({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 wt(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 Xg(e){let{req:t,sessionName:n,sessionStore:r,androidAdbExecutor:i}=e;if(t.command!==C.doctor)return null;let a=r.get(n),o=Og(t,a),s=$g(r,n),c=[];if(qh(c,{id:`agent-device`,status:`pass`,summary:`agent-device ${ye()} using ${s}`,evidence:{version:ye(),stateDir:s}},...kg(t,{required:o.remote}),...Ag(r,n,a,{remote:o.remote})),o.remote)return n_(c,o);let l=await eg(c,t,a);await Fg(c,a?.device.platform??l?.platform);let u=await e_({androidAdbExecutor:i,checks:c,inventory:l,options:o,session:a,stateDir:s});return await Qg(c,u??Zg(l)),n_(c,o,{device:u,includeMetro:!0,inventory:l})}function Zg(e){let t=(e?.devices??[]).filter(e=>D(e)&&e.kind===`simulator`);return t.find(e=>e.booted===!0)??t[0]}async function Qg(e,t){if(!(!t||!D(t)||t.kind!==`simulator`)&&!(process.platform!==`darwin`||Qn(t))){if(O({type:`command`,status:`progress`,message:`Checking iOS runner build cache (${t.name})...`}),await ht(t)){$(e,{id:`ios-runner-cache`,status:`pass`,summary:`iOS runner artifact cached; first open skips the runner build`});return}lt(t,{}),O({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 $g(e,t){let n=V.dirname(e.resolveSessionDir(t));return V.basename(n)===`sessions`?V.dirname(n):n}async function e_(e){let{checks:t,inventory:n,options:r,session:i,androidAdbExecutor:a,stateDir:o}=e,s=i?.device??tg(t,n,r.targetApp);return s&&await t_(t,{androidAdbExecutor:a,device:s,options:r,session:i}),r.shouldProbeMetro&&$(t,await yg(r.metroHost,r.metroPort,r.kind)),await Jg(t,o),s}async function t_(e,t){let{androidAdbExecutor:n,device:r,options:i,session:a}=t;await Zh(e,{device:r,session:a,targetApp:i.targetApp}),await Yh(e,{androidAdbExecutor:n,device:r,metroPort:i.metroPort,shouldProbeMetro:i.shouldProbeMetro})}function n_(e,t,n={}){let r=Wh(e);return{ok:!0,data:{status:r,summary:Gh(r),kind:t.kind,platform:n.device?T(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:Kh(e)}}}async function r_(e){let{req:t,sessionName:n,logPath:r,sessionStore:i}=e,a=t.positionals?.[0]??``;if(a!==`ios-runner`)return M(`INVALID_ARGS`,`prepare requires a subcommand: ios-runner`);let o=i.get(n),s=t.flags??{},c=U(C.prepare,o,s);if(c)return c;let l=await W({session:o,flags:s,ensureReady:!0});if(!E(l.platform))return M(`UNSUPPORTED_OPERATION`,`prepare ios-runner is only supported on Apple runner platforms`);let u=Date.now(),d=await mt(l,i_(t,o,r,u));return{ok:!0,data:o_(a,l,Math.max(0,Date.now()-u),d)}}function i_(e,t,n,r){let i=a_(e);return{...Er({req:e,logPath:n,traceLogPath:t?.trace?.outPath}),cleanStaleBundles:!0,buildTimeoutMs:i,healthTimeoutMs:i,prepareDeadline:Ye.fromTimeoutMs(i,r),startupTimeoutMs:i}}function a_(e){let t=e.flags?.timeoutMs;return typeof t==`number`&&Number.isFinite(t)&&t>0?t:f}function o_(e,t,n,r){return{action:e,platform:T(t),deviceId:t.id,deviceName:t.name,kind:t.kind,durationMs:n,...r,timing:s_(n,r),message:`Prepared Apple runner: ${t.name}`}}function s_(e,t){let n=c_(t.buildMs),r=l_(t.connectMs),i=l_(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 c_(e){return e===void 0?void 0:l_(e)}function l_(e){return Number.isFinite(e)?Math.max(0,Math.round(e)):0}async function u_(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=U(a,l,u);if(d)return d;let f=await W({session:l,flags:u,ensureReady:!0}),p=N(a,f);if(p)return p;let m=await j(f,a,o,t.flags?.out,{...A(r,t.flags,l?.appBundleId,l?.trace?.outPath)});if(l){let e=c?await c(l,m,f):l;Dr(i,e,t,a,m??{},{positionals:s??o}),e!==l&&i.set(n,e)}return{ok:!0,data:m??{}}}async function d_(e){let{req:t,sessionName:n,logPath:r,sessionStore:i}=e,a=i.get(n),o=t.flags??{},s=U(C.clipboard,a,o);if(s)return s;let c=(t.positionals?.[0]??``).toLowerCase();if(c!==`read`&&c!==`write`)return M(`INVALID_ARGS`,`clipboard requires a subcommand: read or write`);let l=await W({session:a,flags:o,ensureReady:!0}),u=N(C.clipboard,l);if(u)return u;let d=await j(l,C.clipboard,t.positionals??[],t.flags?.out,{...A(r,t.flags,a?.appBundleId,a?.trace?.outPath)});return Dr(i,a,t,t.command,d??{}),{ok:!0,data:{platform:T(l),...d??{}}}}async function f_(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,leaseRegistry:a=new Qt,leaseLifecycleProvider:o,invoke:s,invokeReplayAction:c,androidAdbExecutor:l}=e;if(t.command===C.doctor)return await Xg({req:t,sessionName:n,sessionStore:i,androidAdbExecutor:l});if(Un(t.command)===`inventory`)return await eo({req:t,sessionName:n,sessionStore:i});if(t.command===`runtime`)return await Ki({req:t,sessionName:n,sessionStore:i});if(Un(t.command)===`state`)return await so({req:t,sessionName:n,logPath:r,sessionStore:i});if(t.command===C.clipboard)return await d_({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`?M(`SESSION_NOT_FOUND`,`iOS keyboard action requires an active session so the target app stays foregrounded. Run open first.`):await u_({req:t,sessionName:n,logPath:r,sessionStore:i,command:C.keyboard,positionals:t.positionals??[]})}if(Un(t.command)===`observability`)return await ec({req:t,sessionName:n,sessionStore:i,androidAdbExecutor:l});if(t.command===C.prepare)return await r_({req:t,sessionName:n,logPath:r,sessionStore:i});if(t.command===C.install||t.command===C.reinstall)return await Ja({req:t,command:t.command,sessionName:n,sessionStore:i,deployOps:t.command===C.install?qa:Ka});if(t.command===ae.installSource)return await Wr({req:t,sessionName:n,sessionStore:i});if(t.command===ae.releaseMaterializedPaths)return await $r({req:t});if(t.command===C.push){let e=t.positionals?.[0]?.trim(),a=t.positionals?.[1]?.trim();return!e||!a?M(`INVALID_ARGS`,`push requires <bundle|package> <payload.json|inline-json>`):await u_({req:t,sessionName:n,logPath:r,sessionStore:i,command:C.push,positionals:[e,p_(a,t.meta?.cwd)],recordPositionals:[e,a]})}return t.command===C.triggerAppEvent?await u_({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 ya(e.device,n,e.appBundleId,ga)??e.appBundleId:e.appBundleId;return{...e,appBundleId:r}}}):t.command===C.open?await Na({req:t,sessionName:n,logPath:r,sessionStore:i}):Un(t.command)===`replay`?await Uh({req:t,sessionName:n,logPath:r,sessionStore:i,leaseRegistry:a,invoke:c??s}):t.command===C.batch?await $a(t,n,s):t.command===C.close?await Ha({req:t,sessionName:n,logPath:r,sessionStore:i,leaseRegistry:a,leaseLifecycleProvider:o}):null}function p_(e,t){let n=Xt(e,{subject:`Push payload`,cwd:t,expandPath:(e,t)=>k.expandHome(e,t)});return n.kind===`file`?n.path:n.text}export{f_ as handleSessionCommands};
|