agent-device 0.17.9 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +4 -0
  2. package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.17.9.apk → agent-device-android-multitouch-helper-0.18.0.apk} +0 -0
  3. package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.18.0.apk.sha256 +1 -0
  4. package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.17.9.manifest.json → agent-device-android-multitouch-helper-0.18.0.manifest.json} +4 -4
  5. package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.17.9.apk → agent-device-android-snapshot-helper-0.18.0.apk} +0 -0
  6. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.18.0.apk.sha256 +1 -0
  7. package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.17.9.manifest.json → agent-device-android-snapshot-helper-0.18.0.manifest.json} +6 -6
  8. package/dist/src/1848.js +4 -0
  9. package/dist/src/2577.js +1 -1
  10. package/dist/src/2948.js +20 -20
  11. package/dist/src/4291.js +1 -1
  12. package/dist/src/4723.js +1 -1
  13. package/dist/src/5341.js +1 -0
  14. package/dist/src/5643.js +1 -0
  15. package/dist/src/6918.js +1 -1
  16. package/dist/src/8275.js +2 -2
  17. package/dist/src/8936.js +1 -0
  18. package/dist/src/9414.js +1 -0
  19. package/dist/src/9581.js +4 -4
  20. package/dist/src/9722.js +32 -37
  21. package/dist/src/9919.js +5 -5
  22. package/dist/src/apple.js +1 -1
  23. package/dist/src/apps.js +10 -10
  24. package/dist/src/batch.d.ts +20 -3
  25. package/dist/src/batch.js +1 -1
  26. package/dist/src/cli-help.js +111 -35
  27. package/dist/src/cli.js +22 -25
  28. package/dist/src/contracts.d.ts +14 -0
  29. package/dist/src/device-ready.js +2 -0
  30. package/dist/src/find.js +1 -1
  31. package/dist/src/index.d.ts +67 -16
  32. package/dist/src/interaction.js +1 -1
  33. package/dist/src/internal/bin.js +1 -1
  34. package/dist/src/lease.js +1 -1
  35. package/dist/src/metro.js +1 -1
  36. package/dist/src/react-native.js +1 -1
  37. package/dist/src/record-trace-recording.js +3 -3
  38. package/dist/src/remote-config.d.ts +17 -11
  39. package/dist/src/selector-runtime.js +1 -1
  40. package/dist/src/session.js +11 -8
  41. package/dist/src/simulator.js +2 -0
  42. package/dist/src/snapshot.js +1 -1
  43. package/package.json +1 -1
  44. package/server.json +2 -2
  45. package/skills/agent-device/SKILL.md +1 -0
  46. package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.17.9.apk.sha256 +0 -1
  47. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.17.9.apk.sha256 +0 -1
  48. package/dist/src/2133.js +0 -1
  49. package/dist/src/5628.js +0 -1
  50. package/dist/src/8358.js +0 -4
@@ -1,4 +1,7 @@
1
- import{__webpack_require__ as e}from"./rslib-runtime.js";import t from"node:fs";import r from"node:path";import a from"node:vm";import{setTimeout as n}from"node:timers/promises";import{asAppError as i,normalizeError as o,AppError as s}from"./733.js";import{startAndroidSimpleperfProfile as l,APPLE_MEMGRAPH_SNAPSHOT_DESCRIPTION as u,dispatchCommand as p,sessionMatchesScope as d,selectorTargetsSessionDevice as c,appendAppLogMarker as f,resolveCommandDevice as m,hasRuntimeTransportHints as h,sampleAppleFramePerf as g,captureAppleMemorySnapshot as w,getSessionCommandKind as y,inferFillText as v,startAndroidPerfettoTrace as A,stopIosRunnerSession as S,captureAndroidHeapSnapshot as I,stopAppleXctracePerfCapture as b,resolvePublicSessionName as _,writeAppleXctracePerfReport as k,requireSessionOrExplicitSelector as N,cleanupUploadedArtifact as D,resolveSessionRequestLogPath as x,ANDROID_FRAME_SAMPLE_METHOD as R,refreshSessionDeviceIfNeeded as M,buildAppleFrameSamplingMetadata as P,createRequestCanceledError as L,registerRequestAbort as O,errorResponse as E,settleIosSimulator as C,readReplayTestActionProgress as $,buildSessionRecoveryHint as V,applyRuntimeHintsToApp as U,withKeyedLock as F,resolveTargetDevice as q,getAppLogPathMetadata as G,uniqueStrings as T,setSessionSnapshot as B,sampleAndroidMemoryPerf as H,shutdownDeviceTarget as K,ANDROID_HPROF_SNAPSHOT_DESCRIPTION as j,sampleAndroidCpuPerf as z,clearRuntimeHintsFromApp as W,ANDROID_HPROF_SNAPSHOT_METHOD as J,startAppleXctracePerfCapture as X,buildAppleSamplingMetadata as Y,getSnapshotReferenceFrame as Z,clearAppLogFiles as Q,handleCloseCommand as ee,prepareIosRunner as et,session_device_utils_hasExplicitSessionFlag as er,readSessionNetworkCapture as ea,cleanupRetainedMaterializedPaths as en,isImplicitSessionScopeConflict as ei,resolveSessionRunnerLogPath as eo,ANDROID_CPU_SAMPLE_DESCRIPTION as es,buildSnapshotState as el,resolveLogBackend as eu,stopAndroidSimpleperfProfile as ep,context_contextFromFlags as ed,listDeviceInventory as ec,SessionStore as ef,ANDROID_CPU_SAMPLE_METHOD as em,buildAppleMemorySnapshotSupport as eh,stopAndroidPerfettoTrace as eg,isRequestCanceled as ew,resolveRequestTrackingId as ey,retainMaterializedPaths as ev,runAppLogDoctor as eA,resolvePayloadInput as eS,prepareUploadedArtifact as eI,resetAndroidFramePerfStats as eb,ANDROID_FRAME_SAMPLE_DESCRIPTION as e_,withReplayTestActionProgress as ek,markRequestCanceled as eN,stopAppLog as eD,resolveImplicitSessionScope as ex,APPLE_MEMGRAPH_SNAPSHOT_METHOD as eR,ensureDeviceReady as eM,ANDROID_MEMORY_SAMPLE_DESCRIPTION as eP,prewarmIosRunnerSession as eL,clearRequestCanceled as eO,resolveAndroidEmulatorAvdName as eE,writeAndroidSimpleperfReport as eC,resolveFrontmostMacOsApp as e$,isCommandSupportedOnDevice as eV,sampleApplePerfMetrics as eU,sampleAndroidFramePerf as eF,ANDROID_MEMORY_SAMPLE_METHOD as eq,getRequestSignal as eG,markAndroidSnapshotFreshness as eT,startAppLog as eB,emitRequestProgress as eH}from"./9722.js";import{isPerfAction as eK,isPerfSubject as ej,pointFromPercent as ez,PERF_AREA_ERROR_MESSAGE as eW,buildSwipeGesturePlan as eJ,PERF_ACTION_ERROR_MESSAGE as eX,buildSnapshotDisplayLines as eY,isPerfKind as eZ,isPerfMemoryKind as eQ,pointInsideRect as e0,successText as e1,clampGesturePoint as e3,resolveDeployResultTarget as e2,PERF_MEMORY_KIND_ERROR_MESSAGE as e5,PERF_KIND_ERROR_MESSAGE as e4,isPerfArea as e6,LOG_ACTION_VALUES as e8,withSuccessText as e7,clampToRange as e9,parseSessionSurface as te,resolveInstallFromSourceResultTarget as tt,readReactNativeOverlayActionNodes as tr,detectReactNativeOverlay as ta,PERF_SUBJECT_ERROR_MESSAGE as tn}from"./2948.js";import{isApplePlatform as ti,resolveAppleSimulatorSetPathForSelector as to,normalizePlatformSelector as ts,matchesPlatformSelector as tl}from"./5910.js";import{resolveIosSimulatorDeviceSetPath as tu,classifyAndroidAppTarget as tp,resolveIosDeviceDeepLinkBundleId as td,isInfrastructureBootFailureReason as tc,isWebUrl as tf,resolveAndroidSerialAllowlist as tm,isDeepLinkTarget as th,formatAndroidInstalledPackageRequiredMessage as tg,listAndroidApps as tw}from"./3340.js";import{getDiagnosticsMeta as ty,emitDiagnostic as tv}from"./432.js";import{runBatch as tA,mergeParentFlags as tS}from"./6918.js";import{assertResolvedAppsFilter as tI}from"./2748.js";import{listIosApps as tb}from"./apps.js";import{resolveWebProvider as t_}from"./provider.js";import{NETWORK_INCLUDE_MODES as tk}from"./4291.js";import{unsupportedCommand as tN,readEnvMap as tD,parseReplayScriptDetailed as tx,readReplayShellEnvSource as tR,normalizeCommandList as tM,normalizePlatform as tP,readReplayCliEnvEntries as tL,parseMaestroYamlDocuments as tO,parseAbsolutePoint as tE,readReplayScriptMetadata as tC,parseReplayCliEnvEntries as t$,collectReplayShellEnv as tV,support_action as tU,isPlainRecord as tF,requireAppId as tq,assertOnlyKeys as tG,resolveMaestroString as tT,requireStringValue as tB,parseMaestroPoint as tH,unsupportedMaestroSyntax as tK,readTimeoutMs as tj,writeReplayScript as tz,buildReplayVarScope as tW,resolveReplayAction as tJ,mergeReplayVarScopeValues as tX}from"./4428.js";import{runCmdSync as tY}from"./8875.js";import{readSnapshotDiagnosticsSummary as tZ,summarizeSnapshotTimingSamples as tQ,mergeSnapshotDiagnostics as t0}from"./8358.js";import{resolveSelectorChain as t1,extractNodeText as t3,findSnapshotAncestor as t2,isDescendantOfSnapshotNode as t5,splitIsSelectorArgs as t4,buildSelectorChainForNode as t6,buildSnapshotNodeByIndex as t8,matchesSelector as t7,normalizeType as t9}from"./9836.js";import{formatScriptActionSummary as re,evaluateIsPredicate as rt,isTouchTargetCommand as rr}from"./2577.js";import{splitSelectorFromArgs as ra,normalizeText as rn,tryParseSelectorChain as ri,parseSelectorChain as ro}from"./587.js";import{sleep as rs}from"./5560.js";import{handleRecordCommand as rl}from"./record-trace-recording.js";import{INTERNAL_COMMANDS as ru,PUBLIC_COMMANDS as rp}from"./2133.js";import{trimRuntimeValue as rd}from"./5628.js";var rc={};async function rf(e){var t;let r="ios"===(t=e.flags?.platform)||"android"===t?t:void 0;if(e.session){if(r&&e.session.device.platform!==r)throw new s("INVALID_ARGS",`install_from_source requested platform ${r}, but session is bound to ${e.session.device.platform}`);return await eM(e.session.device),e.session.device}if(!r)throw new s("INVALID_ARGS",'install_from_source requires platform "ios" or "android" when no session is provided');let a=await q(e.flags??{});return await eM(a),a}async function rm(e){let{prepared:t,retention:r,req:a,session:n,sessionName:i}=e;if(r.enabled)return await ev({archivePath:t.archivePath,installablePath:t.installablePath,tenantId:a.meta?.tenantId,sessionName:n?i:void 0,ttlMs:r.ttlMs})}function rh(e){return e?{...e.archivePath?{archivePath:e.archivePath}:{},installablePath:e.installablePath,materializationId:e.materializationId,materializationExpiresAt:e.expiresAt}:{}}async function rg(e){let{req:t,sessionName:r,sessionStore:a}=e,n=a.get(r);try{let e,i,o=(e=function(e){let t=e.meta?.installSource;if(!t)throw new s("INVALID_ARGS","install_from_source requires a source payload");switch(t.kind){case"url":if(!t.url||0===t.url.trim().length)throw new s("INVALID_ARGS","install_from_source url source requires a non-empty url");return t;case"path":if(!t.path||0===t.path.trim().length)throw new s("INVALID_ARGS","install_from_source path source requires a non-empty path");return t;case"github-actions-artifact":throw new s("UNSUPPORTED_OPERATION","install_from_source github-actions-artifact sources require a compatible remote daemon");default:throw new s("UNSUPPORTED_OPERATION",`install_from_source ${String(t.kind)} sources require a compatible remote daemon`)}}(t),(i=t.meta?.uploadedArtifactId)&&"path"===e.kind?{source:{kind:"path",path:eI(i,t.meta?.tenantId)},cleanup:()=>{D(i)}}:{source:e,cleanup:()=>{}}),l=function(e){let t=e.meta?.retainMaterializedPaths===!0,r=e.meta?.materializedPathRetentionMs;if(!t)return{enabled:!1};if(void 0!==r&&r<=0)throw new s("INVALID_ARGS","install_from_source retentionMs must be a positive integer");return{enabled:!0,ttlMs:r}}(t),u=await rf({session:n,flags:t.flags});if(!eV("install",u))return E("UNSUPPORTED_OPERATION","install_from_source is not supported on this device");let p=eG(t.meta?.requestId),d=async(e,i)=>{let s;try{var u;s=await rm({prepared:e,retention:l,req:t,session:n,sessionName:r});let o=await i(s),p=e7(o,(u=o,`Installed: ${tt(u)}`));return!function(e){let{session:t,sessionStore:r,req:a,data:n}=e;t&&r.recordAction(t,{command:"install_source",positionals:[],flags:a.flags??{},result:n})}({session:n,sessionStore:a,req:t,data:p}),{ok:!0,data:p}}catch(e){throw s&&await en(s.materializationId,t.meta?.tenantId).catch(()=>{}),e}finally{await e.cleanup(),o.cleanup()}};if("ios"===u.platform){let{installIosInstallablePath:e}=await import("./apps.js"),{prepareIosInstallArtifact:t}=await import("./apps.js"),r=await t(o.source,{signal:p});return await d(r,async t=>{if(await e(u,r.installablePath),!r.bundleId)throw new s("COMMAND_FAILED","Installed iOS app identity could not be resolved from the artifact");return{...rh(t),bundleId:r.bundleId,...r.appName?{appName:r.appName}:{},launchTarget:r.bundleId}})}let{prepareAndroidInstallArtifact:c}=await import("./3340.js"),{installAndroidInstallablePathAndResolvePackageName:f}=await import("./3340.js"),m=await c(o.source,{signal:p});return await d(m,async e=>{let t=await f(u,m.installablePath,m.packageName);if(!t)throw new s("COMMAND_FAILED","Installed Android app identity could not be resolved from the artifact or device state");let{inferAndroidAppName:r}=await import("./3340.js"),a=r(t);return{...rh(e),packageName:t,...a?{appName:a}:{},launchTarget:t}})}catch(e){return{ok:!1,error:o(e)}}}async function rw(e){let{req:t}=e;try{let e=t.meta?.materializationId?.trim();if(!e)throw new s("INVALID_ARGS","release_materialized_paths requires a materializationId");return await en(e,t.meta?.tenantId),{ok:!0,data:{released:!0,materializationId:e}}}catch(e){return{ok:!1,error:o(e)}}}e.r(rc),e.d(rc,{handleSessionCommands:()=>oV});let ry=["platform","metroHost","metroPort","bundleUrl","launchUrl"];function rv(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>void 0!==e&&""!==e).length:0}function rA(e,t){if(void 0!==e){if("string"!=typeof e)throw new s("INVALID_ARGS",`Invalid open runtime ${t}: expected string.`);return rd(e)}}function rS(e){if(void 0!==e){if(!Number.isInteger(e)||e<1||e>65535)throw new s("INVALID_ARGS",`Invalid runtime metroPort: ${String(e)}. Use an integer between 1 and 65535.`);return e}}function rI(e){if("ios"===e||"android"===e)return e}async function rb(e){let{replacedStoredRuntime:t,previousRuntime:r,runtime:a,session:n}=e;!t||!n?.appBundleId||!h(r)||h(a)||await W({device:n.device,appId:n.appBundleId})}async function r_(e){var t,r;let{req:a,sessionName:n,sessionStore:i}=e,o=(a.positionals?.[0]??"show").toLowerCase(),s=i.get(n),l=i.getRuntimeHints(n);if(!["set","show","clear"].includes(o))return E("INVALID_ARGS","runtime requires set, show, or clear");if("clear"===o){h(l)&&s?.appBundleId&&await W({device:s.device,appId:s.appBundleId});let e=i.clearRuntimeHints(n);return{ok:!0,data:{session:n,cleared:e}}}if("show"===o)return{ok:!0,data:{session:n,configured:!!l,runtime:l}};let u=rI(ts(a.flags?.platform)??l?.platform??s?.device.platform);if(!u)return E("INVALID_ARGS","runtime set only supports iOS and Android sessions. Pass --platform ios|android or open an iOS/Android session first.");if(s&&s.device.platform!==u)return E("INVALID_ARGS",`runtime set targets ${u}, but session "${n}" is already bound to ${s.device.platform}.`);let p={platform:(t=a.flags,r={platform:u,metroHost:rd(t?.metroHost),metroPort:rS(t?.metroPort),bundleUrl:rd(t?.bundleUrl),launchUrl:rd(t?.launchUrl)}).platform??l?.platform,metroHost:r.metroHost??l?.metroHost,metroPort:r.metroPort??l?.metroPort,bundleUrl:r.bundleUrl??l?.bundleUrl,launchUrl:r.launchUrl??l?.launchUrl};return 0===rv(p)?E("INVALID_ARGS","runtime set requires at least one hint such as --metro-host, --metro-port, --bundle-url, or --launch-url."):(i.setRuntimeHints(n,p),{ok:!0,data:{session:n,configured:!0,runtime:p}})}let rk="open-command-roundtrip",rN="Not implemented for this platform in this release.";function rD(e){let{existingSession:t,sessionName:r,sessionScope:a,device:n,surface:i,appBundleId:o,appName:s,saveScript:l}=e;return t?{...t,device:n,surface:i,appBundleId:o,appName:s,recordSession:t.recordSession||l,snapshot:void 0}:{name:r,sessionScope:a,device:n,createdAt:Date.now(),surface:i,appBundleId:o,appName:s,recordSession:l,actions:[]}}let rx=new Set(["app","desktop","frontmost-app"]);async function rR(e){if("app"===e||"desktop"===e||"menubar"===e)return{};let t=await e$();return{appBundleId:t.bundleId,appName:t.appName}}async function rM(e,t,r){if(("ios"===e.platform||"macos"===e.platform)&&t)return th(t)?"macos"===e.platform?void 0:"device"===e.kind?td(r,t):tf(t)?void 0:r??await rP(e,t):await rL(e,t)}async function rP(e,t){try{let{resolveIosSimulatorDeepLinkBundleId:r}=await import("./apps.js");return await r(e,t)}catch{return}}async function rL(e,t){try{let{resolveIosApp:r}=await import("./apps.js");return await r(e,t)}catch{return}}async function rO(e,t){if(!("android"!==e.platform||!t||th(t)))try{let{resolveAndroidApp:r}=await import("./3340.js"),a=await r(e,t);return"package"===a.type?a.value:void 0}catch{return}}async function rE(e,t,r){if(r||"android"!==e.platform||!t||!th(t))return r;try{let{getAndroidAppState:t}=await import("./3340.js"),a=await t(e);return a.package?.trim()||r}catch{return r}}async function rC(e,t,r,a){return await rM(e,t,r)??await a(e,t)??("android"===e.platform&&t&&th(t)?r:void 0)}function r$(e){return E("INVALID_ARGS",e)}function rV(e,t,r,a){try{return function(e){let{device:t,surfaceFlag:r,openTarget:a,existingSurface:n}=e;if(("macos"===t.platform||"linux"===t.platform)&&!r)return n??"app";if("linux"===t.platform){if(!r)return"app";let e=te(r);if(!rx.has(e))throw new s("INVALID_ARGS",`Linux supports --surface app, desktop, and frontmost-app (got "${r}")`);if("app"!==e&&a)throw new s("INVALID_ARGS",`open --surface ${e} does not accept an app target`);return e}if("macos"!==t.platform){if(r)throw new s("INVALID_ARGS","surface is only supported on macOS and Linux");return"app"}let i=r?te(r):"app";if("app"!==i&&"menubar"!==i&&a)throw new s("INVALID_ARGS",`open --surface ${i} does not accept an app target`);return i}({device:e,surfaceFlag:t,openTarget:r,existingSurface:a})}catch(e){return E(e instanceof s?e.code:"INVALID_ARGS",String(e.message))}}function rU(e){let{shouldRelaunch:t,openTarget:r,surface:a,device:n}=e;return t?r&&th(r)?r$("open --relaunch does not support URL targets."):"app"!==a?r$("open --relaunch is supported only for app surfaces."):"android"===n.platform&&r&&"binary"===tp(r)?r$(tg(r)):null:null}async function rF(e){let{req:t,sessionName:r,sessionStore:a,device:n,surface:o,openTarget:l,existingSession:u}=e;await eM(n,{deviceHub:t.flags?.deviceHub===!0});let{appBundleId:p,appName:d}=await rq({device:n,surface:o,openTarget:l,existingAppBundleId:u?.appBundleId}),c=function(e){try{return{ok:!0,data:function(e){let{req:t,sessionStore:r,sessionName:a,device:n}=e,i=r.getRuntimeHints(a),o=function(e){let{runtime:t,sessionName:r,platform:a}=e;if(void 0===t)return;if(!t||"object"!=typeof t||Array.isArray(t))throw new s("INVALID_ARGS","open runtime must be an object.");let n=Object.keys(t).find(e=>!ry.includes(e));if(n)throw new s("INVALID_ARGS",`Invalid open runtime field: ${n}. Supported fields are ${ry.join(", ")}.`);return{platform:function(e,t,r){if(void 0===e)return r;if("ios"!==e&&"android"!==e)throw new s("INVALID_ARGS",`Invalid open runtime platform: ${String(e)}. Use "ios" or "android".`);if(r&&e!==r)throw new s("INVALID_ARGS",`open runtime targets ${e}, but session "${t}" is bound to ${r}.`);return e}(t.platform,r,a),metroHost:rA(t.metroHost,"metroHost"),metroPort:function(e){if(void 0!==e){if("number"!=typeof e)throw new s("INVALID_ARGS","Invalid open runtime metroPort: expected integer.");return rS(e)}}(t.metroPort),bundleUrl:rA(t.bundleUrl,"bundleUrl"),launchUrl:rA(t.launchUrl,"launchUrl")}}({runtime:t.runtime,sessionName:a,platform:rI(n.platform)});return void 0===t.runtime?{runtime:function(e,t,r){let a=e.getRuntimeHints(t);if(!a)return;let n=r?.platform,i=rI(n);if(a.platform&&r&&!i)throw new s("INVALID_ARGS",`Session runtime hints are only supported on iOS and Android sessions, but session "${t}" is bound to ${n}.`);if(a.platform&&i&&a.platform!==i)throw new s("INVALID_ARGS",`Session runtime hints target ${a.platform}, but session "${t}" is bound to ${n}. Clear the runtime hints or use a different session.`);return i&&a.platform!==i?{...a,platform:i}:a}(r,a,n),previousRuntime:i,replacedStoredRuntime:!1}:{runtime:o&&rv(o)>0?o:void 0,previousRuntime:i,replacedStoredRuntime:!0}}(e)}}catch(t){let e=i(t);return E(e.code,e.message,e.details)}}({req:t,sessionStore:a,sessionName:r,device:n});if(!c.ok)return{type:"response",response:c};if(u){let{runtime:e,previousRuntime:t,replacedStoredRuntime:r}=c.data;await rb({replacedStoredRuntime:r,previousRuntime:t,runtime:e,session:u})}return{type:"details",details:{appBundleId:p,appName:d,runtime:c.data.runtime}}}async function rq(e){let{device:t,surface:r,openTarget:a,existingAppBundleId:n}=e,i=await rR(r);return{appBundleId:i.appBundleId??await rC(t,a,n,rO),appName:i.appName??a}}let rG=new Map;async function rT(e){let{device:t,closeTarget:r,outFlag:a,context:n}=e;"android"!==t.platform&&await S(t.id),await p(t,"close",[r],a,n),await C(t,300)}async function rB(e){var t,r;let a,{runtime:n,device:i,req:o,logPath:s,appBundleId:l,traceLogPath:u,openPositionals:d}=e,c=n?.launchUrl;if(!c||0===d.length||d.length>1)return;let f=d[0]?.trim();!f||th(f)||await p(i,"open",[c],o.flags?.out,{...(t=s,r=o.flags,a=ed(t,r,l,u),delete a.launchConsole,delete a.launchArgs,a)})}async function rH(e){var t,r,a,n;let i,{req:o,sessionName:s,sessionStore:l,logPath:u,device:d,openTarget:c,openPositionals:f,appName:m,surface:h,appBundleId:g,runtime:w,existingSession:y}=e,v=o.flags?.relaunch===!0,A=y?.trace?.outPath,S=g,I=Date.now(),b={};if(v&&c){let e=S??c,t=Date.now();await rT({device:d,closeTarget:e,outFlag:o.flags?.out,context:{...ed(u,o.flags,S??y?.appBundleId,A)}}),b.relaunchCloseDurationMs=Math.max(0,Date.now()-t)}let k=Date.now();await U({device:d,appId:S,runtime:w}),b.runtimeHintsDurationMs=Math.max(0,Date.now()-k);let N="ios"===d.platform&&"app"===h&&f.length>0,D={verbose:o.flags?.verbose,logPath:u,traceLogPath:A,requestId:o.meta?.requestId,iosXctestrunFile:o.flags?.iosXctestrunFile,iosXctestDerivedDataPath:o.flags?.iosXctestDerivedDataPath,iosXctestEnvDir:o.flags?.iosXctestEnvDir},R=o.flags?.maestro?.prewarmRunnerBeforeOpen===!0;if(N&&S&&(b.runnerPrewarmKind="session",b.runnerPrewarmScheduled=!0,R)){i=eL(d,{...D,propagateError:!0});let e=Date.now();await i,b.runnerPrewarmWaited=!0,b.runnerPrewarmDurationMs=Math.max(0,Date.now()-e)}let M=Date.now(),P=await rK({req:o,sessionName:s,sessionStore:l,device:d,surface:h,sessionAppBundleId:S,appName:m,existingSession:y});if("response"===P.type)return P.response;let O=P.session??y;await p(d,"open",f,o.flags?.out,{...ed(u,o.flags,S)}),b.openDispatchDurationMs=Math.max(0,Date.now()-M);let $=Date.now();if(await rB({runtime:w,device:d,req:o,logPath:u,appBundleId:S,traceLogPath:A,openPositionals:f}),b.launchUrlDurationMs=Math.max(0,Date.now()-$),N&&S&&!i&&(i=eL(d,D)),v&&i&&!0!==b.runnerPrewarmWaited){let e=Date.now();await i,b.runnerPrewarmWaited=!0,b.runnerPrewarmDurationMs=Math.max(0,Date.now()-e)}else i&&!0!==b.runnerPrewarmWaited&&(b.runnerPrewarmWaited=!1);S=await rE(d,c,S),"android"===d.platform&&S&&await eb(d,S);let V=c?(t=S,{durationMs:Math.max(0,Date.now()-M),measuredAt:new Date().toISOString(),method:rk,appTarget:c,appBundleId:t}):void 0,F=Date.now();if(await C(d,300),b.postOpenSettleDurationMs=Math.max(0,Date.now()-F),ew(o.meta?.requestId)){let e=L();return E(e.code,e.message,e.details)}y&&eT(y,"open",y.snapshot);let q=rD({existingSession:O,sessionName:y?.name??_(o),sessionScope:y?.sessionScope??ex(o),device:d,surface:h,appBundleId:S,appName:m,saveScript:!!o.flags?.saveScript});void 0!==o.runtime&&(r=l,a=s,(n=w)&&(0===rv(n)?r.clearRuntimeHints(a):r.setRuntimeHints(a,n)));let G=l.ensureSessionDir(s),T=x(G,o.meta?.requestId??ty().requestId);b.totalDurationMs=Math.max(0,Date.now()-I);let B=function(e){let{sessionName:t,sessionStateDir:r,runnerLogPath:a,requestLogPath:n,appName:i,appBundleId:o,surface:s,startup:l,timing:u,device:p,runtime:d,runtimeHintCount:c}=e,f={session:t,surface:s,sessionStateDir:r,runnerLogPath:a,requestLogPath:n};return i&&(f.appName=i),o&&(f.appBundleId=o),l&&(f.startup=l),u&&(f.timing=u),d&&c(d)>0&&(f.runtime=d),p&&(f.platform=p.platform,f.target=p.target??"mobile",f.device=p.name,f.id=p.id,f.kind=p.kind,"android"===p.platform&&(f.serial=p.id)),p?.platform==="ios"&&(f.device_udid=p.id,f.ios_simulator_device_set=p.simulatorSetPath??null),{...f,...e1(`Opened: ${i??o??t}`)}}({sessionName:q.name,sessionStateDir:G,runnerLogPath:eo(G),requestLogPath:T,appName:m,appBundleId:S,surface:h,startup:V,timing:b,device:d,runtime:w,runtimeHintCount:rv});return l.recordAction(q,{command:"open",positionals:f,flags:o.flags??{},runtime:void 0!==o.runtime?w:void 0,result:B}),l.set(s,q),{ok:!0,data:B}}async function rK(e){let{req:t,sessionName:r,sessionStore:a,device:n,surface:i,sessionAppBundleId:o,appName:s,existingSession:l}=e,u=t.internal?.openLifecycle?.beforeDispatch;if(!u)return{type:"session",session:l};let p=rD({existingSession:l,sessionName:l?.name??_(t),sessionScope:l?.sessionScope??ex(t),device:n,surface:i,appBundleId:o,appName:s,saveScript:!!t.flags?.saveScript});a.set(r,p);let d=await u(p);return d&&!d.ok?{type:"response",response:d}:{type:"session",session:a.get(r)??p}}async function rj(e){let{req:t,sessionName:r,logPath:a,sessionStore:n}=e,i=n.get(r);if(i){let e=t.flags?.relaunch===!0,o=t.positionals?.[0],s=o??(e?i.appName:void 0),l=rV(i.device,t.flags?.surface,s,i.surface);if("string"!=typeof l)return l;if(!s&&"app"===l)return e?r$("open --relaunch requires an app name or an active session app."):r$("Session already active. Close it first or pass a new --session name.");let u=rU({shouldRelaunch:e,openTarget:s,surface:l,device:i.device});if(u)return u;let p=await M(i.device),d=await rF({req:t,sessionName:r,sessionStore:n,device:p,surface:l,openTarget:s,existingSession:i});return"response"===d.type?d.response:await rH({req:t,sessionName:r,sessionStore:n,logPath:a,device:p,openTarget:s,openPositionals:o?t.positionals??[]:s?[s]:[],appBundleId:d.details.appBundleId,appName:d.details.appName,runtime:d.details.runtime,surface:l,existingSession:i})}let o=t.flags?.relaunch===!0,s=t.positionals?.[0];if(o&&!s)return r$("open --relaunch requires an app argument.");let l=function(e){let{shouldRelaunch:t,openTarget:r,platform:a}=e;return t?r&&th(r)?r$("open --relaunch does not support URL targets."):"android"===a&&r&&"binary"===tp(r)?r$(tg(r)):null:null}({shouldRelaunch:o,openTarget:s,platform:t.flags?.platform==="android"?"android":void 0});if(l)return l;let u=await q(t.flags??{}),p=rV(u,t.flags?.surface,s);if("string"!=typeof p)return p;let d=rU({shouldRelaunch:o,openTarget:s,surface:p,device:u});return d||await F(rG,u.id,async()=>{let e=n.toArray().find(e=>e.device.id===u.id);if(e)return ei(t,e)?E("DEVICE_IN_USE","Device is already in use by another workspace session.",{deviceId:u.id,deviceName:u.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:u.id,deviceName:u.name,hint:V(e,"device-in-use")});let i=await rF({req:t,sessionName:r,sessionStore:n,device:u,surface:p,openTarget:s});return"response"===i.type?i.response:await rH({req:t,sessionName:r,sessionStore:n,logPath:a,device:u,openTarget:s,openPositionals:t.positionals??[],appBundleId:i.details.appBundleId,appName:i.details.appName,runtime:i.details.runtime,surface:p})})}let rz={ios:async(e,t,r)=>{let{reinstallIosApp:a}=await import("./apps.js");return await a(e,t,r)},android:async(e,t,r)=>{let{reinstallAndroidApp:a}=await import("./3340.js");return await a(e,t,r)}},rW={ios:async(e,t,r)=>{let{installIosApp:a}=await import("./apps.js"),n=await a(e,r,{appIdentifierHint:t});return{bundleId:n.bundleId,appName:n.appName,launchTarget:n.launchTarget}},android:async(e,t,r)=>{let{installAndroidApp:a}=await import("./3340.js"),n=await a(e,r);return{package:n.packageName,appName:n.appName,launchTarget:n.launchTarget}}};async function rJ(e){let{req:r,command:a,sessionName:n,sessionStore:i,deployOps:o}=e,s=i.get(n),l=r.flags??{},u=N(a,s,l);if(u)return u;let p=r.positionals?.[0]?.trim(),d=r.positionals?.[1]?.trim();if(!p||!d)return E("INVALID_ARGS",`${a} requires: ${a} <app> <path-to-app-binary>`);let c=r.meta?.uploadedArtifactId;try{var f;let e,n=c?eI(c,r.meta?.tenantId):ef.expandHome(d);if(!t.existsSync(n))return E("INVALID_ARGS",`App binary not found: ${n}`);let u=await m({session:s,flags:l,ensureReady:!1});if(!eV(a,u))return E("UNSUPPORTED_OPERATION",`${a} is not supported on this device`);if("ios"===u.platform){let t=await o.ios(u,p,n),r=t.bundleId;e=r?{app:p,appPath:n,platform:"ios",appId:r,bundleId:r,appName:t.appName,launchTarget:t.launchTarget}:{app:p,appPath:n,platform:"ios",appName:t.appName,launchTarget:t.launchTarget}}else{let t=await o.android(u,p,n),r=t.package;e=r?{app:p,appPath:n,platform:"android",appId:r,package:r,packageName:r,appName:t.appName,launchTarget:t.launchTarget}:{app:p,appPath:n,platform:"android",appName:t.appName,launchTarget:t.launchTarget}}let h=e7(e,(f=e,`Installed: ${f.appName??e2(f)}`));return s&&i.recordAction(s,{command:a,positionals:r.positionals??[],flags:r.flags??{},result:h??{}}),{ok:!0,data:h}}finally{c&&D(c)}}async function rX(e,t,r){return await tA(e,t,r)}async function rY(e){let{req:t,sessionName:r,sessionStore:a}=e;if("session_list"===t.command){let e=ex(t);return{ok:!0,data:{sessions:a.toArray().filter(t=>d(t,e)).map(e=>{let t=a.resolveSessionDir(e.name);return{name:e.name,sessionStateDir:t,runnerLogPath:eo(t),platform:e.device.platform,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,..."ios"===e.device.platform&&{device_udid:e.device.id,ios_simulator_device_set:e.device.simulatorSetPath??null}}})}}}if("devices"===t.command)try{let e=tm(t.flags?.androidDeviceAllowlist),r=ts(t.flags?.platform),a=to({simulatorSetPath:tu(t.flags?.iosSimulatorDeviceSet),platform:r,target:t.flags?.target}),n=await ec({platform:r,target:t.flags?.target,deviceName:t.flags?.device,udid:t.flags?.udid,serial:t.flags?.serial,iosSimulatorSetPath:a,androidSerialAllowlist:e?Array.from(e).sort():void 0}),i=r?n.filter(e=>{var t,a;return t=e,!(a=r)||("apple"===a?ti(t.platform):t.platform===a)}):n,o=(t.flags?.target?i.filter(e=>(e.target??"mobile")===t.flags?.target):i).map(({simulatorSetPath:e,...t})=>t);return{ok:!0,data:{devices:o}}}catch(t){let e=i(t);return E(e.code,e.message,e.details)}if("apps"===t.command){let e=a.get(r),n=t.flags??{},i=N(t.command,e,n);if(i)return i;let o=await m({session:e,flags:n,ensureReady:!0});if(!eV("apps",o))return E("UNSUPPORTED_OPERATION","apps is not supported on this device");let s=tI(t.flags?.appsFilter);return ti(o.platform)?{ok:!0,data:{apps:(await tb(o,s)).map(e=>e.name&&e.name!==e.bundleId?`${e.name} (${e.bundleId})`:e.bundleId)}}:{ok:!0,data:{apps:(await tw(o,s)).map(e=>e.name&&e.name!==e.package?`${e.name} (${e.package})`:e.package)}}}return null}async function rZ(e){let{ensureAndroidEmulatorBooted:t}=await import("./3340.js");return await t(e)}let rQ='iOS appstate requires an active session on the target device. Run open first (for example: open --session sim --platform ios --device "<name>" <app>).',r0='macOS appstate requires an active session on the target device. Run open first (for example: open --session macos --platform macos "System Settings").';async function r1(e){let{req:t,sessionName:r,sessionStore:a}=e,n=a.get(r),i=t.flags??{},o=ts(i.platform);if(!n&&er(i))return E("SESSION_NOT_FOUND","ios"===o?`No active session "${r}". Run open with --session ${r} first.`:`No active session "${r}". Run open with --session ${r} first, or omit --session to query by device selector.`);let s=N("appstate",n,i);if(s)return s;let l=ti(n?.device.platform)&&c(i,n);if("ios"===o&&!l)return E("SESSION_NOT_FOUND",rQ);if("macos"===o&&!l)return E("SESSION_NOT_FOUND",r0);if(l&&n){let e=n.appName??n.appBundleId;if(!n.appName&&!n.appBundleId){if("macos"===n.device.platform&&n.surface&&"app"!==n.surface&&"frontmost-app"!==n.surface)return{ok:!0,data:{platform:n.device.platform,appName:n.surface,appBundleId:n.appBundleId,source:"session",surface:n.surface}};let e="macos"===n.device.platform?"macOS":"iOS";return E("COMMAND_FAILED",`No foreground app is tracked for this ${e} session. Open an app in the session, then retry appstate.`)}return{ok:!0,data:{platform:n.device.platform,appName:e??"unknown",appBundleId:n.appBundleId,source:"session",surface:n.surface??"app",..."ios"===n.device.platform?{device_udid:n.device.id,ios_simulator_device_set:n.device.simulatorSetPath??null}:{}}}}let u=await m({session:n,flags:i,ensureReady:!0});if("ios"===u.platform)return E("SESSION_NOT_FOUND",rQ);if("macos"===u.platform)return E("SESSION_NOT_FOUND",r0);if("web"===u.platform)return E("UNSUPPORTED_OPERATION","appstate is not supported on web.");let{getAndroidAppState:p}=await import("./3340.js"),d=await p(u);return{ok:!0,data:{platform:"android",package:d.package,activity:d.activity}}}async function r3(e){let{req:t,sessionName:r,sessionStore:a}=e;if("boot"===t.command){let e,n=a.get(r),o=t.flags??{},s=N(t.command,n,o);if(s)return s;let l="android"===(ts(o.platform)??n?.device.platform),u=!0===o.headless;if(u&&!l)return E("INVALID_ARGS","boot --headless is supported only for Android emulators.");let p=eE({flags:o,sessionDevice:n?.device}),d=l&&!!p,c=!1;try{e=await m({session:n,flags:o,ensureReady:!1})}catch(r){let t=i(r);if(l&&u&&!p&&"DEVICE_NOT_FOUND"===t.code)return E("INVALID_ARGS","boot --headless requires --device <avd-name> (or an Android emulator session target).");if(!d||"DEVICE_NOT_FOUND"!==t.code||!p)throw r;e=await rZ({avdName:p,serial:o.serial,headless:u}),c=!0}if(o.target&&(e.target??"mobile")!==o.target)return E("DEVICE_NOT_FOUND",`No ${e.platform} device found matching --target ${o.target}.`);if(l&&u){if("android"!==e.platform||"emulator"!==e.kind)return E("INVALID_ARGS","boot --headless is supported only for Android emulators.");if(!c){let t=eE({flags:o,sessionDevice:n?.device,resolvedDevice:e});if(!t)return E("INVALID_ARGS","boot --headless requires --device <avd-name> (or an Android emulator session target).");e=await rZ({avdName:t,serial:o.serial,headless:!0})}await eM(e)}else("android"!==e.platform||!0!==e.booted)&&await eM(e);return eV("boot",e)?{ok:!0,data:{platform:e.platform,target:e.target??"mobile",device:e.name,id:e.id,kind:e.kind,booted:!0}}:E("UNSUPPORTED_OPERATION","boot is not supported on this device")}if("shutdown"===t.command){var n;let e,i=a.get(r),o=t.flags??{},s=N(t.command,i,o);if(s)return s;let l=await m({ensureReady:!1,flags:o,session:i});if(!eV("shutdown",l))return E("UNSUPPORTED_OPERATION","shutdown is supported only for Apple simulators and Android emulators.");if(i&&i.device.platform===l.platform&&i.device.id===l.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:l.platform,target:l.target??"mobile",device:l.name,id:l.id,kind:l.kind});let u=await K(l);return u.success?{ok:!0,data:{platform:l.platform,target:l.target??"mobile",device:l.name,id:l.id,kind:l.kind,shutdown:u}}:E(u.error?.code??"COMMAND_FAILED",(n=u,(e=n.error?.message??n.stderr.trim()).length>0?e:"Shutdown failed"),{platform:l.platform,target:l.target??"mobile",device:l.name,id:l.id,kind:l.kind,shutdown:u})}return"appstate"===t.command?await r1({req:t,sessionName:r,sessionStore:a}):null}async function r2(e,t={}){var r,a,n;let i,o,s,l,u=(s=(o=(i=function(e){let t=[];for(let r of e){if("open"!==r.command)continue;let e=r.result?.startup;e&&"object"==typeof e&&"number"==typeof e.durationMs&&Number.isFinite(e.durationMs)&&"string"==typeof e.measuredAt&&0!==e.measuredAt.trim().length&&e.method===rk&&t.push({durationMs:Math.max(0,Math.round(e.durationMs)),measuredAt:e.measuredAt,method:rk,appTarget:"string"==typeof e.appTarget&&e.appTarget.length>0?e.appTarget:void 0,appBundleId:"string"==typeof e.appBundleId&&e.appBundleId.length>0?e.appBundleId:void 0})}return t.slice(-20)}((r=e).actions)).at(-1))?{available:!0,lastDurationMs:o.durationMs,lastMeasuredAt:o.measuredAt,method:rk,sampleCount:i.length,samples:i}:{available:!1,reason:"No startup sample captured yet. Run open <app|url> in this session first.",method:rk},{session:r.name,platform:r.device.platform,device:r.device.name,deviceId:r.device.id,metrics:{startup:s,...{fps:r6(),memory:{available:!1,reason:rN},cpu:{available:!1,reason:rN}}},sampling:{startup:{method:rk,description:"Elapsed wall-clock time around dispatching the open command for the active session app target.",unit:"ms"},..."android"===(a=r).device.platform?{memory:{method:eq,description:eP,unit:"kB"},cpu:{method:em,description:es,unit:"percent"},fps:{method:R,description:e_,unit:"percent",primaryField:"droppedFramePercent",window:"since previous Android gfxinfo reset or app process start",resetsAfterRead:!0,relatedActionsLimit:12}}:Y(a.device)}});return at(e)&&(e.appBundleId?"android"===e.device.platform?await r8(u,e,e.appBundleId,t):await r7(u,e,e.appBundleId):(n=u,l=ar(e),n.metrics.fps={available:!1,reason:l},n.metrics.memory={available:!1,reason:l},n.metrics.cpu={available:!1,reason:l})),u}async function r5(e,t={}){var r,a;let n={session:(r=e).name,platform:r.device.platform,device:r.device.name,deviceId:r.device.id,metrics:{fps:r6()},sampling:{fps:"android"===(a=r).device.platform?{method:R,description:e_,unit:"percent",primaryField:"droppedFramePercent",window:"since previous Android gfxinfo reset or app process start",resetsAfterRead:!0,relatedActionsLimit:12}:P(a.device)}};return at(e)&&(e.appBundleId?await ae(n,e,e.appBundleId,t):n.metrics.fps={available:!1,reason:ar(e)}),n}async function r4(e,t){var r,a;let n={session:(r=e).name,platform:r.device.platform,device:r.device.name,deviceId:r.device.id,sampling:{memory:"android"===(a=r).device.platform?{method:eq,description:eP,unit:"kB",topConsumerLimit:5}:Y(a.device).memory,snapshot:"android"===r.device.platform?{method:J,description:j,defaultKind:"android-hprof",artifactOnly:!0}:{method:eR,description:u,defaultKind:"memgraph",artifactOnly:!0}}};if(!at(e)){if("snapshot"===t.action){let r=al(e,t.kind);return n.artifact=au(e,r),n.support=ad(n.artifact.support)??ap(e),n}return n.metrics={memory:{available:!1,reason:rN}},n}return"sample"===t.action?n.metrics={memory:await ai(e,t)}:(n.artifact=await as(e,t),n.support=ad(n.artifact.support)??ap(e)),n}function r6(){return{available:!1,reason:"Dropped-frame sampling is currently available only on Android app sessions and connected iOS device app sessions."}}async function r8(e,t,r,a){let n=await aa(t,r,a);r9(e,t,n)}async function r7(e,t,r){let a=await an(t,r);r9(e,t,a)}function r9(e,t,r){e.metrics.memory=af(r.memory),e.metrics.cpu=af(r.cpu),e.metrics.fps=am(af(r.fps),t)}async function ae(e,t,r,a){let n="android"===t.device.platform?await ac(eF(t.device,r,{adb:a.androidAdb})):await ac(g(t.device,r));e.metrics.fps=am(af(n),t)}function at(e){return"android"===e.device.platform||"ios"===e.device.platform||"macos"===e.device.platform}function ar(e){return"android"===e.device.platform?"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."}async function aa(e,t,r){let a={adb:r.androidAdb},[n,i,o]=await Promise.allSettled([H(e.device,t,a),z(e.device,t,a),eF(e.device,t,a)]);return{memory:n,cpu:i,fps:o}}async function an(e,t){let r=await ac(g(e.device,t)),a=await ac(eU(e.device,t));if("fulfilled"===a.status){let e=a.value;return{memory:{status:"fulfilled",value:e.memory},cpu:{status:"fulfilled",value:e.cpu},fps:r}}return{memory:{status:"rejected",reason:a.reason},cpu:{status:"rejected",reason:a.reason},fps:r}}async function ai(e,t){return e.appBundleId?af("android"===e.device.platform?await ac(H(e.device,e.appBundleId,{adb:t.androidAdb})):await ac(ao(e))):{available:!1,reason:ar(e)}}async function ao(e){if(!e.appBundleId)throw new s("INVALID_ARGS",ar(e));return(await eU(e.device,e.appBundleId)).memory}async function as(e,t){if(!e.appBundleId)throw new s("INVALID_ARGS",ar(e),{hint:"Run open <app> first so perf memory snapshot can resolve the app process."});let a=al(e,t.kind),n=function(e,t){if(e.out)return ef.expandHome(e.out,e.cwd);let a=new Date().toISOString().replace(/[:.]/g,"-"),n=e.sessionStore.ensureSessionDir(e.sessionName);return r.join(n,"artifacts",`memory-${t}-${a}.${"android-hprof"===t?"hprof":"memgraph"===t?"memgraph":"artifact"}`)}(t,a);return"android"===e.device.platform?"android-hprof"!==a?au(e,a):await I(e.device,e.appBundleId,n,{adb:t.androidAdb}):"memgraph"!==a?au(e,a):await w(e.device,e.appBundleId,n)}function al(e,t){return t||("android"===e.device.platform?"android-hprof":"memgraph")}function au(e,t){var r,a;let n=ap(e),i=(r=e,a=t,"android"===r.device.platform?{reason:`Android perf memory snapshot supports android-hprof, not ${a}.`,hint:"Use perf memory snapshot --kind android-hprof for Android Java heap artifacts."}:"ios"===r.device.platform||"macos"===r.device.platform?{reason:`Apple perf memory snapshot supports memgraph, not ${a}.`,hint:"Use perf memory snapshot --kind memgraph for supported Apple app sessions."}:{reason:`Memory snapshot artifacts are not supported on ${r.device.platform}.`,hint:"Use perf memory sample where supported, or run the snapshot against Android, iOS simulator, or macOS."});return{available:!1,kind:t,reason:i.reason,hint:i.hint,support:n}}function ap(e){return"android"===e.device.platform?{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."}:"ios"!==e.device.platform&&"macos"!==e.device.platform?{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."}:{...eh(e.device),androidHprof:!1,heapprofd:!1,heapprofdDecision:"Deferred because heapprofd is Android/Perfetto-specific and outside this memory artifact slice."}}function ad(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:void 0}async function ac(e){try{return{status:"fulfilled",value:await e}}catch(e){return{status:"rejected",reason:e}}}function af(e){if("fulfilled"===e.status)return{available:!0,...e.value};let t=o(e.reason);return{available:!1,reason:t.message,error:t}}function am(e,t){var r,a;let n,i;if(!0!==e.available)return e;let o=(r=t.actions,n=ah((a=e).windowStartedAt),i=ah(a.windowEndedAt)??ah(a.measuredAt),void 0===n||void 0===i?[]:r.filter(e=>e.ts>=n&&e.ts<=i).map(e=>({command:e.command,at:new Date(e.ts).toISOString(),offsetMs:Math.max(0,Math.round(e.ts-n)),target:function(e){let t=e.result;if(t)for(let e of["refLabel","ref","appName","appBundleId"]){let r=t[e];if("string"==typeof r&&r.length>0)return r}}(e)})).slice(-12));return 0===o.length?e:{...e,relatedActions:o}}function ah(e){if("string"!=typeof e)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}async function ag(e){var t,r,a,n,i,s,l,u,p,d;let c,f,m,h,g,w,y=(t=e.req,r=e.area,c=(a=t,n=r,"string"==typeof a.flags?.out&&a.flags.out.length>0?a.flags.out:(a.positionals??[])["cpu"===n?5:4]||void 0),"cpu"===r?(i=t,s=c,f=aw(i,1),m=aw(i,2),h=aw(i,3),ej(f)?"start"!==(l=m)&&"stop"!==l&&"report"!==l?E("INVALID_ARGS","perf cpu profile action must be start, stop, or report"):"simpleperf"!==h?E("INVALID_ARGS","perf cpu profile requires --kind simpleperf"):{ok:!0,area:"cpu",subject:f,action:m,kind:h,outPath:s}:E("INVALID_ARGS",tn)):(u=t,p=c,g=aw(u,1),w=aw(u,2),"start"!==(d=g)&&"stop"!==d?E("INVALID_ARGS","perf trace action must be start or stop"):eZ(w)?"perfetto"!==w?E("INVALID_ARGS","perf trace requires --kind perfetto"):{ok:!0,area:"trace",action:g,kind:w,outPath:p}:E("INVALID_ARGS",e4)));if(!y.ok)return y;let{session:v}=e;if("android"!==v.device.platform)return E("UNSUPPORTED_OPERATION","Android native perf collectors are supported only on Android sessions.");if(!v.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{let t="cpu"===y.area?await aA(e,v,v.appBundleId,y):await aS(e,v,v.appBundleId,y);return{ok:!0,data:t}}catch(e){return{ok:!1,error:o(e)}}}function aw(e,t){return(e.positionals?.[t]??"").toLowerCase()}function ay(e,t){var r;return e.sessionStore.set(e.sessionName,{...e.session,nativePerf:{android:t}}),{action:(r=t).action,platform:"android",type:r.type,kind:r.kind,packageName:r.packageName,appPid:r.appPid,profilerPid:r.profilerPid,state:r.state,startedAt:new Date(r.startedAt).toISOString(),stoppedAt:"number"==typeof r.stoppedAt?new Date(r.stoppedAt).toISOString():void 0,durationMs:r.durationMs,outPath:r.outPath,sizeBytes:r.sizeBytes,remotePath:r.remotePath,method:r.method,summary:r.summary,message:r.message}}function av(e,t,a){var n,i,o;let s;return t?ef.expandHome(t,e.req.meta?.cwd):(n=e.sessionStore,i=e.sessionName,o=a,s=new Date().toISOString().replace(/[:.]/g,"-"),r.join(n.ensureSessionDir(i),`${s}-${o}`))}async function aA(e,t,r,a){if("start"===a.action){aI(t);let n=av(e,a.outPath,"cpu.perf.data"),i=await l(t.device,r,n,{adb:e.androidAdbExecutor});return ay(e,i)}let n=a_(t,"cpu-profile",a.kind);if("report"===a.action){await function(e){if("running"===e.state)throw new s("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."})}(n);let r=av(e,a.outPath,"cpu-report.json");return await eC(t.device,n,r,{adb:e.androidAdbExecutor})}let i=ab(e,a.outPath,n),o=await ep(t.device,n,i,{adb:e.androidAdbExecutor});return ay(e,o)}async function aS(e,t,r,a){if("start"===a.action){aI(t);let n=av(e,a.outPath,"app.perfetto-trace"),i=await A(t.device,r,n,{adb:e.androidAdbExecutor});return ay(e,i)}let n=a_(t,"trace",a.kind),i=ab(e,a.outPath,n),o=await eg(t.device,n,i,{adb:e.androidAdbExecutor});return ay(e,o)}function aI(e){let t=e.nativePerf?.android;if(t?.state==="running")throw new s("COMMAND_FAILED",`Android ${t.kind} ${t.type} is already running for this session.`,{hint:"cpu-profile"===t.type?"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 ab(e,t,r){return t?av(e,t,r.outPath):r.outPath}function a_(e,t,r){let a=e.nativePerf?.android;if(a?.type===t&&a.kind===r)return a;throw new s("COMMAND_FAILED",`No Android ${r} ${t} is active for this session.`,{hint:"cpu-profile"===t?"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 ak(e,t){let r,a,n=(r=e.req.positionals??[],"cpu"===(a=r[0]?.toLowerCase())?function(e){if(e[1]?.toLowerCase()!=="profile")return E("INVALID_ARGS","perf cpu requires profile");let t=aN(e[2],"perf cpu profile",!0);if(!t.ok)return t;let r=aD(e[3]);return r.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}:r}(r):"trace"===a?function(e){let t=aN(e[1],"perf trace",!1);if(!t.ok)return t;let r=aD(e[2]);return r.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}:r}(r):E("INVALID_ARGS",eW));if(!n.ok)return n;if("android"===t.device.platform)return E("UNSUPPORTED_OPERATION","Android native profiling belongs to the Android perf rollout; Apple xctrace perf supports iOS and macOS sessions only.");if("ios"!==t.device.platform&&"macos"!==t.device.platform)return E("UNSUPPORTED_OPERATION",`Apple xctrace perf is not supported on ${t.device.platform}.`);if(!t.appBundleId)return E("INVALID_ARGS","Apple xctrace perf requires an active app session. Run open <app> first.");try{if("start"===n.action)return await ax(e,t,n);if("stop"===n.action)return await aR(e,t,n);return await aM(e,t,n)}catch(e){return{ok:!1,error:o(e)}}}function aN(e,t,r){let a=e?.toLowerCase();return"start"===a||"stop"===a||r&&"report"===a?{ok:!0,value:a}:E("INVALID_ARGS",r?`${t} requires start, stop, or report`:`${t} requires start or stop`)}function aD(e){return e?.toLowerCase()==="xctrace"?{ok:!0}:E("INVALID_ARGS","perf native collection currently supports --kind xctrace")}async function ax(e,t,r){if(t.applePerf?.active)return E("INVALID_ARGS","Apple xctrace perf capture already in progress");let a=r.template??("cpu-profile"===r.mode?"Time Profiler":"Animation Hitches"),n=aL(e,r),i=await X({device:t.device,appBundleId:t.appBundleId,mode:r.mode,template:a,outPath:n});t.applePerf={...t.applePerf??{},active:i},e.sessionStore.set(e.sessionName,t);let o=aO("started",i);return aP(e,t,o),{ok:!0,data:o}}async function aR(e,t,r){var a,n,o,s,l,u,p;let d,c=t.applePerf?.active;if(!c)return E("INVALID_ARGS","no active Apple xctrace perf capture");let f=r.outPath?ef.expandHome(r.outPath,e.req.meta?.cwd):c.outPath;try{d=await b(c,f)}catch(r){throw a=r,i(a).details?.captureCleanedUp===!0&&(n=e,(o=t).applePerf={...o.applePerf??{},active:void 0},n.sessionStore.set(n.sessionName,o)),r}s=e,l=t,u=d,l.applePerf={...l.applePerf??{},active:void 0,lastMode:u.mode,..."cpu-profile"===(p=u).mode?{lastProfileTracePath:p.outPath,lastProfileTemplate:p.template}:{lastTracePath:p.outPath}},s.sessionStore.set(s.sessionName,l);let m=aO("stopped",d);return aP(e,t,m),{ok:!0,data:m}}async function aM(e,t,r){var a;let n;if("cpu-profile"!==r.mode)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 i=aL(e,r),o=(a=t,(n=r.tracePath??a.applePerf?.lastProfileTracePath??a.applePerf?.active?.outPath)?{ok:!0,value:n}:E("INVALID_ARGS","perf cpu profile report requires a stopped profile trace or tracePath option"));if(!o.ok)return o;let s={perf:"reported",...await k({tracePath:ef.expandHome(o.value,e.req.meta?.cwd),outPath:i,mode:r.mode,template:t.applePerf?.lastProfileTemplate??r.template,appBundleId:t.appBundleId})};return aP(e,t,s),{ok:!0,data:s}}function aP(e,t,r){e.sessionStore.recordAction(t,{command:"perf",positionals:e.req.positionals??[],flags:e.req.flags??{},result:r})}function aL(e,t){if(t.outPath)return ef.expandHome(t.outPath,e.req.meta?.cwd);let r=e.sessionStore.ensureSessionDir(e.sessionName),a=new Date().toISOString().replace(/[:.]/g,"-"),n="report"===t.action?"json":"trace";return`${r}/perf-${t.mode}-${a}.${n}`}function aO(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}}let aE=`logs requires ${e8.slice(0,-1).join(", ")}, or ${e8.at(-1)}`,aC=["dump","log"],a$=`network requires ${aC.join(" or ")}`,aV=`network include mode must be one of: ${tk.join(", ")}`,aU={path:({session:e,sessionName:t,sessionStore:r})=>(function(e,t,r){let a=r.resolveAppLogPath(t),n=G(a);return{ok:!0,data:{path:a,active:!!e.appLog,state:e.appLog?.getState()??"inactive",backend:e.appLog?.backend??eu(e.device),sizeBytes:n.sizeBytes,modifiedAt:n.modifiedAt,startedAt:e.appLog?.startedAt?new Date(e.appLog.startedAt).toISOString():void 0,hint:'Grep the file for token-efficient debugging, e.g. grep -n "Error\\|Exception" <path>'}}})(e,t,r),doctor:({session:e,sessionName:t,sessionStore:r})=>aH(e,t,r),mark:({req:e,sessionName:t,sessionStore:r})=>{var a,n,i;let o,s;return a=e,n=t,i=r,o=a.positionals?.slice(1).join(" ")??"",f(s=i.resolveAppLogPath(n),o),{ok:!0,data:{path:s,marked:!0}}},clear:({session:e,sessionName:t,sessionStore:r,restart:a})=>aK(e,t,r,a),start:({session:e,sessionName:t,sessionStore:r})=>aj(e,t,r),stop:({session:e,sessionName:t,sessionStore:r})=>az(e,t,r)};async function aF(e){let{req:t}=e;return"perf"===t.command?aq(e):"logs"===t.command?aB(e):"network"===t.command?aW(e):null}async function aq(e){var t;let{req:r,sessionName:a,sessionStore:n,androidAdbExecutor:i}=e,l=n.get(a);if(!l)return E("SESSION_NOT_FOUND","perf requires an active session. Run open first.");let u=(r.positionals?.[0]??"metrics").toLowerCase();if("cpu"===(t=u)||"trace"===t)return"android"===l.device.platform?await ag({req:r,sessionName:a,sessionStore:n,session:l,androidAdbExecutor:i,area:u}):await ak(e,l);let p=function(e){var t,r,a,n,i,l,u,p,d,c;let f,m,h=e6(f=(e.positionals?.[0]??"metrics").toString().toLowerCase())?f:void 0;if(!h)return E("INVALID_ARGS",eW);if("cpu"===h||"trace"===h)return{ok:!0,native:!0};let g=eK(m=(e.positionals?.[1]??"sample").toString().toLowerCase())?m:void 0;if(!g)return E("INVALID_ARGS",eX);let w=function(e){if(void 0!==e)return"string"==typeof e&&eZ(e)?e:new s("INVALID_ARGS",e4)}(e.flags?.kind);if(w instanceof s)return{ok:!1,error:o(w)};let y=(t=h,r=g,("memory"===t?aT(r)?void 0:E("INVALID_ARGS","perf memory requires sample or snapshot"):"sample"!==r?E("INVALID_ARGS","perf metrics and perf frames only support sample"):void 0)??(a=e,n=h,i=g,l=w,function(e,t,r){if(e&&("memory"!==t||"snapshot"!==r))return E("INVALID_ARGS","--out is only supported with perf memory snapshot")}(a.flags?.out,n,i)??(u=l,p=n,d=i,u?"memory"!==p||"snapshot"!==d?E("INVALID_ARGS","--kind is only supported with perf memory snapshot"):eQ(u)?void 0:E("INVALID_ARGS",e5):void 0)));return y||{ok:!0,native:!1,area:h,action:g,kind:w,out:"string"==typeof(c=e.flags?.out)&&c.length>0?c:void 0}}(r);if(!p.ok)return p;if(p.native)return await ak(e,l);try{return{ok:!0,data:await aG(e,l,p)}}catch(e){return{ok:!1,error:o(e)}}}async function aG(e,t,r){let{sessionName:a,sessionStore:n,androidAdbExecutor:i}=e;return"memory"===r.area?await r4(t,{action:function(e){if(aT(e))return e;throw new s("INVALID_ARGS","perf memory requires sample or snapshot")}(r.action),kind:r.kind,out:r.out,cwd:e.req.meta?.cwd,sessionName:a,sessionStore:n,androidAdb:i}):"frames"===r.area?await r5(t,{androidAdb:i}):await r2(t,{androidAdb:i})}function aT(e){return"sample"===e||"snapshot"===e}async function aB(e){var t;let r,a,{req:n,sessionName:i,sessionStore:o}=e,s=o.get(i);if(!s)return E("SESSION_NOT_FOUND","logs requires an active session");if(!eV("logs",s.device))return E("UNSUPPORTED_OPERATION","logs is not supported on this device");let l=(t=n,r=(t.positionals?.[0]??"path").toLowerCase(),a=!!t.flags?.restart,e8.includes(r)?a&&"clear"!==r?E("INVALID_ARGS","logs --restart is only supported with logs clear"):{ok:!0,action:r,restart:a}:E("INVALID_ARGS",aE));return l.ok?await aU[l.action]({...e,session:s,restart:l.restart}):l}async function aH(e,t,r){let a=r.resolveAppLogPath(t),n=await eA(e.device,e.appBundleId);return{ok:!0,data:{path:a,active:!!e.appLog,state:e.appLog?.getState()??"inactive",checks:n.checks,notes:n.notes}}}async function aK(e,t,r,a){if(e.appLog&&!a)return E("INVALID_ARGS","logs clear requires logs to be stopped first; run logs stop");let n=r.resolveAppLogPath(t);if(!a)return{ok:!0,data:Q(n)};let i=e.appBundleId;if(!i)return E("INVALID_ARGS","logs clear --restart requires an app session; run open <app> first");e.appLog&&await eD(e.appLog);let s=Q(n),l=r.resolveAppLogPidPath(t);try{let a=await eB(e.device,i,n,l);return r.set(t,{...e,appLog:{platform:e.device.platform,backend:a.backend,outPath:n,startedAt:a.startedAt,getState:a.getState,stop:a.stop,wait:a.wait}}),{ok:!0,data:{...s,restarted:!0}}}catch(a){return r.set(t,{...e,appLog:void 0}),{ok:!1,error:o(a)}}}async function aj(e,t,r){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 a=r.resolveAppLogPath(t),n=r.resolveAppLogPidPath(t);try{let i=await eB(e.device,e.appBundleId,a,n);return r.set(t,{...e,appLog:{platform:e.device.platform,backend:i.backend,outPath:a,startedAt:i.startedAt,getState:i.getState,stop:i.stop,wait:i.wait}}),{ok:!0,data:{path:a,started:!0}}}catch(e){return{ok:!1,error:o(e)}}}async function az(e,t,r){if(!e.appLog)return E("INVALID_ARGS","no app log stream active");let a=e.appLog.outPath;return await eD(e.appLog),r.set(t,{...e,appLog:void 0}),{ok:!0,data:{path:a,stopped:!0}}}async function aW(e){let t=function(e){let{req:t,sessionName:r,sessionStore:a}=e,n=a.get(r);if(!n)return E("SESSION_NOT_FOUND","network requires an active session");if(!eV("network",n.device))return E("UNSUPPORTED_OPERATION","network is not supported on this device");let i=(t.positionals?.[0]??"dump").toLowerCase();if(!aC.includes(i))return E("INVALID_ARGS",a$);let o=t.positionals?.[1]?Number.parseInt(t.positionals[1],10):25;if(!Number.isInteger(o)||o<1||o>200)return E("INVALID_ARGS","network dump limit must be an integer in range 1..200");let s=function(e){let t=e.positionals?.[2]?.toLowerCase(),r=e.flags?.networkInclude;if(t&&r&&t!==r)return E("INVALID_ARGS","network include mode was provided both positionally and via --include with different values");let a=(r??t??"summary").toLowerCase();return tk.includes(a)?{ok:!0,include:a}:E("INVALID_ARGS",aV)}(t);return s.ok?{ok:!0,session:n,maxEntries:o,include:s.include}:s}(e);if(!t.ok)return t;let{include:r,maxEntries:a,session:n}=t;if("web"===n.device.platform)return await aJ({include:r,maxEntries:a});let i=await ea({device:n.device,appBundleId:n.appBundleId,appLogState:n.appLog?.getState(),appLogStartedAt:n.appLog?.startedAt,appLogPath:e.sessionStore.resolveAppLogPath(e.sessionName),maxEntries:a,include:r,maxPayloadChars:2048,maxScanLines:4e3});return{ok:!0,data:{...i.dump,active:!!n.appLog,state:n.appLog?.getState()??"inactive",backend:i.backend,notes:i.notes}}}async function aJ(e){let t=t_();if(!t.dumpNetwork)return E("UNSUPPORTED_OPERATION","network is not supported by this web provider");try{let r=await t.dumpNetwork({include:e.include,limit:e.maxEntries});return{ok:!0,data:{entries:r.entries,active:!0,state:"active",backend:r.backend??"agent-browser",include:e.include,matchedLines:r.entries.length,scannedLines:r.entries.length,limits:{maxEntries:e.maxEntries,maxPayloadChars:2048,maxScanLines:r.entries.length},notes:r.notes}}}catch(e){return{ok:!1,error:o(e)}}}function aX(e,t,r){var a,n;if(null==e)return tU("open",[tT(tq(t,"launchApp"),r)]);if("string"==typeof e)return tU("open",[tT(e,r)]);if(!tF(e))throw new s("INVALID_ARGS","launchApp expects a string or map.");tG(e,"launchApp",["appId","stopApp","clearState","clearKeychain","arguments","permissions","launchArguments"]),a0(e,"permissions"),a0(e,"clearKeychain");let i=tT("string"==typeof e.appId?e.appId:tq(t,"launchApp"),r),o=(a=e,n=r,[...aZ(a.arguments,"launchApp.arguments",n),...aZ(a.launchArguments,"launchApp.launchArguments",n)]),l=!0===e.clearState;return tU("open",[i],{...!l&&(!0===e.stopApp||o.length>0)?{relaunch:!0}:{},...l?{clearAppState:!0}:{},...o.length>0?{launchArgs:o}:{}})}function aY(e,t,r){if(null==e)return tU("close",[tT(tq(t,"stopApp"),r)]);if("string"==typeof e)return tU("close",[tT(e,r)]);throw new s("INVALID_ARGS","stopApp expects a string appId or no value.")}function aZ(e,t,r){if(null==e)return[];if("string"==typeof e)return[tT(e,r)];if(Array.isArray(e))return e.map((e,a)=>aQ(e,`${t}[${a}]`,r));if(tF(e))return Object.entries(e).flatMap(([e,a])=>[tT(e,r),aQ(a,`${t}.${e}`,r)]);throw new s("INVALID_ARGS",`${t} expects a string, list, or map.`)}function aQ(e,t,r){if("string"==typeof e)return tT(e,r);if("number"==typeof e||"boolean"==typeof e)return String(e);throw new s("INVALID_ARGS",`${t} must be a string, number, or boolean.`)}function a0(e,t){if(void 0!==e[t])throw tK(`Maestro launchApp field "${t}" is not supported yet.`)}let a1="__maestroRunScript",a3="__maestroAssertVisible",a2="__maestroAssertNotVisible",a5="__maestroPressEnter",a4="__maestroWaitForAnimationToEnd",a6="__maestroScrollUntilVisible",a8="__maestroSwipeScreen",a7="__maestroSwipeOn",a9="__maestroTapOn",ne="__maestroTapPointPercent";function nt(e){if(null==e)return tU("type",["\b".repeat(50)]);if("number"==typeof e&&Number.isInteger(e)&&e>0)return tU("type",["\b".repeat(e)]);if(!tF(e))throw new s("INVALID_ARGS","eraseText expects empty, a positive count, or a map.");if(tG(e,"eraseText",["charactersToErase"]),void 0===e.charactersToErase)return tU("type",["\b".repeat(50)]);if("number"!=typeof e.charactersToErase||!Number.isInteger(e.charactersToErase)||e.charactersToErase<=0)throw new s("INVALID_ARGS","eraseText.charactersToErase must be a positive integer.");return tU("type",["\b".repeat(e.charactersToErase)])}function nr(e){return"number"==typeof e&&Number.isFinite(e)?String(Math.max(16,Math.floor(e))):void 0}function na(e,t){let r=e.toLowerCase();switch(r){case"up":case"down":case"left":case"right":return r;default:throw tK(`Maestro ${t} must be UP, DOWN, LEFT, or RIGHT.`)}}function nn(e){return na(e,"swipe direction")}function ni(e,t,r=[],a){if("string"==typeof e)return no(tT(e,a));if(!tF(e))throw new s("INVALID_ARGS",`${t} expects a string or selector map.`);tG(e,t,["id","text","enabled","selected",...r]);let n=[],i=[];if("boolean"==typeof e.enabled&&i.push(nl("enabled",String(e.enabled))),"boolean"==typeof e.selected&&i.push(nl("selected",String(e.selected))),"string"==typeof e.id&&n.push(nl("id",tT(e.id,a)),...i),"string"==typeof e.text&&0===n.length)return no(tT(e.text,a),i);if("string"==typeof e.label&&0===n.length&&n.push(nl("label",tT(e.label,a)),...i),0===n.length&&i.length>0&&n.push(...i),0===n.length)throw new s("INVALID_ARGS",`${t} selector map must include one of id, text, label, enabled, or selected.`);return n.join(" ")}function no(e,t=[]){return[[nl("label",e),...t].join(" "),[nl("text",e),...t].join(" "),[nl("id",e),...t].join(" ")].join(" || ")}function ns(e){let t=nr(e.duration);return t?[t]:[]}function nl(e,t){return`${e}=${JSON.stringify(t)}`}function nu(e){var t,r;if(!tF(e))return;let a={},n="number"==typeof(t=e.repeat)&&Number.isInteger(t)&&t>0?t:void 0,i="number"==typeof(r=e.delay)&&Number.isInteger(r)&&r>=0?r:void 0;return n&&n>1&&(a.count=n),void 0!==i&&(a.intervalMs=i),!0===e.optional&&(a.maestro={optional:!0}),Object.keys(a).length>0?a:void 0}function np(e){let t=nu(e)??{};return{...t,maestro:{...t.maestro??{},allowNonHittableCoordinateFallback:!0}}}function nd(e){let t={doubleTap:!0};return tF(e)&&"number"==typeof e.delay&&Number.isInteger(e.delay)&&(t.intervalMs=Math.max(0,e.delay)),t}class nc{index=0;tokens;context;constructor(e,t){this.tokens=e,this.context=t}parse(){let e=this.parseOr();if(this.peek())throw new s("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 s("INVALID_ARGS","Incomplete runFlow.when.true expression.");if("boolean"===e.type)return this.index+=1,e.value;if("paren"===e.type&&"("===e.value){this.index+=1;let e=this.parseOr();if(!this.consumeParen(")"))throw new s("INVALID_ARGS","Unclosed runFlow.when.true parenthesis.");return e}return this.parsePlatformComparison()}parsePlatformComparison(){this.expectPlatform();let e=this.expectEqualityOperator(),t=this.expectString().toLowerCase(),r=this.context.platform;return"=="===e?r===t:r!==t}expectPlatform(){if(this.peek()?.type!=="platform")throw new s("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 s("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 s("INVALID_ARGS","runFlow.when.true comparison requires a string literal.")}consumeOperator(e){let t=this.peek();return t?.type==="operator"&&t.value===e&&(this.index+=1,!0)}consumeParen(e){let t=this.peek();return t?.type==="paren"&&t.value===e&&(this.index+=1,!0)}peek(){return this.tokens[this.index]}}function nf(e,t,r){return{...tU(e,t),replayControl:r}}function nm(e,t,r){let a="string"==typeof e?tT(e,t):e,n="number"==typeof a?a:"string"==typeof a&&/^\d+$/.test(a)?Number(a):void 0;if(void 0===n||!Number.isInteger(n)||n<0)throw new s("INVALID_ARGS",`${r} must be a non-negative integer or \${VAR} resolving to one.`);return n}let nh=`
1
+ import{__webpack_require__ as e}from"./rslib-runtime.js";import t from"node:fs";import r from"node:path";import a from"node:vm";import{setTimeout as n}from"node:timers/promises";import{asAppError as i,normalizeError as o,AppError as s}from"./733.js";import{runXcrun as l,startAndroidSimpleperfProfile as u,APPLE_MEMGRAPH_SNAPSHOT_DESCRIPTION as d,dispatchCommand as p,sessionMatchesScope as c,appendAppLogMarker as f,sampleAppleFramePerf as m,captureAppleMemorySnapshot as h,getSessionCommandKind as g,inferFillText as w,startAndroidPerfettoTrace as y,stopIosRunnerSession as v,captureAndroidHeapSnapshot as A,stopAppleXctracePerfCapture as S,resolvePublicSessionName as _,writeAppleXctracePerfReport as b,stopSessionApplePerfCapture as I,resolveSessionRequestLogPath as k,cleanupUploadedArtifact as N,ANDROID_FRAME_SAMPLE_METHOD as D,buildAppleFrameSamplingMetadata as x,createRequestCanceledError as R,stopAppleRunnerForClose as M,registerRequestAbort as P,errorResponse as L,readReplayTestActionProgress as O,buildSessionRecoveryHint as C,releaseSessionLease as E,withKeyedLock as $,resolveTargetDevice as V,getAppLogPathMetadata as U,uniqueStrings as F,setSessionSnapshot as q,sampleAndroidMemoryPerf as T,ANDROID_HPROF_SNAPSHOT_DESCRIPTION as G,sampleAndroidCpuPerf as K,ANDROID_HPROF_SNAPSHOT_METHOD as B,startAppleXctracePerfCapture as H,getSnapshotReferenceFrame as j,buildAppleSamplingMetadata as z,cleanupRetainedMaterializedPathsForSession as W,clearAppLogFiles as J,LeaseRegistry as X,prepareIosRunner as Y,hasExplicitDeviceSelector as Z,stopSessionAndroidNativePerfCapture as Q,readSessionNetworkCapture as ee,cleanupRetainedMaterializedPaths as et,isImplicitSessionScopeConflict as er,resolveSessionRunnerLogPath as ea,ANDROID_CPU_SAMPLE_DESCRIPTION as en,buildSnapshotState as ei,resolveLogBackend as eo,resolveSessionLeaseForRequest as es,stopAndroidSimpleperfProfile as el,context_contextFromFlags as eu,listDeviceInventory as ed,SessionStore as ep,ANDROID_CPU_SAMPLE_METHOD as ec,buildAppleMemorySnapshotSupport as ef,stopAndroidPerfettoTrace as em,isRequestCanceled as eh,resolveRequestTrackingId as eg,retainMaterializedPaths as ew,runAppLogDoctor as ey,resolvePayloadInput as ev,prepareUploadedArtifact as eA,resetAndroidFramePerfStats as eS,ANDROID_FRAME_SAMPLE_DESCRIPTION as e_,listSessionSelectorConflicts as eb,stopSessionAppLog as eI,stopSessionAndroidSnapshotHelper as ek,withReplayTestActionProgress as eN,markRequestCanceled as eD,stopAppLog as ex,resolveImplicitSessionScope as eR,APPLE_MEMGRAPH_SNAPSHOT_METHOD as eM,ANDROID_MEMORY_SAMPLE_DESCRIPTION as eP,writeAndroidSimpleperfReport as eL,prewarmIosRunnerSession as eO,clearRequestCanceled as eC,buildSimctlArgsForDevice as eE,resolveFrontmostMacOsApp as e$,isCommandSupportedOnDevice as eV,sampleApplePerfMetrics as eU,sampleAndroidFramePerf as eF,ANDROID_MEMORY_SAMPLE_METHOD as eq,getRequestSignal as eT,markAndroidSnapshotFreshness as eG,startAppLog as eK,emitRequestProgress as eB}from"./9722.js";import{ensureDeviceReady as eH}from"./device-ready.js";import{isPerfAction as ej,isPerfSubject as ez,pointFromPercent as eW,PERF_AREA_ERROR_MESSAGE as eJ,buildSwipeGesturePlan as eX,PERF_ACTION_ERROR_MESSAGE as eY,buildSnapshotDisplayLines as eZ,isPerfKind as eQ,isPerfMemoryKind as e0,pointInsideRect as e1,successText as e3,clampGesturePoint as e2,resolveDeployResultTarget as e5,PERF_MEMORY_KIND_ERROR_MESSAGE as e4,PERF_KIND_ERROR_MESSAGE as e6,isPerfArea as e8,LOG_ACTION_VALUES as e7,withSuccessText as e9,clampToRange as te,parseSessionSurface as tt,resolveInstallFromSourceResultTarget as tr,readReactNativeOverlayActionNodes as ta,detectReactNativeOverlay as tn,PERF_SUBJECT_ERROR_MESSAGE as ti}from"./2948.js";import{trimRuntimeValue as to,resolveRuntimeTransportHints as ts}from"./8936.js";import{runAndroidAdb as tl,resolveIosSimulatorDeviceSetPath as tu,classifyAndroidAppTarget as td,resolveIosDeviceDeepLinkBundleId as tp,isInfrastructureBootFailureReason as tc,isWebUrl as tf,resolveAndroidSerialAllowlist as tm,isDeepLinkTarget as th,formatAndroidInstalledPackageRequiredMessage as tg,listAndroidApps as tw}from"./3340.js";import{isApplePlatform as ty,resolveAppleSimulatorSetPathForSelector as tv,normalizePlatformSelector as tA,matchesPlatformSelector as tS}from"./5910.js";import{getDiagnosticsMeta as t_,emitDiagnostic as tb}from"./432.js";import{shutdownSimulator as tI,getSimulatorState as tk}from"./simulator.js";import{runBatch as tN,mergeParentFlags as tD}from"./6918.js";import{assertResolvedAppsFilter as tx}from"./2748.js";import{listIosApps as tR}from"./apps.js";import{resolveWebProvider as tM}from"./provider.js";import{NETWORK_INCLUDE_MODES as tP}from"./4291.js";import{unsupportedCommand as tL,readEnvMap as tO,parseReplayScriptDetailed as tC,readReplayShellEnvSource as tE,normalizeCommandList as t$,normalizePlatform as tV,readReplayCliEnvEntries as tU,parseMaestroYamlDocuments as tF,parseAbsolutePoint as tq,readReplayScriptMetadata as tT,parseReplayCliEnvEntries as tG,collectReplayShellEnv as tK,support_action as tB,isPlainRecord as tH,requireAppId as tj,assertOnlyKeys as tz,resolveMaestroString as tW,requireStringValue as tJ,parseMaestroPoint as tX,unsupportedMaestroSyntax as tY,readTimeoutMs as tZ,writeReplayScript as tQ,buildReplayVarScope as t0,resolveReplayAction as t1,mergeReplayVarScopeValues as t3}from"./4428.js";import{runCmdSync as t2}from"./8875.js";import{readSnapshotDiagnosticsSummary as t5,summarizeSnapshotTimingSamples as t4,mergeSnapshotDiagnostics as t6}from"./1848.js";import{resolveSelectorChain as t8,extractNodeText as t7,findSnapshotAncestor as t9,isDescendantOfSnapshotNode as re,splitIsSelectorArgs as rt,buildSelectorChainForNode as rr,buildSnapshotNodeByIndex as ra,matchesSelector as rn,normalizeType as ri}from"./9836.js";import{formatScriptActionSummary as ro,evaluateIsPredicate as rs,isTouchTargetCommand as rl}from"./2577.js";import{splitSelectorFromArgs as ru,normalizeText as rd,tryParseSelectorChain as rp,parseSelectorChain as rc}from"./587.js";import{sleep as rf}from"./5560.js";import{handleRecordCommand as rm}from"./record-trace-recording.js";import{recordingExtensionForPlatform as rh,defaultRecordingPath as rg}from"./5643.js";import{INTERNAL_COMMANDS as rw,PUBLIC_COMMANDS as ry}from"./5341.js";var rv={};async function rA(e){var t;let r="ios"===(t=e.flags?.platform)||"android"===t?t:void 0;if(e.session){if(r&&e.session.device.platform!==r)throw new s("INVALID_ARGS",`install_from_source requested platform ${r}, but session is bound to ${e.session.device.platform}`);return await eH(e.session.device),e.session.device}if(!r)throw new s("INVALID_ARGS",'install_from_source requires platform "ios" or "android" when no session is provided');let a=await V(e.flags??{});return await eH(a),a}async function rS(e){let{prepared:t,retention:r,req:a,session:n,sessionName:i}=e;if(r.enabled)return await ew({archivePath:t.archivePath,installablePath:t.installablePath,tenantId:a.meta?.tenantId,sessionName:n?i:void 0,ttlMs:r.ttlMs})}function r_(e){return e?{...e.archivePath?{archivePath:e.archivePath}:{},installablePath:e.installablePath,materializationId:e.materializationId,materializationExpiresAt:e.expiresAt}:{}}async function rb(e){let{req:t,sessionName:r,sessionStore:a}=e,n=a.get(r);try{let e,i,o=(e=function(e){let t=e.meta?.installSource;if(!t)throw new s("INVALID_ARGS","install_from_source requires a source payload");switch(t.kind){case"url":if(!t.url||0===t.url.trim().length)throw new s("INVALID_ARGS","install_from_source url source requires a non-empty url");return t;case"path":if(!t.path||0===t.path.trim().length)throw new s("INVALID_ARGS","install_from_source path source requires a non-empty path");return t;case"github-actions-artifact":throw new s("UNSUPPORTED_OPERATION","install_from_source github-actions-artifact sources require a compatible remote daemon");default:throw new s("UNSUPPORTED_OPERATION",`install_from_source ${String(t.kind)} sources require a compatible remote daemon`)}}(t),(i=t.meta?.uploadedArtifactId)&&"path"===e.kind?{source:{kind:"path",path:eA(i,t.meta?.tenantId)},cleanup:()=>{N(i)}}:{source:e,cleanup:()=>{}}),l=function(e){let t=e.meta?.retainMaterializedPaths===!0,r=e.meta?.materializedPathRetentionMs;if(!t)return{enabled:!1};if(void 0!==r&&r<=0)throw new s("INVALID_ARGS","install_from_source retentionMs must be a positive integer");return{enabled:!0,ttlMs:r}}(t),u=await rA({session:n,flags:t.flags});if(!eV("install",u))return L("UNSUPPORTED_OPERATION","install_from_source is not supported on this device");let d=eT(t.meta?.requestId),p=async(e,i)=>{let s;try{var u;s=await rS({prepared:e,retention:l,req:t,session:n,sessionName:r});let o=await i(s),d=e9(o,(u=o,`Installed: ${tr(u)}`));return!function(e){let{session:t,sessionStore:r,req:a,data:n}=e;t&&r.recordAction(t,{command:"install_source",positionals:[],flags:a.flags??{},result:n})}({session:n,sessionStore:a,req:t,data:d}),{ok:!0,data:d}}catch(e){throw s&&await et(s.materializationId,t.meta?.tenantId).catch(()=>{}),e}finally{await e.cleanup(),o.cleanup()}};if("ios"===u.platform){let{installIosInstallablePath:e}=await import("./apps.js"),{prepareIosInstallArtifact:t}=await import("./apps.js"),r=await t(o.source,{signal:d});return await p(r,async t=>{if(await e(u,r.installablePath),!r.bundleId)throw new s("COMMAND_FAILED","Installed iOS app identity could not be resolved from the artifact");return{...r_(t),bundleId:r.bundleId,...r.appName?{appName:r.appName}:{},launchTarget:r.bundleId}})}let{prepareAndroidInstallArtifact:c}=await import("./3340.js"),{installAndroidInstallablePathAndResolvePackageName:f}=await import("./3340.js"),m=await c(o.source,{signal:d});return await p(m,async e=>{let t=await f(u,m.installablePath,m.packageName);if(!t)throw new s("COMMAND_FAILED","Installed Android app identity could not be resolved from the artifact or device state");let{inferAndroidAppName:r}=await import("./3340.js"),a=r(t);return{...r_(e),packageName:t,...a?{appName:a}:{},launchTarget:t}})}catch(e){return{ok:!1,error:o(e)}}}async function rI(e){let{req:t}=e;try{let e=t.meta?.materializationId?.trim();if(!e)throw new s("INVALID_ARGS","release_materialized_paths requires a materializationId");return await et(e,t.meta?.tenantId),{ok:!0,data:{released:!0,materializationId:e}}}catch(e){return{ok:!1,error:o(e)}}}function rk(e){return"ios"===e.platform&&"simulator"===e.kind}function rN(e,t,r){return t||Z(r)?null:L("INVALID_ARGS",`${e} requires an active session or an explicit device selector (e.g. --platform ios).`)}async function rD(e,t){rk(e)&&!(t<=0)&&await new Promise(e=>setTimeout(e,t))}async function rx(e){let t=Z(e.flags)||!e.session?await V(e.flags??{}):await rR(e.session.device);return!1!==e.ensureReady&&await eH(t),t}async function rR(e){if("ios"!==e.platform||"simulator"!==e.kind||"darwin"!==process.platform)return e;let t={platform:"ios",target:e.target,udid:e.id,...e.simulatorSetPath?{iosSimulatorDeviceSet:e.simulatorSetPath}:{}};try{return await V(t)}catch(e){if(!(e instanceof s)||"DEVICE_NOT_FOUND"!==e.code)throw e}return await V({platform:"ios",target:e.target,device:e.name,...e.simulatorSetPath?{iosSimulatorDeviceSet:e.simulatorSetPath}:{}})}function rM(e){let t=e.flags?.device?.trim();return t||(e.resolvedDevice?.platform==="android"&&"emulator"===e.resolvedDevice.kind?e.resolvedDevice.name:e.sessionDevice?.platform==="android"&&"emulator"===e.sessionDevice.kind?e.sessionDevice.name:void 0)}e.r(rv),e.d(rv,{handleSessionCommands:()=>sh});let rP="shared_prefs/ReactNativeDevPrefs.xml",rL="debug_http_host",rO="dev_server_https",rC="RCT_jsLocation",rE="RCT_packager_scheme",r$="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.",rV='<?xml version="1.0" encoding="utf-8" standalone="yes" ?>\n<map>\n</map>\n';function rU(e){return void 0!==ts(e)}async function rF(e){let{device:t,appId:r,runtime:a}=e;if(!r)return;let n=ts(a);if(n){if("android"===t.platform)return void await rT(t,r,n);"ios"===t.platform&&"simulator"===t.kind&&await rH(t,r,n)}}async function rq(e){let{device:t,appId:r}=e;if(r){if("android"===t.platform)return void await rG(t,r);"ios"===t.platform&&"simulator"===t.kind&&await rj(t,r)}}async function rT(e,t,r){var a,n,i,o,s,l;let u,d;rX(t);let p=(a=await rK(e,t),n=rL,i=`${r.host}:${r.port}`,u=` <string name="${rY(n)}">${rY(i)}</string>`,rW(rJ(a,n),u));o=p,s=rO,l="https"===r.scheme,d=` <boolean name="${rY(s)}" value="${l?"true":"false"}" />`,p=rW(rJ(o,s),d),await rB(e,t,p)}async function rG(e,t){rX(t);let r=await rK(e,t),a=rJ(r,rL),n=rJ(a,rO);n!==r&&await rB(e,t,n)}async function rK(e,t){let r=await tl(e,["shell","run-as",t,"cat",rP],{allowFailure:!0});return 0!==r.exitCode?rV:rz(r.stdout)}async function rB(e,t,r){let a=["shell","run-as",t,"id"],n=await tl(e,a,{allowFailure:!0});if(0!==n.exitCode){let e=rZ(n.stdout,n.stderr);throw new s("COMMAND_FAILED",e?`Failed to access Android app sandbox for ${t}`:`Failed to probe Android app sandbox for ${t}`,{package:t,cmd:"adb",args:a,stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode,hint:e?r$:"adb shell run-as probe failed. Check adb connectivity and that the device is reachable. Inspect stderr/details for more information."})}try{await tl(e,["shell","run-as",t,"mkdir","-p","shared_prefs"]),await tl(e,["shell","run-as",t,"tee",rP],{stdin:r.trimEnd()})}catch(a){let e=i(a);if("TOOL_MISSING"===e.code)throw e;let r=rZ("string"==typeof e.details?.stdout?e.details.stdout:"","string"==typeof e.details?.stderr?e.details.stderr:"");throw new s("COMMAND_FAILED",r?`Failed to access Android app sandbox for ${t}`:`Failed to write Android runtime hints for ${t}`,{...e.details??{},package:t,cmd:"adb",phase:"write-runtime-hints",hint:r?r$:"adb run-as succeeded, but writing ReactNativeDevPrefs.xml failed. Inspect stderr/details for the failing shell command."},e)}}async function rH(e,t,r){await l(eE(e,["spawn",e.id,"defaults","write",t,rC,"-string",`${r.host}:${r.port}`])),await l(eE(e,["spawn",e.id,"defaults","write",t,rE,"-string",r.scheme]))}async function rj(e,t){await l(eE(e,["spawn",e.id,"defaults","delete",t,rC]),{allowFailure:!0}),await l(eE(e,["spawn",e.id,"defaults","delete",t,rE]),{allowFailure:!0})}function rz(e){let t=e.trim();return t.includes("<map")&&t.includes("</map>")?`${t}
2
+ `:rV}function rW(e,t){return rz(e).replace("</map>",`${t}
3
+ </map>`)}function rJ(e,t){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return rz(e).replace(RegExp(`^\\s*<string name="${r}">[\\s\\S]*?<\\/string>\\n?`,"m"),"").replace(RegExp(`^\\s*<boolean name="${r}" value="(?:true|false)"\\s*\\/?>\\n?`,"m"),"")}function rX(e){if("binary"!==td(e))return;let t=tg(e);throw new s("INVALID_ARGS",t,{package:e,hint:t})}function rY(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}function rZ(e,t){let r=`${e}
4
+ ${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=>r.includes(e))}let rQ=["platform","metroHost","metroPort","bundleUrl","launchUrl"];function r0(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>void 0!==e&&""!==e).length:0}function r1(e,t){if(void 0!==e){if("string"!=typeof e)throw new s("INVALID_ARGS",`Invalid open runtime ${t}: expected string.`);return to(e)}}function r3(e){if(void 0!==e){if(!Number.isInteger(e)||e<1||e>65535)throw new s("INVALID_ARGS",`Invalid runtime metroPort: ${String(e)}. Use an integer between 1 and 65535.`);return e}}function r2(e){if("ios"===e||"android"===e)return e}async function r5(e){let{replacedStoredRuntime:t,previousRuntime:r,runtime:a,session:n}=e;!t||!n?.appBundleId||!rU(r)||rU(a)||await rq({device:n.device,appId:n.appBundleId})}async function r4(e){var t,r;let{req:a,sessionName:n,sessionStore:i}=e,o=(a.positionals?.[0]??"show").toLowerCase(),s=i.get(n),l=i.getRuntimeHints(n);if(!["set","show","clear"].includes(o))return L("INVALID_ARGS","runtime requires set, show, or clear");if("clear"===o){rU(l)&&s?.appBundleId&&await rq({device:s.device,appId:s.appBundleId});let e=i.clearRuntimeHints(n);return{ok:!0,data:{session:n,cleared:e}}}if("show"===o)return{ok:!0,data:{session:n,configured:!!l,runtime:l}};let u=r2(tA(a.flags?.platform)??l?.platform??s?.device.platform);if(!u)return L("INVALID_ARGS","runtime set only supports iOS and Android sessions. Pass --platform ios|android or open an iOS/Android session first.");if(s&&s.device.platform!==u)return L("INVALID_ARGS",`runtime set targets ${u}, but session "${n}" is already bound to ${s.device.platform}.`);let d={platform:(t=a.flags,r={platform:u,metroHost:to(t?.metroHost),metroPort:r3(t?.metroPort),bundleUrl:to(t?.bundleUrl),launchUrl:to(t?.launchUrl)}).platform??l?.platform,metroHost:r.metroHost??l?.metroHost,metroPort:r.metroPort??l?.metroPort,bundleUrl:r.bundleUrl??l?.bundleUrl,launchUrl:r.launchUrl??l?.launchUrl};return 0===r0(d)?L("INVALID_ARGS","runtime set requires at least one hint such as --metro-host, --metro-port, --bundle-url, or --launch-url."):(i.setRuntimeHints(n,d),{ok:!0,data:{session:n,configured:!0,runtime:d}})}let r6="open-command-roundtrip",r8="Not implemented for this platform in this release.";function r7(e){let{existingSession:t,sessionName:r,sessionScope:a,device:n,surface:i,appBundleId:o,appName:s,saveScript:l}=e;return t?{...t,device:n,surface:i,appBundleId:o,appName:s,recordSession:t.recordSession||l,snapshot:void 0}:{name:r,sessionScope:a,device:n,createdAt:Date.now(),surface:i,appBundleId:o,appName:s,recordSession:l,actions:[]}}let r9=new Set(["app","desktop","frontmost-app"]);async function ae(e){if("app"===e||"desktop"===e||"menubar"===e)return{};let t=await e$();return{appBundleId:t.bundleId,appName:t.appName}}async function at(e,t,r){if(("ios"===e.platform||"macos"===e.platform)&&t)return th(t)?"macos"===e.platform?void 0:"device"===e.kind?tp(r,t):tf(t)?void 0:r??await ar(e,t):await aa(e,t)}async function ar(e,t){try{let{resolveIosSimulatorDeepLinkBundleId:r}=await import("./apps.js");return await r(e,t)}catch{return}}async function aa(e,t){try{let{resolveIosApp:r}=await import("./apps.js");return await r(e,t)}catch{return}}async function an(e,t){if(!("android"!==e.platform||!t||th(t)))try{let{resolveAndroidApp:r}=await import("./3340.js"),a=await r(e,t);return"package"===a.type?a.value:void 0}catch{return}}async function ai(e,t,r){if(r||"android"!==e.platform||!t||!th(t))return r;try{let{getAndroidAppState:t}=await import("./3340.js"),a=await t(e);return a.package?.trim()||r}catch{return r}}async function ao(e,t,r,a){return await at(e,t,r)??await a(e,t)??("android"===e.platform&&t&&th(t)?r:void 0)}function as(e){return L("INVALID_ARGS",e)}function al(e,t,r,a){try{return function(e){let{device:t,surfaceFlag:r,openTarget:a,existingSurface:n}=e;if(("macos"===t.platform||"linux"===t.platform)&&!r)return n??"app";if("linux"===t.platform){if(!r)return"app";let e=tt(r);if(!r9.has(e))throw new s("INVALID_ARGS",`Linux supports --surface app, desktop, and frontmost-app (got "${r}")`);if("app"!==e&&a)throw new s("INVALID_ARGS",`open --surface ${e} does not accept an app target`);return e}if("macos"!==t.platform){if(r)throw new s("INVALID_ARGS","surface is only supported on macOS and Linux");return"app"}let i=r?tt(r):"app";if("app"!==i&&"menubar"!==i&&a)throw new s("INVALID_ARGS",`open --surface ${i} does not accept an app target`);return i}({device:e,surfaceFlag:t,openTarget:r,existingSurface:a})}catch(e){return L(e instanceof s?e.code:"INVALID_ARGS",String(e.message))}}function au(e){let{shouldRelaunch:t,openTarget:r,surface:a,device:n}=e;return t?r&&th(r)?as("open --relaunch does not support URL targets."):"app"!==a?as("open --relaunch is supported only for app surfaces."):"android"===n.platform&&r&&"binary"===td(r)?as(tg(r)):null:null}async function ad(e){let{req:t,sessionName:r,sessionStore:a,device:n,surface:o,openTarget:l,existingSession:u}=e;await eH(n,{deviceHub:t.flags?.deviceHub===!0});let{appBundleId:d,appName:p}=await ap({device:n,surface:o,openTarget:l,existingAppBundleId:u?.appBundleId}),c=function(e){try{return{ok:!0,data:function(e){let{req:t,sessionStore:r,sessionName:a,device:n}=e,i=r.getRuntimeHints(a),o=function(e){let{runtime:t,sessionName:r,platform:a}=e;if(void 0===t)return;if(!t||"object"!=typeof t||Array.isArray(t))throw new s("INVALID_ARGS","open runtime must be an object.");let n=Object.keys(t).find(e=>!rQ.includes(e));if(n)throw new s("INVALID_ARGS",`Invalid open runtime field: ${n}. Supported fields are ${rQ.join(", ")}.`);return{platform:function(e,t,r){if(void 0===e)return r;if("ios"!==e&&"android"!==e)throw new s("INVALID_ARGS",`Invalid open runtime platform: ${String(e)}. Use "ios" or "android".`);if(r&&e!==r)throw new s("INVALID_ARGS",`open runtime targets ${e}, but session "${t}" is bound to ${r}.`);return e}(t.platform,r,a),metroHost:r1(t.metroHost,"metroHost"),metroPort:function(e){if(void 0!==e){if("number"!=typeof e)throw new s("INVALID_ARGS","Invalid open runtime metroPort: expected integer.");return r3(e)}}(t.metroPort),bundleUrl:r1(t.bundleUrl,"bundleUrl"),launchUrl:r1(t.launchUrl,"launchUrl")}}({runtime:t.runtime,sessionName:a,platform:r2(n.platform)});return void 0===t.runtime?{runtime:function(e,t,r){let a=e.getRuntimeHints(t);if(!a)return;let n=r?.platform,i=r2(n);if(a.platform&&r&&!i)throw new s("INVALID_ARGS",`Session runtime hints are only supported on iOS and Android sessions, but session "${t}" is bound to ${n}.`);if(a.platform&&i&&a.platform!==i)throw new s("INVALID_ARGS",`Session runtime hints target ${a.platform}, but session "${t}" is bound to ${n}. Clear the runtime hints or use a different session.`);return i&&a.platform!==i?{...a,platform:i}:a}(r,a,n),previousRuntime:i,replacedStoredRuntime:!1}:{runtime:o&&r0(o)>0?o:void 0,previousRuntime:i,replacedStoredRuntime:!0}}(e)}}catch(t){let e=i(t);return L(e.code,e.message,e.details)}}({req:t,sessionStore:a,sessionName:r,device:n});if(!c.ok)return{type:"response",response:c};if(u){let{runtime:e,previousRuntime:t,replacedStoredRuntime:r}=c.data;await r5({replacedStoredRuntime:r,previousRuntime:t,runtime:e,session:u})}return{type:"details",details:{appBundleId:d,appName:p,runtime:c.data.runtime}}}async function ap(e){let{device:t,surface:r,openTarget:a,existingAppBundleId:n}=e,i=await ae(r);return{appBundleId:i.appBundleId??await ao(t,a,n,an),appName:i.appName??a}}let ac=new Map;async function af(e){let{device:t,closeTarget:r,outFlag:a,context:n}=e;"android"!==t.platform&&await v(t.id),await p(t,"close",[r],a,n),await rD(t,300)}async function am(e){var t,r;let a,{runtime:n,device:i,req:o,logPath:s,appBundleId:l,traceLogPath:u,openPositionals:d}=e,c=n?.launchUrl;if(!c||0===d.length||d.length>1)return;let f=d[0]?.trim();!f||th(f)||await p(i,"open",[c],o.flags?.out,{...(t=s,r=o.flags,a=eu(t,r,l,u),delete a.launchConsole,delete a.launchArgs,a)})}async function ah(e){var t,r,a,n;let i,{req:o,sessionName:s,sessionStore:l,logPath:u,device:d,openTarget:c,openPositionals:f,appName:m,surface:h,appBundleId:g,runtime:w,existingSession:y}=e,v=o.flags?.relaunch===!0,A=y?.trace?.outPath,S=g,b=Date.now(),I={};if(v&&c){let e=S??c,t=Date.now();await af({device:d,closeTarget:e,outFlag:o.flags?.out,context:{...eu(u,o.flags,S??y?.appBundleId,A)}}),I.relaunchCloseDurationMs=Math.max(0,Date.now()-t)}let N=Date.now();await rF({device:d,appId:S,runtime:w}),I.runtimeHintsDurationMs=Math.max(0,Date.now()-N);let D="ios"===d.platform&&"app"===h&&f.length>0,x={verbose:o.flags?.verbose,logPath:u,traceLogPath:A,requestId:o.meta?.requestId,runnerLeaseContext:eu(u,o.flags,S,A,o.meta?.requestId,o.meta).runnerLeaseContext,iosXctestrunFile:o.flags?.iosXctestrunFile,iosXctestDerivedDataPath:o.flags?.iosXctestDerivedDataPath,iosXctestEnvDir:o.flags?.iosXctestEnvDir},M=o.flags?.maestro?.prewarmRunnerBeforeOpen===!0;if(D&&S&&(I.runnerPrewarmKind="session",I.runnerPrewarmScheduled=!0,M)){i=eO(d,{...x,propagateError:!0});let e=Date.now();await i,I.runnerPrewarmWaited=!0,I.runnerPrewarmDurationMs=Math.max(0,Date.now()-e)}let P=Date.now(),O=await ag({req:o,sessionName:s,sessionStore:l,device:d,surface:h,sessionAppBundleId:S,appName:m,existingSession:y});if("response"===O.type)return O.response;let C=O.session??y;await p(d,"open",f,o.flags?.out,{...eu(u,o.flags,S)}),I.openDispatchDurationMs=Math.max(0,Date.now()-P);let E=Date.now();if(await am({runtime:w,device:d,req:o,logPath:u,appBundleId:S,traceLogPath:A,openPositionals:f}),I.launchUrlDurationMs=Math.max(0,Date.now()-E),D&&S&&!i&&(i=eO(d,x)),v&&i&&!0!==I.runnerPrewarmWaited){let e=Date.now();await i,I.runnerPrewarmWaited=!0,I.runnerPrewarmDurationMs=Math.max(0,Date.now()-e)}else i&&!0!==I.runnerPrewarmWaited&&(I.runnerPrewarmWaited=!1);S=await ai(d,c,S),"android"===d.platform&&S&&await eS(d,S);let $=c?(t=S,{durationMs:Math.max(0,Date.now()-P),measuredAt:new Date().toISOString(),method:r6,appTarget:c,appBundleId:t}):void 0,V=Date.now();if(await rD(d,300),I.postOpenSettleDurationMs=Math.max(0,Date.now()-V),eh(o.meta?.requestId)){let e=R();return L(e.code,e.message,e.details)}y&&eG(y,"open",y.snapshot);let U=r7({existingSession:C,sessionName:y?.name??_(o),sessionScope:y?.sessionScope??eR(o),device:d,surface:h,appBundleId:S,appName:m,saveScript:!!o.flags?.saveScript});U.lease=es({req:o,existingLease:y?.lease}),void 0!==o.runtime&&(r=l,a=s,(n=w)&&(0===r0(n)?r.clearRuntimeHints(a):r.setRuntimeHints(a,n)));let F=l.ensureSessionDir(s),q=k(F,o.meta?.requestId??t_().requestId);I.totalDurationMs=Math.max(0,Date.now()-b);let T=function(e){let{sessionName:t,sessionStateDir:r,runnerLogPath:a,requestLogPath:n,appName:i,appBundleId:o,surface:s,startup:l,timing:u,device:d,runtime:p,runtimeHintCount:c}=e,f={session:t,surface:s,sessionStateDir:r,runnerLogPath:a,requestLogPath:n};return i&&(f.appName=i),o&&(f.appBundleId=o),l&&(f.startup=l),u&&(f.timing=u),p&&c(p)>0&&(f.runtime=p),d&&(f.platform=d.platform,f.target=d.target??"mobile",f.device=d.name,f.id=d.id,f.kind=d.kind,"android"===d.platform&&(f.serial=d.id)),d?.platform==="ios"&&(f.device_udid=d.id,f.ios_simulator_device_set=d.simulatorSetPath??null),{...f,...e3(`Opened: ${i??o??t}`)}}({sessionName:U.name,sessionStateDir:F,runnerLogPath:ea(F),requestLogPath:q,appName:m,appBundleId:S,surface:h,startup:$,timing:I,device:d,runtime:w,runtimeHintCount:r0});return l.recordAction(U,{command:"open",positionals:f,flags:o.flags??{},runtime:void 0!==o.runtime?w:void 0,result:T}),l.set(s,U),{ok:!0,data:T}}async function ag(e){let{req:t,sessionName:r,sessionStore:a,device:n,surface:i,sessionAppBundleId:o,appName:s,existingSession:l}=e,u=t.internal?.openLifecycle?.beforeDispatch;if(!u)return{type:"session",session:l};let d=r7({existingSession:l,sessionName:l?.name??_(t),sessionScope:l?.sessionScope??eR(t),device:n,surface:i,appBundleId:o,appName:s,saveScript:!!t.flags?.saveScript});d.lease=es({req:t,existingLease:l?.lease}),a.set(r,d);let p=await u(d);return p&&!p.ok?{type:"response",response:p}:{type:"session",session:a.get(r)??d}}async function aw(e){let{req:t,sessionName:r,logPath:a,sessionStore:n}=e,i=n.get(r);if(i){let e=t.flags?.relaunch===!0,o=t.positionals?.[0],s=o??(e?i.appName:void 0),l=al(i.device,t.flags?.surface,s,i.surface);if("string"!=typeof l)return l;if(!s&&"app"===l)return e?as("open --relaunch requires an app name or an active session app."):as("Session already active. Close it first or pass a new --session name.");let u=au({shouldRelaunch:e,openTarget:s,surface:l,device:i.device});if(u)return u;let d=await rR(i.device),p=await ad({req:t,sessionName:r,sessionStore:n,device:d,surface:l,openTarget:s,existingSession:i});return"response"===p.type?p.response:await ah({req:t,sessionName:r,sessionStore:n,logPath:a,device:d,openTarget:s,openPositionals:o?t.positionals??[]:s?[s]:[],appBundleId:p.details.appBundleId,appName:p.details.appName,runtime:p.details.runtime,surface:l,existingSession:i})}let o=t.flags?.relaunch===!0,s=t.positionals?.[0];if(o&&!s)return as("open --relaunch requires an app argument.");let l=function(e){let{shouldRelaunch:t,openTarget:r,platform:a}=e;return t?r&&th(r)?as("open --relaunch does not support URL targets."):"android"===a&&r&&"binary"===td(r)?as(tg(r)):null:null}({shouldRelaunch:o,openTarget:s,platform:t.flags?.platform==="android"?"android":void 0});if(l)return l;let u=await V(t.flags??{}),d=al(u,t.flags?.surface,s);if("string"!=typeof d)return d;let p=au({shouldRelaunch:o,openTarget:s,surface:d,device:u});return p||await $(ac,u.id,async()=>{let e=n.toArray().find(e=>e.device.id===u.id);if(e)return er(t,e)?L("DEVICE_IN_USE","Device is already in use by another workspace session.",{deviceId:u.id,deviceName:u.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."}):L("DEVICE_IN_USE",`Device is already in use by session "${e.name}".`,{session:e.name,deviceId:u.id,deviceName:u.name,hint:C(e,"device-in-use")});let i=await ad({req:t,sessionName:r,sessionStore:n,device:u,surface:d,openTarget:s});return"response"===i.type?i.response:await ah({req:t,sessionName:r,sessionStore:n,logPath:a,device:u,openTarget:s,openPositionals:t.positionals??[],appBundleId:i.details.appBundleId,appName:i.details.appName,runtime:i.details.runtime,surface:d})})}async function ay(e){if(!1===e.booted)return{success:!0,exitCode:0,stdout:"",stderr:""};try{return rk(e)?await av(e):await aS(e)}catch(t){let e=o(t);return{success:!1,exitCode:-1,stdout:"",stderr:e.message,error:e}}}async function av(e){let t=await tI(e);return t.success?t:"Shutdown"===await aA(e)?{...t,success:!0,exitCode:0}:t}async function aA(e){try{return await tk(e)}catch{return null}}async function aS(e){let t=await tl(e,["emu","kill"],{allowFailure:!0,timeoutMs:15e3});return{success:0===t.exitCode,exitCode:t.exitCode,stdout:String(t.stdout??""),stderr:String(t.stderr??"")}}async function a_(e){let{device:t,shutdownRequested:r}=e;if(r&&(rk(t)||"android"===t.platform&&"emulator"===t.kind))return await ay(t)}async function ab(e){let{req:t,sessionName:r,logPath:a,sessionStore:n,leaseRegistry:i}=e,o=n.get(r);if(!o)return await aI(t,a);try{var s,l,u;(await eI(o),await I(o),await Q(o),await ek(o),s=t,l=o,u=s,(u.positionals?.length??0)>0||"web"===l.device.platform)&&(ty(o.device.platform)&&!rk(o.device)&&await M(o),await p(o.device,"close",t.positionals??[],t.flags?.out,{...eu(a,t.flags,o.appBundleId,o.trace?.outPath)}),await rD(o.device,300));ty(o.device.platform)&&(!rk(o.device)||t.flags?.shutdown||o.recording)?await M(o):ty(o.device.platform)&&tb({level:"debug",phase:"ios_runner_retained_after_close",data:{session:o.name,deviceId:o.device.id}});let e=n.getRuntimeHints(r);rU(e)&&o.appBundleId&&await rq({device:o.device,appId:o.appBundleId}).catch(()=>{}),n.recordAction(o,{command:"close",positionals:t.positionals??[],flags:t.flags??{},result:{session:o.name,...e3(`Closed: ${o.name}`)}}),t.flags?.saveScript&&(o.recordSession=!0),n.writeSessionLog(o),await W(r).catch(()=>{})}finally{E({session:o,leaseRegistry:i}),n.delete(r)}let d=await a_({device:o.device,shutdownRequested:t.flags?.shutdown});return d?{ok:!0,data:e9({session:o.name,shutdown:d},`Closed: ${o.name}`)}:{ok:!0,data:{session:o.name,...e3(`Closed: ${o.name}`)}}}async function aI(e,t){if(!e.positionals||0===e.positionals.length)return L("SESSION_NOT_FOUND","No active session");let r=await rx({session:void 0,flags:e.flags,ensureReady:!0});return await p(r,"close",e.positionals,e.flags?.out,{...eu(t,e.flags)}),await rD(r,300),{ok:!0,data:{app:e.positionals[0],...e3(`Closed: ${e.positionals[0]}`)}}}let ak={ios:async(e,t,r)=>{let{reinstallIosApp:a}=await import("./apps.js");return await a(e,t,r)},android:async(e,t,r)=>{let{reinstallAndroidApp:a}=await import("./3340.js");return await a(e,t,r)}},aN={ios:async(e,t,r)=>{let{installIosApp:a}=await import("./apps.js"),n=await a(e,r,{appIdentifierHint:t});return{bundleId:n.bundleId,appName:n.appName,launchTarget:n.launchTarget}},android:async(e,t,r)=>{let{installAndroidApp:a}=await import("./3340.js"),n=await a(e,r);return{package:n.packageName,appName:n.appName,launchTarget:n.launchTarget}}};async function aD(e){let{req:r,command:a,sessionName:n,sessionStore:i,deployOps:o}=e,s=i.get(n),l=r.flags??{},u=rN(a,s,l);if(u)return u;let d=r.positionals?.[0]?.trim(),p=r.positionals?.[1]?.trim();if(!d||!p)return L("INVALID_ARGS",`${a} requires: ${a} <app> <path-to-app-binary>`);let c=r.meta?.uploadedArtifactId;try{var f;let e,n=c?eA(c,r.meta?.tenantId):ep.expandHome(p);if(!t.existsSync(n))return L("INVALID_ARGS",`App binary not found: ${n}`);let u=await rx({session:s,flags:l,ensureReady:!1});if(!eV(a,u))return L("UNSUPPORTED_OPERATION",`${a} is not supported on this device`);if("ios"===u.platform){let t=await o.ios(u,d,n),r=t.bundleId;e=r?{app:d,appPath:n,platform:"ios",appId:r,bundleId:r,appName:t.appName,launchTarget:t.launchTarget}:{app:d,appPath:n,platform:"ios",appName:t.appName,launchTarget:t.launchTarget}}else{let t=await o.android(u,d,n),r=t.package;e=r?{app:d,appPath:n,platform:"android",appId:r,package:r,packageName:r,appName:t.appName,launchTarget:t.launchTarget}:{app:d,appPath:n,platform:"android",appName:t.appName,launchTarget:t.launchTarget}}let m=e9(e,(f=e,`Installed: ${f.appName??e5(f)}`));return s&&i.recordAction(s,{command:a,positionals:r.positionals??[],flags:r.flags??{},result:m??{}}),{ok:!0,data:m}}finally{c&&N(c)}}async function ax(e,t,r){return await tN(e,t,r)}async function aR(e){let{req:t,sessionName:r,sessionStore:a}=e;if("session_list"===t.command){let e=eR(t);return{ok:!0,data:{sessions:a.toArray().filter(t=>c(t,e)).map(e=>{let t=a.resolveSessionDir(e.name);return{name:e.name,sessionStateDir:t,runnerLogPath:ea(t),platform:e.device.platform,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,..."ios"===e.device.platform&&{device_udid:e.device.id,ios_simulator_device_set:e.device.simulatorSetPath??null}}})}}}if("devices"===t.command)try{let e=tm(t.flags?.androidDeviceAllowlist),r=tA(t.flags?.platform),a=tv({simulatorSetPath:tu(t.flags?.iosSimulatorDeviceSet),platform:r,target:t.flags?.target}),n=await ed({platform:r,target:t.flags?.target,deviceName:t.flags?.device,udid:t.flags?.udid,serial:t.flags?.serial,iosSimulatorSetPath:a,androidSerialAllowlist:e?Array.from(e).sort():void 0}),i=r?n.filter(e=>{var t,a;return t=e,!(a=r)||("apple"===a?ty(t.platform):t.platform===a)}):n,o=(t.flags?.target?i.filter(e=>(e.target??"mobile")===t.flags?.target):i).map(({simulatorSetPath:e,...t})=>t);return{ok:!0,data:{devices:o}}}catch(t){let e=i(t);return L(e.code,e.message,e.details)}if("apps"===t.command){let e=a.get(r),n=t.flags??{},i=rN(t.command,e,n);if(i)return i;let o=await rx({session:e,flags:n,ensureReady:!0});if(!eV("apps",o))return L("UNSUPPORTED_OPERATION","apps is not supported on this device");let s=tx(t.flags?.appsFilter);return ty(o.platform)?{ok:!0,data:{apps:(await tR(o,s)).map(e=>e.name&&e.name!==e.bundleId?`${e.name} (${e.bundleId})`:e.bundleId)}}:{ok:!0,data:{apps:(await tw(o,s)).map(e=>e.name&&e.name!==e.package?`${e.name} (${e.package})`:e.package)}}}return null}async function aM(e){let{ensureAndroidEmulatorBooted:t}=await import("./3340.js");return await t(e)}let aP='iOS appstate requires an active session on the target device. Run open first (for example: open --session sim --platform ios --device "<name>" <app>).',aL='macOS appstate requires an active session on the target device. Run open first (for example: open --session macos --platform macos "System Settings").';async function aO(e){let{req:t,sessionName:r,sessionStore:a}=e,n=a.get(r),i=t.flags??{},o=tA(i.platform);if(!n&&"string"==typeof i?.session&&i.session.trim().length>0)return L("SESSION_NOT_FOUND","ios"===o?`No active session "${r}". Run open with --session ${r} first.`:`No active session "${r}". Run open with --session ${r} first, or omit --session to query by device selector.`);let s=rN("appstate",n,i);if(s)return s;let l=ty(n?.device.platform)&&!!n&&0===eb(n,i).length;if("ios"===o&&!l)return L("SESSION_NOT_FOUND",aP);if("macos"===o&&!l)return L("SESSION_NOT_FOUND",aL);if(l&&n){let e=n.appName??n.appBundleId;if(!n.appName&&!n.appBundleId){if("macos"===n.device.platform&&n.surface&&"app"!==n.surface&&"frontmost-app"!==n.surface)return{ok:!0,data:{platform:n.device.platform,appName:n.surface,appBundleId:n.appBundleId,source:"session",surface:n.surface}};let e="macos"===n.device.platform?"macOS":"iOS";return L("COMMAND_FAILED",`No foreground app is tracked for this ${e} session. Open an app in the session, then retry appstate.`)}return{ok:!0,data:{platform:n.device.platform,appName:e??"unknown",appBundleId:n.appBundleId,source:"session",surface:n.surface??"app",..."ios"===n.device.platform?{device_udid:n.device.id,ios_simulator_device_set:n.device.simulatorSetPath??null}:{}}}}let u=await rx({session:n,flags:i,ensureReady:!0});if("ios"===u.platform)return L("SESSION_NOT_FOUND",aP);if("macos"===u.platform)return L("SESSION_NOT_FOUND",aL);if("web"===u.platform)return L("UNSUPPORTED_OPERATION","appstate is not supported on web.");let{getAndroidAppState:d}=await import("./3340.js"),p=await d(u);return{ok:!0,data:{platform:"android",package:p.package,activity:p.activity}}}async function aC(e){let{req:t,sessionName:r,sessionStore:a}=e;if("boot"===t.command){let e,n=a.get(r),o=t.flags??{},s=rN(t.command,n,o);if(s)return s;let l="android"===(tA(o.platform)??n?.device.platform),u=!0===o.headless;if(u&&!l)return L("INVALID_ARGS","boot --headless is supported only for Android emulators.");let d=rM({flags:o,sessionDevice:n?.device}),p=l&&!!d,c=!1;try{e=await rx({session:n,flags:o,ensureReady:!1})}catch(r){let t=i(r);if(l&&u&&!d&&"DEVICE_NOT_FOUND"===t.code)return L("INVALID_ARGS","boot --headless requires --device <avd-name> (or an Android emulator session target).");if(!p||"DEVICE_NOT_FOUND"!==t.code||!d)throw r;e=await aM({avdName:d,serial:o.serial,headless:u}),c=!0}if(o.target&&(e.target??"mobile")!==o.target)return L("DEVICE_NOT_FOUND",`No ${e.platform} device found matching --target ${o.target}.`);if(l&&u){if("android"!==e.platform||"emulator"!==e.kind)return L("INVALID_ARGS","boot --headless is supported only for Android emulators.");if(!c){let t=rM({flags:o,sessionDevice:n?.device,resolvedDevice:e});if(!t)return L("INVALID_ARGS","boot --headless requires --device <avd-name> (or an Android emulator session target).");e=await aM({avdName:t,serial:o.serial,headless:!0})}await eH(e)}else("android"!==e.platform||!0!==e.booted)&&await eH(e);return eV("boot",e)?{ok:!0,data:{platform:e.platform,target:e.target??"mobile",device:e.name,id:e.id,kind:e.kind,booted:!0}}:L("UNSUPPORTED_OPERATION","boot is not supported on this device")}if("shutdown"===t.command){var n;let e,i=a.get(r),o=t.flags??{},s=rN(t.command,i,o);if(s)return s;let l=await rx({ensureReady:!1,flags:o,session:i});if(!eV("shutdown",l))return L("UNSUPPORTED_OPERATION","shutdown is supported only for Apple simulators and Android emulators.");if(i&&i.device.platform===l.platform&&i.device.id===l.id)return L("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:l.platform,target:l.target??"mobile",device:l.name,id:l.id,kind:l.kind});let u=await ay(l);return u.success?{ok:!0,data:{platform:l.platform,target:l.target??"mobile",device:l.name,id:l.id,kind:l.kind,shutdown:u}}:L(u.error?.code??"COMMAND_FAILED",(n=u,(e=n.error?.message??n.stderr.trim()).length>0?e:"Shutdown failed"),{platform:l.platform,target:l.target??"mobile",device:l.name,id:l.id,kind:l.kind,shutdown:u})}return"appstate"===t.command?await aO({req:t,sessionName:r,sessionStore:a}):null}async function aE(e,t={}){var r,a,n;let i,o,s,l,u=(s=(o=(i=function(e){let t=[];for(let r of e){if("open"!==r.command)continue;let e=r.result?.startup;e&&"object"==typeof e&&"number"==typeof e.durationMs&&Number.isFinite(e.durationMs)&&"string"==typeof e.measuredAt&&0!==e.measuredAt.trim().length&&e.method===r6&&t.push({durationMs:Math.max(0,Math.round(e.durationMs)),measuredAt:e.measuredAt,method:r6,appTarget:"string"==typeof e.appTarget&&e.appTarget.length>0?e.appTarget:void 0,appBundleId:"string"==typeof e.appBundleId&&e.appBundleId.length>0?e.appBundleId:void 0})}return t.slice(-20)}((r=e).actions)).at(-1))?{available:!0,lastDurationMs:o.durationMs,lastMeasuredAt:o.measuredAt,method:r6,sampleCount:i.length,samples:i}:{available:!1,reason:"No startup sample captured yet. Run open <app|url> in this session first.",method:r6},{session:r.name,platform:r.device.platform,device:r.device.name,deviceId:r.device.id,metrics:{startup:s,...{fps:aU(),memory:{available:!1,reason:r8},cpu:{available:!1,reason:r8}}},sampling:{startup:{method:r6,description:"Elapsed wall-clock time around dispatching the open command for the active session app target.",unit:"ms"},..."android"===(a=r).device.platform?{memory:{method:eq,description:eP,unit:"kB"},cpu:{method:ec,description:en,unit:"percent"},fps:{method:D,description:e_,unit:"percent",primaryField:"droppedFramePercent",window:"since previous Android gfxinfo reset or app process start",resetsAfterRead:!0,relatedActionsLimit:12}}:z(a.device)}});return aK(e)&&(e.appBundleId?"android"===e.device.platform?await aF(u,e,e.appBundleId,t):await aq(u,e,e.appBundleId):(n=u,l=aB(e),n.metrics.fps={available:!1,reason:l},n.metrics.memory={available:!1,reason:l},n.metrics.cpu={available:!1,reason:l})),u}async function a$(e,t={}){var r,a;let n={session:(r=e).name,platform:r.device.platform,device:r.device.name,deviceId:r.device.id,metrics:{fps:aU()},sampling:{fps:"android"===(a=r).device.platform?{method:D,description:e_,unit:"percent",primaryField:"droppedFramePercent",window:"since previous Android gfxinfo reset or app process start",resetsAfterRead:!0,relatedActionsLimit:12}:x(a.device)}};return aK(e)&&(e.appBundleId?await aG(n,e,e.appBundleId,t):n.metrics.fps={available:!1,reason:aB(e)}),n}async function aV(e,t){var r,a;let n={session:(r=e).name,platform:r.device.platform,device:r.device.name,deviceId:r.device.id,sampling:{memory:"android"===(a=r).device.platform?{method:eq,description:eP,unit:"kB",topConsumerLimit:5}:z(a.device).memory,snapshot:"android"===r.device.platform?{method:B,description:G,defaultKind:"android-hprof",artifactOnly:!0}:{method:eM,description:d,defaultKind:"memgraph",artifactOnly:!0}}};if(!aK(e)){if("snapshot"===t.action){let r=aX(e,t.kind);return n.artifact=aY(e,r),n.support=aQ(n.artifact.support)??aZ(e),n}return n.metrics={memory:{available:!1,reason:r8}},n}return"sample"===t.action?n.metrics={memory:await az(e,t)}:(n.artifact=await aJ(e,t),n.support=aQ(n.artifact.support)??aZ(e)),n}function aU(){return{available:!1,reason:"Dropped-frame sampling is currently available only on Android app sessions and connected iOS device app sessions."}}async function aF(e,t,r,a){let n=await aH(t,r,a);aT(e,t,n)}async function aq(e,t,r){let a=await aj(t,r);aT(e,t,a)}function aT(e,t,r){e.metrics.memory=a1(r.memory),e.metrics.cpu=a1(r.cpu),e.metrics.fps=a3(a1(r.fps),t)}async function aG(e,t,r,a){let n="android"===t.device.platform?await a0(eF(t.device,r,{adb:a.androidAdb})):await a0(m(t.device,r));e.metrics.fps=a3(a1(n),t)}function aK(e){return"android"===e.device.platform||"ios"===e.device.platform||"macos"===e.device.platform}function aB(e){return"android"===e.device.platform?"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."}async function aH(e,t,r){let a={adb:r.androidAdb},[n,i,o]=await Promise.allSettled([T(e.device,t,a),K(e.device,t,a),eF(e.device,t,a)]);return{memory:n,cpu:i,fps:o}}async function aj(e,t){let r=await a0(m(e.device,t)),a=await a0(eU(e.device,t));if("fulfilled"===a.status){let e=a.value;return{memory:{status:"fulfilled",value:e.memory},cpu:{status:"fulfilled",value:e.cpu},fps:r}}return{memory:{status:"rejected",reason:a.reason},cpu:{status:"rejected",reason:a.reason},fps:r}}async function az(e,t){return e.appBundleId?a1("android"===e.device.platform?await a0(T(e.device,e.appBundleId,{adb:t.androidAdb})):await a0(aW(e))):{available:!1,reason:aB(e)}}async function aW(e){if(!e.appBundleId)throw new s("INVALID_ARGS",aB(e));return(await eU(e.device,e.appBundleId)).memory}async function aJ(e,t){if(!e.appBundleId)throw new s("INVALID_ARGS",aB(e),{hint:"Run open <app> first so perf memory snapshot can resolve the app process."});let a=aX(e,t.kind),n=function(e,t){if(e.out)return ep.expandHome(e.out,e.cwd);let a=new Date().toISOString().replace(/[:.]/g,"-"),n=e.sessionStore.ensureSessionDir(e.sessionName);return r.join(n,"artifacts",`memory-${t}-${a}.${"android-hprof"===t?"hprof":"memgraph"===t?"memgraph":"artifact"}`)}(t,a);return"android"===e.device.platform?"android-hprof"!==a?aY(e,a):await A(e.device,e.appBundleId,n,{adb:t.androidAdb}):"memgraph"!==a?aY(e,a):await h(e.device,e.appBundleId,n)}function aX(e,t){return t||("android"===e.device.platform?"android-hprof":"memgraph")}function aY(e,t){var r,a;let n=aZ(e),i=(r=e,a=t,"android"===r.device.platform?{reason:`Android perf memory snapshot supports android-hprof, not ${a}.`,hint:"Use perf memory snapshot --kind android-hprof for Android Java heap artifacts."}:"ios"===r.device.platform||"macos"===r.device.platform?{reason:`Apple perf memory snapshot supports memgraph, not ${a}.`,hint:"Use perf memory snapshot --kind memgraph for supported Apple app sessions."}:{reason:`Memory snapshot artifacts are not supported on ${r.device.platform}.`,hint:"Use perf memory sample where supported, or run the snapshot against Android, iOS simulator, or macOS."});return{available:!1,kind:t,reason:i.reason,hint:i.hint,support:n}}function aZ(e){return"android"===e.device.platform?{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."}:"ios"!==e.device.platform&&"macos"!==e.device.platform?{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."}:{...ef(e.device),androidHprof:!1,heapprofd:!1,heapprofdDecision:"Deferred because heapprofd is Android/Perfetto-specific and outside this memory artifact slice."}}function aQ(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:void 0}async function a0(e){try{return{status:"fulfilled",value:await e}}catch(e){return{status:"rejected",reason:e}}}function a1(e){if("fulfilled"===e.status)return{available:!0,...e.value};let t=o(e.reason);return{available:!1,reason:t.message,error:t}}function a3(e,t){var r,a;let n,i;if(!0!==e.available)return e;let o=(r=t.actions,n=a2((a=e).windowStartedAt),i=a2(a.windowEndedAt)??a2(a.measuredAt),void 0===n||void 0===i?[]:r.filter(e=>e.ts>=n&&e.ts<=i).map(e=>({command:e.command,at:new Date(e.ts).toISOString(),offsetMs:Math.max(0,Math.round(e.ts-n)),target:function(e){let t=e.result;if(t)for(let e of["refLabel","ref","appName","appBundleId"]){let r=t[e];if("string"==typeof r&&r.length>0)return r}}(e)})).slice(-12));return 0===o.length?e:{...e,relatedActions:o}}function a2(e){if("string"!=typeof e)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}async function a5(e){var t,r,a,n,i,s,l,u,d,p;let c,f,m,h,g,w,y=(t=e.req,r=e.area,c=(a=t,n=r,"string"==typeof a.flags?.out&&a.flags.out.length>0?a.flags.out:(a.positionals??[])["cpu"===n?5:4]||void 0),"cpu"===r?(i=t,s=c,f=a4(i,1),m=a4(i,2),h=a4(i,3),ez(f)?"start"!==(l=m)&&"stop"!==l&&"report"!==l?L("INVALID_ARGS","perf cpu profile action must be start, stop, or report"):"simpleperf"!==h?L("INVALID_ARGS","perf cpu profile requires --kind simpleperf"):{ok:!0,area:"cpu",subject:f,action:m,kind:h,outPath:s}:L("INVALID_ARGS",ti)):(u=t,d=c,g=a4(u,1),w=a4(u,2),"start"!==(p=g)&&"stop"!==p?L("INVALID_ARGS","perf trace action must be start or stop"):eQ(w)?"perfetto"!==w?L("INVALID_ARGS","perf trace requires --kind perfetto"):{ok:!0,area:"trace",action:g,kind:w,outPath:d}:L("INVALID_ARGS",e6)));if(!y.ok)return y;let{session:v}=e;if("android"!==v.device.platform)return L("UNSUPPORTED_OPERATION","Android native perf collectors are supported only on Android sessions.");if(!v.appBundleId)return L("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{let t="cpu"===y.area?await a7(e,v,v.appBundleId,y):await a9(e,v,v.appBundleId,y);return{ok:!0,data:t}}catch(e){return{ok:!1,error:o(e)}}}function a4(e,t){return(e.positionals?.[t]??"").toLowerCase()}function a6(e,t){var r;return e.sessionStore.set(e.sessionName,{...e.session,nativePerf:{android:t}}),{action:(r=t).action,platform:"android",type:r.type,kind:r.kind,packageName:r.packageName,appPid:r.appPid,profilerPid:r.profilerPid,state:r.state,startedAt:new Date(r.startedAt).toISOString(),stoppedAt:"number"==typeof r.stoppedAt?new Date(r.stoppedAt).toISOString():void 0,durationMs:r.durationMs,outPath:r.outPath,sizeBytes:r.sizeBytes,remotePath:r.remotePath,method:r.method,summary:r.summary,message:r.message}}function a8(e,t,a){var n,i,o;let s;return t?ep.expandHome(t,e.req.meta?.cwd):(n=e.sessionStore,i=e.sessionName,o=a,s=new Date().toISOString().replace(/[:.]/g,"-"),r.join(n.ensureSessionDir(i),`${s}-${o}`))}async function a7(e,t,r,a){if("start"===a.action){ne(t);let n=a8(e,a.outPath,"cpu.perf.data"),i=await u(t.device,r,n,{adb:e.androidAdbExecutor});return a6(e,i)}let n=nr(t,"cpu-profile",a.kind);if("report"===a.action){await function(e){if("running"===e.state)throw new s("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."})}(n);let r=a8(e,a.outPath,"cpu-report.json");return await eL(t.device,n,r,{adb:e.androidAdbExecutor})}let i=nt(e,a.outPath,n),o=await el(t.device,n,i,{adb:e.androidAdbExecutor});return a6(e,o)}async function a9(e,t,r,a){if("start"===a.action){ne(t);let n=a8(e,a.outPath,"app.perfetto-trace"),i=await y(t.device,r,n,{adb:e.androidAdbExecutor});return a6(e,i)}let n=nr(t,"trace",a.kind),i=nt(e,a.outPath,n),o=await em(t.device,n,i,{adb:e.androidAdbExecutor});return a6(e,o)}function ne(e){let t=e.nativePerf?.android;if(t?.state==="running")throw new s("COMMAND_FAILED",`Android ${t.kind} ${t.type} is already running for this session.`,{hint:"cpu-profile"===t.type?"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 nt(e,t,r){return t?a8(e,t,r.outPath):r.outPath}function nr(e,t,r){let a=e.nativePerf?.android;if(a?.type===t&&a.kind===r)return a;throw new s("COMMAND_FAILED",`No Android ${r} ${t} is active for this session.`,{hint:"cpu-profile"===t?"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 na(e,t){let r,a,n=(r=e.req.positionals??[],"cpu"===(a=r[0]?.toLowerCase())?function(e){if(e[1]?.toLowerCase()!=="profile")return L("INVALID_ARGS","perf cpu requires profile");let t=nn(e[2],"perf cpu profile",!0);if(!t.ok)return t;let r=ni(e[3]);return r.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}:r}(r):"trace"===a?function(e){let t=nn(e[1],"perf trace",!1);if(!t.ok)return t;let r=ni(e[2]);return r.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}:r}(r):L("INVALID_ARGS",eJ));if(!n.ok)return n;if("android"===t.device.platform)return L("UNSUPPORTED_OPERATION","Android native profiling belongs to the Android perf rollout; Apple xctrace perf supports iOS and macOS sessions only.");if("ios"!==t.device.platform&&"macos"!==t.device.platform)return L("UNSUPPORTED_OPERATION",`Apple xctrace perf is not supported on ${t.device.platform}.`);if(!t.appBundleId)return L("INVALID_ARGS","Apple xctrace perf requires an active app session. Run open <app> first.");try{if("start"===n.action)return await no(e,t,n);if("stop"===n.action)return await ns(e,t,n);return await nl(e,t,n)}catch(e){return{ok:!1,error:o(e)}}}function nn(e,t,r){let a=e?.toLowerCase();return"start"===a||"stop"===a||r&&"report"===a?{ok:!0,value:a}:L("INVALID_ARGS",r?`${t} requires start, stop, or report`:`${t} requires start or stop`)}function ni(e){return e?.toLowerCase()==="xctrace"?{ok:!0}:L("INVALID_ARGS","perf native collection currently supports --kind xctrace")}async function no(e,t,r){if(t.applePerf?.active)return L("INVALID_ARGS","Apple xctrace perf capture already in progress");let a=r.template??("cpu-profile"===r.mode?"Time Profiler":"Animation Hitches"),n=nd(e,r),i=await H({device:t.device,appBundleId:t.appBundleId,mode:r.mode,template:a,outPath:n});t.applePerf={...t.applePerf??{},active:i},e.sessionStore.set(e.sessionName,t);let o=np("started",i);return nu(e,t,o),{ok:!0,data:o}}async function ns(e,t,r){var a,n,o,s,l,u,d;let p,c=t.applePerf?.active;if(!c)return L("INVALID_ARGS","no active Apple xctrace perf capture");let f=r.outPath?ep.expandHome(r.outPath,e.req.meta?.cwd):c.outPath;try{p=await S(c,f)}catch(r){throw a=r,i(a).details?.captureCleanedUp===!0&&(n=e,(o=t).applePerf={...o.applePerf??{},active:void 0},n.sessionStore.set(n.sessionName,o)),r}s=e,l=t,u=p,l.applePerf={...l.applePerf??{},active:void 0,lastMode:u.mode,..."cpu-profile"===(d=u).mode?{lastProfileTracePath:d.outPath,lastProfileTemplate:d.template}:{lastTracePath:d.outPath}},s.sessionStore.set(s.sessionName,l);let m=np("stopped",p);return nu(e,t,m),{ok:!0,data:m}}async function nl(e,t,r){var a;let n;if("cpu-profile"!==r.mode)return L("INVALID_ARGS","perf trace does not support report");if(t.applePerf?.active)return L("INVALID_ARGS","perf cpu profile report requires a stopped profile trace; stop the active capture first.");let i=nd(e,r),o=(a=t,(n=r.tracePath??a.applePerf?.lastProfileTracePath??a.applePerf?.active?.outPath)?{ok:!0,value:n}:L("INVALID_ARGS","perf cpu profile report requires a stopped profile trace or tracePath option"));if(!o.ok)return o;let s={perf:"reported",...await b({tracePath:ep.expandHome(o.value,e.req.meta?.cwd),outPath:i,mode:r.mode,template:t.applePerf?.lastProfileTemplate??r.template,appBundleId:t.appBundleId})};return nu(e,t,s),{ok:!0,data:s}}function nu(e,t,r){e.sessionStore.recordAction(t,{command:"perf",positionals:e.req.positionals??[],flags:e.req.flags??{},result:r})}function nd(e,t){if(t.outPath)return ep.expandHome(t.outPath,e.req.meta?.cwd);let r=e.sessionStore.ensureSessionDir(e.sessionName),a=new Date().toISOString().replace(/[:.]/g,"-"),n="report"===t.action?"json":"trace";return`${r}/perf-${t.mode}-${a}.${n}`}function np(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}}let nc=`logs requires ${e7.slice(0,-1).join(", ")}, or ${e7.at(-1)}`,nf=["dump","log"],nm=`network requires ${nf.join(" or ")}`,nh=`network include mode must be one of: ${tP.join(", ")}`,ng={path:({session:e,sessionName:t,sessionStore:r})=>(function(e,t,r){let a=r.resolveAppLogPath(t),n=U(a);return{ok:!0,data:{path:a,active:!!e.appLog,state:e.appLog?.getState()??"inactive",backend:e.appLog?.backend??eo(e.device),sizeBytes:n.sizeBytes,modifiedAt:n.modifiedAt,startedAt:e.appLog?.startedAt?new Date(e.appLog.startedAt).toISOString():void 0,hint:'Grep the file for token-efficient debugging, e.g. grep -n "Error\\|Exception" <path>'}}})(e,t,r),doctor:({session:e,sessionName:t,sessionStore:r})=>n_(e,t,r),mark:({req:e,sessionName:t,sessionStore:r})=>{var a,n,i;let o,s;return a=e,n=t,i=r,o=a.positionals?.slice(1).join(" ")??"",f(s=i.resolveAppLogPath(n),o),{ok:!0,data:{path:s,marked:!0}}},clear:({session:e,sessionName:t,sessionStore:r,restart:a})=>nb(e,t,r,a),start:({session:e,sessionName:t,sessionStore:r})=>nI(e,t,r),stop:({session:e,sessionName:t,sessionStore:r})=>nk(e,t,r)};async function nw(e){let{req:t}=e;return"perf"===t.command?ny(e):"logs"===t.command?nS(e):"network"===t.command?nN(e):null}async function ny(e){var t;let{req:r,sessionName:a,sessionStore:n,androidAdbExecutor:i}=e,l=n.get(a);if(!l)return L("SESSION_NOT_FOUND","perf requires an active session. Run open first.");let u=(r.positionals?.[0]??"metrics").toLowerCase();if("cpu"===(t=u)||"trace"===t)return"android"===l.device.platform?await a5({req:r,sessionName:a,sessionStore:n,session:l,androidAdbExecutor:i,area:u}):await na(e,l);let d=function(e){var t,r,a,n,i,l,u,d,p,c;let f,m,h=e8(f=(e.positionals?.[0]??"metrics").toString().toLowerCase())?f:void 0;if(!h)return L("INVALID_ARGS",eJ);if("cpu"===h||"trace"===h)return{ok:!0,native:!0};let g=ej(m=(e.positionals?.[1]??"sample").toString().toLowerCase())?m:void 0;if(!g)return L("INVALID_ARGS",eY);let w=function(e){if(void 0!==e)return"string"==typeof e&&eQ(e)?e:new s("INVALID_ARGS",e6)}(e.flags?.kind);if(w instanceof s)return{ok:!1,error:o(w)};let y=(t=h,r=g,("memory"===t?nA(r)?void 0:L("INVALID_ARGS","perf memory requires sample or snapshot"):"sample"!==r?L("INVALID_ARGS","perf metrics and perf frames only support sample"):void 0)??(a=e,n=h,i=g,l=w,function(e,t,r){if(e&&("memory"!==t||"snapshot"!==r))return L("INVALID_ARGS","--out is only supported with perf memory snapshot")}(a.flags?.out,n,i)??(u=l,d=n,p=i,u?"memory"!==d||"snapshot"!==p?L("INVALID_ARGS","--kind is only supported with perf memory snapshot"):e0(u)?void 0:L("INVALID_ARGS",e4):void 0)));return y||{ok:!0,native:!1,area:h,action:g,kind:w,out:"string"==typeof(c=e.flags?.out)&&c.length>0?c:void 0}}(r);if(!d.ok)return d;if(d.native)return await na(e,l);try{return{ok:!0,data:await nv(e,l,d)}}catch(e){return{ok:!1,error:o(e)}}}async function nv(e,t,r){let{sessionName:a,sessionStore:n,androidAdbExecutor:i}=e;return"memory"===r.area?await aV(t,{action:function(e){if(nA(e))return e;throw new s("INVALID_ARGS","perf memory requires sample or snapshot")}(r.action),kind:r.kind,out:r.out,cwd:e.req.meta?.cwd,sessionName:a,sessionStore:n,androidAdb:i}):"frames"===r.area?await a$(t,{androidAdb:i}):await aE(t,{androidAdb:i})}function nA(e){return"sample"===e||"snapshot"===e}async function nS(e){var t;let r,a,{req:n,sessionName:i,sessionStore:o}=e,s=o.get(i);if(!s)return L("SESSION_NOT_FOUND","logs requires an active session");if(!eV("logs",s.device))return L("UNSUPPORTED_OPERATION","logs is not supported on this device");let l=(t=n,r=(t.positionals?.[0]??"path").toLowerCase(),a=!!t.flags?.restart,e7.includes(r)?a&&"clear"!==r?L("INVALID_ARGS","logs --restart is only supported with logs clear"):{ok:!0,action:r,restart:a}:L("INVALID_ARGS",nc));return l.ok?await ng[l.action]({...e,session:s,restart:l.restart}):l}async function n_(e,t,r){let a=r.resolveAppLogPath(t),n=await ey(e.device,e.appBundleId);return{ok:!0,data:{path:a,active:!!e.appLog,state:e.appLog?.getState()??"inactive",checks:n.checks,notes:n.notes}}}async function nb(e,t,r,a){if(e.appLog&&!a)return L("INVALID_ARGS","logs clear requires logs to be stopped first; run logs stop");let n=r.resolveAppLogPath(t);if(!a)return{ok:!0,data:J(n)};let i=e.appBundleId;if(!i)return L("INVALID_ARGS","logs clear --restart requires an app session; run open <app> first");e.appLog&&await ex(e.appLog);let s=J(n),l=r.resolveAppLogPidPath(t);try{let a=await eK(e.device,i,n,l);return r.set(t,{...e,appLog:{platform:e.device.platform,backend:a.backend,outPath:n,startedAt:a.startedAt,getState:a.getState,stop:a.stop,wait:a.wait}}),{ok:!0,data:{...s,restarted:!0}}}catch(a){return r.set(t,{...e,appLog:void 0}),{ok:!1,error:o(a)}}}async function nI(e,t,r){if(e.appLog)return L("INVALID_ARGS","app log already streaming; run logs stop first");if(!e.appBundleId)return L("INVALID_ARGS","logs start requires an app session; run open <app> first");let a=r.resolveAppLogPath(t),n=r.resolveAppLogPidPath(t);try{let i=await eK(e.device,e.appBundleId,a,n);return r.set(t,{...e,appLog:{platform:e.device.platform,backend:i.backend,outPath:a,startedAt:i.startedAt,getState:i.getState,stop:i.stop,wait:i.wait}}),{ok:!0,data:{path:a,started:!0}}}catch(e){return{ok:!1,error:o(e)}}}async function nk(e,t,r){if(!e.appLog)return L("INVALID_ARGS","no app log stream active");let a=e.appLog.outPath;return await ex(e.appLog),r.set(t,{...e,appLog:void 0}),{ok:!0,data:{path:a,stopped:!0}}}async function nN(e){let t=function(e){let{req:t,sessionName:r,sessionStore:a}=e,n=a.get(r);if(!n)return L("SESSION_NOT_FOUND","network requires an active session");if(!eV("network",n.device))return L("UNSUPPORTED_OPERATION","network is not supported on this device");let i=(t.positionals?.[0]??"dump").toLowerCase();if(!nf.includes(i))return L("INVALID_ARGS",nm);let o=t.positionals?.[1]?Number.parseInt(t.positionals[1],10):25;if(!Number.isInteger(o)||o<1||o>200)return L("INVALID_ARGS","network dump limit must be an integer in range 1..200");let s=function(e){let t=e.positionals?.[2]?.toLowerCase(),r=e.flags?.networkInclude;if(t&&r&&t!==r)return L("INVALID_ARGS","network include mode was provided both positionally and via --include with different values");let a=(r??t??"summary").toLowerCase();return tP.includes(a)?{ok:!0,include:a}:L("INVALID_ARGS",nh)}(t);return s.ok?{ok:!0,session:n,maxEntries:o,include:s.include}:s}(e);if(!t.ok)return t;let{include:r,maxEntries:a,session:n}=t;if("web"===n.device.platform)return await nD({include:r,maxEntries:a});let i=await ee({device:n.device,appBundleId:n.appBundleId,appLogState:n.appLog?.getState(),appLogStartedAt:n.appLog?.startedAt,appLogPath:e.sessionStore.resolveAppLogPath(e.sessionName),maxEntries:a,include:r,maxPayloadChars:2048,maxScanLines:4e3});return{ok:!0,data:{...i.dump,active:!!n.appLog,state:n.appLog?.getState()??"inactive",backend:i.backend,notes:i.notes}}}async function nD(e){let t=tM();if(!t.dumpNetwork)return L("UNSUPPORTED_OPERATION","network is not supported by this web provider");try{let r=await t.dumpNetwork({include:e.include,limit:e.maxEntries});return{ok:!0,data:{entries:r.entries,active:!0,state:"active",backend:r.backend??"agent-browser",include:e.include,matchedLines:r.entries.length,scannedLines:r.entries.length,limits:{maxEntries:e.maxEntries,maxPayloadChars:2048,maxScanLines:r.entries.length},notes:r.notes}}}catch(e){return{ok:!1,error:o(e)}}}function nx(e,t,r){var a,n;if(null==e)return tB("open",[tW(tj(t,"launchApp"),r)]);if("string"==typeof e)return tB("open",[tW(e,r)]);if(!tH(e))throw new s("INVALID_ARGS","launchApp expects a string or map.");tz(e,"launchApp",["appId","stopApp","clearState","clearKeychain","arguments","permissions","launchArguments"]),nL(e,"permissions"),nL(e,"clearKeychain");let i=tW("string"==typeof e.appId?e.appId:tj(t,"launchApp"),r),o=(a=e,n=r,[...nM(a.arguments,"launchApp.arguments",n),...nM(a.launchArguments,"launchApp.launchArguments",n)]),l=!0===e.clearState;return tB("open",[i],{...!l&&(!0===e.stopApp||o.length>0)?{relaunch:!0}:{},...l?{clearAppState:!0}:{},...o.length>0?{launchArgs:o}:{}})}function nR(e,t,r){if(null==e)return tB("close",[tW(tj(t,"stopApp"),r)]);if("string"==typeof e)return tB("close",[tW(e,r)]);throw new s("INVALID_ARGS","stopApp expects a string appId or no value.")}function nM(e,t,r){if(null==e)return[];if("string"==typeof e)return[tW(e,r)];if(Array.isArray(e))return e.map((e,a)=>nP(e,`${t}[${a}]`,r));if(tH(e))return Object.entries(e).flatMap(([e,a])=>[tW(e,r),nP(a,`${t}.${e}`,r)]);throw new s("INVALID_ARGS",`${t} expects a string, list, or map.`)}function nP(e,t,r){if("string"==typeof e)return tW(e,r);if("number"==typeof e||"boolean"==typeof e)return String(e);throw new s("INVALID_ARGS",`${t} must be a string, number, or boolean.`)}function nL(e,t){if(void 0!==e[t])throw tY(`Maestro launchApp field "${t}" is not supported yet.`)}let nO="__maestroRunScript",nC="__maestroAssertVisible",nE="__maestroAssertNotVisible",n$="__maestroPressEnter",nV="__maestroWaitForAnimationToEnd",nU="__maestroScrollUntilVisible",nF="__maestroSwipeScreen",nq="__maestroSwipeOn",nT="__maestroTapOn",nG="__maestroTapPointPercent";function nK(e){if(null==e)return tB("type",["\b".repeat(50)]);if("number"==typeof e&&Number.isInteger(e)&&e>0)return tB("type",["\b".repeat(e)]);if(!tH(e))throw new s("INVALID_ARGS","eraseText expects empty, a positive count, or a map.");if(tz(e,"eraseText",["charactersToErase"]),void 0===e.charactersToErase)return tB("type",["\b".repeat(50)]);if("number"!=typeof e.charactersToErase||!Number.isInteger(e.charactersToErase)||e.charactersToErase<=0)throw new s("INVALID_ARGS","eraseText.charactersToErase must be a positive integer.");return tB("type",["\b".repeat(e.charactersToErase)])}function nB(e){return"number"==typeof e&&Number.isFinite(e)?String(Math.max(16,Math.floor(e))):void 0}function nH(e,t){let r=e.toLowerCase();switch(r){case"up":case"down":case"left":case"right":return r;default:throw tY(`Maestro ${t} must be UP, DOWN, LEFT, or RIGHT.`)}}function nj(e){return nH(e,"swipe direction")}function nz(e,t,r=[],a){if("string"==typeof e)return nW(tW(e,a));if(!tH(e))throw new s("INVALID_ARGS",`${t} expects a string or selector map.`);tz(e,t,["id","text","enabled","selected",...r]);let n=[],i=[];if("boolean"==typeof e.enabled&&i.push(nX("enabled",String(e.enabled))),"boolean"==typeof e.selected&&i.push(nX("selected",String(e.selected))),"string"==typeof e.id&&n.push(nX("id",tW(e.id,a)),...i),"string"==typeof e.text&&0===n.length)return nW(tW(e.text,a),i);if("string"==typeof e.label&&0===n.length&&n.push(nX("label",tW(e.label,a)),...i),0===n.length&&i.length>0&&n.push(...i),0===n.length)throw new s("INVALID_ARGS",`${t} selector map must include one of id, text, label, enabled, or selected.`);return n.join(" ")}function nW(e,t=[]){return[[nX("label",e),...t].join(" "),[nX("text",e),...t].join(" "),[nX("id",e),...t].join(" ")].join(" || ")}function nJ(e){let t=nB(e.duration);return t?[t]:[]}function nX(e,t){return`${e}=${JSON.stringify(t)}`}function nY(e){var t,r;if(!tH(e))return;let a={},n="number"==typeof(t=e.repeat)&&Number.isInteger(t)&&t>0?t:void 0,i="number"==typeof(r=e.delay)&&Number.isInteger(r)&&r>=0?r:void 0;return n&&n>1&&(a.count=n),void 0!==i&&(a.intervalMs=i),!0===e.optional&&(a.maestro={optional:!0}),Object.keys(a).length>0?a:void 0}function nZ(e){let t=nY(e)??{};return{...t,maestro:{...t.maestro??{},allowNonHittableCoordinateFallback:!0}}}function nQ(e){let t={doubleTap:!0};return tH(e)&&"number"==typeof e.delay&&Number.isInteger(e.delay)&&(t.intervalMs=Math.max(0,e.delay)),t}class n0{index=0;tokens;context;constructor(e,t){this.tokens=e,this.context=t}parse(){let e=this.parseOr();if(this.peek())throw new s("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 s("INVALID_ARGS","Incomplete runFlow.when.true expression.");if("boolean"===e.type)return this.index+=1,e.value;if("paren"===e.type&&"("===e.value){this.index+=1;let e=this.parseOr();if(!this.consumeParen(")"))throw new s("INVALID_ARGS","Unclosed runFlow.when.true parenthesis.");return e}return this.parsePlatformComparison()}parsePlatformComparison(){this.expectPlatform();let e=this.expectEqualityOperator(),t=this.expectString().toLowerCase(),r=this.context.platform;return"=="===e?r===t:r!==t}expectPlatform(){if(this.peek()?.type!=="platform")throw new s("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 s("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 s("INVALID_ARGS","runFlow.when.true comparison requires a string literal.")}consumeOperator(e){let t=this.peek();return t?.type==="operator"&&t.value===e&&(this.index+=1,!0)}consumeParen(e){let t=this.peek();return t?.type==="paren"&&t.value===e&&(this.index+=1,!0)}peek(){return this.tokens[this.index]}}function n1(e,t,r){return{...tB(e,t),replayControl:r}}function n3(e,t,r){let a="string"==typeof e?tW(e,t):e,n="number"==typeof a?a:"string"==typeof a&&/^\d+$/.test(a)?Number(a):void 0;if(void 0===n||!Number.isInteger(n)||n<0)throw new s("INVALID_ARGS",`${r} must be a non-negative integer or \${VAR} resolving to one.`);return n}let n2=`
2
5
  const fs = require('node:fs');
3
6
  const input = JSON.parse(fs.readFileSync(0, 'utf8'));
4
7
  if (typeof fetch !== 'function') {
@@ -19,10 +22,10 @@ fetch(input.url, {
19
22
  console.error(error && error.stack ? error.stack : String(error));
20
23
  process.exit(1);
21
24
  });
22
- `;function ng(e){if("string"!=typeof e)throw new s("COMMAND_FAILED",`Maestro runScript json() expected a string body, received ${typeof e}.`);if(0===e.trim().length)throw new s("COMMAND_FAILED","Maestro runScript json() received an empty body. Check the preceding http response status and setup server output.");try{return JSON.parse(e,nw)}catch(t){throw new s("COMMAND_FAILED",`Maestro runScript json() could not parse response body: ${t instanceof Error?t.message:String(t)}`,{bodyPreview:e.slice(0,1e3)},t instanceof Error?t:void 0)}}function nw(e,t){return"__proto__"===e||"constructor"===e||"prototype"===e?void 0:t}let ny={launchApp:({value:e,config:t,context:r})=>[aX(e,t,r)],tapOn:({value:e,context:t})=>[function(e,t){if("string"==typeof e)return tU(a9,[no(tT(e,t))],np(e));if(tF(e)&&"string"==typeof e.point){tG(e,"tapOn",["point","repeat","delay","optional","label"]);let t=tH(e.point);return"percent"===t.kind?tU(ne,[String(t.x),String(t.y)],nu(e)):tU("click",[String(t.x),String(t.y)],nu(e))}tF(e)&&tG(e,"tapOn",["id","text","childOf","enabled","index","selected","repeat","delay","optional","label"]);let r=np(e);return tU(a9,[ni(e,"tapOn",["repeat","delay","optional","label","index","childOf"],t),...function(e,t){if(!tF(e))return[];let r={};if(void 0!==e.index){if("number"!=typeof e.index||!Number.isInteger(e.index)||e.index<0)throw new s("INVALID_ARGS","tapOn.index must be a non-negative integer.");r.index=e.index}return void 0!==e.childOf&&(r.childOf=ni(e.childOf,"tapOn.childOf",[],t)),Object.keys(r).length>0?[JSON.stringify(r)]:[]}(e,t)],r)}(e,t)],doubleTapOn:({value:e,context:t})=>[function(e,t){if(tF(e)&&"string"==typeof e.point){tG(e,"doubleTapOn",["point","delay"]);let t=tE(e.point);return tU("click",[String(t.x),String(t.y)],nd(e))}return tF(e)&&tG(e,"doubleTapOn",["id","text","enabled","selected","delay"]),tU("click",[ni(e,"doubleTapOn",["delay"],t)],nd(e))}(e,t)],longPressOn:({value:e,context:t})=>[function(e,t){if(tF(e)&&"string"==typeof e.point){tG(e,"longPressOn",["point"]);let t=tE(e.point);return tU("longpress",[String(t.x),String(t.y),"3000"])}return tF(e)&&tG(e,"longPressOn",["id","text","enabled","selected"]),tU("click",[ni(e,"longPressOn",[],t)],{holdMs:3e3})}(e,t)],inputText:({value:e,context:t})=>[tU("type",[tT(function(e){if("string"==typeof e)return e;if(!tF(e))throw new s("INVALID_ARGS","inputText expects a string or map.");if(tG(e,"inputText",["text","label"]),"string"!=typeof e.text)throw new s("INVALID_ARGS","inputText map requires a string text field.");return e.text}(e),t)])],eraseText:({value:e})=>[nt(e)],pasteText:({value:e,context:t,name:r})=>[tU("type",[tT(tB(r,e),t)])],openLink:({value:e,config:t,context:r,name:a})=>{var n,i,o,s,l,u;let p;return[(n=e,i=t,o=r,s=a,p=tT((l=n,u=s,"string"==typeof l?l:tF(l)?(tG(l,u,["link"]),tB(`${u}.link`,l.link)):tB(u,l)),o),("ios"===o.platform||"android"===o.platform)&&i.appId?tU("open",[tT(tq(i,s),o),p],"ios"===o.platform?{maestro:{prewarmRunnerBeforeOpen:!0}}:void 0):tU("open",[p]))]},assertVisible:({value:e,context:t,name:r})=>[tU(a3,[ni(e,r,[],t),"17000"])],assertNotVisible:({value:e,context:t,name:r})=>[tU(a2,[ni(e,r,[],t)])],extendedWaitUntil:({value:e,context:t})=>(function(e,t){if(!tF(e))throw new s("INVALID_ARGS","extendedWaitUntil expects a map.");tG(e,"extendedWaitUntil",["visible","notVisible","timeout"]);let r=e.visible??e.notVisible;if(void 0===r)throw tK("Only Maestro extendedWaitUntil.visible/notVisible is supported.");let a=ni(r,"extendedWaitUntil",[],t),n=String(tj(e,17e3));return void 0!==e.notVisible?[tU(a2,[a,n])]:[tU(a3,[a,n],{maestro:{allowAlreadyPastLoading:!0}})]})(e,t),takeScreenshot:({value:e,context:t,name:r})=>[tU("screenshot",[tT(tB(r,e),t)])],scroll:({value:e})=>[function(e){if(null!=e)throw tK("Maestro scroll options are not supported yet.");return tU("scroll",["down"])}(e)],scrollUntilVisible:({value:e,context:t})=>(function(e,t){if("string"==typeof e)return[tU(a6,[no(tT(e,t)),"5000","down"])];if(!tF(e))throw new s("INVALID_ARGS","scrollUntilVisible expects a string or map.");tG(e,"scrollUntilVisible",["element","direction","timeout"]);let r=ni(e.element,"scrollUntilVisible.element",[],t),a="string"==typeof e.direction?na(e.direction,"scrollUntilVisible.direction"):"down";return[tU(a6,[r,String(tj(e,5e3)),a])]})(e,t),swipe:({value:e,context:t})=>[function(e,t){var r,a,n;let i;if(!tF(e))throw new s("INVALID_ARGS","swipe expects a map.");tG(e,"swipe",["start","end","direction","duration","from","label"]);let o=e.from??("string"==typeof e.label?e.label:void 0);return void 0!==o?(r=e,a=o,n=t,i=nn("string"==typeof r.direction?r.direction:"up"),tU(a7,[ni(a,"swipe.from",[],n),i,...ns(r)])):"string"==typeof e.direction?tU(a8,["direction",nn(e.direction),...ns(e)]):function(e){let{start:t,end:r}=function(e){if("string"==typeof e.start&&"string"==typeof e.end)return{start:tH(e.start),end:tH(e.end)};throw tK("Only Maestro swipe start/end coordinates are supported.")}(e);var a=t,n=r,i=nr(e.duration);if("absolute"===a.kind&&"absolute"===n.kind)return tU("swipe",[String(a.x),String(a.y),String(n.x),String(n.y),...i?[i]:[]]);if("percent"===a.kind&&"percent"===n.kind)return tU(a8,["percent",String(a.x),String(a.y),String(n.x),String(n.y),...i?[i]:[]]);throw tK("Maestro swipe start/end must both be absolute pixels or both be percentages.")}(e)}(e,t)],hideKeyboard:()=>[tU("keyboard",["dismiss"])],pressKey:({value:e})=>[function(e){let t=tB("pressKey",e).toLowerCase();if("back"===t)return tU("back");if("enter"===t||"return"===t)return tU(a5);if("home"===t)return tU("home");throw tK(`Maestro pressKey "${t}" is not supported yet.`)}(e)],back:()=>[tU("back")],waitForAnimationToEnd:({value:e})=>[tU(a4,[String(tj(e,15e3))])],stopApp:({value:e,config:t,context:r})=>[aY(e,t,r)],runScript:({value:e,context:t})=>{let a;return[tU(a1,[function(e,t){if(r.isAbsolute(e))return e;if(!t.baseDir)throw new s("INVALID_ARGS","runScript file paths require replay input to have a source path.");return r.resolve(t.baseDir,e)}((a=function(e,t){if("string"==typeof e)return{file:tT(e,t),env:{}};if(!tF(e))throw new s("INVALID_ARGS","runScript expects a file path string or map.");return tG(e,"runScript",["file","env"]),{file:tT(tB("runScript.file",e.file),t),env:Object.fromEntries(Object.entries(tD(e.env,"runScript.env")).map(([e,r])=>[e,tT(r,t)]))}}(e,t)).file,t)],{...Object.keys(a.env).length>0?{maestro:{runScriptEnv:a.env}}:{}})]},runFlow:({value:e,config:t,context:r,deps:a})=>(function(e,t,r,a,n){if("string"==typeof e)return a.parseRunFlowFile(tT(e,r),r).actions;if(!tF(e))throw new s("INVALID_ARGS","runFlow expects a file path string or map.");tG(e,"runFlow",["file","commands","env","when","label"]);let i=function(e,t){var r,a;if(null==e)return{shouldRun:!0};if(!tF(e))throw new s("INVALID_ARGS","runFlow.when expects a map.");return(tG(e,"runFlow.when",["platform","visible","notVisible","true"]),!function(e,t){if(void 0!==e.true&&!function(e,t){let r;if("boolean"==typeof e)return e;if("string"!=typeof e)throw new s("INVALID_ARGS","runFlow.when.true expects a boolean or expression string.");return new nc(function(e){let t=[],r=0;for(;r<e.length;){var a,n;let i=e.slice(r),o=(a=i,/^\s+/.exec(a)?.[0].length??0);if(o>0){r+=o;continue}let l=function(e){let t="maestro.platform";return e.startsWith(t)?{token:{type:"platform"},length:t.length}:null}(n=i)??function(e){let t=/^(==|!=|&&|\|\|)/.exec(e)?.[1];return t?{token:{type:"operator",value:t},length:t.length}:null}(n)??function(e){let t=e[0];return"("===t||")"===t?{token:{type:"paren",value:t},length:1}:null}(n)??function(e){let t=/^(['"])(.*?)\1/.exec(e);return t?{token:{type:"string",value:t[2]??""},length:t[0].length}:null}(n)??function(e){let t=/^(true|false)\b/.exec(e)?.[1];return t?{token:{type:"boolean",value:"true"===t},length:t.length}:null}(n);if(l){t.push(l.token),r+=l.length;continue}throw new s("INVALID_ARGS",`Unsupported runFlow.when.true expression near "${i.slice(0,24)}".`)}return t}((r=tT(e,t).trim()).startsWith("${")&&r.endsWith("}")?r.slice(2,-1).trim():r),{platform:t.platform}).parse()}(e.true,t))return!1;if(void 0===e.platform)return!0;let r=function(e,t){if("string"!=typeof e)throw new s("INVALID_ARGS",`${t} expects Android, iOS, or Web.`);let r=e.trim().toLowerCase();if("android"===r||"ios"===r||"web"===r)return r;throw new s("INVALID_ARGS",`${t} expects Android, iOS, or Web.`)}(e.platform,"runFlow.when.platform");if(!t.platform)throw new s("INVALID_ARGS","Maestro runFlow.when.platform requires replay to be run with --platform ios|android.");return r===t.platform}(e,t))?{shouldRun:!1}:{shouldRun:!0,...(r=e,a=t,{...void 0!==r.visible?{visibleSelector:ni(r.visible,"runFlow.when.visible",[],a)}:{},...void 0!==r.notVisible?{notVisibleSelector:ni(r.notVisible,"runFlow.when.notVisible",[],a)}:{}})}}(e.when,r);if(!i.shouldRun)return[];let o={...r,env:{...r.env,...tD(e.env,"runFlow.env"),...r.envOverrides}};return function(e,t){let{visibleSelector:r,notVisibleSelector:a}=t;if(!r&&!a)return e;if(r&&a)throw tK("Maestro runFlow.when cannot combine visible and notVisible yet.");let n=r?"visible":"notVisible",i=r??a??"";return[nf("runFlow.when",[n,i],{kind:"maestroRunFlowWhen",mode:n,selector:i,actions:e})]}(function(e,t,r,a,n){if("string"==typeof e.file)return a.parseRunFlowFile(tT(e.file,r),r).actions;if(Array.isArray(e.commands))return n(tM(e.commands),t,r,a);throw new s("INVALID_ARGS","runFlow map requires either file or commands.")}(e,t,o,a,n),i)})(e,t,r,a,nS),repeat:({value:e,config:t,context:r,deps:a})=>(function(e,t,r,a,n){var i;if(!tF(e))throw new s("INVALID_ARGS","repeat expects a map.");if(tG(e,"repeat",["times","commands","while"]),void 0!==e.while)throw tK("Maestro repeat.while is not supported yet. Only deterministic repeat.times is supported.");let o=(i=e.times,nm(i,r,"repeat.times"));if(!Array.isArray(e.commands))throw new s("INVALID_ARGS","repeat requires a commands list.");if(o>1e3)throw new s("INVALID_ARGS","repeat.times must be <= 1000 for deterministic replay expansion.");let l=tM(e.commands);return Array.from({length:o}).flatMap(()=>n(l,t,r,a))})(e,t,r,a,nS),retry:({value:e,config:t,context:r,deps:a})=>(function(e,t,r,a,n){var i,o;if(!tF(e))throw new s("INVALID_ARGS","retry expects a map.");if(tG(e,"retry",["maxRetries","commands"]),!Array.isArray(e.commands))throw new s("INVALID_ARGS","retry requires a commands list.");let l=(i=e.maxRetries,o=r,void 0===i?1:nm(i,o,"retry.maxRetries")),u=n(tM(e.commands),t,r,a);return[nf("retry",[String(l)],{kind:"retry",maxRetries:l,actions:u})]})(e,t,r,a,nS)},nv={launchApp:(e,t)=>[aX(void 0,e,t)],scroll:()=>[tU("scroll",["down"])],hideKeyboard:()=>[tU("keyboard",["dismiss"])],eraseText:()=>[nt(void 0)],back:()=>[tU("back")],waitForAnimationToEnd:()=>[tU(a4,["15000"])],stopApp:(e,t)=>[aY(void 0,e,t)]};function nA(e,t,r,a,n){try{return function(e,t,r,a){if("string"==typeof e){var n,i,o;let a;return n=e,i=t,o=r,(a=nv[n])?a(i,o):tN(n)}let l=Object.entries(e);if(1!==l.length)throw new s("INVALID_ARGS","Maestro command maps must contain exactly one command.");let[u,p]=l[0],d=ny[u];return d?d({value:p,config:t,context:r,deps:a,name:u}):tN(u)}(e,t,a,n)}catch(e){if(e instanceof s&&!/\bline \d+\b/.test(e.message))throw new s(e.code,`${e.message} (line ${r})`,e.details);throw e}}function nS(e,t,r,a){return e.flatMap((e,n)=>nA(e,t,n+1,r,a))}function nI(e,t){let{config:r,commands:a}=nb(tO(e)),n={...t,env:{...t.env,...r.env??{},...t.envOverrides}},{actions:i,actionLines:o}=function(e){let{config:t,commands:r,commandLines:a,context:n}=e,i=[...t.onFlowStart??[],...r,...t.onFlowComplete??[]],o=[...Array.from({length:t.onFlowStart?.length??0},()=>1),...a,...Array.from({length:t.onFlowComplete?.length??0},()=>a.at(-1)??1)],s=[],l=[];for(let[e,r]of i.entries()){let a=o[e]??e+1,i=nA(r,t,a,n,{parseRunFlowFile:n_});s.push(...i),i.forEach(()=>l.push(a))}return function(e,t){let r=[],a=[];for(let n=0;n<e.length;n+=1){let i=e[n],o=function(e,t,r){var a;let n=function(e,t,r){let a=e[r],n=e[r+1],i=e[r+2];if(i?.command!==a5||a.flags?.maestro?.optional===!0)return null;let o=function(e){if(e?.command!=="type"||e.flags&&Object.keys(e.flags).length>0)return null;let[t,...r]=e.positionals??[];return r.length>0||"string"!=typeof t?null:t}(n),s=function(e){if(e?.command!==a9)return null;let[t,...r]=e.positionals??[];return r.length>0||"string"!=typeof t?null:t}(a);return n&&null!==o&&null!==s?{action:a,nextAction:n,pressEnterAction:i,tapSelector:s,typedAfterTap:o,line:t[r]??1}:null}(e,t,r);if(!n)return null;let{action:i,nextAction:o,pressEnterAction:s,tapSelector:l,typedAfterTap:u,line:p}=n;return(a=l,/\b(input|textfield|textarea|field|email|password|username|search|query)\b/i.test(a.replace(/([a-z])([A-Z])/g,"$1 $2")))?{actions:[{...i,command:"wait",positionals:[l,"30000"]},{...o,command:"fill",positionals:[l,u],flags:i.flags},s],actionLines:[p,p,t[r+2]??p],consumed:3}:{actions:[function(e){let t={...e.flags?.maestro??{}};return delete t.allowNonHittableCoordinateFallback,{...e,flags:{...e.flags??{},maestro:{...t}}}}(i)],actionLines:[p],consumed:1}}(e,t,n);if(o){r.push(...o.actions),a.push(...o.actionLines),n+=o.consumed-1;continue}r.push(i),a.push(t[n]??1)}return{actions:r,actionLines:a}}(s,l)}({config:r,commands:a,commandLines:function(e){let t=e.split(/\r?\n/),r=t.findIndex(e=>"---"===e.trim()),a=-1===r?0:r+1,n=[];for(let e=a;e<t.length;e+=1)/^-\s+/.test(t[e]??"")&&n.push(e+1);return n}(e),context:n});return{actions:i,actionLines:o,metadata:{env:r.env}}}function nb(e){if(0===e.length)throw new s("INVALID_ARGS","Maestro flow is empty.");if(Array.isArray(e[0]))return{config:{},commands:tM(e[0])};let t=function(e){if(!tF(e))throw new s("INVALID_ARGS","Maestro flow config must be a YAML map.");return{..."string"==typeof e.name&&e.name.length>0?{name:e.name}:{},..."string"==typeof e.appId&&e.appId.length>0?{appId:e.appId}:{},...tF(e.env)?{env:tD(e.env,"env")}:{},...Array.isArray(e.onFlowStart)?{onFlowStart:tM(e.onFlowStart)}:{},...Array.isArray(e.onFlowComplete)?{onFlowComplete:tM(e.onFlowComplete)}:{}}}(e[0]),r=e[1];if(!Array.isArray(r))throw new s("INVALID_ARGS","Maestro flow must contain a command list after the YAML document separator.");return{config:t,commands:tM(r)}}function n_(e,a){let n=function(e,t){if(r.isAbsolute(e))return e;if(!t.baseDir)throw new s("INVALID_ARGS","runFlow file paths require replay input to have a source path.");return r.resolve(t.baseDir,e)}(e,a);if(a.visitedPaths.has(n))throw new s("INVALID_ARGS",`Maestro runFlow cycle detected at ${n}.`);let i=t.readFileSync(n,"utf8"),o=new Set(a.visitedPaths);return o.add(n),nI(i,{...a,baseDir:r.dirname(n),visitedPaths:o})}let nk=/[*?[\]{}]/;function nN(e,t,a,n,i=0){let o=r.basename(a,r.extname(a)).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return`${e}:test:${t}:${n+1}${o?`-${o}`:""}:attempt-${i+1}`}function nD(e,t){return"number"==typeof e?e:t}function nx(e,t){let r="number"==typeof e?e:t;return"number"!=typeof r?0:Math.max(0,Math.min(3,r))}function nR(e,a,n){var i,o;let l=ef.expandHome(e,a);if(t.existsSync(l)){let a=t.statSync(l);if(a.isDirectory())return{paths:[...n].map(e=>`**/*${e}`).flatMap(e=>t.globSync(e,{cwd:l}).map(e=>r.join(l,e))),source:"directory"};if(a.isFile()){if(!n.has(r.extname(l)))throw new s("INVALID_ARGS",`test does not support this file type: ${e}`);return{paths:[l],source:"file"}}return{paths:[],source:"file"}}if(i=e,!nk.test(i)&&(o=l,!nk.test(o)))throw new s("INVALID_ARGS",`test input not found: ${e}`);let u=r.isAbsolute(l)?l:e;return{paths:t.globSync(u,{cwd:r.isAbsolute(l)?void 0:a}).map(e=>r.isAbsolute(e)?e:r.resolve(a,e)).filter(e=>n.has(r.extname(e))&&function(e){try{return t.statSync(e).isFile()}catch{return!1}}(e)),source:"glob"}}function nM(e,t){let r=nP(e),a=nP(t);return r!==a?r-a:e.localeCompare(t)}function nP(e){return+(".ad"===r.extname(e))}function nL(e){return[...new Set(e.map(e=>r.normalize(e)))]}function nO(e){return"maestro"===e}let nE=["failed to start daemon","runner did not accept connection","xcodebuild exited early","device is offline","device offline","device unauthorized"];function nC(e){var t,r,a,n;let i,o,s="ok"in(t=e)?t.ok?null:t.error:"failed"===t.status?t.error:null;return!!s&&(r=s.details,"timeout_cleanup_pending"===(i="string"==typeof r?.reason?r.reason:"")||!!i&&tc(i)||(a=s.code,n=s.message,o=`${a}
23
- ${n}`.toLowerCase(),nE.some(e=>o.includes(e))))}async function n$(e){let a,n,{filePath:i,sessionName:s,requestId:l,parentRequestId:u,timeoutMs:p,platform:d,target:c,artifactsDir:f,shard:m,progress:h,runReplay:g,cleanupSession:w,finalizeAttempt:y}=e;O(l);let v=function(e,t){if(!t||t===e)return()=>{};let r=eG(t);if(!r)return()=>{};let a=()=>{eN(e)};return r.aborted?(a(),()=>{}):(r.addEventListener("abort",a,{once:!0}),()=>{r.removeEventListener("abort",a)})}(l,u),A=new Set,S=!1,I=Date.now(),b=function(e){let{artifactsDir:a,artifactPaths:n,filePath:i,sessionName:o,requestId:s,timeoutMs:l,platform:u,target:p}=e;if(!a)return;let d=r.join(a,"replay-timing.ndjson");return t.mkdirSync(r.dirname(d),{recursive:!0}),t.writeFileSync(d,""),n.add(d),nq(d,{type:"replay_test_attempt_start",ts:new Date().toISOString(),replayPath:i,session:o,requestId:s,timeoutMs:l,platform:u,target:p}),d}({artifactsDir:f,artifactPaths:A,filePath:i,sessionName:s,requestId:l,timeoutMs:p,platform:d,target:c}),_=ek(h,async()=>await g({filePath:i,sessionName:s,platform:d,target:c,requestId:l,artifactsDir:f,artifactPaths:A,tracePath:b,shard:m})).catch(e=>({ok:!1,error:o(e)})).finally(()=>{v(),eO(l)});try{n="number"==typeof p?await Promise.race([_,new Promise(e=>{a=setTimeout(()=>{S=!0,eN(l),e(function(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}}}}(p,[...A]))},p)})]):await _,nq(b,{type:"replay_test_attempt_stop",ts:new Date().toISOString(),session:s,ok:n.ok,timedOut:S,durationMs:Date.now()-I,errorCode:n.ok?void 0:n.error.code})}finally{var k,N,D;let e,t;a&&clearTimeout(a),S&&(await nV(_)||((k=n)&&!k.ok&&(k.error.details={...k.error.details??{},reason:"timeout_cleanup_pending",timeoutCleanupPending:!0}),tv({level:"warn",phase:"test_timeout_cleanup_race",data:{session:s,requestId:l,graceMs:2e3}}),nU({replayPromise:_,cleanupSession:w,sessionName:s,requestId:l})));let r=await nF({finalizeAttempt:y,sessionName:s,artifactPaths:A,artifactsDir:f,tracePath:b});n?.ok&&r&&!r.ok&&(N=n,D=`Replay test finalization failed: ${r.error.message}`,t=Array.isArray((e=N.data??={}).warnings)?e.warnings.filter(e=>"string"==typeof e):[],e.warnings=[...t,D]);let i=Date.now();try{nq(b,{type:"replay_test_cleanup_start",ts:new Date().toISOString(),session:s}),await w(s),nq(b,{type:"replay_test_cleanup_stop",ts:new Date().toISOString(),session:s,ok:!0,durationMs:Date.now()-i})}catch(t){let e=o(t);nq(b,{type:"replay_test_cleanup_stop",ts:new Date().toISOString(),session:s,ok:!1,durationMs:Date.now()-i,errorCode:e.code}),tv({level:"warn",phase:"test_cleanup_failed",data:{session:s,error:e.message}})}}return n??{ok:!1,error:{code:"COMMAND_FAILED",message:"Unknown replay test failure"}}}async function nV(e){return await Promise.race([e.then(()=>!0),n(2e3).then(()=>!1)])}async function nU(e){let{replayPromise:t,cleanupSession:r,sessionName:a,requestId:n}=e;try{await t}finally{try{await r(a)}catch(e){tv({level:"warn",phase:"test_late_cleanup_failed",data:{session:a,requestId:n,error:o(e).message}})}}}async function nF(e){let{finalizeAttempt:t,sessionName:r,artifactPaths:a,artifactsDir:n,tracePath:i}=e;if(!t)return;let s=Date.now();nq(i,{type:"replay_test_finalize_start",ts:new Date().toISOString(),session:r});try{let e=await t({sessionName:r,artifactPaths:a,artifactsDir:n,tracePath:i});return nq(i,{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 e=o(t);return nq(i,{type:"replay_test_finalize_stop",ts:new Date().toISOString(),session:r,ok:!1,durationMs:Date.now()-s,errorCode:e.code}),tv({level:"warn",phase:"test_finalize_failed",data:{session:r,error:e.message}}),{ok:!1,error:e}}}function nq(e,r){e&&t.appendFileSync(e,`${JSON.stringify(r)}
24
- `)}async function nG(e){var t,a,n;let i,o=function(e){var t;let a,{entry:n,cwd:i,retries:o,suiteArtifactsDir:s,shard:l}=e;return{testStartedAt:Date.now(),testArtifactsDir:r.join(s,...l?[`shard-${l.shardIndex+1}`]:[],(t=n.path,(0===(a=i?r.relative(i,t):r.basename(t)).length||a.startsWith("..")?r.basename(t):a).toLowerCase().replace(/[\\/]+/g,"__").replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"test")),maxAttempts:o+1}}(e),s=await nT(e,o);return t=e,a=o,n=s,i=Date.now()-a.testStartedAt,n.finalResponse?.ok?function(e,t,r,a){var n;let{entry:i,suiteIndex:o,suiteTotal:s,shard:l}=e,u=r.finalResponse;if(!u?.ok)throw Error("Expected passing replay test response.");return eH({type:"replay-test",file:i.path,title:i.title,status:"pass",index:o,total:s,attempt:r.attempts,maxAttempts:t.maxAttempts,durationMs:a,session:r.finalSessionName,artifactsDir:t.testArtifactsDir,...nK(l)}),{file:i.path,title:i.title,session:r.finalSessionName,status:"passed",durationMs:a,finalAttemptDurationMs:r.finalAttemptDurationMs,attempts:r.attempts,artifactsDir:t.testArtifactsDir,...(n=u,{replayed:"number"==typeof n.data?.replayed?n.data.replayed:0,healed:"number"==typeof n.data?.healed?n.data.healed:0}),...function(e){if(!Array.isArray(e))return{};let t=e.filter(e=>"string"==typeof e);return t.length>0?{warnings:t}:{}}(u.data?.warnings),...nH(u.data?.snapshotDiagnostics),...function(e){return nK(e)}(l),...r.attemptFailures.length>0?{attemptFailures:r.attemptFailures}:{}}}(t,a,n,i):function(e,t,r,a){var n,i;let{entry:o,suiteIndex:s,suiteTotal:l,shard:u}=e,p=(n=r.finalResponse)&&!n.ok?n.error:{code:"COMMAND_FAILED",message:"Unknown replay test failure"};return eH({type:"replay-test",file:o.path,title:o.title,status:"fail",index:s,total:l,attempt:r.attempts,maxAttempts:t.maxAttempts,durationMs:a,session:r.finalSessionName,artifactsDir:t.testArtifactsDir,message:p.message,...nK(u)}),{file:o.path,title:o.title,session:r.finalSessionName,status:"failed",durationMs:a,attempts:r.attempts,artifactsDir:t.testArtifactsDir,error:p,...nH((i=r.finalResponse,i?.ok?i.data?.snapshotDiagnostics:i?.error.details?.snapshotDiagnostics)),...function(e){return nK(e)}(u)}}(t,a,n,i)}async function nT(e,t){!function(e,t){let{entry:r,sessionName:a,suiteInvocationId:n,caseIndex:i,suiteIndex:o,suiteTotal:s,shard:l}=e;eH({type:"replay-test",file:r.path,title:r.title,status:"start",index:o,total:s,maxAttempts:t.maxAttempts,session:nN(a,n,r.path,i),artifactsDir:t.testArtifactsDir,...nK(l)})}(e,t);let r={finalSessionName:"",attempts:0,finalAttemptDurationMs:0,attemptFailures:[]};for(let d=0;d<=e.retries&&!ew(e.requestId);d+=1){var a,n,i,o,s,l,u,p;let c=await nB(e,t,d);if((a=r).finalResponse=(n=c).response,a.finalSessionName=n.sessionName,a.attempts=n.attempt,a.finalAttemptDurationMs=n.durationMs,n.response.ok||a.attemptFailures.push({attempt:n.attempt,message:n.response.error.message,durationMs:n.durationMs}),i=e,o=c.response,s=d,o.ok||ew(i.requestId)||nC(o)||s>=i.retries)break;l=e,u=t,(p=c).response.ok||eH({type:"replay-test",file:l.entry.path,title:l.entry.title,status:"fail",index:l.suiteIndex,total:l.suiteTotal,attempt:p.attempt,maxAttempts:u.maxAttempts,durationMs:p.durationMs,retrying:!0,message:p.response.error.message,session:p.sessionName,artifactsDir:u.testArtifactsDir,...nK(l.shard)})}return r}async function nB(e,a,n){var i;let{entry:o,sessionName:s,suiteInvocationId:l,caseIndex:u,suiteIndex:p,suiteTotal:d,requestId:c,timeoutMs:f,shard:m}=e,h=n+1,g=Date.now(),w=nN(s,l,o.path,u,n),y=r.join(a.testArtifactsDir,`attempt-${h}`);i=o.path,t.mkdirSync(y,{recursive:!0}),function(e,a){var n;let i,o=r.join(a,"replay.ad");if(t.copyFileSync(e,o),n=e,".yml"!==(i=r.extname(n).toLowerCase())&&".yaml"!==i)return;let s=r.join(a,r.basename(e));r.resolve(s)!==r.resolve(o)&&t.copyFileSync(e,s)}(i,y);let v=function(e){let{requestId:t,suiteInvocationId:a,filePath:n,caseIndex:i,attemptIndex:o,shardIndex:s}=e,l=void 0===s?"":`:shard:${s+1}`;return ey(`${t??a}${l}:test:${i+1}:${r.basename(n)}:attempt:${o+1}`,a)}({requestId:c,suiteInvocationId:l,filePath:o.path,caseIndex:u,attemptIndex:n,shardIndex:m?.shardIndex}),A=await n$({filePath:o.path,sessionName:w,requestId:v,parentRequestId:c,timeoutMs:f,platform:o.metadata.platform,target:o.metadata.target,artifactsDir:y,shard:m,progress:{file:o.path,title:o.title,index:p,total:d,attempt:h,maxAttempts:a.maxAttempts,session:w,artifactsDir:a.testArtifactsDir,...nK(m)},runReplay:e.runReplay,cleanupSession:e.cleanupSession,finalizeAttempt:e.finalizeAttempt}),S=Date.now()-g;return!function(e){var a;let n,{response:i,filePath:o,sessionName:s,attempts:l,maxAttempts:u,attemptArtifactsDir:p}=e,d=[...Array.isArray(n=(a=i).ok?a.data?.artifactPaths:a.error.details?.artifactPaths)?[...new Set(n.filter(e=>"string"==typeof e))]:[]];i.ok||"string"!=typeof i.error.logPath||d.push(i.error.logPath);let c=function(e,a){let n=[],i=new Map;for(let o of e){if(!function(e){try{return t.statSync(e).isFile()}catch{return!1}}(o))continue;let e=function(e,t){let a=r.extname(e),n=a?e.slice(0,-a.length):e,i=t.get(e)??0;return(t.set(e,i+1),0===i)?e:`${n}-${i+1}${a}`}(r.basename(o),i),s=r.join(a,e);r.resolve(o)!==r.resolve(s)&&t.copyFileSync(o,s),n.push(s)}return n}(d,p),f=[`file: ${o}`,`session: ${s}`,`attempt: ${l}/${u}`,`status: ${i.ok?"passed":"failed"}`];if(i.ok){let e="number"==typeof i.data?.replayed?i.data.replayed:0,t="number"==typeof i.data?.healed?i.data.healed:0;f.push(`replayed: ${e}`,`healed: ${t}`)}else f.push(`code: ${i.error.code}`,`message: ${i.error.message}`),i.error.hint&&f.push(`hint: ${i.error.hint}`),i.error.diagnosticId&&f.push(`diagnosticId: ${i.error.diagnosticId}`),i.error.logPath&&f.push(`logPath: ${i.error.logPath}`),i.error.details?.reason==="timeout"&&f.push("timeoutMode: cooperative");c.length>0&&f.push(`copiedArtifacts: ${c.map(e=>r.basename(e)).join(", ")}`);let m=r.join(p,"result.txt"),h=`${f.join("\n")}
25
- `;t.writeFileSync(m,h),i.ok||t.writeFileSync(r.join(p,"failure.txt"),h)}({response:A,filePath:o.path,sessionName:w,attempts:h,maxAttempts:a.maxAttempts,attemptArtifactsDir:y}),{response:A,sessionName:w,attempt:h,durationMs:S}}function nH(e){let t=tZ(e);return t?{snapshotDiagnostics:t}:{}}function nK(e){return e?{shardIndex:e.shardIndex,shardCount:e.shardCount,deviceId:e.device.id}:{}}async function nj(e,t,r){let a=function(e){let t=nz(e?.shardAll,"--shard-all"),r=nz(e?.shardSplit,"--shard-split");if(void 0!==t&&void 0!==r)throw new s("INVALID_ARGS","--shard-all and --shard-split are mutually exclusive");return void 0!==t?{kind:"all",count:t}:void 0!==r?{kind:"split",count:r}:void 0}(e);if(!a||0===t.length)return;let n=await nW(e,a.count);return{mode:a.kind,shardCount:a.count,total:r+("all"===a.kind?t.length*a.count:t.length),shards:n.map((e,r)=>({shardIndex:r,shardCount:a.count,device:e,entries:"all"===a.kind?t:t.filter((e,t)=>t%a.count===r)}))}}function nz(e,t){if(void 0!==e){if("number"!=typeof e||!Number.isInteger(e)||e<1)throw new s("INVALID_ARGS",`${t} requires a positive integer`);return e}}async function nW(e,t){var r,a,n,i,o,l,u,p,d;let c,f,m=(r=e,"string"!=typeof(c=r?.device)||0===c.trim().length?[]:c.split(",").map(e=>e.trim()).filter(Boolean)),h=(n=await ec((a=e,f=tm(a?.androidDeviceAllowlist),{platform:a?.platform,target:a?.target,iosSimulatorSetPath:to({simulatorSetPath:tu(a?.iosSimulatorDeviceSet),platform:a?.platform,target:a?.target}),androidSerialAllowlist:f?Array.from(f).sort():void 0})),i=m,o=e,i.length>0?(l=n,u=i,p=o,u.map(e=>{let t=nX(e),r=l.find(r=>nJ(r,p)&&(r.id===e||nX(r.name)===t));if(!r)throw new s("DEVICE_NOT_FOUND",`No shard device matched ${e}`);return r})):n.filter(e=>{var t;return!!nJ(t=e,o)&&("ios"===t.platform||"android"===t.platform)&&!1!==t.booted}).sort(nY));if(h.length<t){throw new s("DEVICE_NOT_FOUND",`test sharding requires ${(d=t,`${d} device${1===d?"":"s"}`)}, but only ${h.length} matched`)}return h.slice(0,t)}function nJ(e,t){return!(!tl(e.platform,t?.platform)||t?.target&&(e.target??"mobile")!==t.target)}function nX(e){return e.toLowerCase().replace(/_/g," ").replace(/\s+/g," ").trim()}function nY(e,t){return e.id.localeCompare(t.id)}async function nZ(e){let{req:t,sessionName:r,runReplay:a,cleanupSession:n,finalizeAttempt:o}=e;if((t.positionals?.length??0)===0)return E("INVALID_ARGS","test requires at least one path or glob");try{var s,l,u,p;let e,i,d,c,f,m,h=Date.now(),g=await nQ(t);s=g,eH({type:"replay-test-suite",status:"start",total:s.total,runnable:s.runnable.length,skipped:s.entries.length-s.runnable.length,artifactsDir:s.suiteArtifactsDir,shardMode:s.shardPlan?.mode,shardCount:s.shardPlan?.shardCount});let w=g.shardPlan?function(e){let{entries:t,total:r}=e,a=[];for(let[e,n]of t.entries())"skip"===n.kind&&(eH({type:"replay-test",file:n.path,status:"skip",index:e+1,total:r,message:n.message}),a.push({file:n.path,status:"skipped",durationMs:0,reason:n.reason,message:n.message}));return a}({entries:g.entries,total:g.total}):[];g.shardPlan?w.push(...await n0({shards:g.shardPlan.shards,sessionName:r,suiteInvocationId:g.suiteInvocationId,cwd:t.meta?.cwd,requestId:t.meta?.requestId,flags:t.flags,suiteArtifactsDir:g.suiteArtifactsDir,suiteTotal:g.total,runReplay:a,cleanupSession:n,finalizeAttempt:o})):w.push(...await n2({discoveryEntries:g.entries,sessionName:r,suiteInvocationId:g.suiteInvocationId,cwd:t.meta?.cwd,requestId:t.meta?.requestId,flags:t.flags,suiteArtifactsDir:g.suiteArtifactsDir,suiteTotal:g.total,runReplay:a,cleanupSession:n,finalizeAttempt:o}));let y=(l=g.total,u=w,p=Date.now()-h,e=u.filter(e=>"passed"===e.status).length,d=(i=u.filter(e=>"failed"===e.status)).length,c=u.filter(e=>"skipped"===e.status).length,f=e+d,m=t0(u.map(e=>"skipped"===e.status?void 0:e.snapshotDiagnostics)),{total:l,executed:f,passed:e,failed:d,skipped:c,notRun:Math.max(0,l-f-c),durationMs:p,failures:i,tests:u,...m?{snapshotDiagnostics:m}:{}});return{ok:!0,data:y}}catch(t){let e=i(t);return E(e.code,e.message)}}async function nQ(e){var a,n,i,o;let l=function(e){let{inputs:a,cwd:n,platformFilter:i,replayBackend:o}=e,l=new Set(nO(o)?[".yaml",".yml",".ad"]:[".ad"]),u=function(e,a,n,i){if(!nO(i))return[...new Set(e.flatMap(e=>nR(e,a,n).paths))].map(e=>r.normalize(e)).sort((e,t)=>e.localeCompare(t));let o=[],s=[];for(let i of e){let e=function(e,a,n){let i=ef.expandHome(e,a);return t.existsSync(i)&&t.statSync(i).isDirectory()?{paths:function e(a,n){let i=[],o=t.opendirSync(a);try{let t;for(;null!==(t=o.readSync());){let o=r.join(a,t.name);t.isDirectory()?i.push(...e(o,n)):t.isFile()&&n.has(r.extname(t.name))&&i.push(o)}}finally{o.closeSync()}return i}(i,n),source:"directory"}:nR(e,a,n)}(i,a,n);"file"===e.source?o.push(...e.paths):s.push("directory"===e.source?nL(e.paths):e.paths.map(e=>r.normalize(e)).sort(nM))}return nL([...o,...s.flat()])}(a,n??process.cwd(),l,o),p=[];for(let e of u){var d,c,f,m;let a=t.readFileSync(e,"utf8"),n=tC(a),s=(d=a,c=e,nO(o)&&".ad"!==r.extname(c)?function(e){let{config:t}=nb(tO(e));return t.name}(d):void 0);if(!i){p.push({kind:"run",path:e,title:s,metadata:n});continue}if(!n.platform){nO(o)?p.push({kind:"run",path:e,title:s,metadata:n}):p.push({kind:"skip",path:e,reason:"skipped-by-filter",message:`missing platform metadata for --platform ${i}`});continue}f=i,m=n.platform,("apple"===f?"apple"===m||"ios"===m||"macos"===m:m===f)&&p.push({kind:"run",path:e,title:s,metadata:n})}if(0===p.filter(e=>"run"===e.kind).length){let e=i?` for --platform ${i}`:"";throw new s("INVALID_ARGS",`No replay tests matched${e}.`)}return p}({inputs:(n=e).positionals??[],cwd:n.meta?.cwd,platformFilter:n.flags?.platform,replayBackend:n.flags?.replayBackend}),u=l.flatMap((e,t)=>"run"===e.kind?[{entry:e,suiteIndex:t+1}]:[]),p=l.length-u.length,d=(a=e.meta?.requestId,(a?.trim()||`${process.pid}-${Date.now().toString(36)}`).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"suite"),c=await nj(e.flags,u,p);return{entries:l,runnable:u,shardPlan:c,suiteInvocationId:d,suiteArtifactsDir:(i=e,o=d,function(e){let{artifactsDir:t,cwd:a,suiteInvocationId:n}=e,i=ef.expandHome(t??".agent-device/test-artifacts",a);return r.join(i,n)}({artifactsDir:"string"==typeof i.flags?.artifactsDir?i.flags.artifactsDir:void 0,cwd:i.meta?.cwd,suiteInvocationId:o})),total:c?.total??l.length}}async function n0(e){return(await Promise.allSettled(e.shards.map(async t=>await n1({...e,shard:t})))).flatMap((t,r)=>{var a,n;let i;if("fulfilled"===t.status)return t.value;let s=e.shards[r];return s?[(a=s,n=e.sessionName,i=o(t.reason),{file:a.entries[0]?.entry.path??`shard-${a.shardIndex+1}`,session:n3(n,a),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:a.shardIndex,shardCount:a.shardCount,deviceId:a.device.id})]:[]})}async function n1(e){let{shard:t,sessionName:r}=e;return await n5({...e,entries:t.entries,sessionName:n3(r,t),shard:t})}function n3(e,t){return`${e}:shard-${t.shardIndex+1}`}async function n2(e){let{discoveryEntries:t,sessionName:r,suiteInvocationId:a,cwd:n,requestId:i,flags:o,suiteArtifactsDir:s,suiteTotal:l,runReplay:u,cleanupSession:p,finalizeAttempt:d}=e,c=[],f=0;for(let[e,m]of t.entries()){if(ew(i))break;if("skip"===m.kind){eH({type:"replay-test",file:m.path,status:"skip",index:e+1,total:l,message:m.message}),c.push({file:m.path,status:"skipped",durationMs:0,reason:m.reason,message:m.message});continue}f+=1;let t=await nG({entry:m,sessionName:r,suiteInvocationId:a,caseIndex:f-1,cwd:n,requestId:i,retries:nx(o?.retries,m.metadata.retries),timeoutMs:nD(o?.timeoutMs,m.metadata.timeoutMs),suiteArtifactsDir:s,suiteIndex:e+1,suiteTotal:l,runReplay:u,cleanupSession:p,finalizeAttempt:d});if(c.push(t),n4(t,o,i))break}return c}async function n5(e){let{entries:t,sessionName:r,suiteInvocationId:a,cwd:n,requestId:i,flags:o,suiteArtifactsDir:s,suiteTotal:l,shard:u,runReplay:p,cleanupSession:d,finalizeAttempt:c}=e,f=[];for(let[e,m]of t.entries()){if(ew(i))break;let{entry:t,suiteIndex:h}=m,g=await nG({entry:t,sessionName:r,suiteInvocationId:a,caseIndex:e,cwd:n,requestId:i,retries:nx(o?.retries,t.metadata.retries),timeoutMs:nD(o?.timeoutMs,t.metadata.timeoutMs),suiteArtifactsDir:s,suiteIndex:h,suiteTotal:l,shard:u,runReplay:p,cleanupSession:d,finalizeAttempt:c});if(f.push(g),n4(g,o,i))break}return f}function n4(e,t,r){return ew(r)||t?.failFast===!0||nC(e)}let n6={maestro:{parse:function(e,t={}){var a;let n;return nI(e,(n=(a=t).visitedPaths??new Set,a.sourcePath&&n.add(r.resolve(a.sourcePath)),{baseDir:a.sourcePath?r.dirname(a.sourcePath):void 0,platform:tP(a.platform),env:{},envOverrides:a.env??{},visitedPaths:n}))}}};function n8(e){if(0===e.length)return{selectorExpression:null,selectorTimeout:null};let t=e[e.length-1],r=void 0!==t&&/^\d+$/.test(t)?t:null,a=ra(null!==r?e.slice(0,-1):e.slice());return!a||a.rest.length>0?{selectorExpression:null,selectorTimeout:null}:{selectorExpression:a.selectorExpression,selectorTimeout:r}}async function n7(e){let{action:t,sessionName:r,logPath:a,sessionStore:n}=e;if(!(rr(t.command)||["fill","get","is","wait"].includes(t.command)))return null;let i=n.get(r);if(!i)return null;let o=(function(e){let t=[],r=Array.isArray(e.result?.selectorChain)&&e.result?.selectorChain.every(e=>"string"==typeof e)?e.result.selectorChain:[];if(t.push(...r),rr(e.command)){let r=function(e){let t=e.positionals??[];if("longpress"!==e.command)return t;let r=t.at(-1);return t.length>1&&n9(r)?t.slice(0,-1):t}(e),a=r[0]??"";a&&!a.startsWith("@")&&t.push(r.join(" "))}if("fill"===e.command){let r=e.positionals?.[0]??"";r&&!r.startsWith("@")&&Number.isNaN(Number(r))&&t.push(r)}if("get"===e.command){let r=e.positionals?.[1]??"";r&&!r.startsWith("@")&&t.push(e.positionals.slice(1).join(" "))}if("is"===e.command){let{split:r}=t4(e.positionals);r&&t.push(r.selectorExpression)}if("wait"===e.command){let{selectorExpression:r}=n8(e.positionals??[]);r&&t.push(r)}return T(t).filter(e=>e.trim().length>0)})(t).map(e=>ri(e)).filter(e=>null!==e);if(0===o.length)return null;let s=rr(t.command)||"fill"===t.command,l=rr(t.command)||"fill"===t.command||"get"===t.command&&t.positionals?.[0]==="text",u=await ie(i,t,a,s,n);for(let e of o){let r=t1(u.nodes,e,{platform:i.device.platform,requireRect:s,requireUnique:!0,disambiguateAmbiguous:l});if(!r)continue;let a=t6(r.node,i.device.platform,{action:"fill"===t.command?"fill":rr(t.command)?"click":"get"}).join(" || ");if(rr(t.command))return{...t,positionals:"longpress"===t.command?function(e,t){let r="number"==typeof e.result?.durationMs?String(e.result.durationMs):function(e){let t=e.at(-1);return e.length>1&&n9(t)?t:void 0}(e.positionals??[]);return r?[t,r]:[t]}(t,a):[a]};if("fill"===t.command){let e=v(t);if(!e)continue;return{...t,positionals:[a,e]}}if("get"===t.command){let e=t.positionals?.[0];if("text"!==e&&"attrs"!==e)continue;return{...t,positionals:[e,a]}}if("is"===t.command){let{predicate:e,split:r}=t4(t.positionals);if(!e)continue;let n=r?.rest.join(" ").trim()??"",i=[e,a];return"text"===e&&n.length>0&&i.push(n),{...t,positionals:i}}if("wait"===t.command){let{selectorTimeout:e}=n8(t.positionals??[]),r=[a];return e&&r.push(e),{...t,positionals:r}}}return null}function n9(e){return void 0!==e&&""!==e.trim()&&Number.isFinite(Number(e))}async function ie(e,t,r,a,n){let i=el(await p(e.device,"snapshot",[],t.flags?.out,{...ed(r,{...t.flags??{},snapshotInteractiveOnly:a},e.appBundleId,e.trace?.outPath)}),{...t.flags??{},snapshotInteractiveOnly:a});return B(e,i),n.set(e.name,e),i}let it=.35,ir=120,ia=360,ii=8;function io(e,t){return Math.round(Math.min(ia,Math.max(ir,"number"==typeof e?e*it:0,1.5*t)))}let is=new WeakMap,il=new WeakMap,iu=new WeakMap;function ip(e,t,r){return{ok:!1,error:{code:e,message:t,...r?{details:r}:{}}}}async function id(e){var t;let r,a=!0===e.raw||"1"===process.env.AGENT_DEVICE_MAESTRO_RAW_SNAPSHOTS,n=await e.invoke({...e.baseReq,command:"snapshot",positionals:[],flags:{...e.baseReq.flags,noRecord:!0,...a?{snapshotRaw:!0}:{}}});return n.ok&&e.scope&&(t=e.scope,(r=Z(ic(n.data)))&&is.set(t,r)),n}function ic(e){return Array.isArray(e?.nodes)?e:void 0}function im(e,t){e&&il.set(e,{selector:t})}function ih(e){e&&iu.delete(e)}let ig=new Map([["button",0],["link",0],["textfield",0],["textview",0],["searchfield",0],["switch",0],["slider",0],["cell",1],["statictext",2]]);function iw(e,t,r,a,n,i={}){let o=iI(e,t,a);if(r.childOf){let t=iI(e,r.childOf,a);if(0===t.length)return{ok:!1,message:`Maestro childOf parent did not match: ${r.childOf}`};let n=t8(e.nodes);o=o.filter(r=>t.some(t=>t5(e.nodes,r,t,n)))}let s=iv({nodes:e.nodes,matches:o,platform:a}),l=ik(e.nodes,s.matches,r.index,iS(t),n,!0===i.requireOnScreen,i.promoteTapTarget,i.preferredContext);if(!l){let e=r.index??0;return{ok:!1,message:s.blockedByReactNativeOverlay?`React Native overlay is covering app content: ${t}`:o.length>0&&0===s.matches.length?`Maestro selector matched ${o.length} element(s), but none were visible: ${t}`:`Maestro selector did not match index ${e}: ${t}`}}return{ok:!0,node:l.node,rect:l.rect}}function iy(e,t,r,a){let n=iI(e,t,r,{allowLeadingCompositeLabelMatch:!1}),i=iv({nodes:e.nodes,matches:n,platform:r}),o=ik(e.nodes,i.matches,void 0,iS(t),a,!0);return o?{ok:!0,node:o.node,rect:o.rect,matches:i.matches.length}:{ok:!1,message:i.blockedByReactNativeOverlay?`React Native overlay is covering app content: ${t}`:n.length>0?`Maestro selector matched ${n.length} element(s), but none were visible: ${t}`:`Maestro selector did not match: ${t}`}}function iv(e){let t=e.matches.filter(t=>rt({predicate:"visible",node:t,nodes:e.nodes,platform:e.platform}).pass),r=function(e,t,r){let a=ta(e);if(!a.detected||!a.redBox)return{matches:t,blockedByReactNativeOverlay:!1};let n=tr(a),i=n.filter(t=>rt({predicate:"visible",node:t,nodes:e,platform:r}).pass);if(0===i.length)return 0===n.length?{matches:[],blockedByReactNativeOverlay:!0}:{matches:t,blockedByReactNativeOverlay:!1};let o=new Set(i.map(e=>e.index)),s=t.filter(e=>o.has(e.index));return{matches:s,blockedByReactNativeOverlay:t.length>0&&0===s.length}}(e.nodes,t,e.platform);return{matches:r.matches,blockedByReactNativeOverlay:r.blockedByReactNativeOverlay}}function iA(e){return e?.platform==="android"?"android":"ios"}function iS(e){let t=ro(e).selectors.flatMap(e=>e.terms);if(0===t.length||!t.some(e=>"label"===e.key||"text"===e.key)||!t.every(e=>["label","text","id"].includes(e.key)))return null;let r=t.map(e=>"string"==typeof e.value?e.value:""),a=r[0];return a&&r.every(e=>e===a)?a:null}function iI(e,t,r,a={}){for(let n of ro(t).selectors){let t=e.nodes.filter(e=>(function(e,t,r,a){return!!t7(e,t,r)||t.terms.every(t=>(function(e,t,r,a){var n,i,o;return"string"!=typeof t.value||"id"!==(n=t.key)&&"label"!==n&&"text"!==n&&"value"!==n?t7(e,{raw:t.key,terms:[t]},r):ib((i=e,"id"===(o=t.key)?i.identifier:"label"===o?i.label:"value"===o?i.value:t3(i)),t.value,a)})(e,t,r,a))})(e,n,r,a));if(t.length>0)return t}return[]}function ib(e,t,r={}){var a;let n=e??"",i=rn(n),o=rn(t);if(i===o||!1!==r.allowLeadingCompositeLabelMatch&&function(e,t){if(!e||!t||!e.startsWith(t))return!1;let r=e.at(t.length);return","===r||":"===r||";"===r}(i,o))return!0;if(a=t,!/(?:\.\*|\.\+|\[[^\]]+\]|\([^)]*\)|\||\^|\$|\\[dDsSwWbB])/.test(a))return!1;try{return new RegExp(t).test(n)}catch{return!1}}function i_(e,t,r){if(t.rect&&t.rect.width>0&&t.rect.height>0)return{rect:t.rect,inherited:!1};if(t.rect)return null;let a=function(e,t,r){let a=t;for(;"number"==typeof a.parentIndex&&(a=r.get(a.parentIndex)??e[a.parentIndex]);)if(a.rect)return a.rect.width>0&&a.rect.height>0?a.rect:null;return null}(e,t,r);return a?{rect:a,inherited:!0}:null}function ik(e,t,r,a,n,i=!1,o=!1,s){var l,u,p,d,c,f,m,h,g,w,y,v,A,S,I,b,_,k,N;let D,x,R,M,P=t8(e),L=(l=e,u=t,p=P,d=a,c=r,f=n,m=i,R=(x=(D=u.map(e=>{var t;let r;return(r=i_(l,t=e,p))?{node:t,rect:r.rect,inheritedRect:r.inherited}:null}).filter(e=>!!e)).filter(e=>!e.inheritedRect)).length>0?x:D,d&&void 0===c?(h=R,g=f,w=m,M=h.filter(e=>{var t,r;let a,n;return t=e.rect,r=g,a=r?.referenceWidth??1/0,n=r?.referenceHeight??1/0,t.x<a&&t.y<n&&t.x+t.width>0&&t.y+t.height>0}),w||M.length>0?M:h):D),O=function(e,t,r,a,n,i){var o,s,l,u,p,d,c;if(void 0!==r)return t[r]??null;let f=(o=e,s=t,l=a,u=n,p=i,u&&l?function(e,t,r,a){let n=t.filter(e=>0===iC(e.node,r));if(n.length>=2){let t=iD(e,n,r,a);if(t)return t}let i=t.filter(e=>1===iC(e.node,r));return n.length>0||i.length<2?null:iD(e,i,r,a)}(o,s,l,p)??iN(o,s,l,p):iN(o,s,l,p));return(d=f,c=a,n&&c&&d)?function(e,t,r){var a,n,i,o,s,l,u,p,d,c,f,m,h,g,w,y,v,A;let S,I,b,_,k,N,D,x;if(a=t,n=r,!(("cell"===(S=t9(a.node.type??""))||"other"===S||"scrollview"===S||"scroll-area"===S)&&!(a.rect.width<120)&&!(a.rect.height<32)&&!(a.rect.height>80)&&1>=iC(a.node,n)))return null;let R=(i=e,o=t,s=r,l=t8(e),i.filter(e=>{var t,r,a;let n;return e.index!==o.node.index&&!!e.rect&&t5(i,e,o.node,l)&&(t=e,r=o.rect,a=s,!("button"!==(n=t9(t.type??""))&&"cell"!==n&&"other"!==n||1>=iC(t,a))&&!(t.rect.width<16)&&!(t.rect.height<16)&&!!iO(r,t.rect)&&iP(r,t.rect)>=.5)}).sort((e,t)=>e.rect.x-t.rect.x));if(0===R.length)return null;let M=(b=Math.floor((I=[...R.map(e=>e.rect.width)].sort((e,t)=>e-t)).length/2),I[b]??0),P=function(e,t){let r=[],a=e.x,n=e.x+e.width;for(let i of t){let t=Math.max(e.x,i.x),o=Math.min(n,i.x+i.width);t>a&&r.push({x:a,width:t-a}),a=Math.max(a,o)}return n>a&&r.push({x:a,width:n-a}),r}(t.rect,R.map(e=>e.rect)),L=(u=t,p=r,d=P,c=M,N=d.filter(e=>{var t,r;return t=e.width,r=c,!(t<24)&&!(r<24)&&t>=.4*r&&t<=1.6*r}),D=(f=u,m=p,_=d.find(e=>1>Math.abs(e.x-f.rect.x)),k=Math.max(48,Math.min(220,8*m.length+24)),(h=f,g=m,w=_,y=k,w&&"scrollview"===t9(h.node.type??"")&&1>=iC(h.node,g)&&h.rect.width>=240&&h.rect.height>=32&&h.rect.height<=80&&w.width<=.55*h.rect.width&&w.width>=.6*y)?{x:f.rect.x,width:Math.min(k,_.width)}:null),x=N.some(e=>{var t;return t=u.rect,1>Math.abs(e.x-t.x)}),D&&!x?D:1===N.length?N[0]??null:D);return L?(v=t,A=L,{...v,rect:{x:A.x,y:v.rect.y,width:A.width,height:v.rect.height}}):null}(e,f,a)??f:f}(e,L,r,a,o,s);return y=e,v=O,A=P,S=o,I=n,v?S?(b=y,_=v,k=A,N=I,(iL(_.node)?null:t2(b,_.node,k,e=>{if(!iL(e))return null;let t=i_(b,e,k);return t&&function(e,t,r){var a,n;if(!iO(t,e)||(a=e,!((n=t).height<32||n.height>80||a.height<.75*n.height||.75>iP(a,n))&&!(n.width<240)&&n.width>=3*a.width))return!1;let i=iR(t),o=iR(e);if(o>0&&i>30*o)return!1;if(r){let e=r.referenceWidth*r.referenceHeight;if(e>0&&i>.5*e)return!1}return!0}(_.rect,t.rect,N)?{node:e,rect:t.rect}:null}))??{node:v.node,rect:v.rect}):{node:v.node,rect:v.rect}:null}function iN(e,t,r,a){return(function(e,t,r,a){var n;let i,o,s;if(!r||t.length<2)return t;let l=t.filter(e=>0===iC(e.node,r));if(l.length<2)return t;let u=t8(e),p=l.map(t=>({candidate:t,container:ix(e,t.node,u)})).filter(e=>!!e.container);if(p.length<2||p.length!==l.length)return t;let d=p.filter(e=>{var t;return t=e,p.some(e=>e!==t&&t.container.index!==e.container.index&&iE(t.container.rect,e.container.rect)>=.6)});if(d.length<2)return t;let c=(o=Math.max(...i=(n=d).map(e=>iR(e.container.rect))),(s=Math.min(...i))<=0||o<1.2*s?[]:n.filter(e=>iR(e.container.rect)===o).map(e=>e.candidate));if(c.length>0)return c;let f=function(e,t,r,a){if(!r)return[];let n=ix(e,r.node,a),i=n&&iO(n.rect,r.rect)?n:null,o=t.map(e=>({entry:e,score:function(e,t,r){if(r)return e.index===r.index?0:.6>iE(e.rect,r.rect)?1/0:Math.abs(e.index-r.index);if(iE(e.rect,t.rect)>=.6)return 0;let a=e.index-t.node.index;return a>=0?a:1e5+Math.abs(a)}(e.container,r,i)})),s=Math.min(...o.map(e=>e.score));return Number.isFinite(s)?o.filter(e=>e.score===s).map(e=>e.entry.candidate):[]}(e,d,a,u);if(f.length>0)return f;let m=Math.max(...d.map(e=>e.container.index)),h=d.filter(e=>e.container.index===m).map(e=>e.candidate);return h.length>0?h:t})(e,t,r,a).sort((e,t)=>(function(e,t,r){var a,n;let i=function(e,t,r){if(r){let a=iC(e.node,r)-iC(t.node,r);if(0!==a)return a}let a=iM(e.node)-iM(t.node);if(0!==a)return a;let n=Number(e.inheritedRect)-Number(t.inheritedRect);if(0!==n)return n;let i=r&&iM(e.node)===iM(t.node)?iR(t.rect)-iR(e.rect):iR(e.rect)-iR(t.rect);return 0!==i?i:0}(e,t,r);if(0!==i)return i;if(a=e.rect,n=t.rect,Math.round(a.x)!==Math.round(n.x)||Math.round(a.y)!==Math.round(n.y)||Math.round(a.width)!==Math.round(n.width)||Math.round(a.height)!==Math.round(n.height))return e.node.index-t.node.index;let o=(t.node.depth??0)-(e.node.depth??0);return 0!==o?o:t.node.index-e.node.index})(e,t,r))[0]??null}function iD(e,t,r,a){let n=t8(e),i=t.filter(r=>{var a;return(a=r).rect.width>=16&&a.rect.width<=260&&a.rect.height>=24&&a.rect.height<=80&&t.some(t=>{var a,i,o,s;return a=e,i=t,o=r,s=n,!(i.node.index===o.node.index||!iO(i.rect,o.rect)||iR(i.rect)<2*iR(o.rect))&&t5(a,o.node,i.node,s)})});return iN(e,i,r,a)}function ix(e,t,r){return t2(e,t,r,e=>{let t;return!e.rect||"scrollview"!==(t=t9(e.type??""))&&"scroll-area"!==t&&"list"!==t||e.rect.width<240||e.rect.height<320?null:e})}function iR(e){return e.width*e.height}function iM(e){return ig.get(t9(e.type??""))??3}function iP(e,t){let r=Math.max(e.y,t.y);return Math.max(0,Math.min(e.y+e.height,t.y+t.height)-r)/Math.max(1,Math.min(e.height,t.height))}function iL(e){let t=t9(e.type??"");return!0===e.hittable||"button"===t||"link"===t||"cell"===t||"textfield"===t||"searchfield"===t||"switch"===t||"slider"===t}function iO(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 iE(e,t){let r=Math.max(e.x,t.x),a=Math.min(e.x+e.width,t.x+t.width),n=Math.max(e.y,t.y);return Math.max(0,a-r)*Math.max(0,Math.min(e.y+e.height,t.y+t.height)-n)/Math.max(1,Math.min(iR(e),iR(t)))}function iC(e,t){let r=[e.label,t3(e),e.identifier,e.value].filter(e=>!!e);return r.some(e=>e===t)?0:r.some(e=>rn(e)===rn(t))?1:r.some(e=>ib(e,t))?2:3}async function i$(e){let t=iJ(e.positionals,{command:"assertVisible",defaultTimeoutMs:17e3});if(!t.ok)return t.response;let r=iW(e.baseReq,t.selector);return r?await iV(e,t,r):await iF(e,t)}async function iV(e,t,r){let a=Date.now(),n=await iU(e,t,r);if(n.ok){var i;if(i=e.baseReq,i.flags?.platform==="android"){let r=await iX(e,t.selector,"assertVisible");if(!r.visible){let n=iz(e.baseReq,t,r,a);return"return"===n.kind?n.response:await iF(e,t)}}return im(e.scope,t.selector),iQ({ok:!0,data:{selector:t.selector,nativeWait:!0,query:r,response:n.data}},t.selector,a)}return await iq(e,t,n,a)}async function iU(e,t,r){return await e.invoke({...e.baseReq,command:"wait",positionals:[r,String(t.timeoutMs)]})}async function iF(e,t){let r,a,n=Date.now(),i=t.timeoutMs+1e3,o=!1;for(;;){let s=Date.now(),l=await iX(e,t.selector,"assertVisible");if(l.visible)return iQ(l.response,t.selector,n);r=l.response,a=l.snapshot??a;let u=iz(e.baseReq,t,l,n);if("return"===u.kind)return u.response;let p=function(e){var t,r,a,n;return Date.now()-e.startedAt<e.deadlineMs?"wait":(t=e.capturedAfterDeadline,r=e.captureStartedAt,a=e.startedAt,n=e.deadlineMs,!t&&r-a<n)?"capture-again":"finish"}({captureStartedAt:s,capturedAfterDeadline:o,startedAt:n,deadlineMs:i});if("capture-again"===p){o=!0;continue}if("finish"===p)break;await rs(250)}let s=r??ip("COMMAND_FAILED",`Expected visible but did not match: ${t.selector}`,{selector:t.selector,timeoutMs:t.timeoutMs}),l=await iG(e,t,a);return l||i0(s,a,e.baseReq)}async function iq(e,t,r,a){let n=await iX(e,t.selector,"assertVisible");if(n.visible)return iQ(n.response,t.selector,a);let i=iz(e.baseReq,t,n,a);if("return"===i.kind)return i.response;let o=await iG(e,t,n.snapshot);return o||i0(r,n.snapshot,e.baseReq)}async function iG(e,t,r){if(e.baseReq.flags?.platform!=="android")return null;let a=function(e){if(!e)return;let t=iu.get(e);return iu.delete(e),t}(e.scope);return a?"tap"===a.kind?await iT(e,t,r,a):await iB(e,t,a):null}async function iT(e,t,r,a){if(!r)return null;let n=function(e,t,r){var a;let n,i=iA(e.baseReq.flags),o=Z(t),s=iw(t,r.selector,r.options??{},i,o,{promoteTapTarget:!0});if(s.ok)return{ok:!0,target:{kind:"point",point:e0(s.rect)}};let l=iS(r.selector);return l&&(a=t,(n=l.trim().toLowerCase())&&a.nodes.some(e=>[e.label,e.value,e.identifier].some(e=>e?.trim().toLowerCase().includes(n))))?{ok:!0,target:{kind:"text",query:l}}:{ok:!1}}(e,r,a);return n.ok&&(tv({level:"info",phase:"maestro_assert_visible_retry_tap",data:{selector:t.selector,tapSelector:a.selector,originalPoint:a.point,retryTarget:n.target,timeoutMs:5e3}}),(await iK(e,n.target)).ok)?await iH(e,t,"retryTap"):null}async function iB(e,t,r){return(tv({level:"info",phase:"maestro_assert_visible_retry_swipe",data:{selector:t.selector,swipePositionals:r.positionals,timeoutMs:5e3}}),(await ij(e,r)).ok)?await iH(e,t,"retrySwipe"):null}async function iH(e,t,r){let a={...t,timeoutMs:Math.min(t.timeoutMs,5e3)},n=iW(e.baseReq,a.selector);if(!n)return await iF(e,a);let i=Date.now(),o=await iU(e,a,n);return o.ok?(im(e.scope,a.selector),iQ({ok:!0,data:{selector:a.selector,nativeWait:!0,[r]:!0,query:n,response:o.data}},a.selector,i)):await iq(e,a,o,i)}async function iK(e,t){return"text"===t.kind?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 ij(e,t){return await e.invoke({...e.baseReq,command:"swipe",positionals:t.positionals})}function iz(e,t,r,a){var n,i,o,s,l,u,p;return!(n=r.response).ok&&"COMMAND_FAILED"===n.error.code&&n.error.message.includes("React Native overlay")?{kind:"return",response:r.response}:(i=e,o=t.selector,s=r.snapshot,i.flags?.maestro?.allowAlreadyPastLoading===!0&&void 0!==s&&function(e,t){let r=iY(iS(e));if(!iZ(r))return!1;let a=t.nodes.flatMap(e=>[e.label,e.value,e.identifier]).filter(e=>!!e?.trim()).map(e=>iY(e));return!a.some(e=>e.includes("something went wrong"))&&a.some(e=>e!==r&&!iZ(e))}(o,s))?{kind:"return",response:(l=t.selector,u=t.timeoutMs,p=a,{ok:!0,data:{selector:l,alreadyPastLoading:!0,waitedMs:Date.now()-p,timeoutMs:u}})}:{kind:"continue"}}function iW(e,t){return e.flags?.platform!=="ios"&&e.flags?.platform!=="android"?null:iS(t)}function iJ(e,t){let[r,a=String(t.defaultTimeoutMs)]=e;if(!r)return{ok:!1,response:ip("INVALID_ARGS",`${t.command} requires a selector.`)};let n=Number(a);return!Number.isFinite(n)||n<0?{ok:!1,response:ip("INVALID_ARGS",`${t.command} timeout must be a non-negative number.`)}:{ok:!0,selector:r,timeoutMs:n}}async function iX(e,t,r){let a=await id(e);var n=e,i=t,o=r,s=a;if(!s.ok)return{visible:!1,response:s,infrastructureFailure:!0};let l=ic(s.data);if(!l)return{visible:!1,response:ip("COMMAND_FAILED",`Unable to read snapshot data for ${o}.`),infrastructureFailure:!0};let u=iy(l,i,iA(n.baseReq.flags),Z(l));return u.ok?(im(n.scope,i),{visible:!0,response:{ok:!0,data:{selector:i,matches:u.matches,nodeIndex:u.node.index,nodeType:u.node.type,nodeLabel:u.node.label,nodeIdentifier:u.node.identifier,rect:u.rect}}}):{visible:!1,response:ip("COMMAND_FAILED",u.message,{selector:i}),infrastructureFailure:!1,snapshot:l}}function iY(e){return e?.trim().toLowerCase().replace(/\u2026/g,"...")??""}function iZ(e){return"loading"===e||"loading..."===e}function iQ(e,t,r){return e.ok?{ok:!0,data:{selector:t,...e.data,waitedMs:Date.now()-r}}:e}function i0(e,a,n){var i;if(e.ok||!a)return e;let o="string"==typeof n.flags?.artifactsDir?n.flags.artifactsDir:void 0;if(!o)return e;let s=function(e,a){try{t.mkdirSync(a,{recursive:!0});let n=r.join(a,"failure-snapshot.json"),i=r.join(a,"failure-snapshot.txt");t.writeFileSync(n,`${JSON.stringify(e,null,2)}
26
- `);let o=eY(e.nodes,{summarizeTextSurfaces:!0}).map(e=>e.text);return t.writeFileSync(i,`${o.join("\n")}
27
- `),[n,i]}catch{return[]}}(a,o);return 0===s.length?e:{ok:!1,error:{...e.error,details:{...e.error.details??{},artifactPaths:[...new Set([...Array.isArray(i=e.error.details?.artifactPaths)?i.filter(e=>"string"==typeof e):[],...s])]}}}}async function i1(e){let t,r=iJ(e.positionals,{command:"assertNotVisible",defaultTimeoutMs:3e3});if(!r.ok)return r.response;let a=Date.now(),n=0;for(;Date.now()-a<=r.timeoutMs;){let i=await iX(e,r.selector,"assertNotVisible");if(!i.visible&&i.infrastructureFailure)return i.response;if(i.visible)n=0,t=i.response;else{n+=1;let e=Date.now()-a;if(n>=2||e>=r.timeoutMs)return{ok:!0,data:{pass:!0,selector:r.selector,stableSamples:n,waitedMs:e,timeoutMs:r.timeoutMs}}}await rs(250)}return n>0?{ok:!0,data:{pass:!0,selector:r.selector,stableSamples:n,waitedMs:Date.now()-a,timeoutMs:r.timeoutMs}}:ip("COMMAND_FAILED",`Expected not visible but matched: ${r.selector}`,{selector:r.selector,timeoutMs:r.timeoutMs,lastResponse:t})}async function i3(e){let t,r,a=Number(e.positionals[0]??15e3);if(!Number.isFinite(a)||a<0)return ip("INVALID_ARGS","waitForAnimationToEnd timeout must be a number.");let n=Date.now();for(;Date.now()-n<a;){let n=await id(e),i=function(e,t,r){let a=function(e){if(!e.ok)return null;let t=ic(e.data);return t?JSON.stringify(t.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}))):null}(e);return e.ok?a?t===a?{done:!0,response:{ok:!0,data:{stable:!0,timeoutMs:r}}}:{done:!1,signature:a}:{done:!0,response:e}:{done:!1}}(n,t,a);if(i.done)return i.response;t=i.signature??t,r=n,await rs(250)}return r?.ok===!1?r:{ok:!0,data:{stable:!1,timeoutMs:a}}}async function i2(e){var t,r,a;let[n,i="5000",o="down"]=e.positionals;if(!n)return ip("INVALID_ARGS","scrollUntilVisible requires a selector.");let s=Number(i);if(!Number.isFinite(s)||s<=0)return ip("INVALID_ARGS","scrollUntilVisible timeout must be a positive number.");let l=iS(n),u=Math.max(1,Math.ceil(s/500)),p=null;for(let t=0;t<u;t+=1){let r=await on(e,n,l,Math.min(500,Math.max(1,s-500*t)));if(r.ok)return r;if(p=r,t===u-1)break;let a=await e.invoke({...e.baseReq,command:"scroll",positionals:[o]});if(!a.ok)return a}return t=p,r=n,a=s,t?{ok:!1,error:{...t.error,message:`scrollUntilVisible timed out after ${a}ms for selector: ${r}. Last wait: ${t.error.message}`}}:ip("COMMAND_FAILED",`scrollUntilVisible timed out after ${a}ms for selector: ${r}`)}async function i5(e){let[t,r]=e.positionals,a=Number(t),n=Number(r);if(!Number.isFinite(a)||!Number.isFinite(n))return ip("INVALID_ARGS","tapOn percentage point requires numeric x/y values.");let i=await id(e);if(!i.ok)return i;let o=ic(i.data);if(!o)return ip("COMMAND_FAILED","Unable to read snapshot data for Maestro percentage point tap.");let s=Z(o);if(!s)return ip("COMMAND_FAILED","Unable to resolve screen size for Maestro percentage point tap.");let l=ez(s,a,n),u=await e.invoke({...e.baseReq,command:"click",positionals:[String(l.x),String(l.y)],flags:{...e.baseReq.flags,postGestureStabilization:!0}});return u.ok&&ih(e.scope),u}async function i4(e){let t=await i6(e);if(t)return t;let r=await oe(e);return r.ok?await i9(e,r,r.durationMs):r.response}async function i6(e){let[t,r,a]=e.positionals;if("direction"===t&&("left"===r||"right"===r)&&"android"!==iA(e.baseReq.flags))return await e.invoke({...e.baseReq,command:"gesture",positionals:["swipe",r,...a?[a]:[]]})}async function i8(e){var t,r,a,n;let i,[o,s]=e.positionals;if(!o)return ip("INVALID_ARGS","tapOn requires a selector.");let l=function(e){if(!e)return{ok:!0,value:null};try{let t=JSON.parse(e);return{ok:!0,value:t}}catch{return{ok:!1,response:ip("INVALID_ARGS","tapOn runtime options must be valid JSON.")}}}(s);if(!l.ok)return l.response;let u=Date.now(),p=(t=e,t.baseReq.flags?.maestro?.optional===!0?3e3:3e4);for(;Date.now()-u<p;){let t=await oi(e,o,l.value??{});if(!t.retry)return t.response;i=t.response,await rs(250)}return r=e,a=o,n=i,r.baseReq.flags?.maestro?.optional===!0?{ok:!0,data:{skipped:!0,optional:!0,selector:a}}:n??ip("COMMAND_FAILED",`tapOn timed out for selector: ${a}`)}async function i7(e){let[t,r="up",a]=e.positionals;if(!t)return ip("INVALID_ARGS","swipe.label requires a label selector.");let n=await ou(e,t,{},"swipe.label",{promoteTapTarget:!1});if(!n.ok)return n.response;let i=function(e,t){let r=e0(e.rect),a=e.frame,n=io(a?.referenceWidth,e.rect.width),i=io(a?.referenceHeight,e.rect.height),o=ii,s=a?a.referenceWidth-o:r.x+n,l=a?a.referenceHeight-o:r.y+i;switch(t.toLowerCase()){case"up":return{ok:!0,start:r,end:{x:r.x,y:e9(r.y-i,o,l)}};case"down":return{ok:!0,start:r,end:{x:r.x,y:e9(r.y+i,o,l)}};case"left":return{ok:!0,start:r,end:{x:e9(r.x-n,o,s),y:r.y}};case"right":return{ok:!0,start:r,end:{x:e9(r.x+n,o,s),y:r.y}};default:return{ok:!1,message:"swipe.label direction must be up, down, left, or right."}}}(n.target,r);return i.ok?await i9(e,i,a):ip("INVALID_ARGS",i.message)}async function i9(e,t,r){var a,n;let i=[String(t.start.x),String(t.start.y),String(t.end.x),String(t.end.y),...r?[r]:[]],o=await e.invoke({...e.baseReq,command:"swipe",positionals:i});return o.ok&&(a=e.scope,n={kind:"swipe",positionals:i},a&&iu.set(a,n)),o}async function oe(e){var t;let r=((t=e.scope)?is.get(t):void 0)??await ot(e);if(!r)return{ok:!1,response:ip("COMMAND_FAILED","Unable to resolve screen size for Maestro swipe.")};let[a,...n]=e.positionals;return"direction"===a?function(e,t,r){let[a,n]=e;if(!a)return{ok:!1,response:ip("INVALID_ARGS","Maestro direction swipe requires a direction.")};switch(a){case"up":case"down":var i,o,s;let l;return i=a,o=t,s=n,{ok:!0,start:e3({x:(l=eJ({direction:i,amount:.6,referenceWidth:o.referenceWidth,referenceHeight:o.referenceHeight})).x1,y:l.y1},o,8),end:e3({x:l.x2,y:l.y2},o,8),durationMs:s};case"left":case"right":return function(e,t,r,a){let n=oa(r,85,50,15,50),[i,o]="left"===e?[85,15]:[15,85],s=or(r,t,i,50,o,50);return{ok:!0,start:ez(t,i,n.startY,{marginPx:s}),end:ez(t,o,n.endY,{marginPx:s}),durationMs:a}}(a,t,r,n);default:return{ok:!1,response:ip("INVALID_ARGS","Maestro swipe direction must be UP, DOWN, LEFT, or RIGHT.")}}}(n,r,iA(e.baseReq.flags)):"percent"===a?function(e,t,r){let[a,n,i,o,s]=e,l=[a,n,i,o].map(Number);if(l.some(e=>!Number.isFinite(e)))return{ok:!1,response:ip("INVALID_ARGS","Maestro percentage swipe requires numeric points.")};let[u,p,d,c]=l,f=oa(r,u,p,d,c),m=or(r,t,u,p,d,c);return{ok:!0,start:ez(t,u,f.startY,{marginPx:m}),end:ez(t,d,f.endY,{marginPx:m}),durationMs:s}}(n,r,iA(e.baseReq.flags)):{ok:!1,response:ip("INVALID_ARGS","Maestro screen swipe requires direction or percent.")}}async function ot(e){let t=await id(e);if(t.ok)return Z(ic(t.data))}function or(e,t,r,a,n,i){return"ios"!==e||a!==i||30>Math.abs(n-r)?1:Math.max(1,Math.round(.15*t.referenceWidth))}function oa(e,t,r,a,n){return"android"!==e||r!==n||50!==r||30>Math.abs(a-t)?{startY:r,endY:n}:{startY:65,endY:65}}async function on(e,t,r,a){let n=await e.invoke({...e.baseReq,command:"wait",positionals:[t,String(a)]});return n.ok||!r?n:await e.invoke({...e.baseReq,command:"find",positionals:[r,"wait",String(a)]})}async function oi(e,t,r){let a=iS(t),n=await oo(e,t,r);return n.response.ok?{retry:!1,response:n.response}:n.targetResolved&&a?await ol(e,a):{retry:!0,response:n.response}}async function oo(e,t,r){let a=await ou(e,t,r,"tapOn",{promoteTapTarget:!0});return a.ok?await os(e,t,a.target,r):{response:a.response,targetResolved:!1}}async function os(e,t,r,a){let n=e0(r.rect);tv({level:"debug",phase:"maestro_tap_target",data:{selector:t,node:{index:r.node.index,type:r.node.type,label:r.node.label,value:r.node.value,identifier:r.node.identifier,visibleToUser:r.node.visibleToUser},rect:r.rect,point:n}});let i=await e.invoke({...e.baseReq,command:"click",positionals:[String(n.x),String(n.y)],flags:{...e.baseReq.flags,postGestureStabilization:!0}});if(i.ok){var o,s,l;(o=e.scope)&&il.delete(o),s=e.scope,l={kind:"tap",selector:t,point:n,options:{...a}},s&&iu.set(s,l)}return{response:i,targetResolved:!0}}async function ol(e,t){let r=await e.invoke({...e.baseReq,command:"find",positionals:[t,"click"],flags:{...e.baseReq.flags,findFirst:!0,postGestureStabilization:!0}});return(tv({level:r.ok?"info":"debug",phase:"maestro_fuzzy_tap_fallback",data:{query:t,ok:r.ok}}),r.ok)?(ih(e.scope),{retry:!1,response:r}):{retry:!0,response:r}}async function ou(e,t,r,a,n){let i=await id({...e,raw:!0});return function(e,t,r,a,n,i){if(!i.ok)return{ok:!1,response:i};let o=ic(i.data);if(!o)return{ok:!1,response:ip("COMMAND_FAILED",`Unable to read snapshot data for ${a}.`)};let s=Z(o),l=iA(e.baseReq.flags),u=function(e,t,r,a){var n;let i=(n=e.scope)?il.get(n):void 0;if(!i)return;let o=iy(t,i.selector,r,a);if(o.ok)return tv({level:"debug",phase:"maestro_preferred_context",data:{selector:i.selector,node:{index:o.node.index,type:o.node.type,label:o.node.label,value:o.node.value,identifier:o.node.identifier},rect:o.rect}}),{node:o.node,rect:o.rect}}(e,o,l,s),p=iw(o,t,r,l,s,{...n,preferredContext:u,requireOnScreen:!0});if(!p.ok){let e=iS(t);if(e){let t=function(e,t,r,a,n={}){let i=function(e,t){let r=rn(t);if(!r)return[];let a=[],n=[];for(let t of e.nodes){let e=[t.label,t3(t),t.identifier,t.value].filter(e=>!!e).map(e=>rn(e));e.some(e=>e===r)?a.push(t):e.some(e=>e.includes(r))&&n.push(t)}return a.length>0?a:n}(e,t),o=iv({nodes:e.nodes,matches:i,platform:r}),s=ik(e.nodes,o.matches,void 0,t,a,!0===n.requireOnScreen,n.promoteTapTarget,n.preferredContext);return s?{ok:!0,node:s.node,rect:s.rect}:{ok:!1,message:`Maestro fuzzy text did not match: ${t}`}}(o,e,l,s,{...n,preferredContext:u,requireOnScreen:!0});if(t.ok)return{ok:!0,target:{node:t.node,rect:t.rect,frame:s}}}}return p.ok?{ok:!0,target:{node:p.node,rect:p.rect,frame:s}}:{ok:!1,response:ip("ELEMENT_NOT_FOUND",p.message,{selector:t,options:r,command:a})}}(e,t,r,a,n,i)}async function op(e){switch(e.command){case a3:return await i$(e);case a2:return await i1(e);case a5:return await od(e);case a4:return await i3(e);case a6:return await i2(e);case a8:return await i4(e);case a7:return await i7(e);case a9:return await i8(e);case ne:return await i5(e);case a1:return function(e){let[r]=e.positionals;if(!r)return ip("INVALID_ARGS","runScript requires a file path.");try{let n=function(e){let{scriptPath:r,env:n}=e,i=t.readFileSync(r,"utf8"),o=Object.create(null);try{var l,u;a.runInNewContext(i,(l=n,u=o,{...l,output:u,json:ng,http:{post:(e,t)=>(function(e,t,r){let a=tY(process.execPath,["-e",nh],{stdin:JSON.stringify({method:e,url:t,headers:r?.headers??{},body:r?.body??""}),timeoutMs:3e4,allowFailure:!0});if(0!==a.exitCode){let r;throw new s("COMMAND_FAILED",`Maestro runScript http.${e.toLowerCase()} failed for ${t}: ${(r=a.stderr.trim()).length>0?r.slice(0,1e3):"request process exited without stderr"}`,{exitCode:a.exitCode,stderr:a.stderr})}try{return JSON.parse(a.stdout)}catch(r){throw new s("COMMAND_FAILED",`Maestro runScript http.${e.toLowerCase()} returned invalid JSON for ${t}`,{stdout:a.stdout.slice(0,1e3),stderr:a.stderr.slice(0,1e3)},r instanceof Error?r:void 0)}})("POST",e,t)}}),{filename:r,timeout:3e4})}catch(e){throw new s("COMMAND_FAILED",`Maestro runScript failed for ${r}: ${e instanceof Error?e.message:String(e)}`,{scriptPath:r},e instanceof Error?e:void 0)}return function(e,t){for(let r of Object.keys(e))if(r.includes("."))throw new s("INVALID_ARGS",`Maestro runScript output key cannot contain ".": ${r}`,{scriptPath:t,key:r})}(o,r),Object.fromEntries(Object.entries(o).map(([e,t])=>{var r;return[`output.${e}`,(r=t,"string"==typeof r?r:"number"==typeof r||"boolean"==typeof r?String(r):JSON.stringify(r))]}))}({scriptPath:r,env:{...e.scope.values,...e.baseReq.flags?.maestro?.runScriptEnv??{}}});return{ok:!0,data:{outputEnv:n}}}catch(t){let e=i(t);return ip(e.code,e.message,e.details)}}(e);default:return}}async function od(e){let t=await e.invoke({...e.baseReq,command:"keyboard",positionals:["enter"]});return t.ok?t:await e.invoke({...e.baseReq,command:"type",positionals:["\n"]})}async function oc(e){for(let[t,r]of e.actions.entries()){let a=await e.invokeReplayAction({action:r,line:e.line,step:e.step+t/1e3});if(!a.ok)return a}return{ok:!0,data:{ran:e.actions.length}}}async function of(e){let t;for(let r=0;r<=e.maxRetries;r+=1){let a=await oc({actions:e.actions,line:e.line,step:e.step+r,invokeReplayAction:e.invokeReplayAction});if(a.ok)return{ok:!0,data:{attempts:r+1,retried:r>0}};t=a}return t??{ok:!1,error:{code:"COMMAND_FAILED",message:"retry commands failed."}}}async function om(e){let t=await oh(e,e.control);return t.ok?t.matched?await oy(e):{ok:!0,data:{skipped:!0,condition:e.control.mode,selector:e.control.selector}}:t.response}async function oh(e,t){if("visible"===t.mode)return await og(e,t);let r=await ow(e,t.selector);return r.ok?{ok:!0,matched:!r.matched}:{ok:!1,response:r.response}}async function og(e,t){let r=Date.now();for(;;){let a=await ow(e,t.selector);if(!a.ok)return{ok:!1,response:a.response};if(a.matched)return{ok:!0,matched:!0};if(Date.now()-r>=3e3)return{ok:!0,matched:!1};await rs(250)}}async function ow(e,t){var r,a;let n,i=await id(e);return i.ok?(r=e,a=t,(n=ic(i.data))?{ok:!0,matched:iy(n,a,iA(r.baseReq.flags),Z(n)).ok}:{ok:!1,response:ip("COMMAND_FAILED","Unable to read snapshot data for runFlow.when.")}):{ok:!1,response:i}}async function oy(e){let t=await oc({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 ov(e){let{req:t,sessionName:r,action:a,scope:n,filePath:i,line:o,step:s,tracePath:l,invoke:u}=e,p=tJ(a,n,{file:i,line:o}),d=Date.now();oI(l,{type:"replay_action_start",ts:new Date(d).toISOString(),replayPath:i,line:o,step:s,command:p.command,positionals:p.positionals??[]});let c=await oA({req:t,sessionName:r,resolved:p,scope:n,line:o,step:s,invoke:u,invokeReplayAction:e=>ov({req:t,sessionName:r,action:e.action,scope:n,filePath:i,line:e.line,step:e.step,tracePath:l,invoke:u})}),f=Date.now();return oI(l,{type:"replay_action_stop",ts:new Date(f).toISOString(),replayPath:i,line:o,step:s,command:p.command,ok:c.ok,durationMs:f-d,resultTiming:c.ok?function(e){if(!e||"object"!=typeof e||Array.isArray(e))return;let t=e.timing;if(!(!t||"object"!=typeof t||Array.isArray(t)))return Object.fromEntries(Object.entries(t).filter(([,e])=>{let t=typeof e;return"number"===t||"string"===t||"boolean"===t}))}(c.data):void 0,errorCode:c.ok?void 0:c.error.code}),c}async function oA(e){var t;let{req:r,sessionName:a,resolved:n,scope:i,line:o,step:s,invoke:l,invokeReplayAction:u}=e,p=(t=r.flags,tS(t,{...n.flags??{}})),d={token:r.token,session:a,flags:p,runtime:n.runtime,meta:r.meta,internal:r.internal},c=await oS({control:n.replayControl,baseReq:d,line:o,step:s,invoke:l,invokeReplayAction:u})??await op({command:n.command,baseReq:d,positionals:n.positionals??[],scope:i,line:o,step:s,invoke:l,invokeReplayAction:u})??await l({...d,command:n.command,positionals:n.positionals??[]});if(c.ok){let e=function(e){if(!e||"object"!=typeof e)return null;let t=e.outputEnv;if(!t||"object"!=typeof t||Array.isArray(t))return null;let r=Object.entries(t).filter(e=>"string"==typeof e[1]);return r.length>0?Object.fromEntries(r):null}(c.data);e&&tX(i,e)}return c}async function oS(e){let{control:t,baseReq:r,line:a,step:n,invoke:i,invokeReplayAction:o}=e;if(t){switch(t.kind){case"retry":return await of({actions:t.actions,maxRetries:t.maxRetries,line:a,step:n,invokeReplayAction:o});case"maestroRunFlowWhen":return await om({baseReq:r,control:t,line:a,step:n,invoke:i,invokeReplayAction:o})}return t}}function oI(e,r){e&&t.appendFileSync(e,`${JSON.stringify(r)}
28
- `)}async function ob(e){let{req:a,sessionName:n,logPath:o,sessionStore:l,tracePath:u,invoke:p}=e,d=a.positionals?.[0];if(!d)return E("INVALID_ARGS","replay requires a path");let c="",f=new Set;try{var m,h,g,w,y,v,A,S,I,b,_,k,N,D,x,R,M,P,L,O;c=ef.expandHome(d,a.meta?.cwd);let e=t.readFileSync(c,"utf8"),i=e.trimStart()[0];if("{"===i||"["===i)return E("INVALID_ARGS","replay accepts .ad script files. JSON replay payloads are no longer supported.");let C=function(e,t,r={}){var a;let n=function(e){let t=e?.replayBackend;if("string"!=typeof t)return;let r=n6[t];if(!r)throw new s("INVALID_ARGS",`Unsupported replay backend "${t}".`);return r}(t);return n?{...n.parse(e,{...r,platform:t?.platform,env:(a=t,{...tV(tR(a?.replayShellEnv)),...t$(tL(a?.replayEnv))})}),updateUnsupportedMessage:"replay -u is not supported for compat flow input. Convert to .ad first, then update that replay file."}:{...tx(e),metadata:tC(e)}}(e,a.flags,{sourcePath:c}),V=C.metadata,U=V.platform||V.target?{...a,flags:(m=a.flags,h=V,{...m??{},...void 0!==h.platform&&m?.platform===void 0?{platform:h.platform}:{},...void 0!==h.target&&m?.target===void 0?{target:h.target}:{}})}:a,F=C.actions,q=C.actionLines;if(a.flags?.replayUpdate===!0&&C.updateUnsupportedMessage)return E("INVALID_ARGS",C.updateUnsupportedMessage);if(a.flags?.replayUpdate===!0&&V.env&&Object.keys(V.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(a.flags?.replayUpdate===!0&&function(e){for(let t of e){for(let e of t.positionals??[])if("string"==typeof e&&e.includes("${"))return!0;if(oR(t.flags)||oR(t.runtime))return!0}return!1}(F))return E("INVALID_ARGS","replay -u does not yet preserve ${VAR} substitutions. Resolve or inline the variables before running with -u.");let G=tW({builtins:function(e){let{req:t,sessionName:a,metadata:n,resolvedPath:i}=e,o=t.flags??{},s=t.meta?.cwd??process.cwd(),l={AD_SESSION:a,AD_FILENAME:r.relative(s,i)||i},u=o.platform??n.platform;u&&(l.AD_PLATFORM=u);let p=o.target??n.target;p&&(l.AD_TARGET=p);let d=o.device;"string"==typeof d&&d.length>0&&(l.AD_DEVICE=d);let c="string"==typeof o.serial?o.serial:o.udid;"string"==typeof c&&c.length>0&&(l.AD_DEVICE_ID=c),"number"==typeof o.shardIndex&&(l.AD_SHARD_INDEX=String(o.shardIndex)),"number"==typeof o.shardCount&&(l.AD_SHARD_COUNT=String(o.shardCount));let f=o.artifactsDir;return"string"==typeof f&&f.length>0&&(l.AD_ARTIFACTS=f),l}({req:U,sessionName:n,metadata:V,resolvedPath:c}),fileEnv:V.env,shellEnv:tV(tR(a.flags?.replayShellEnv)),cliEnv:t$(tL(a.flags?.replayEnv))}),T=a.flags?.replayUpdate===!0,B=u??l.get(n)?.trace?.outPath,H=[],K=0;for(let e=0;e<F.length;e+=1){let t=F[e];if(!t||"replay"===t.command)continue;!function(e,t,r){let a=$();a&&eH({type:"replay-test",...a,file:a.file||e,status:"progress",stepIndex:t+1,stepTotal:r})}(c,e,F.length);let r=oN(l,n),a=await ov({req:U,sessionName:n,action:t,scope:G,filePath:c,line:q[e]??0,step:e+1,tracePath:B,invoke:p});if(H.push(...oD(l,n,r)),a.ok){ok(a).forEach(e=>f.add(e));continue}if(ok(a).forEach(e=>f.add(e)),!T){return g=a,w=t,y=e,v=c,A=[...f],S=H,o_(g,w,y,v,A,tQ(S))}let i=await n7({action:t,sessionName:n,logPath:o,sessionStore:l});if(!i){return I=a,b=t,_=e,k=c,N=[...f],D=H,o_(I,b,_,k,N,tQ(D))}F[e]=i;let s=oN(l,n);if(a=await ov({req:U,sessionName:n,action:i,scope:G,filePath:c,line:q[e]??0,step:e+1,tracePath:B,invoke:p}),H.push(...oD(l,n,s)),!a.ok){return ok(a).forEach(e=>f.add(e)),x=a,R=i,M=e,P=c,L=[...f],O=H,o_(x,R,M,P,L,tQ(O))}ok(a).forEach(e=>f.add(e)),K+=1}T&&K>0&&tz(c,F,l.get(n));let j=tQ(H);return{ok:!0,data:{replayed:F.length,healed:K,session:n,artifactPaths:[...f],...j?{snapshotDiagnostics:j}:{}}}}catch(t){let e=i(t);return E(e.code,e.message,f.size>0?{artifactPaths:[...f]}:void 0)}}function o_(e,t,r,a,n=[],i){if(e.ok)return e;let o=r+1;return{ok:!1,error:{code:e.error.code,message:`Replay failed at step ${o} (${re(t)}): ${e.error.message}`,hint:e.error.hint,diagnosticId:e.error.diagnosticId,logPath:e.error.logPath,details:{...e.error.details??{},replayPath:a,step:o,action:t.command,positionals:t.positionals??[],artifactPaths:n,...i?{snapshotDiagnostics:i}:{}}}}}function ok(e){if(!e.ok){let t=e.error.details?.artifactPaths;return Array.isArray(t)?[...new Set(t.filter(e=>"string"==typeof e&&ox(e)))]:[]}if(!e.data)return[];let t=[];if("string"==typeof e.data.path&&t.push(e.data.path),"string"==typeof e.data.outPath&&t.push(e.data.outPath),Array.isArray(e.data.artifacts))for(let r of e.data.artifacts){if(!r||"object"!=typeof r)continue;let e="string"==typeof r.localPath?r.localPath:void 0,a="string"==typeof r.path?r.path:void 0;e?t.push(e):a&&t.push(a)}return[...new Set(t.filter(e=>ox(e)))]}function oN(e,t){return e.get(t)?.snapshotDiagnostics?.samples.length??0}function oD(e,t,r){return e.get(t)?.snapshotDiagnostics?.samples.slice(r)??[]}function ox(e){try{return t.statSync(e).isFile()}catch{return!1}}function oR(e){return"string"==typeof e?e.includes("${"):Array.isArray(e)?e.some(oR):!!e&&"object"==typeof e&&Object.values(e).some(oR)}async function oM(e){let{req:t,sessionName:a,logPath:n,sessionStore:i,artifactsDir:o,tracePath:s}=e;if(t.flags?.recordVideo!==!0)return;let l=i.get(a);if(!l||l.recording)return;let u=o?r.join(o,"recording.mp4"):`./recording-${Date.now()}.mp4`;oL(s,{type:"video_recording_start",session:a,videoPath:u}),tv({phase:"replay_test_video_recording_start",data:{session:a,videoPath:u}});let p=await rl({req:{token:t.token,session:a,command:"record",positionals:["start",u],flags:{},meta:t.meta},sessionName:a,sessionStore:i,logPath:n});if(!p.ok)return oL(s,{type:"video_recording_start_failed",session:a,videoPath:u,errorCode:p.error.code}),p;let d=Date.now();return await rs(1e3),oL(s,{type:"video_preroll_done",session:a,durationMs:Date.now()-d,requestedDurationMs:1e3}),tv({phase:"replay_test_video_recording_preroll_done",durationMs:Date.now()-d,data:{session:a,requestedDurationMs:1e3}}),p}async function oP(e){let{req:t,sessionName:r,logPath:a,sessionStore:n,tracePath:i,artifactPaths:o}=e;if(t.flags?.recordVideo!==!0||!n.get(r)?.recording)return;oL(i,{type:"video_tail_start",session:r,requestedDurationMs:3e3});let s=Date.now();await rs(3e3);let l=Date.now(),u=await rl({req:{token:t.token,session:r,command:"record",positionals:["stop"],flags:{},meta:t.meta},sessionName:r,sessionStore:n,logPath:a});return ok(u).forEach(e=>o.add(e)),oL(i,{type:"video_recording_stop",session:r,ok:u.ok,durationMs:Date.now()-l,tailDurationMs:l-s,errorCode:u.ok?void 0:u.error.code}),tv({phase:"replay_test_video_recording_stop",durationMs:Date.now()-l,data:{session:r,ok:u.ok,tailDurationMs:l-s}}),u}function oL(e,t){nq(e,{...t,ts:new Date().toISOString()})}async function oO(e){let{req:t,sessionName:r,logPath:a,sessionStore:n,invoke:i}=e;return"replay"===t.command?await ob({req:t,sessionName:r,logPath:a,sessionStore:n,invoke:i}):"test"===t.command?await nZ({req:t,sessionName:r,runReplay:async({filePath:e,sessionName:r,platform:o,target:s,requestId:l,artifactsDir:u,artifactPaths:p,tracePath:d,shard:c})=>{let f=function(e){let{platform:t,target:r,artifactsDir:a,shard:n}=e,i=function(e){if(e?.recordVideo!==!0)return e;let t={...e};return delete t.recordVideo,Object.keys(t).length>0?t:void 0}(e.parentFlags);if(void 0===t&&void 0===r&&void 0===a&&void 0===n)return i;var o={...i??{},...void 0!==t?{platform:t}:{},...void 0!==r?{target:r}:{},...void 0!==a?{artifactsDir:a}:{}};if(!n)return o;let s={...o??{},device:void 0,udid:void 0,serial:void 0,platform:n.device.platform,target:n.device.target,shardAll:void 0,shardSplit:void 0,shardCount:n.shardCount,shardIndex:n.shardIndex};return"android"===n.device.platform?{...s,serial:n.device.id}:{...s,udid:n.device.id}}({parentFlags:t.flags,platform:o,target:s,artifactsDir:u,shard:c}),m={req:t,sessionName:r,logPath:a,sessionStore:n,artifactsDir:u,tracePath:d},h=function(e){if(e.req.flags?.recordVideo===!0)return{beforeDispatch:async()=>await oM(e)}}(m);return await ob({req:{...t,command:"replay",session:r,positionals:[e],flags:f,meta:{...t.meta??{},...l?{requestId:l}:{}},...t.internal||h?{internal:{...t.internal??{},...h?{openLifecycle:h}:{}}}:{}},sessionName:r,logPath:a,sessionStore:n,tracePath:d,invoke:async e=>{var t;let r=await oM(m);return r&&!r.ok?r:(t=await i(e),p&&ok(t).forEach(e=>p.add(e)),t)}})},finalizeAttempt:async({sessionName:e,artifactPaths:r,artifactsDir:i,tracePath:o})=>await oP({req:t,sessionName:e,logPath:a,sessionStore:n,artifactsDir:i,tracePath:o,artifactPaths:r}),cleanupSession:async e=>{n.get(e)&&await ee({req:{token:t.token,session:e,command:"close",positionals:[],flags:{},meta:t.meta},sessionName:e,logPath:a,sessionStore:n})}}):null}async function oE(e){var t,r,a,n,i,o,s,l;let u,p,{req:d,sessionName:c,logPath:f,sessionStore:h}=e,g=d.positionals?.[0]??"";if("ios-runner"!==g)return E("INVALID_ARGS","prepare requires a subcommand: ios-runner");let w=h.get(c),y=d.flags??{},v=N(rp.prepare,w,y);if(v)return v;let A=await m({session:w,flags:y,ensureReady:!0});if(!ti(A.platform))return E("UNSUPPORTED_OPERATION","prepare ios-runner is only supported on Apple runner platforms");let S=Date.now(),I=await et(A,(t=d,r=w,a=f,p=(n=t,"number"==typeof(u=n.flags?.timeoutMs)&&Number.isFinite(u)&&u>0?u:3e5),{verbose:t.flags?.verbose,logPath:a,traceLogPath:r?.trace?.outPath,cleanStaleBundles:!0,startupTimeoutMs:function(e){if("number"==typeof e&&Number.isFinite(e)&&!(e<=0))return Math.max(45e3,Math.floor(e))}(t.flags?.timeoutMs),requestId:t.meta?.requestId,buildTimeoutMs:p,healthTimeoutMs:Math.min(p,9e4),iosXctestrunFile:t.flags?.iosXctestrunFile,iosXctestDerivedDataPath:t.flags?.iosXctestDerivedDataPath,iosXctestEnvDir:t.flags?.iosXctestEnvDir}));return{ok:!0,data:(i=g,o=A,s=Math.max(0,Date.now()-S),l=I,{action:i,platform:o.platform,deviceId:o.id,deviceName:o.name,kind:o.kind,durationMs:s,...l,message:`Prepared Apple runner: ${o.name}`})}}async function oC(e){let{req:t,sessionName:r,logPath:a,sessionStore:n,command:i,positionals:o,recordPositionals:s,deriveNextSession:l}=e,u=n.get(r),d=t.flags??{},c=N(i,u,d);if(c)return c;let f=await m({session:u,flags:d,ensureReady:!0});if(!eV(i,f))return E("UNSUPPORTED_OPERATION",`${i} is not supported on this device`);let h=await p(f,i,o,t.flags?.out,{...ed(a,t.flags,u?.appBundleId,u?.trace?.outPath)});if(u){let e=l?await l(u,h,f):u;n.recordAction(e,{command:i,positionals:s??o,flags:t.flags??{},result:h??{}}),e!==u&&n.set(r,e)}return{ok:!0,data:h??{}}}async function o$(e){let{req:t,sessionName:r,logPath:a,sessionStore:n}=e,i=n.get(r),o=t.flags??{},s=N(rp.clipboard,i,o);if(s)return s;let l=(t.positionals?.[0]??"").toLowerCase();if("read"!==l&&"write"!==l)return E("INVALID_ARGS","clipboard requires a subcommand: read or write");let u=await m({session:i,flags:o,ensureReady:!0});if(!eV(rp.clipboard,u))return E("UNSUPPORTED_OPERATION","clipboard is not supported on this device");let d=await p(u,rp.clipboard,t.positionals??[],t.flags?.out,{...ed(a,t.flags,i?.appBundleId,i?.trace?.outPath)});return i&&n.recordAction(i,{command:t.command,positionals:t.positionals??[],flags:t.flags??{},result:d??{}}),{ok:!0,data:{platform:u.platform,...d??{}}}}async function oV(e){let{req:t,sessionName:r,logPath:a,sessionStore:n,invoke:i,invokeReplayAction:o,androidAdbExecutor:s}=e;if("inventory"===y(t.command))return await rY({req:t,sessionName:r,sessionStore:n});if("runtime"===t.command)return await r_({req:t,sessionName:r,sessionStore:n});if("state"===y(t.command))return await r3({req:t,sessionName:r,sessionStore:n});if(t.command===rp.clipboard)return await o$({req:t,sessionName:r,logPath:a,sessionStore:n});if(t.command===rp.keyboard){let e=n.get(r),i=t.positionals?.[0]?.trim().toLowerCase();return e||"dismiss"!==i&&"enter"!==i&&"return"!==i||"ios"!==ts((t.flags??{}).platform)?await oC({req:t,sessionName:r,logPath:a,sessionStore:n,command:rp.keyboard,positionals:t.positionals??[]}):E("SESSION_NOT_FOUND","iOS keyboard action requires an active session so the target app stays foregrounded. Run open first.")}if("observability"===y(t.command))return await aF({req:t,sessionName:r,sessionStore:n,androidAdbExecutor:s});if(t.command===rp.prepare)return await oE({req:t,sessionName:r,logPath:a,sessionStore:n});if(t.command===rp.install||t.command===rp.reinstall)return await rJ({req:t,command:t.command,sessionName:r,sessionStore:n,deployOps:t.command===rp.install?rW:rz});if(t.command===ru.installSource)return await rg({req:t,sessionName:r,sessionStore:n});if(t.command===ru.releaseMaterializedPaths)return await rw({req:t});if(t.command===rp.push){let e,i=t.positionals?.[0]?.trim(),o=t.positionals?.[1]?.trim();return i&&o?await oC({req:t,sessionName:r,logPath:a,sessionStore:n,command:rp.push,positionals:[i,"file"===(e=eS(o,{subject:"Push payload",cwd:t.meta?.cwd,expandPath:(e,t)=>ef.expandHome(e,t)})).kind?e.path:e.text],recordPositionals:[i,o]}):E("INVALID_ARGS","push requires <bundle|package> <payload.json|inline-json>")}return t.command===rp.triggerAppEvent?await oC({req:t,sessionName:r,logPath:a,sessionStore:n,command:rp.triggerAppEvent,positionals:t.positionals??[],deriveNextSession:async(e,t)=>{let r="string"==typeof t?.eventUrl?t.eventUrl:void 0,a=r?await rC(e.device,r,e.appBundleId,rO)??e.appBundleId:e.appBundleId;return{...e,appBundleId:a}}}):t.command===rp.open?await rj({req:t,sessionName:r,logPath:a,sessionStore:n}):"replay"===y(t.command)?await oO({req:t,sessionName:r,logPath:a,sessionStore:n,invoke:o??i}):t.command===rp.batch?await rX(t,r,i):t.command===rp.close?await ee({req:t,sessionName:r,logPath:a,sessionStore:n}):null}export{rc as session_namespaceObject};
25
+ `;function n5(e){if("string"!=typeof e)throw new s("COMMAND_FAILED",`Maestro runScript json() expected a string body, received ${typeof e}.`);if(0===e.trim().length)throw new s("COMMAND_FAILED","Maestro runScript json() received an empty body. Check the preceding http response status and setup server output.");try{return JSON.parse(e,n4)}catch(t){throw new s("COMMAND_FAILED",`Maestro runScript json() could not parse response body: ${t instanceof Error?t.message:String(t)}`,{bodyPreview:e.slice(0,1e3)},t instanceof Error?t:void 0)}}function n4(e,t){return"__proto__"===e||"constructor"===e||"prototype"===e?void 0:t}let n6={launchApp:({value:e,config:t,context:r})=>[nx(e,t,r)],tapOn:({value:e,context:t})=>[function(e,t){if("string"==typeof e)return tB(nT,[nW(tW(e,t))],nZ(e));if(tH(e)&&"string"==typeof e.point){tz(e,"tapOn",["point","repeat","delay","optional","label"]);let t=tX(e.point);return"percent"===t.kind?tB(nG,[String(t.x),String(t.y)],nY(e)):tB("click",[String(t.x),String(t.y)],nY(e))}tH(e)&&tz(e,"tapOn",["id","text","childOf","enabled","index","selected","repeat","delay","optional","label"]);let r=nZ(e);return tB(nT,[nz(e,"tapOn",["repeat","delay","optional","label","index","childOf"],t),...function(e,t){if(!tH(e))return[];let r={};if(void 0!==e.index){if("number"!=typeof e.index||!Number.isInteger(e.index)||e.index<0)throw new s("INVALID_ARGS","tapOn.index must be a non-negative integer.");r.index=e.index}return void 0!==e.childOf&&(r.childOf=nz(e.childOf,"tapOn.childOf",[],t)),Object.keys(r).length>0?[JSON.stringify(r)]:[]}(e,t)],r)}(e,t)],doubleTapOn:({value:e,context:t})=>[function(e,t){if(tH(e)&&"string"==typeof e.point){tz(e,"doubleTapOn",["point","delay"]);let t=tq(e.point);return tB("click",[String(t.x),String(t.y)],nQ(e))}return tH(e)&&tz(e,"doubleTapOn",["id","text","enabled","selected","delay"]),tB("click",[nz(e,"doubleTapOn",["delay"],t)],nQ(e))}(e,t)],longPressOn:({value:e,context:t})=>[function(e,t){if(tH(e)&&"string"==typeof e.point){tz(e,"longPressOn",["point"]);let t=tq(e.point);return tB("longpress",[String(t.x),String(t.y),"3000"])}return tH(e)&&tz(e,"longPressOn",["id","text","enabled","selected"]),tB("click",[nz(e,"longPressOn",[],t)],{holdMs:3e3})}(e,t)],inputText:({value:e,context:t})=>[tB("type",[tW(function(e){if("string"==typeof e)return e;if(!tH(e))throw new s("INVALID_ARGS","inputText expects a string or map.");if(tz(e,"inputText",["text","label"]),"string"!=typeof e.text)throw new s("INVALID_ARGS","inputText map requires a string text field.");return e.text}(e),t)])],eraseText:({value:e})=>[nK(e)],pasteText:({value:e,context:t,name:r})=>[tB("type",[tW(tJ(r,e),t)])],openLink:({value:e,config:t,context:r,name:a})=>{var n,i,o,s,l,u;let d;return[(n=e,i=t,o=r,s=a,d=tW((l=n,u=s,"string"==typeof l?l:tH(l)?(tz(l,u,["link"]),tJ(`${u}.link`,l.link)):tJ(u,l)),o),("ios"===o.platform||"android"===o.platform)&&i.appId?tB("open",[tW(tj(i,s),o),d],"ios"===o.platform?{maestro:{prewarmRunnerBeforeOpen:!0}}:void 0):tB("open",[d]))]},assertVisible:({value:e,context:t,name:r})=>[tB(nC,[nz(e,r,[],t),"17000"])],assertNotVisible:({value:e,context:t,name:r})=>[tB(nE,[nz(e,r,[],t)])],extendedWaitUntil:({value:e,context:t})=>(function(e,t){if(!tH(e))throw new s("INVALID_ARGS","extendedWaitUntil expects a map.");tz(e,"extendedWaitUntil",["visible","notVisible","timeout"]);let r=e.visible??e.notVisible;if(void 0===r)throw tY("Only Maestro extendedWaitUntil.visible/notVisible is supported.");let a=nz(r,"extendedWaitUntil",[],t),n=String(tZ(e,17e3));return void 0!==e.notVisible?[tB(nE,[a,n])]:[tB(nC,[a,n],{maestro:{allowAlreadyPastLoading:!0}})]})(e,t),takeScreenshot:({value:e,context:t,name:r})=>[tB("screenshot",[tW(tJ(r,e),t)])],scroll:({value:e})=>[function(e){if(null!=e)throw tY("Maestro scroll options are not supported yet.");return tB("scroll",["down"])}(e)],scrollUntilVisible:({value:e,context:t})=>(function(e,t){if("string"==typeof e)return[tB(nU,[nW(tW(e,t)),"5000","down"])];if(!tH(e))throw new s("INVALID_ARGS","scrollUntilVisible expects a string or map.");tz(e,"scrollUntilVisible",["element","direction","timeout"]);let r=nz(e.element,"scrollUntilVisible.element",[],t),a="string"==typeof e.direction?nH(e.direction,"scrollUntilVisible.direction"):"down";return[tB(nU,[r,String(tZ(e,5e3)),a])]})(e,t),swipe:({value:e,context:t})=>[function(e,t){var r,a,n;let i;if(!tH(e))throw new s("INVALID_ARGS","swipe expects a map.");tz(e,"swipe",["start","end","direction","duration","from","label"]);let o=e.from??("string"==typeof e.label?e.label:void 0);return void 0!==o?(r=e,a=o,n=t,i=nj("string"==typeof r.direction?r.direction:"up"),tB(nq,[nz(a,"swipe.from",[],n),i,...nJ(r)])):"string"==typeof e.direction?tB(nF,["direction",nj(e.direction),...nJ(e)]):function(e){let{start:t,end:r}=function(e){if("string"==typeof e.start&&"string"==typeof e.end)return{start:tX(e.start),end:tX(e.end)};throw tY("Only Maestro swipe start/end coordinates are supported.")}(e);var a=t,n=r,i=nB(e.duration);if("absolute"===a.kind&&"absolute"===n.kind)return tB("swipe",[String(a.x),String(a.y),String(n.x),String(n.y),...i?[i]:[]]);if("percent"===a.kind&&"percent"===n.kind)return tB(nF,["percent",String(a.x),String(a.y),String(n.x),String(n.y),...i?[i]:[]]);throw tY("Maestro swipe start/end must both be absolute pixels or both be percentages.")}(e)}(e,t)],hideKeyboard:()=>[tB("keyboard",["dismiss"])],pressKey:({value:e})=>[function(e){let t=tJ("pressKey",e).toLowerCase();if("back"===t)return tB("back");if("enter"===t||"return"===t)return tB(n$);if("home"===t)return tB("home");throw tY(`Maestro pressKey "${t}" is not supported yet.`)}(e)],back:()=>[tB("back")],waitForAnimationToEnd:({value:e})=>[tB(nV,[String(tZ(e,15e3))])],stopApp:({value:e,config:t,context:r})=>[nR(e,t,r)],runScript:({value:e,context:t})=>{let a;return[tB(nO,[function(e,t){if(r.isAbsolute(e))return e;if(!t.baseDir)throw new s("INVALID_ARGS","runScript file paths require replay input to have a source path.");return r.resolve(t.baseDir,e)}((a=function(e,t){if("string"==typeof e)return{file:tW(e,t),env:{}};if(!tH(e))throw new s("INVALID_ARGS","runScript expects a file path string or map.");return tz(e,"runScript",["file","env"]),{file:tW(tJ("runScript.file",e.file),t),env:Object.fromEntries(Object.entries(tO(e.env,"runScript.env")).map(([e,r])=>[e,tW(r,t)]))}}(e,t)).file,t)],{...Object.keys(a.env).length>0?{maestro:{runScriptEnv:a.env}}:{}})]},runFlow:({value:e,config:t,context:r,deps:a})=>(function(e,t,r,a,n){if("string"==typeof e)return a.parseRunFlowFile(tW(e,r),r).actions;if(!tH(e))throw new s("INVALID_ARGS","runFlow expects a file path string or map.");tz(e,"runFlow",["file","commands","env","when","label"]);let i=function(e,t){var r,a;if(null==e)return{shouldRun:!0};if(!tH(e))throw new s("INVALID_ARGS","runFlow.when expects a map.");return(tz(e,"runFlow.when",["platform","visible","notVisible","true"]),!function(e,t){if(void 0!==e.true&&!function(e,t){let r;if("boolean"==typeof e)return e;if("string"!=typeof e)throw new s("INVALID_ARGS","runFlow.when.true expects a boolean or expression string.");return new n0(function(e){let t=[],r=0;for(;r<e.length;){var a,n;let i=e.slice(r),o=(a=i,/^\s+/.exec(a)?.[0].length??0);if(o>0){r+=o;continue}let l=function(e){let t="maestro.platform";return e.startsWith(t)?{token:{type:"platform"},length:t.length}:null}(n=i)??function(e){let t=/^(==|!=|&&|\|\|)/.exec(e)?.[1];return t?{token:{type:"operator",value:t},length:t.length}:null}(n)??function(e){let t=e[0];return"("===t||")"===t?{token:{type:"paren",value:t},length:1}:null}(n)??function(e){let t=/^(['"])(.*?)\1/.exec(e);return t?{token:{type:"string",value:t[2]??""},length:t[0].length}:null}(n)??function(e){let t=/^(true|false)\b/.exec(e)?.[1];return t?{token:{type:"boolean",value:"true"===t},length:t.length}:null}(n);if(l){t.push(l.token),r+=l.length;continue}throw new s("INVALID_ARGS",`Unsupported runFlow.when.true expression near "${i.slice(0,24)}".`)}return t}((r=tW(e,t).trim()).startsWith("${")&&r.endsWith("}")?r.slice(2,-1).trim():r),{platform:t.platform}).parse()}(e.true,t))return!1;if(void 0===e.platform)return!0;let r=function(e,t){if("string"!=typeof e)throw new s("INVALID_ARGS",`${t} expects Android, iOS, or Web.`);let r=e.trim().toLowerCase();if("android"===r||"ios"===r||"web"===r)return r;throw new s("INVALID_ARGS",`${t} expects Android, iOS, or Web.`)}(e.platform,"runFlow.when.platform");if(!t.platform)throw new s("INVALID_ARGS","Maestro runFlow.when.platform requires replay to be run with --platform ios|android.");return r===t.platform}(e,t))?{shouldRun:!1}:{shouldRun:!0,...(r=e,a=t,{...void 0!==r.visible?{visibleSelector:nz(r.visible,"runFlow.when.visible",[],a)}:{},...void 0!==r.notVisible?{notVisibleSelector:nz(r.notVisible,"runFlow.when.notVisible",[],a)}:{}})}}(e.when,r);if(!i.shouldRun)return[];let o={...r,env:{...r.env,...tO(e.env,"runFlow.env"),...r.envOverrides}};return function(e,t){let{visibleSelector:r,notVisibleSelector:a}=t;if(!r&&!a)return e;if(r&&a)throw tY("Maestro runFlow.when cannot combine visible and notVisible yet.");let n=r?"visible":"notVisible",i=r??a??"";return[n1("runFlow.when",[n,i],{kind:"maestroRunFlowWhen",mode:n,selector:i,actions:e})]}(function(e,t,r,a,n){if("string"==typeof e.file)return a.parseRunFlowFile(tW(e.file,r),r).actions;if(Array.isArray(e.commands))return n(t$(e.commands),t,r,a);throw new s("INVALID_ARGS","runFlow map requires either file or commands.")}(e,t,o,a,n),i)})(e,t,r,a,n9),repeat:({value:e,config:t,context:r,deps:a})=>(function(e,t,r,a,n){var i;if(!tH(e))throw new s("INVALID_ARGS","repeat expects a map.");if(tz(e,"repeat",["times","commands","while"]),void 0!==e.while)throw tY("Maestro repeat.while is not supported yet. Only deterministic repeat.times is supported.");let o=(i=e.times,n3(i,r,"repeat.times"));if(!Array.isArray(e.commands))throw new s("INVALID_ARGS","repeat requires a commands list.");if(o>1e3)throw new s("INVALID_ARGS","repeat.times must be <= 1000 for deterministic replay expansion.");let l=t$(e.commands);return Array.from({length:o}).flatMap(()=>n(l,t,r,a))})(e,t,r,a,n9),retry:({value:e,config:t,context:r,deps:a})=>(function(e,t,r,a,n){var i,o;if(!tH(e))throw new s("INVALID_ARGS","retry expects a map.");if(tz(e,"retry",["maxRetries","commands"]),!Array.isArray(e.commands))throw new s("INVALID_ARGS","retry requires a commands list.");let l=(i=e.maxRetries,o=r,void 0===i?1:n3(i,o,"retry.maxRetries")),u=n(t$(e.commands),t,r,a);return[n1("retry",[String(l)],{kind:"retry",maxRetries:l,actions:u})]})(e,t,r,a,n9)},n8={launchApp:(e,t)=>[nx(void 0,e,t)],scroll:()=>[tB("scroll",["down"])],hideKeyboard:()=>[tB("keyboard",["dismiss"])],eraseText:()=>[nK(void 0)],back:()=>[tB("back")],waitForAnimationToEnd:()=>[tB(nV,["15000"])],stopApp:(e,t)=>[nR(void 0,e,t)]};function n7(e,t,r,a,n){try{return function(e,t,r,a){if("string"==typeof e){var n,i,o;let a;return n=e,i=t,o=r,(a=n8[n])?a(i,o):tL(n)}let l=Object.entries(e);if(1!==l.length)throw new s("INVALID_ARGS","Maestro command maps must contain exactly one command.");let[u,d]=l[0],p=n6[u];return p?p({value:d,config:t,context:r,deps:a,name:u}):tL(u)}(e,t,a,n)}catch(e){if(e instanceof s&&!/\bline \d+\b/.test(e.message))throw new s(e.code,`${e.message} (line ${r})`,e.details);throw e}}function n9(e,t,r,a){return e.flatMap((e,n)=>n7(e,t,n+1,r,a))}function ie(e,t){let{config:r,commands:a}=it(tF(e)),n={...t,env:{...t.env,...r.env??{},...t.envOverrides}},{actions:i,actionLines:o}=function(e){let{config:t,commands:r,commandLines:a,context:n}=e,i=[...t.onFlowStart??[],...r,...t.onFlowComplete??[]],o=[...Array.from({length:t.onFlowStart?.length??0},()=>1),...a,...Array.from({length:t.onFlowComplete?.length??0},()=>a.at(-1)??1)],s=[],l=[];for(let[e,r]of i.entries()){let a=o[e]??e+1,i=n7(r,t,a,n,{parseRunFlowFile:ir});s.push(...i),i.forEach(()=>l.push(a))}return function(e,t){let r=[],a=[];for(let n=0;n<e.length;n+=1){let i=e[n],o=function(e,t,r){var a;let n=function(e,t,r){let a=e[r],n=e[r+1],i=e[r+2];if(i?.command!==n$||a.flags?.maestro?.optional===!0)return null;let o=function(e){if(e?.command!=="type"||e.flags&&Object.keys(e.flags).length>0)return null;let[t,...r]=e.positionals??[];return r.length>0||"string"!=typeof t?null:t}(n),s=function(e){if(e?.command!==nT)return null;let[t,...r]=e.positionals??[];return r.length>0||"string"!=typeof t?null:t}(a);return n&&null!==o&&null!==s?{action:a,nextAction:n,pressEnterAction:i,tapSelector:s,typedAfterTap:o,line:t[r]??1}:null}(e,t,r);if(!n)return null;let{action:i,nextAction:o,pressEnterAction:s,tapSelector:l,typedAfterTap:u,line:d}=n;return(a=l,/\b(input|textfield|textarea|field|email|password|username|search|query)\b/i.test(a.replace(/([a-z])([A-Z])/g,"$1 $2")))?{actions:[{...i,command:"wait",positionals:[l,"30000"]},{...o,command:"fill",positionals:[l,u],flags:i.flags},s],actionLines:[d,d,t[r+2]??d],consumed:3}:{actions:[function(e){let t={...e.flags?.maestro??{}};return delete t.allowNonHittableCoordinateFallback,{...e,flags:{...e.flags??{},maestro:{...t}}}}(i)],actionLines:[d],consumed:1}}(e,t,n);if(o){r.push(...o.actions),a.push(...o.actionLines),n+=o.consumed-1;continue}r.push(i),a.push(t[n]??1)}return{actions:r,actionLines:a}}(s,l)}({config:r,commands:a,commandLines:function(e){let t=e.split(/\r?\n/),r=t.findIndex(e=>"---"===e.trim()),a=-1===r?0:r+1,n=[];for(let e=a;e<t.length;e+=1)/^-\s+/.test(t[e]??"")&&n.push(e+1);return n}(e),context:n});return{actions:i,actionLines:o,metadata:{env:r.env}}}function it(e){if(0===e.length)throw new s("INVALID_ARGS","Maestro flow is empty.");if(Array.isArray(e[0]))return{config:{},commands:t$(e[0])};let t=function(e){if(!tH(e))throw new s("INVALID_ARGS","Maestro flow config must be a YAML map.");return{..."string"==typeof e.name&&e.name.length>0?{name:e.name}:{},..."string"==typeof e.appId&&e.appId.length>0?{appId:e.appId}:{},...tH(e.env)?{env:tO(e.env,"env")}:{},...Array.isArray(e.onFlowStart)?{onFlowStart:t$(e.onFlowStart)}:{},...Array.isArray(e.onFlowComplete)?{onFlowComplete:t$(e.onFlowComplete)}:{}}}(e[0]),r=e[1];if(!Array.isArray(r))throw new s("INVALID_ARGS","Maestro flow must contain a command list after the YAML document separator.");return{config:t,commands:t$(r)}}function ir(e,a){let n=function(e,t){if(r.isAbsolute(e))return e;if(!t.baseDir)throw new s("INVALID_ARGS","runFlow file paths require replay input to have a source path.");return r.resolve(t.baseDir,e)}(e,a);if(a.visitedPaths.has(n))throw new s("INVALID_ARGS",`Maestro runFlow cycle detected at ${n}.`);let i=t.readFileSync(n,"utf8"),o=new Set(a.visitedPaths);return o.add(n),ie(i,{...a,baseDir:r.dirname(n),visitedPaths:o})}let ia=/[*?[\]{}]/;function ii(e,t,a,n,i=0){let o=r.basename(a,r.extname(a)).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return`${e}:test:${t}:${n+1}${o?`-${o}`:""}:attempt-${i+1}`}function io(e,t){return"number"==typeof e?e:t}function is(e,t){let r="number"==typeof e?e:t;return"number"!=typeof r?0:Math.max(0,Math.min(3,r))}function il(e,a,n){var i,o;let l=ep.expandHome(e,a);if(t.existsSync(l)){let a=t.statSync(l);if(a.isDirectory())return{paths:[...n].map(e=>`**/*${e}`).flatMap(e=>t.globSync(e,{cwd:l}).map(e=>r.join(l,e))),source:"directory"};if(a.isFile()){if(!n.has(r.extname(l)))throw new s("INVALID_ARGS",`test does not support this file type: ${e}`);return{paths:[l],source:"file"}}return{paths:[],source:"file"}}if(i=e,!ia.test(i)&&(o=l,!ia.test(o)))throw new s("INVALID_ARGS",`test input not found: ${e}`);let u=r.isAbsolute(l)?l:e;return{paths:t.globSync(u,{cwd:r.isAbsolute(l)?void 0:a}).map(e=>r.isAbsolute(e)?e:r.resolve(a,e)).filter(e=>n.has(r.extname(e))&&function(e){try{return t.statSync(e).isFile()}catch{return!1}}(e)),source:"glob"}}function iu(e,t){let r=id(e),a=id(t);return r!==a?r-a:e.localeCompare(t)}function id(e){return+(".ad"===r.extname(e))}function ip(e){return[...new Set(e.map(e=>r.normalize(e)))]}function ic(e){return"maestro"===e}let im=["failed to start daemon","runner did not accept connection","xcodebuild exited early","device is offline","device offline","device unauthorized"];function ih(e){var t,r,a,n;let i,o,s="ok"in(t=e)?t.ok?null:t.error:"failed"===t.status?t.error:null;return!!s&&(r=s.details,"timeout_cleanup_pending"===(i="string"==typeof r?.reason?r.reason:"")||!!i&&tc(i)||(a=s.code,n=s.message,o=`${a}
26
+ ${n}`.toLowerCase(),im.some(e=>o.includes(e))))}async function ig(e){let a,n,{filePath:i,sessionName:s,requestId:l,parentRequestId:u,timeoutMs:d,platform:p,target:c,artifactsDir:f,shard:m,progress:h,runReplay:g,cleanupSession:w,finalizeAttempt:y}=e;P(l);let v=function(e,t){if(!t||t===e)return()=>{};let r=eT(t);if(!r)return()=>{};let a=()=>{eD(e)};return r.aborted?(a(),()=>{}):(r.addEventListener("abort",a,{once:!0}),()=>{r.removeEventListener("abort",a)})}(l,u),A=new Set,S=!1,_=Date.now(),b=function(e){let{artifactsDir:a,artifactPaths:n,filePath:i,sessionName:o,requestId:s,timeoutMs:l,platform:u,target:d}=e;if(!a)return;let p=r.join(a,"replay-timing.ndjson");return t.mkdirSync(r.dirname(p),{recursive:!0}),t.writeFileSync(p,""),n.add(p),iA(p,{type:"replay_test_attempt_start",ts:new Date().toISOString(),replayPath:i,session:o,requestId:s,timeoutMs:l,platform:u,target:d}),p}({artifactsDir:f,artifactPaths:A,filePath:i,sessionName:s,requestId:l,timeoutMs:d,platform:p,target:c}),I=eN(h,async()=>await g({filePath:i,sessionName:s,platform:p,target:c,requestId:l,artifactsDir:f,artifactPaths:A,tracePath:b,shard:m})).catch(e=>({ok:!1,error:o(e)})).finally(()=>{v(),eC(l)});try{n="number"==typeof d?await Promise.race([I,new Promise(e=>{a=setTimeout(()=>{S=!0,eD(l),e(function(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}}}}(d,[...A]))},d)})]):await I,iA(b,{type:"replay_test_attempt_stop",ts:new Date().toISOString(),session:s,ok:n.ok,timedOut:S,durationMs:Date.now()-_,errorCode:n.ok?void 0:n.error.code})}finally{var k,N,D;let e,t;a&&clearTimeout(a),S&&(await iw(I)||((k=n)&&!k.ok&&(k.error.details={...k.error.details??{},reason:"timeout_cleanup_pending",timeoutCleanupPending:!0}),tb({level:"warn",phase:"test_timeout_cleanup_race",data:{session:s,requestId:l,graceMs:2e3}}),iy({replayPromise:I,cleanupSession:w,sessionName:s,requestId:l})));let r=await iv({finalizeAttempt:y,sessionName:s,artifactPaths:A,artifactsDir:f,tracePath:b});n?.ok&&r&&!r.ok&&(N=n,D=`Replay test finalization failed: ${r.error.message}`,t=Array.isArray((e=N.data??={}).warnings)?e.warnings.filter(e=>"string"==typeof e):[],e.warnings=[...t,D]);let i=Date.now();try{iA(b,{type:"replay_test_cleanup_start",ts:new Date().toISOString(),session:s}),await w(s),iA(b,{type:"replay_test_cleanup_stop",ts:new Date().toISOString(),session:s,ok:!0,durationMs:Date.now()-i})}catch(t){let e=o(t);iA(b,{type:"replay_test_cleanup_stop",ts:new Date().toISOString(),session:s,ok:!1,durationMs:Date.now()-i,errorCode:e.code}),tb({level:"warn",phase:"test_cleanup_failed",data:{session:s,error:e.message}})}}return n??{ok:!1,error:{code:"COMMAND_FAILED",message:"Unknown replay test failure"}}}async function iw(e){return await Promise.race([e.then(()=>!0),n(2e3).then(()=>!1)])}async function iy(e){let{replayPromise:t,cleanupSession:r,sessionName:a,requestId:n}=e;try{await t}finally{try{await r(a)}catch(e){tb({level:"warn",phase:"test_late_cleanup_failed",data:{session:a,requestId:n,error:o(e).message}})}}}async function iv(e){let{finalizeAttempt:t,sessionName:r,artifactPaths:a,artifactsDir:n,tracePath:i}=e;if(!t)return;let s=Date.now();iA(i,{type:"replay_test_finalize_start",ts:new Date().toISOString(),session:r});try{let e=await t({sessionName:r,artifactPaths:a,artifactsDir:n,tracePath:i});return iA(i,{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 e=o(t);return iA(i,{type:"replay_test_finalize_stop",ts:new Date().toISOString(),session:r,ok:!1,durationMs:Date.now()-s,errorCode:e.code}),tb({level:"warn",phase:"test_finalize_failed",data:{session:r,error:e.message}}),{ok:!1,error:e}}}function iA(e,r){e&&t.appendFileSync(e,`${JSON.stringify(r)}
27
+ `)}async function iS(e){var t,a,n;let i,o=function(e){var t;let a,{entry:n,cwd:i,retries:o,suiteArtifactsDir:s,shard:l}=e;return{testStartedAt:Date.now(),testArtifactsDir:r.join(s,...l?[`shard-${l.shardIndex+1}`]:[],(t=n.path,(0===(a=i?r.relative(i,t):r.basename(t)).length||a.startsWith("..")?r.basename(t):a).toLowerCase().replace(/[\\/]+/g,"__").replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"test")),maxAttempts:o+1}}(e),s=await i_(e,o);return t=e,a=o,n=s,i=Date.now()-a.testStartedAt,n.finalResponse?.ok?function(e,t,r,a){var n;let{entry:i,suiteIndex:o,suiteTotal:s,shard:l}=e,u=r.finalResponse;if(!u?.ok)throw Error("Expected passing replay test response.");return eB({type:"replay-test",file:i.path,title:i.title,status:"pass",index:o,total:s,attempt:r.attempts,maxAttempts:t.maxAttempts,durationMs:a,session:r.finalSessionName,artifactsDir:t.testArtifactsDir,...ik(l)}),{file:i.path,title:i.title,session:r.finalSessionName,status:"passed",durationMs:a,finalAttemptDurationMs:r.finalAttemptDurationMs,attempts:r.attempts,artifactsDir:t.testArtifactsDir,...(n=u,{replayed:"number"==typeof n.data?.replayed?n.data.replayed:0,healed:"number"==typeof n.data?.healed?n.data.healed:0}),...function(e){if(!Array.isArray(e))return{};let t=e.filter(e=>"string"==typeof e);return t.length>0?{warnings:t}:{}}(u.data?.warnings),...iI(u.data?.snapshotDiagnostics),...function(e){return ik(e)}(l),...r.attemptFailures.length>0?{attemptFailures:r.attemptFailures}:{}}}(t,a,n,i):function(e,t,r,a){var n,i;let{entry:o,suiteIndex:s,suiteTotal:l,shard:u}=e,d=(n=r.finalResponse)&&!n.ok?n.error:{code:"COMMAND_FAILED",message:"Unknown replay test failure"};return eB({type:"replay-test",file:o.path,title:o.title,status:"fail",index:s,total:l,attempt:r.attempts,maxAttempts:t.maxAttempts,durationMs:a,session:r.finalSessionName,artifactsDir:t.testArtifactsDir,message:d.message,...ik(u)}),{file:o.path,title:o.title,session:r.finalSessionName,status:"failed",durationMs:a,attempts:r.attempts,artifactsDir:t.testArtifactsDir,error:d,...iI((i=r.finalResponse,i?.ok?i.data?.snapshotDiagnostics:i?.error.details?.snapshotDiagnostics)),...function(e){return ik(e)}(u)}}(t,a,n,i)}async function i_(e,t){!function(e,t){let{entry:r,sessionName:a,suiteInvocationId:n,caseIndex:i,suiteIndex:o,suiteTotal:s,shard:l}=e;eB({type:"replay-test",file:r.path,title:r.title,status:"start",index:o,total:s,maxAttempts:t.maxAttempts,session:ii(a,n,r.path,i),artifactsDir:t.testArtifactsDir,...ik(l)})}(e,t);let r={finalSessionName:"",attempts:0,finalAttemptDurationMs:0,attemptFailures:[]};for(let p=0;p<=e.retries&&!eh(e.requestId);p+=1){var a,n,i,o,s,l,u,d;let c=await ib(e,t,p);if((a=r).finalResponse=(n=c).response,a.finalSessionName=n.sessionName,a.attempts=n.attempt,a.finalAttemptDurationMs=n.durationMs,n.response.ok||a.attemptFailures.push({attempt:n.attempt,message:n.response.error.message,durationMs:n.durationMs}),i=e,o=c.response,s=p,o.ok||eh(i.requestId)||ih(o)||s>=i.retries)break;l=e,u=t,(d=c).response.ok||eB({type:"replay-test",file:l.entry.path,title:l.entry.title,status:"fail",index:l.suiteIndex,total:l.suiteTotal,attempt:d.attempt,maxAttempts:u.maxAttempts,durationMs:d.durationMs,retrying:!0,message:d.response.error.message,session:d.sessionName,artifactsDir:u.testArtifactsDir,...ik(l.shard)})}return r}async function ib(e,a,n){var i;let{entry:o,sessionName:s,suiteInvocationId:l,caseIndex:u,suiteIndex:d,suiteTotal:p,requestId:c,timeoutMs:f,shard:m}=e,h=n+1,g=Date.now(),w=ii(s,l,o.path,u,n),y=r.join(a.testArtifactsDir,`attempt-${h}`);i=o.path,t.mkdirSync(y,{recursive:!0}),function(e,a){var n;let i,o=r.join(a,"replay.ad");if(t.copyFileSync(e,o),n=e,".yml"!==(i=r.extname(n).toLowerCase())&&".yaml"!==i)return;let s=r.join(a,r.basename(e));r.resolve(s)!==r.resolve(o)&&t.copyFileSync(e,s)}(i,y);let v=function(e){let{requestId:t,suiteInvocationId:a,filePath:n,caseIndex:i,attemptIndex:o,shardIndex:s}=e,l=void 0===s?"":`:shard:${s+1}`;return eg(`${t??a}${l}:test:${i+1}:${r.basename(n)}:attempt:${o+1}`,a)}({requestId:c,suiteInvocationId:l,filePath:o.path,caseIndex:u,attemptIndex:n,shardIndex:m?.shardIndex}),A=await ig({filePath:o.path,sessionName:w,requestId:v,parentRequestId:c,timeoutMs:f,platform:o.metadata.platform,target:o.metadata.target,artifactsDir:y,shard:m,progress:{file:o.path,title:o.title,index:d,total:p,attempt:h,maxAttempts:a.maxAttempts,session:w,artifactsDir:a.testArtifactsDir,...ik(m)},runReplay:e.runReplay,cleanupSession:e.cleanupSession,finalizeAttempt:e.finalizeAttempt}),S=Date.now()-g;return!function(e){var a;let n,{response:i,filePath:o,sessionName:s,attempts:l,maxAttempts:u,attemptArtifactsDir:d}=e,p=[...Array.isArray(n=(a=i).ok?a.data?.artifactPaths:a.error.details?.artifactPaths)?[...new Set(n.filter(e=>"string"==typeof e))]:[]];i.ok||"string"!=typeof i.error.logPath||p.push(i.error.logPath);let c=function(e,a){let n=[],i=new Map;for(let o of e){if(!function(e){try{return t.statSync(e).isFile()}catch{return!1}}(o))continue;let e=function(e,t){let a=r.extname(e),n=a?e.slice(0,-a.length):e,i=t.get(e)??0;return(t.set(e,i+1),0===i)?e:`${n}-${i+1}${a}`}(r.basename(o),i),s=r.join(a,e);r.resolve(o)!==r.resolve(s)&&t.copyFileSync(o,s),n.push(s)}return n}(p,d),f=[`file: ${o}`,`session: ${s}`,`attempt: ${l}/${u}`,`status: ${i.ok?"passed":"failed"}`];if(i.ok){let e="number"==typeof i.data?.replayed?i.data.replayed:0,t="number"==typeof i.data?.healed?i.data.healed:0;f.push(`replayed: ${e}`,`healed: ${t}`)}else f.push(`code: ${i.error.code}`,`message: ${i.error.message}`),i.error.hint&&f.push(`hint: ${i.error.hint}`),i.error.diagnosticId&&f.push(`diagnosticId: ${i.error.diagnosticId}`),i.error.logPath&&f.push(`logPath: ${i.error.logPath}`),i.error.details?.reason==="timeout"&&f.push("timeoutMode: cooperative");c.length>0&&f.push(`copiedArtifacts: ${c.map(e=>r.basename(e)).join(", ")}`);let m=r.join(d,"result.txt"),h=`${f.join("\n")}
28
+ `;t.writeFileSync(m,h),i.ok||t.writeFileSync(r.join(d,"failure.txt"),h)}({response:A,filePath:o.path,sessionName:w,attempts:h,maxAttempts:a.maxAttempts,attemptArtifactsDir:y}),{response:A,sessionName:w,attempt:h,durationMs:S}}function iI(e){let t=t5(e);return t?{snapshotDiagnostics:t}:{}}function ik(e){return e?{shardIndex:e.shardIndex,shardCount:e.shardCount,deviceId:e.device.id}:{}}async function iN(e,t,r){let a=function(e){let t=iD(e?.shardAll,"--shard-all"),r=iD(e?.shardSplit,"--shard-split");if(void 0!==t&&void 0!==r)throw new s("INVALID_ARGS","--shard-all and --shard-split are mutually exclusive");return void 0!==t?{kind:"all",count:t}:void 0!==r?{kind:"split",count:r}:void 0}(e);if(!a||0===t.length)return;let n=await ix(e,a.count);return{mode:a.kind,shardCount:a.count,total:r+("all"===a.kind?t.length*a.count:t.length),shards:n.map((e,r)=>({shardIndex:r,shardCount:a.count,device:e,entries:"all"===a.kind?t:t.filter((e,t)=>t%a.count===r)}))}}function iD(e,t){if(void 0!==e){if("number"!=typeof e||!Number.isInteger(e)||e<1)throw new s("INVALID_ARGS",`${t} requires a positive integer`);return e}}async function ix(e,t){var r,a,n,i,o,l,u,d,p;let c,f,m=(r=e,"string"!=typeof(c=r?.device)||0===c.trim().length?[]:c.split(",").map(e=>e.trim()).filter(Boolean)),h=(n=await ed((a=e,f=tm(a?.androidDeviceAllowlist),{platform:a?.platform,target:a?.target,iosSimulatorSetPath:tv({simulatorSetPath:tu(a?.iosSimulatorDeviceSet),platform:a?.platform,target:a?.target}),androidSerialAllowlist:f?Array.from(f).sort():void 0})),i=m,o=e,i.length>0?(l=n,u=i,d=o,u.map(e=>{let t=iM(e),r=l.find(r=>iR(r,d)&&(r.id===e||iM(r.name)===t));if(!r)throw new s("DEVICE_NOT_FOUND",`No shard device matched ${e}`);return r})):n.filter(e=>{var t;return!!iR(t=e,o)&&("ios"===t.platform||"android"===t.platform)&&!1!==t.booted}).sort(iP));if(h.length<t){throw new s("DEVICE_NOT_FOUND",`test sharding requires ${(p=t,`${p} device${1===p?"":"s"}`)}, but only ${h.length} matched`)}return h.slice(0,t)}function iR(e,t){return!(!tS(e.platform,t?.platform)||t?.target&&(e.target??"mobile")!==t.target)}function iM(e){return e.toLowerCase().replace(/_/g," ").replace(/\s+/g," ").trim()}function iP(e,t){return e.id.localeCompare(t.id)}async function iL(e){let{req:t,sessionName:r,runReplay:a,cleanupSession:n,finalizeAttempt:o}=e;if((t.positionals?.length??0)===0)return L("INVALID_ARGS","test requires at least one path or glob");try{var s,l,u,d;let e,i,p,c,f,m,h=Date.now(),g=await iO(t);s=g,eB({type:"replay-test-suite",status:"start",total:s.total,runnable:s.runnable.length,skipped:s.entries.length-s.runnable.length,artifactsDir:s.suiteArtifactsDir,shardMode:s.shardPlan?.mode,shardCount:s.shardPlan?.shardCount});let w=g.shardPlan?function(e){let{entries:t,total:r}=e,a=[];for(let[e,n]of t.entries())"skip"===n.kind&&(eB({type:"replay-test",file:n.path,status:"skip",index:e+1,total:r,message:n.message}),a.push({file:n.path,status:"skipped",durationMs:0,reason:n.reason,message:n.message}));return a}({entries:g.entries,total:g.total}):[];g.shardPlan?w.push(...await iC({shards:g.shardPlan.shards,sessionName:r,suiteInvocationId:g.suiteInvocationId,cwd:t.meta?.cwd,requestId:t.meta?.requestId,flags:t.flags,suiteArtifactsDir:g.suiteArtifactsDir,suiteTotal:g.total,runReplay:a,cleanupSession:n,finalizeAttempt:o})):w.push(...await iV({discoveryEntries:g.entries,sessionName:r,suiteInvocationId:g.suiteInvocationId,cwd:t.meta?.cwd,requestId:t.meta?.requestId,flags:t.flags,suiteArtifactsDir:g.suiteArtifactsDir,suiteTotal:g.total,runReplay:a,cleanupSession:n,finalizeAttempt:o}));let y=(l=g.total,u=w,d=Date.now()-h,e=u.filter(e=>"passed"===e.status).length,p=(i=u.filter(e=>"failed"===e.status)).length,c=u.filter(e=>"skipped"===e.status).length,f=e+p,m=t6(u.map(e=>"skipped"===e.status?void 0:e.snapshotDiagnostics)),{total:l,executed:f,passed:e,failed:p,skipped:c,notRun:Math.max(0,l-f-c),durationMs:d,failures:i,tests:u,...m?{snapshotDiagnostics:m}:{}});return{ok:!0,data:y}}catch(t){let e=i(t);return L(e.code,e.message)}}async function iO(e){var a,n,i,o;let l=function(e){let{inputs:a,cwd:n,platformFilter:i,replayBackend:o}=e,l=new Set(ic(o)?[".yaml",".yml",".ad"]:[".ad"]),u=function(e,a,n,i){if(!ic(i))return[...new Set(e.flatMap(e=>il(e,a,n).paths))].map(e=>r.normalize(e)).sort((e,t)=>e.localeCompare(t));let o=[],s=[];for(let i of e){let e=function(e,a,n){let i=ep.expandHome(e,a);return t.existsSync(i)&&t.statSync(i).isDirectory()?{paths:function e(a,n){let i=[],o=t.opendirSync(a);try{let t;for(;null!==(t=o.readSync());){let o=r.join(a,t.name);t.isDirectory()?i.push(...e(o,n)):t.isFile()&&n.has(r.extname(t.name))&&i.push(o)}}finally{o.closeSync()}return i}(i,n),source:"directory"}:il(e,a,n)}(i,a,n);"file"===e.source?o.push(...e.paths):s.push("directory"===e.source?ip(e.paths):e.paths.map(e=>r.normalize(e)).sort(iu))}return ip([...o,...s.flat()])}(a,n??process.cwd(),l,o),d=[];for(let e of u){var p,c,f,m;let a=t.readFileSync(e,"utf8"),n=tT(a),s=(p=a,c=e,ic(o)&&".ad"!==r.extname(c)?function(e){let{config:t}=it(tF(e));return t.name}(p):void 0);if(!i){d.push({kind:"run",path:e,title:s,metadata:n});continue}if(!n.platform){ic(o)?d.push({kind:"run",path:e,title:s,metadata:n}):d.push({kind:"skip",path:e,reason:"skipped-by-filter",message:`missing platform metadata for --platform ${i}`});continue}f=i,m=n.platform,("apple"===f?"apple"===m||"ios"===m||"macos"===m:m===f)&&d.push({kind:"run",path:e,title:s,metadata:n})}if(0===d.filter(e=>"run"===e.kind).length){let e=i?` for --platform ${i}`:"";throw new s("INVALID_ARGS",`No replay tests matched${e}.`)}return d}({inputs:(n=e).positionals??[],cwd:n.meta?.cwd,platformFilter:n.flags?.platform,replayBackend:n.flags?.replayBackend}),u=l.flatMap((e,t)=>"run"===e.kind?[{entry:e,suiteIndex:t+1}]:[]),d=l.length-u.length,p=(a=e.meta?.requestId,(a?.trim()||`${process.pid}-${Date.now().toString(36)}`).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"suite"),c=await iN(e.flags,u,d);return{entries:l,runnable:u,shardPlan:c,suiteInvocationId:p,suiteArtifactsDir:(i=e,o=p,function(e){let{artifactsDir:t,cwd:a,suiteInvocationId:n}=e,i=ep.expandHome(t??".agent-device/test-artifacts",a);return r.join(i,n)}({artifactsDir:"string"==typeof i.flags?.artifactsDir?i.flags.artifactsDir:void 0,cwd:i.meta?.cwd,suiteInvocationId:o})),total:c?.total??l.length}}async function iC(e){return(await Promise.allSettled(e.shards.map(async t=>await iE({...e,shard:t})))).flatMap((t,r)=>{var a,n;let i;if("fulfilled"===t.status)return t.value;let s=e.shards[r];return s?[(a=s,n=e.sessionName,i=o(t.reason),{file:a.entries[0]?.entry.path??`shard-${a.shardIndex+1}`,session:i$(n,a),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:a.shardIndex,shardCount:a.shardCount,deviceId:a.device.id})]:[]})}async function iE(e){let{shard:t,sessionName:r}=e;return await iU({...e,entries:t.entries,sessionName:i$(r,t),shard:t})}function i$(e,t){return`${e}:shard-${t.shardIndex+1}`}async function iV(e){let{discoveryEntries:t,sessionName:r,suiteInvocationId:a,cwd:n,requestId:i,flags:o,suiteArtifactsDir:s,suiteTotal:l,runReplay:u,cleanupSession:d,finalizeAttempt:p}=e,c=[],f=0;for(let[e,m]of t.entries()){if(eh(i))break;if("skip"===m.kind){eB({type:"replay-test",file:m.path,status:"skip",index:e+1,total:l,message:m.message}),c.push({file:m.path,status:"skipped",durationMs:0,reason:m.reason,message:m.message});continue}f+=1;let t=await iS({entry:m,sessionName:r,suiteInvocationId:a,caseIndex:f-1,cwd:n,requestId:i,retries:is(o?.retries,m.metadata.retries),timeoutMs:io(o?.timeoutMs,m.metadata.timeoutMs),suiteArtifactsDir:s,suiteIndex:e+1,suiteTotal:l,runReplay:u,cleanupSession:d,finalizeAttempt:p});if(c.push(t),iF(t,o,i))break}return c}async function iU(e){let{entries:t,sessionName:r,suiteInvocationId:a,cwd:n,requestId:i,flags:o,suiteArtifactsDir:s,suiteTotal:l,shard:u,runReplay:d,cleanupSession:p,finalizeAttempt:c}=e,f=[];for(let[e,m]of t.entries()){if(eh(i))break;let{entry:t,suiteIndex:h}=m,g=await iS({entry:t,sessionName:r,suiteInvocationId:a,caseIndex:e,cwd:n,requestId:i,retries:is(o?.retries,t.metadata.retries),timeoutMs:io(o?.timeoutMs,t.metadata.timeoutMs),suiteArtifactsDir:s,suiteIndex:h,suiteTotal:l,shard:u,runReplay:d,cleanupSession:p,finalizeAttempt:c});if(f.push(g),iF(g,o,i))break}return f}function iF(e,t,r){return eh(r)||t?.failFast===!0||ih(e)}let iq={maestro:{parse:function(e,t={}){var a;let n;return ie(e,(n=(a=t).visitedPaths??new Set,a.sourcePath&&n.add(r.resolve(a.sourcePath)),{baseDir:a.sourcePath?r.dirname(a.sourcePath):void 0,platform:tV(a.platform),env:{},envOverrides:a.env??{},visitedPaths:n}))}}};function iT(e){if(0===e.length)return{selectorExpression:null,selectorTimeout:null};let t=e[e.length-1],r=void 0!==t&&/^\d+$/.test(t)?t:null,a=ru(null!==r?e.slice(0,-1):e.slice());return!a||a.rest.length>0?{selectorExpression:null,selectorTimeout:null}:{selectorExpression:a.selectorExpression,selectorTimeout:r}}async function iG(e){let{action:t,sessionName:r,logPath:a,sessionStore:n}=e;if(!(rl(t.command)||["fill","get","is","wait"].includes(t.command)))return null;let i=n.get(r);if(!i)return null;let o=(function(e){let t=[],r=Array.isArray(e.result?.selectorChain)&&e.result?.selectorChain.every(e=>"string"==typeof e)?e.result.selectorChain:[];if(t.push(...r),rl(e.command)){let r=function(e){let t=e.positionals??[];if("longpress"!==e.command)return t;let r=t.at(-1);return t.length>1&&iK(r)?t.slice(0,-1):t}(e),a=r[0]??"";a&&!a.startsWith("@")&&t.push(r.join(" "))}if("fill"===e.command){let r=e.positionals?.[0]??"";r&&!r.startsWith("@")&&Number.isNaN(Number(r))&&t.push(r)}if("get"===e.command){let r=e.positionals?.[1]??"";r&&!r.startsWith("@")&&t.push(e.positionals.slice(1).join(" "))}if("is"===e.command){let{split:r}=rt(e.positionals);r&&t.push(r.selectorExpression)}if("wait"===e.command){let{selectorExpression:r}=iT(e.positionals??[]);r&&t.push(r)}return F(t).filter(e=>e.trim().length>0)})(t).map(e=>rp(e)).filter(e=>null!==e);if(0===o.length)return null;let s=rl(t.command)||"fill"===t.command,l=rl(t.command)||"fill"===t.command||"get"===t.command&&t.positionals?.[0]==="text",u=await iB(i,t,a,s,n);for(let e of o){let r=t8(u.nodes,e,{platform:i.device.platform,requireRect:s,requireUnique:!0,disambiguateAmbiguous:l});if(!r)continue;let a=rr(r.node,i.device.platform,{action:"fill"===t.command?"fill":rl(t.command)?"click":"get"}).join(" || ");if(rl(t.command))return{...t,positionals:"longpress"===t.command?function(e,t){let r="number"==typeof e.result?.durationMs?String(e.result.durationMs):function(e){let t=e.at(-1);return e.length>1&&iK(t)?t:void 0}(e.positionals??[]);return r?[t,r]:[t]}(t,a):[a]};if("fill"===t.command){let e=w(t);if(!e)continue;return{...t,positionals:[a,e]}}if("get"===t.command){let e=t.positionals?.[0];if("text"!==e&&"attrs"!==e)continue;return{...t,positionals:[e,a]}}if("is"===t.command){let{predicate:e,split:r}=rt(t.positionals);if(!e)continue;let n=r?.rest.join(" ").trim()??"",i=[e,a];return"text"===e&&n.length>0&&i.push(n),{...t,positionals:i}}if("wait"===t.command){let{selectorTimeout:e}=iT(t.positionals??[]),r=[a];return e&&r.push(e),{...t,positionals:r}}}return null}function iK(e){return void 0!==e&&""!==e.trim()&&Number.isFinite(Number(e))}async function iB(e,t,r,a,n){let i=ei(await p(e.device,"snapshot",[],t.flags?.out,{...eu(r,{...t.flags??{},snapshotInteractiveOnly:a},e.appBundleId,e.trace?.outPath)}),{...t.flags??{},snapshotInteractiveOnly:a});return q(e,i),n.set(e.name,e),i}let iH=.35,ij=120,iz=360,iW=8;function iJ(e,t){return Math.round(Math.min(iz,Math.max(ij,"number"==typeof e?e*iH:0,1.5*t)))}let iX=new WeakMap,iY=new WeakMap,iZ=new WeakMap;function iQ(e,t,r){return{ok:!1,error:{code:e,message:t,...r?{details:r}:{}}}}async function i0(e){var t;let r,a=!0===e.raw||"1"===process.env.AGENT_DEVICE_MAESTRO_RAW_SNAPSHOTS,n=await e.invoke({...e.baseReq,command:"snapshot",positionals:[],flags:{...e.baseReq.flags,noRecord:!0,...a?{snapshotRaw:!0}:{}}});return n.ok&&e.scope&&(t=e.scope,(r=j(i1(n.data)))&&iX.set(t,r)),n}function i1(e){return Array.isArray(e?.nodes)?e:void 0}function i3(e,t){e&&iY.set(e,{selector:t})}function i2(e){e&&iZ.delete(e)}let i5=new Map([["button",0],["link",0],["textfield",0],["textview",0],["searchfield",0],["switch",0],["slider",0],["cell",1],["statictext",2]]);function i4(e,t,r,a,n,i={}){let o=oe(e,t,a);if(r.childOf){let t=oe(e,r.childOf,a);if(0===t.length)return{ok:!1,message:`Maestro childOf parent did not match: ${r.childOf}`};let n=ra(e.nodes);o=o.filter(r=>t.some(t=>re(e.nodes,r,t,n)))}let s=i8({nodes:e.nodes,matches:o,platform:a}),l=oa(e.nodes,s.matches,r.index,i9(t),n,!0===i.requireOnScreen,i.promoteTapTarget,i.preferredContext);if(!l){let e=r.index??0;return{ok:!1,message:s.blockedByReactNativeOverlay?`React Native overlay is covering app content: ${t}`:o.length>0&&0===s.matches.length?`Maestro selector matched ${o.length} element(s), but none were visible: ${t}`:`Maestro selector did not match index ${e}: ${t}`}}return{ok:!0,node:l.node,rect:l.rect}}function i6(e,t,r,a){let n=oe(e,t,r,{allowLeadingCompositeLabelMatch:!1}),i=i8({nodes:e.nodes,matches:n,platform:r}),o=oa(e.nodes,i.matches,void 0,i9(t),a,!0);return o?{ok:!0,node:o.node,rect:o.rect,matches:i.matches.length}:{ok:!1,message:i.blockedByReactNativeOverlay?`React Native overlay is covering app content: ${t}`:n.length>0?`Maestro selector matched ${n.length} element(s), but none were visible: ${t}`:`Maestro selector did not match: ${t}`}}function i8(e){let t=e.matches.filter(t=>rs({predicate:"visible",node:t,nodes:e.nodes,platform:e.platform}).pass),r=function(e,t,r){let a=tn(e);if(!a.detected||!a.redBox)return{matches:t,blockedByReactNativeOverlay:!1};let n=ta(a),i=n.filter(t=>rs({predicate:"visible",node:t,nodes:e,platform:r}).pass);if(0===i.length)return 0===n.length?{matches:[],blockedByReactNativeOverlay:!0}:{matches:t,blockedByReactNativeOverlay:!1};let o=new Set(i.map(e=>e.index)),s=t.filter(e=>o.has(e.index));return{matches:s,blockedByReactNativeOverlay:t.length>0&&0===s.length}}(e.nodes,t,e.platform);return{matches:r.matches,blockedByReactNativeOverlay:r.blockedByReactNativeOverlay}}function i7(e){return e?.platform==="android"?"android":"ios"}function i9(e){let t=rc(e).selectors.flatMap(e=>e.terms);if(0===t.length||!t.some(e=>"label"===e.key||"text"===e.key)||!t.every(e=>["label","text","id"].includes(e.key)))return null;let r=t.map(e=>"string"==typeof e.value?e.value:""),a=r[0];return a&&r.every(e=>e===a)?a:null}function oe(e,t,r,a={}){for(let n of rc(t).selectors){let t=e.nodes.filter(e=>(function(e,t,r,a){return!!rn(e,t,r)||t.terms.every(t=>(function(e,t,r,a){var n,i,o;return"string"!=typeof t.value||"id"!==(n=t.key)&&"label"!==n&&"text"!==n&&"value"!==n?rn(e,{raw:t.key,terms:[t]},r):ot((i=e,"id"===(o=t.key)?i.identifier:"label"===o?i.label:"value"===o?i.value:t7(i)),t.value,a)})(e,t,r,a))})(e,n,r,a));if(t.length>0)return t}return[]}function ot(e,t,r={}){var a;let n=e??"",i=rd(n),o=rd(t);if(i===o||!1!==r.allowLeadingCompositeLabelMatch&&function(e,t){if(!e||!t||!e.startsWith(t))return!1;let r=e.at(t.length);return","===r||":"===r||";"===r}(i,o))return!0;if(a=t,!/(?:\.\*|\.\+|\[[^\]]+\]|\([^)]*\)|\||\^|\$|\\[dDsSwWbB])/.test(a))return!1;try{return new RegExp(t).test(n)}catch{return!1}}function or(e,t,r){if(t.rect&&t.rect.width>0&&t.rect.height>0)return{rect:t.rect,inherited:!1};if(t.rect)return null;let a=function(e,t,r){let a=t;for(;"number"==typeof a.parentIndex&&(a=r.get(a.parentIndex)??e[a.parentIndex]);)if(a.rect)return a.rect.width>0&&a.rect.height>0?a.rect:null;return null}(e,t,r);return a?{rect:a,inherited:!0}:null}function oa(e,t,r,a,n,i=!1,o=!1,s){var l,u,d,p,c,f,m,h,g,w,y,v,A,S,_,b,I,k,N;let D,x,R,M,P=ra(e),L=(l=e,u=t,d=P,p=a,c=r,f=n,m=i,R=(x=(D=u.map(e=>{var t;let r;return(r=or(l,t=e,d))?{node:t,rect:r.rect,inheritedRect:r.inherited}:null}).filter(e=>!!e)).filter(e=>!e.inheritedRect)).length>0?x:D,p&&void 0===c?(h=R,g=f,w=m,M=h.filter(e=>{var t,r;let a,n;return t=e.rect,r=g,a=r?.referenceWidth??1/0,n=r?.referenceHeight??1/0,t.x<a&&t.y<n&&t.x+t.width>0&&t.y+t.height>0}),w||M.length>0?M:h):D),O=function(e,t,r,a,n,i){var o,s,l,u,d,p,c;if(void 0!==r)return t[r]??null;let f=(o=e,s=t,l=a,u=n,d=i,u&&l?function(e,t,r,a){let n=t.filter(e=>0===of(e.node,r));if(n.length>=2){let t=oi(e,n,r,a);if(t)return t}let i=t.filter(e=>1===of(e.node,r));return n.length>0||i.length<2?null:oi(e,i,r,a)}(o,s,l,d)??on(o,s,l,d):on(o,s,l,d));return(p=f,c=a,n&&c&&p)?function(e,t,r){var a,n,i,o,s,l,u,d,p,c,f,m,h,g,w,y,v,A;let S,_,b,I,k,N,D,x;if(a=t,n=r,!(("cell"===(S=ri(a.node.type??""))||"other"===S||"scrollview"===S||"scroll-area"===S)&&!(a.rect.width<120)&&!(a.rect.height<32)&&!(a.rect.height>80)&&1>=of(a.node,n)))return null;let R=(i=e,o=t,s=r,l=ra(e),i.filter(e=>{var t,r,a;let n;return e.index!==o.node.index&&!!e.rect&&re(i,e,o.node,l)&&(t=e,r=o.rect,a=s,!("button"!==(n=ri(t.type??""))&&"cell"!==n&&"other"!==n||1>=of(t,a))&&!(t.rect.width<16)&&!(t.rect.height<16)&&!!op(r,t.rect)&&ou(r,t.rect)>=.5)}).sort((e,t)=>e.rect.x-t.rect.x));if(0===R.length)return null;let M=(b=Math.floor((_=[...R.map(e=>e.rect.width)].sort((e,t)=>e-t)).length/2),_[b]??0),P=function(e,t){let r=[],a=e.x,n=e.x+e.width;for(let i of t){let t=Math.max(e.x,i.x),o=Math.min(n,i.x+i.width);t>a&&r.push({x:a,width:t-a}),a=Math.max(a,o)}return n>a&&r.push({x:a,width:n-a}),r}(t.rect,R.map(e=>e.rect)),L=(u=t,d=r,p=P,c=M,N=p.filter(e=>{var t,r;return t=e.width,r=c,!(t<24)&&!(r<24)&&t>=.4*r&&t<=1.6*r}),D=(f=u,m=d,I=p.find(e=>1>Math.abs(e.x-f.rect.x)),k=Math.max(48,Math.min(220,8*m.length+24)),(h=f,g=m,w=I,y=k,w&&"scrollview"===ri(h.node.type??"")&&1>=of(h.node,g)&&h.rect.width>=240&&h.rect.height>=32&&h.rect.height<=80&&w.width<=.55*h.rect.width&&w.width>=.6*y)?{x:f.rect.x,width:Math.min(k,I.width)}:null),x=N.some(e=>{var t;return t=u.rect,1>Math.abs(e.x-t.x)}),D&&!x?D:1===N.length?N[0]??null:D);return L?(v=t,A=L,{...v,rect:{x:A.x,y:v.rect.y,width:A.width,height:v.rect.height}}):null}(e,f,a)??f:f}(e,L,r,a,o,s);return y=e,v=O,A=P,S=o,_=n,v?S?(b=y,I=v,k=A,N=_,(od(I.node)?null:t9(b,I.node,k,e=>{if(!od(e))return null;let t=or(b,e,k);return t&&function(e,t,r){var a,n;if(!op(t,e)||(a=e,!((n=t).height<32||n.height>80||a.height<.75*n.height||.75>ou(a,n))&&!(n.width<240)&&n.width>=3*a.width))return!1;let i=os(t),o=os(e);if(o>0&&i>30*o)return!1;if(r){let e=r.referenceWidth*r.referenceHeight;if(e>0&&i>.5*e)return!1}return!0}(I.rect,t.rect,N)?{node:e,rect:t.rect}:null}))??{node:v.node,rect:v.rect}):{node:v.node,rect:v.rect}:null}function on(e,t,r,a){return(function(e,t,r,a){var n;let i,o,s;if(!r||t.length<2)return t;let l=t.filter(e=>0===of(e.node,r));if(l.length<2)return t;let u=ra(e),d=l.map(t=>({candidate:t,container:oo(e,t.node,u)})).filter(e=>!!e.container);if(d.length<2||d.length!==l.length)return t;let p=d.filter(e=>{var t;return t=e,d.some(e=>e!==t&&t.container.index!==e.container.index&&oc(t.container.rect,e.container.rect)>=.6)});if(p.length<2)return t;let c=(o=Math.max(...i=(n=p).map(e=>os(e.container.rect))),(s=Math.min(...i))<=0||o<1.2*s?[]:n.filter(e=>os(e.container.rect)===o).map(e=>e.candidate));if(c.length>0)return c;let f=function(e,t,r,a){if(!r)return[];let n=oo(e,r.node,a),i=n&&op(n.rect,r.rect)?n:null,o=t.map(e=>({entry:e,score:function(e,t,r){if(r)return e.index===r.index?0:.6>oc(e.rect,r.rect)?1/0:Math.abs(e.index-r.index);if(oc(e.rect,t.rect)>=.6)return 0;let a=e.index-t.node.index;return a>=0?a:1e5+Math.abs(a)}(e.container,r,i)})),s=Math.min(...o.map(e=>e.score));return Number.isFinite(s)?o.filter(e=>e.score===s).map(e=>e.entry.candidate):[]}(e,p,a,u);if(f.length>0)return f;let m=Math.max(...p.map(e=>e.container.index)),h=p.filter(e=>e.container.index===m).map(e=>e.candidate);return h.length>0?h:t})(e,t,r,a).sort((e,t)=>(function(e,t,r){var a,n;let i=function(e,t,r){if(r){let a=of(e.node,r)-of(t.node,r);if(0!==a)return a}let a=ol(e.node)-ol(t.node);if(0!==a)return a;let n=Number(e.inheritedRect)-Number(t.inheritedRect);if(0!==n)return n;let i=r&&ol(e.node)===ol(t.node)?os(t.rect)-os(e.rect):os(e.rect)-os(t.rect);return 0!==i?i:0}(e,t,r);if(0!==i)return i;if(a=e.rect,n=t.rect,Math.round(a.x)!==Math.round(n.x)||Math.round(a.y)!==Math.round(n.y)||Math.round(a.width)!==Math.round(n.width)||Math.round(a.height)!==Math.round(n.height))return e.node.index-t.node.index;let o=(t.node.depth??0)-(e.node.depth??0);return 0!==o?o:t.node.index-e.node.index})(e,t,r))[0]??null}function oi(e,t,r,a){let n=ra(e),i=t.filter(r=>{var a;return(a=r).rect.width>=16&&a.rect.width<=260&&a.rect.height>=24&&a.rect.height<=80&&t.some(t=>{var a,i,o,s;return a=e,i=t,o=r,s=n,!(i.node.index===o.node.index||!op(i.rect,o.rect)||os(i.rect)<2*os(o.rect))&&re(a,o.node,i.node,s)})});return on(e,i,r,a)}function oo(e,t,r){return t9(e,t,r,e=>{let t;return!e.rect||"scrollview"!==(t=ri(e.type??""))&&"scroll-area"!==t&&"list"!==t||e.rect.width<240||e.rect.height<320?null:e})}function os(e){return e.width*e.height}function ol(e){return i5.get(ri(e.type??""))??3}function ou(e,t){let r=Math.max(e.y,t.y);return Math.max(0,Math.min(e.y+e.height,t.y+t.height)-r)/Math.max(1,Math.min(e.height,t.height))}function od(e){let t=ri(e.type??"");return!0===e.hittable||"button"===t||"link"===t||"cell"===t||"textfield"===t||"searchfield"===t||"switch"===t||"slider"===t}function op(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 oc(e,t){let r=Math.max(e.x,t.x),a=Math.min(e.x+e.width,t.x+t.width),n=Math.max(e.y,t.y);return Math.max(0,a-r)*Math.max(0,Math.min(e.y+e.height,t.y+t.height)-n)/Math.max(1,Math.min(os(e),os(t)))}function of(e,t){let r=[e.label,t7(e),e.identifier,e.value].filter(e=>!!e);return r.some(e=>e===t)?0:r.some(e=>rd(e)===rd(t))?1:r.some(e=>ot(e,t))?2:3}async function om(e){let t=oD(e.positionals,{command:"assertVisible",defaultTimeoutMs:17e3});if(!t.ok)return t.response;let r=oN(e.baseReq,t.selector);return r?await oh(e,t,r):await ow(e,t)}async function oh(e,t,r){let a=Date.now(),n=await og(e,t,r);if(n.ok){var i;if(i=e.baseReq,i.flags?.platform==="android"){let r=await ox(e,t.selector,"assertVisible");if(!r.visible){let n=ok(e.baseReq,t,r,a);return"return"===n.kind?n.response:await ow(e,t)}}return i3(e.scope,t.selector),oP({ok:!0,data:{selector:t.selector,nativeWait:!0,query:r,response:n.data}},t.selector,a)}return await oy(e,t,n,a)}async function og(e,t,r){return await e.invoke({...e.baseReq,command:"wait",positionals:[r,String(t.timeoutMs)]})}async function ow(e,t){let r,a,n=Date.now(),i=t.timeoutMs+1e3,o=!1;for(;;){let s=Date.now(),l=await ox(e,t.selector,"assertVisible");if(l.visible)return oP(l.response,t.selector,n);r=l.response,a=l.snapshot??a;let u=ok(e.baseReq,t,l,n);if("return"===u.kind)return u.response;let d=function(e){var t,r,a,n;return Date.now()-e.startedAt<e.deadlineMs?"wait":(t=e.capturedAfterDeadline,r=e.captureStartedAt,a=e.startedAt,n=e.deadlineMs,!t&&r-a<n)?"capture-again":"finish"}({captureStartedAt:s,capturedAfterDeadline:o,startedAt:n,deadlineMs:i});if("capture-again"===d){o=!0;continue}if("finish"===d)break;await rf(250)}let s=r??iQ("COMMAND_FAILED",`Expected visible but did not match: ${t.selector}`,{selector:t.selector,timeoutMs:t.timeoutMs}),l=await ov(e,t,a);return l||oL(s,a,e.baseReq)}async function oy(e,t,r,a){let n=await ox(e,t.selector,"assertVisible");if(n.visible)return oP(n.response,t.selector,a);let i=ok(e.baseReq,t,n,a);if("return"===i.kind)return i.response;let o=await ov(e,t,n.snapshot);return o||oL(r,n.snapshot,e.baseReq)}async function ov(e,t,r){if(e.baseReq.flags?.platform!=="android")return null;let a=function(e){if(!e)return;let t=iZ.get(e);return iZ.delete(e),t}(e.scope);return a?"tap"===a.kind?await oA(e,t,r,a):await oS(e,t,a):null}async function oA(e,t,r,a){if(!r)return null;let n=function(e,t,r){var a;let n,i=i7(e.baseReq.flags),o=j(t),s=i4(t,r.selector,r.options??{},i,o,{promoteTapTarget:!0});if(s.ok)return{ok:!0,target:{kind:"point",point:e1(s.rect)}};let l=i9(r.selector);return l&&(a=t,(n=l.trim().toLowerCase())&&a.nodes.some(e=>[e.label,e.value,e.identifier].some(e=>e?.trim().toLowerCase().includes(n))))?{ok:!0,target:{kind:"text",query:l}}:{ok:!1}}(e,r,a);return n.ok&&(tb({level:"info",phase:"maestro_assert_visible_retry_tap",data:{selector:t.selector,tapSelector:a.selector,originalPoint:a.point,retryTarget:n.target,timeoutMs:5e3}}),(await ob(e,n.target)).ok)?await o_(e,t,"retryTap"):null}async function oS(e,t,r){return(tb({level:"info",phase:"maestro_assert_visible_retry_swipe",data:{selector:t.selector,swipePositionals:r.positionals,timeoutMs:5e3}}),(await oI(e,r)).ok)?await o_(e,t,"retrySwipe"):null}async function o_(e,t,r){let a={...t,timeoutMs:Math.min(t.timeoutMs,5e3)},n=oN(e.baseReq,a.selector);if(!n)return await ow(e,a);let i=Date.now(),o=await og(e,a,n);return o.ok?(i3(e.scope,a.selector),oP({ok:!0,data:{selector:a.selector,nativeWait:!0,[r]:!0,query:n,response:o.data}},a.selector,i)):await oy(e,a,o,i)}async function ob(e,t){return"text"===t.kind?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 oI(e,t){return await e.invoke({...e.baseReq,command:"swipe",positionals:t.positionals})}function ok(e,t,r,a){var n,i,o,s,l,u,d;return!(n=r.response).ok&&"COMMAND_FAILED"===n.error.code&&n.error.message.includes("React Native overlay")?{kind:"return",response:r.response}:(i=e,o=t.selector,s=r.snapshot,i.flags?.maestro?.allowAlreadyPastLoading===!0&&void 0!==s&&function(e,t){let r=oR(i9(e));if(!oM(r))return!1;let a=t.nodes.flatMap(e=>[e.label,e.value,e.identifier]).filter(e=>!!e?.trim()).map(e=>oR(e));return!a.some(e=>e.includes("something went wrong"))&&a.some(e=>e!==r&&!oM(e))}(o,s))?{kind:"return",response:(l=t.selector,u=t.timeoutMs,d=a,{ok:!0,data:{selector:l,alreadyPastLoading:!0,waitedMs:Date.now()-d,timeoutMs:u}})}:{kind:"continue"}}function oN(e,t){return e.flags?.platform!=="ios"&&e.flags?.platform!=="android"?null:i9(t)}function oD(e,t){let[r,a=String(t.defaultTimeoutMs)]=e;if(!r)return{ok:!1,response:iQ("INVALID_ARGS",`${t.command} requires a selector.`)};let n=Number(a);return!Number.isFinite(n)||n<0?{ok:!1,response:iQ("INVALID_ARGS",`${t.command} timeout must be a non-negative number.`)}:{ok:!0,selector:r,timeoutMs:n}}async function ox(e,t,r){let a=await i0(e);var n=e,i=t,o=r,s=a;if(!s.ok)return{visible:!1,response:s,infrastructureFailure:!0};let l=i1(s.data);if(!l)return{visible:!1,response:iQ("COMMAND_FAILED",`Unable to read snapshot data for ${o}.`),infrastructureFailure:!0};let u=i6(l,i,i7(n.baseReq.flags),j(l));return u.ok?(i3(n.scope,i),{visible:!0,response:{ok:!0,data:{selector:i,matches:u.matches,nodeIndex:u.node.index,nodeType:u.node.type,nodeLabel:u.node.label,nodeIdentifier:u.node.identifier,rect:u.rect}}}):{visible:!1,response:iQ("COMMAND_FAILED",u.message,{selector:i}),infrastructureFailure:!1,snapshot:l}}function oR(e){return e?.trim().toLowerCase().replace(/\u2026/g,"...")??""}function oM(e){return"loading"===e||"loading..."===e}function oP(e,t,r){return e.ok?{ok:!0,data:{selector:t,...e.data,waitedMs:Date.now()-r}}:e}function oL(e,a,n){var i;if(e.ok||!a)return e;let o="string"==typeof n.flags?.artifactsDir?n.flags.artifactsDir:void 0;if(!o)return e;let s=function(e,a){try{t.mkdirSync(a,{recursive:!0});let n=r.join(a,"failure-snapshot.json"),i=r.join(a,"failure-snapshot.txt");t.writeFileSync(n,`${JSON.stringify(e,null,2)}
29
+ `);let o=eZ(e.nodes,{summarizeTextSurfaces:!0}).map(e=>e.text);return t.writeFileSync(i,`${o.join("\n")}
30
+ `),[n,i]}catch{return[]}}(a,o);return 0===s.length?e:{ok:!1,error:{...e.error,details:{...e.error.details??{},artifactPaths:[...new Set([...Array.isArray(i=e.error.details?.artifactPaths)?i.filter(e=>"string"==typeof e):[],...s])]}}}}async function oO(e){let t,r=oD(e.positionals,{command:"assertNotVisible",defaultTimeoutMs:3e3});if(!r.ok)return r.response;let a=Date.now(),n=0;for(;Date.now()-a<=r.timeoutMs;){let i=await ox(e,r.selector,"assertNotVisible");if(!i.visible&&i.infrastructureFailure)return i.response;if(i.visible)n=0,t=i.response;else{n+=1;let e=Date.now()-a;if(n>=2||e>=r.timeoutMs)return{ok:!0,data:{pass:!0,selector:r.selector,stableSamples:n,waitedMs:e,timeoutMs:r.timeoutMs}}}await rf(250)}return n>0?{ok:!0,data:{pass:!0,selector:r.selector,stableSamples:n,waitedMs:Date.now()-a,timeoutMs:r.timeoutMs}}:iQ("COMMAND_FAILED",`Expected not visible but matched: ${r.selector}`,{selector:r.selector,timeoutMs:r.timeoutMs,lastResponse:t})}async function oC(e){let t,r,a=Number(e.positionals[0]??15e3);if(!Number.isFinite(a)||a<0)return iQ("INVALID_ARGS","waitForAnimationToEnd timeout must be a number.");let n=Date.now();for(;Date.now()-n<a;){let n=await i0(e),i=function(e,t,r){let a=function(e){if(!e.ok)return null;let t=i1(e.data);return t?JSON.stringify(t.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}))):null}(e);return e.ok?a?t===a?{done:!0,response:{ok:!0,data:{stable:!0,timeoutMs:r}}}:{done:!1,signature:a}:{done:!0,response:e}:{done:!1}}(n,t,a);if(i.done)return i.response;t=i.signature??t,r=n,await rf(250)}return r?.ok===!1?r:{ok:!0,data:{stable:!1,timeoutMs:a}}}async function oE(e){var t,r,a;let[n,i="5000",o="down"]=e.positionals;if(!n)return iQ("INVALID_ARGS","scrollUntilVisible requires a selector.");let s=Number(i);if(!Number.isFinite(s)||s<=0)return iQ("INVALID_ARGS","scrollUntilVisible timeout must be a positive number.");let l=i9(n),u=Math.max(1,Math.ceil(s/500)),d=null;for(let t=0;t<u;t+=1){let r=await oj(e,n,l,Math.min(500,Math.max(1,s-500*t)));if(r.ok)return r;if(d=r,t===u-1)break;let a=await e.invoke({...e.baseReq,command:"scroll",positionals:[o]});if(!a.ok)return a}return t=d,r=n,a=s,t?{ok:!1,error:{...t.error,message:`scrollUntilVisible timed out after ${a}ms for selector: ${r}. Last wait: ${t.error.message}`}}:iQ("COMMAND_FAILED",`scrollUntilVisible timed out after ${a}ms for selector: ${r}`)}async function o$(e){let[t,r]=e.positionals,a=Number(t),n=Number(r);if(!Number.isFinite(a)||!Number.isFinite(n))return iQ("INVALID_ARGS","tapOn percentage point requires numeric x/y values.");let i=await i0(e);if(!i.ok)return i;let o=i1(i.data);if(!o)return iQ("COMMAND_FAILED","Unable to read snapshot data for Maestro percentage point tap.");let s=j(o);if(!s)return iQ("COMMAND_FAILED","Unable to resolve screen size for Maestro percentage point tap.");let l=eW(s,a,n),u=await e.invoke({...e.baseReq,command:"click",positionals:[String(l.x),String(l.y)],flags:{...e.baseReq.flags,postGestureStabilization:!0}});return u.ok&&i2(e.scope),u}async function oV(e){let t=await oU(e);if(t)return t;let r=await oG(e);return r.ok?await oT(e,r,r.durationMs):r.response}async function oU(e){let[t,r,a]=e.positionals;if("direction"===t&&("left"===r||"right"===r)&&"android"!==i7(e.baseReq.flags))return await e.invoke({...e.baseReq,command:"gesture",positionals:["swipe",r,...a?[a]:[]]})}async function oF(e){var t,r,a,n;let i,[o,s]=e.positionals;if(!o)return iQ("INVALID_ARGS","tapOn requires a selector.");let l=function(e){if(!e)return{ok:!0,value:null};try{let t=JSON.parse(e);return{ok:!0,value:t}}catch{return{ok:!1,response:iQ("INVALID_ARGS","tapOn runtime options must be valid JSON.")}}}(s);if(!l.ok)return l.response;let u=Date.now(),d=(t=e,t.baseReq.flags?.maestro?.optional===!0?3e3:3e4);for(;Date.now()-u<d;){let t=await oz(e,o,l.value??{});if(!t.retry)return t.response;i=t.response,await rf(250)}return r=e,a=o,n=i,r.baseReq.flags?.maestro?.optional===!0?{ok:!0,data:{skipped:!0,optional:!0,selector:a}}:n??iQ("COMMAND_FAILED",`tapOn timed out for selector: ${a}`)}async function oq(e){let[t,r="up",a]=e.positionals;if(!t)return iQ("INVALID_ARGS","swipe.label requires a label selector.");let n=await oY(e,t,{},"swipe.label",{promoteTapTarget:!1});if(!n.ok)return n.response;let i=function(e,t){let r=e1(e.rect),a=e.frame,n=iJ(a?.referenceWidth,e.rect.width),i=iJ(a?.referenceHeight,e.rect.height),o=iW,s=a?a.referenceWidth-o:r.x+n,l=a?a.referenceHeight-o:r.y+i;switch(t.toLowerCase()){case"up":return{ok:!0,start:r,end:{x:r.x,y:te(r.y-i,o,l)}};case"down":return{ok:!0,start:r,end:{x:r.x,y:te(r.y+i,o,l)}};case"left":return{ok:!0,start:r,end:{x:te(r.x-n,o,s),y:r.y}};case"right":return{ok:!0,start:r,end:{x:te(r.x+n,o,s),y:r.y}};default:return{ok:!1,message:"swipe.label direction must be up, down, left, or right."}}}(n.target,r);return i.ok?await oT(e,i,a):iQ("INVALID_ARGS",i.message)}async function oT(e,t,r){var a,n;let i=[String(t.start.x),String(t.start.y),String(t.end.x),String(t.end.y),...r?[r]:[]],o=await e.invoke({...e.baseReq,command:"swipe",positionals:i});return o.ok&&(a=e.scope,n={kind:"swipe",positionals:i},a&&iZ.set(a,n)),o}async function oG(e){var t;let r=((t=e.scope)?iX.get(t):void 0)??await oK(e);if(!r)return{ok:!1,response:iQ("COMMAND_FAILED","Unable to resolve screen size for Maestro swipe.")};let[a,...n]=e.positionals;return"direction"===a?function(e,t,r){let[a,n]=e;if(!a)return{ok:!1,response:iQ("INVALID_ARGS","Maestro direction swipe requires a direction.")};switch(a){case"up":case"down":var i,o,s;let l;return i=a,o=t,s=n,{ok:!0,start:e2({x:(l=eX({direction:i,amount:.6,referenceWidth:o.referenceWidth,referenceHeight:o.referenceHeight})).x1,y:l.y1},o,8),end:e2({x:l.x2,y:l.y2},o,8),durationMs:s};case"left":case"right":return function(e,t,r,a){let n=oH(r,85,50,15,50),[i,o]="left"===e?[85,15]:[15,85],s=oB(r,t,i,50,o,50);return{ok:!0,start:eW(t,i,n.startY,{marginPx:s}),end:eW(t,o,n.endY,{marginPx:s}),durationMs:a}}(a,t,r,n);default:return{ok:!1,response:iQ("INVALID_ARGS","Maestro swipe direction must be UP, DOWN, LEFT, or RIGHT.")}}}(n,r,i7(e.baseReq.flags)):"percent"===a?function(e,t,r){let[a,n,i,o,s]=e,l=[a,n,i,o].map(Number);if(l.some(e=>!Number.isFinite(e)))return{ok:!1,response:iQ("INVALID_ARGS","Maestro percentage swipe requires numeric points.")};let[u,d,p,c]=l,f=oH(r,u,d,p,c),m=oB(r,t,u,d,p,c);return{ok:!0,start:eW(t,u,f.startY,{marginPx:m}),end:eW(t,p,f.endY,{marginPx:m}),durationMs:s}}(n,r,i7(e.baseReq.flags)):{ok:!1,response:iQ("INVALID_ARGS","Maestro screen swipe requires direction or percent.")}}async function oK(e){let t=await i0(e);if(t.ok)return j(i1(t.data))}function oB(e,t,r,a,n,i){return"ios"!==e||a!==i||30>Math.abs(n-r)?1:Math.max(1,Math.round(.15*t.referenceWidth))}function oH(e,t,r,a,n){return"android"!==e||r!==n||50!==r||30>Math.abs(a-t)?{startY:r,endY:n}:{startY:65,endY:65}}async function oj(e,t,r,a){let n=await e.invoke({...e.baseReq,command:"wait",positionals:[t,String(a)]});return n.ok||!r?n:await e.invoke({...e.baseReq,command:"find",positionals:[r,"wait",String(a)]})}async function oz(e,t,r){let a=i9(t),n=await oW(e,t,r);return n.response.ok?{retry:!1,response:n.response}:n.targetResolved&&a?await oX(e,a):{retry:!0,response:n.response}}async function oW(e,t,r){let a=await oY(e,t,r,"tapOn",{promoteTapTarget:!0});return a.ok?await oJ(e,t,a.target,r):{response:a.response,targetResolved:!1}}async function oJ(e,t,r,a){let n=e1(r.rect);tb({level:"debug",phase:"maestro_tap_target",data:{selector:t,node:{index:r.node.index,type:r.node.type,label:r.node.label,value:r.node.value,identifier:r.node.identifier,visibleToUser:r.node.visibleToUser},rect:r.rect,point:n}});let i=await e.invoke({...e.baseReq,command:"click",positionals:[String(n.x),String(n.y)],flags:{...e.baseReq.flags,postGestureStabilization:!0}});if(i.ok){var o,s,l;(o=e.scope)&&iY.delete(o),s=e.scope,l={kind:"tap",selector:t,point:n,options:{...a}},s&&iZ.set(s,l)}return{response:i,targetResolved:!0}}async function oX(e,t){let r=await e.invoke({...e.baseReq,command:"find",positionals:[t,"click"],flags:{...e.baseReq.flags,findFirst:!0,postGestureStabilization:!0}});return(tb({level:r.ok?"info":"debug",phase:"maestro_fuzzy_tap_fallback",data:{query:t,ok:r.ok}}),r.ok)?(i2(e.scope),{retry:!1,response:r}):{retry:!0,response:r}}async function oY(e,t,r,a,n){let i=await i0({...e,raw:!0});return function(e,t,r,a,n,i){if(!i.ok)return{ok:!1,response:i};let o=i1(i.data);if(!o)return{ok:!1,response:iQ("COMMAND_FAILED",`Unable to read snapshot data for ${a}.`)};let s=j(o),l=i7(e.baseReq.flags),u=function(e,t,r,a){var n;let i=(n=e.scope)?iY.get(n):void 0;if(!i)return;let o=i6(t,i.selector,r,a);if(o.ok)return tb({level:"debug",phase:"maestro_preferred_context",data:{selector:i.selector,node:{index:o.node.index,type:o.node.type,label:o.node.label,value:o.node.value,identifier:o.node.identifier},rect:o.rect}}),{node:o.node,rect:o.rect}}(e,o,l,s),d=i4(o,t,r,l,s,{...n,preferredContext:u,requireOnScreen:!0});if(!d.ok){let e=i9(t);if(e){let t=function(e,t,r,a,n={}){let i=function(e,t){let r=rd(t);if(!r)return[];let a=[],n=[];for(let t of e.nodes){let e=[t.label,t7(t),t.identifier,t.value].filter(e=>!!e).map(e=>rd(e));e.some(e=>e===r)?a.push(t):e.some(e=>e.includes(r))&&n.push(t)}return a.length>0?a:n}(e,t),o=i8({nodes:e.nodes,matches:i,platform:r}),s=oa(e.nodes,o.matches,void 0,t,a,!0===n.requireOnScreen,n.promoteTapTarget,n.preferredContext);return s?{ok:!0,node:s.node,rect:s.rect}:{ok:!1,message:`Maestro fuzzy text did not match: ${t}`}}(o,e,l,s,{...n,preferredContext:u,requireOnScreen:!0});if(t.ok)return{ok:!0,target:{node:t.node,rect:t.rect,frame:s}}}}return d.ok?{ok:!0,target:{node:d.node,rect:d.rect,frame:s}}:{ok:!1,response:iQ("ELEMENT_NOT_FOUND",d.message,{selector:t,options:r,command:a})}}(e,t,r,a,n,i)}async function oZ(e){switch(e.command){case nC:return await om(e);case nE:return await oO(e);case n$:return await oQ(e);case nV:return await oC(e);case nU:return await oE(e);case nF:return await oV(e);case nq:return await oq(e);case nT:return await oF(e);case nG:return await o$(e);case nO:return function(e){let[r]=e.positionals;if(!r)return iQ("INVALID_ARGS","runScript requires a file path.");try{let n=function(e){let{scriptPath:r,env:n}=e,i=t.readFileSync(r,"utf8"),o=Object.create(null);try{var l,u;a.runInNewContext(i,(l=n,u=o,{...l,output:u,json:n5,http:{post:(e,t)=>(function(e,t,r){let a=t2(process.execPath,["-e",n2],{stdin:JSON.stringify({method:e,url:t,headers:r?.headers??{},body:r?.body??""}),timeoutMs:3e4,allowFailure:!0});if(0!==a.exitCode){let r;throw new s("COMMAND_FAILED",`Maestro runScript http.${e.toLowerCase()} failed for ${t}: ${(r=a.stderr.trim()).length>0?r.slice(0,1e3):"request process exited without stderr"}`,{exitCode:a.exitCode,stderr:a.stderr})}try{return JSON.parse(a.stdout)}catch(r){throw new s("COMMAND_FAILED",`Maestro runScript http.${e.toLowerCase()} returned invalid JSON for ${t}`,{stdout:a.stdout.slice(0,1e3),stderr:a.stderr.slice(0,1e3)},r instanceof Error?r:void 0)}})("POST",e,t)}}),{filename:r,timeout:3e4})}catch(e){throw new s("COMMAND_FAILED",`Maestro runScript failed for ${r}: ${e instanceof Error?e.message:String(e)}`,{scriptPath:r},e instanceof Error?e:void 0)}return function(e,t){for(let r of Object.keys(e))if(r.includes("."))throw new s("INVALID_ARGS",`Maestro runScript output key cannot contain ".": ${r}`,{scriptPath:t,key:r})}(o,r),Object.fromEntries(Object.entries(o).map(([e,t])=>{var r;return[`output.${e}`,(r=t,"string"==typeof r?r:"number"==typeof r||"boolean"==typeof r?String(r):JSON.stringify(r))]}))}({scriptPath:r,env:{...e.scope.values,...e.baseReq.flags?.maestro?.runScriptEnv??{}}});return{ok:!0,data:{outputEnv:n}}}catch(t){let e=i(t);return iQ(e.code,e.message,e.details)}}(e);default:return}}async function oQ(e){let t=await e.invoke({...e.baseReq,command:"keyboard",positionals:["enter"]});return t.ok?t:await e.invoke({...e.baseReq,command:"type",positionals:["\n"]})}async function o0(e){for(let[t,r]of e.actions.entries()){let a=await e.invokeReplayAction({action:r,line:e.line,step:e.step+t/1e3});if(!a.ok)return a}return{ok:!0,data:{ran:e.actions.length}}}async function o1(e){let t;for(let r=0;r<=e.maxRetries;r+=1){let a=await o0({actions:e.actions,line:e.line,step:e.step+r,invokeReplayAction:e.invokeReplayAction});if(a.ok)return{ok:!0,data:{attempts:r+1,retried:r>0}};t=a}return t??{ok:!1,error:{code:"COMMAND_FAILED",message:"retry commands failed."}}}async function o3(e){let t=await o2(e,e.control);return t.ok?t.matched?await o6(e):{ok:!0,data:{skipped:!0,condition:e.control.mode,selector:e.control.selector}}:t.response}async function o2(e,t){if("visible"===t.mode)return await o5(e,t);let r=await o4(e,t.selector);return r.ok?{ok:!0,matched:!r.matched}:{ok:!1,response:r.response}}async function o5(e,t){let r=Date.now();for(;;){let a=await o4(e,t.selector);if(!a.ok)return{ok:!1,response:a.response};if(a.matched)return{ok:!0,matched:!0};if(Date.now()-r>=3e3)return{ok:!0,matched:!1};await rf(250)}}async function o4(e,t){var r,a;let n,i=await i0(e);return i.ok?(r=e,a=t,(n=i1(i.data))?{ok:!0,matched:i6(n,a,i7(r.baseReq.flags),j(n)).ok}:{ok:!1,response:iQ("COMMAND_FAILED","Unable to read snapshot data for runFlow.when.")}):{ok:!1,response:i}}async function o6(e){let t=await o0({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 o8(e){let{req:t,sessionName:r,action:a,scope:n,filePath:i,line:o,step:s,tracePath:l,invoke:u}=e,d=t1(a,n,{file:i,line:o}),p=Date.now();se(l,{type:"replay_action_start",ts:new Date(p).toISOString(),replayPath:i,line:o,step:s,command:d.command,positionals:d.positionals??[]});let c=await o7({req:t,sessionName:r,resolved:d,scope:n,line:o,step:s,invoke:u,invokeReplayAction:e=>o8({req:t,sessionName:r,action:e.action,scope:n,filePath:i,line:e.line,step:e.step,tracePath:l,invoke:u})}),f=Date.now();return se(l,{type:"replay_action_stop",ts:new Date(f).toISOString(),replayPath:i,line:o,step:s,command:d.command,ok:c.ok,durationMs:f-p,resultTiming:c.ok?function(e){if(!e||"object"!=typeof e||Array.isArray(e))return;let t=e.timing;if(!(!t||"object"!=typeof t||Array.isArray(t)))return Object.fromEntries(Object.entries(t).filter(([,e])=>{let t=typeof e;return"number"===t||"string"===t||"boolean"===t}))}(c.data):void 0,errorCode:c.ok?void 0:c.error.code}),c}async function o7(e){var t;let{req:r,sessionName:a,resolved:n,scope:i,line:o,step:s,invoke:l,invokeReplayAction:u}=e,d=(t=r.flags,tD(t,{...n.flags??{}})),p={token:r.token,session:a,flags:d,runtime:n.runtime,meta:r.meta,internal:r.internal},c=await o9({control:n.replayControl,baseReq:p,line:o,step:s,invoke:l,invokeReplayAction:u})??await oZ({command:n.command,baseReq:p,positionals:n.positionals??[],scope:i,line:o,step:s,invoke:l,invokeReplayAction:u})??await l({...p,command:n.command,positionals:n.positionals??[]});if(c.ok){let e=function(e){if(!e||"object"!=typeof e)return null;let t=e.outputEnv;if(!t||"object"!=typeof t||Array.isArray(t))return null;let r=Object.entries(t).filter(e=>"string"==typeof e[1]);return r.length>0?Object.fromEntries(r):null}(c.data);e&&t3(i,e)}return c}async function o9(e){let{control:t,baseReq:r,line:a,step:n,invoke:i,invokeReplayAction:o}=e;if(t){switch(t.kind){case"retry":return await o1({actions:t.actions,maxRetries:t.maxRetries,line:a,step:n,invokeReplayAction:o});case"maestroRunFlowWhen":return await o3({baseReq:r,control:t,line:a,step:n,invoke:i,invokeReplayAction:o})}return t}}function se(e,r){e&&t.appendFileSync(e,`${JSON.stringify(r)}
31
+ `)}async function st(e){let{req:a,sessionName:n,logPath:o,sessionStore:l,tracePath:u,invoke:d}=e,p=a.positionals?.[0];if(!p)return L("INVALID_ARGS","replay requires a path");let c="",f=new Set;try{var m,h,g,w,y,v,A,S,_,b,I,k,N,D,x,R,M,P,C,E;c=ep.expandHome(p,a.meta?.cwd);let e=t.readFileSync(c,"utf8"),i=e.trimStart()[0];if("{"===i||"["===i)return L("INVALID_ARGS","replay accepts .ad script files. JSON replay payloads are no longer supported.");let $=function(e,t,r={}){var a;let n=function(e){let t=e?.replayBackend;if("string"!=typeof t)return;let r=iq[t];if(!r)throw new s("INVALID_ARGS",`Unsupported replay backend "${t}".`);return r}(t);return n?{...n.parse(e,{...r,platform:t?.platform,env:(a=t,{...tK(tE(a?.replayShellEnv)),...tG(tU(a?.replayEnv))})}),updateUnsupportedMessage:"replay -u is not supported for compat flow input. Convert to .ad first, then update that replay file."}:{...tC(e),metadata:tT(e)}}(e,a.flags,{sourcePath:c}),V=$.metadata,U=V.platform||V.target?{...a,flags:(m=a.flags,h=V,{...m??{},...void 0!==h.platform&&m?.platform===void 0?{platform:h.platform}:{},...void 0!==h.target&&m?.target===void 0?{target:h.target}:{}})}:a,F=$.actions,q=$.actionLines;if(a.flags?.replayUpdate===!0&&$.updateUnsupportedMessage)return L("INVALID_ARGS",$.updateUnsupportedMessage);if(a.flags?.replayUpdate===!0&&V.env&&Object.keys(V.env).length>0)return L("INVALID_ARGS","replay -u does not yet preserve env directives. Temporarily remove the env lines, run replay -u, then restore them.");if(a.flags?.replayUpdate===!0&&function(e){for(let t of e){for(let e of t.positionals??[])if("string"==typeof e&&e.includes("${"))return!0;if(ss(t.flags)||ss(t.runtime))return!0}return!1}(F))return L("INVALID_ARGS","replay -u does not yet preserve ${VAR} substitutions. Resolve or inline the variables before running with -u.");let T=t0({builtins:function(e){let{req:t,sessionName:a,metadata:n,resolvedPath:i}=e,o=t.flags??{},s=t.meta?.cwd??process.cwd(),l={AD_SESSION:a,AD_FILENAME:r.relative(s,i)||i},u=o.platform??n.platform;u&&(l.AD_PLATFORM=u);let d=o.target??n.target;d&&(l.AD_TARGET=d);let p=o.device;"string"==typeof p&&p.length>0&&(l.AD_DEVICE=p);let c="string"==typeof o.serial?o.serial:o.udid;"string"==typeof c&&c.length>0&&(l.AD_DEVICE_ID=c),"number"==typeof o.shardIndex&&(l.AD_SHARD_INDEX=String(o.shardIndex)),"number"==typeof o.shardCount&&(l.AD_SHARD_COUNT=String(o.shardCount));let f=o.artifactsDir;return"string"==typeof f&&f.length>0&&(l.AD_ARTIFACTS=f),l}({req:U,sessionName:n,metadata:V,resolvedPath:c}),fileEnv:V.env,shellEnv:tK(tE(a.flags?.replayShellEnv)),cliEnv:tG(tU(a.flags?.replayEnv))}),G=a.flags?.replayUpdate===!0,K=u??l.get(n)?.trace?.outPath,B=[],H=0;for(let e=0;e<F.length;e+=1){let t=F[e];if(!t||"replay"===t.command)continue;!function(e,t,r){let a=O();a&&eB({type:"replay-test",...a,file:a.file||e,status:"progress",stepIndex:t+1,stepTotal:r})}(c,e,F.length);let r=sn(l,n),a=await o8({req:U,sessionName:n,action:t,scope:T,filePath:c,line:q[e]??0,step:e+1,tracePath:K,invoke:d});if(B.push(...si(l,n,r)),a.ok){sa(a).forEach(e=>f.add(e));continue}if(sa(a).forEach(e=>f.add(e)),!G){return g=a,w=t,y=e,v=c,A=[...f],S=B,sr(g,w,y,v,A,t4(S))}let i=await iG({action:t,sessionName:n,logPath:o,sessionStore:l});if(!i){return _=a,b=t,I=e,k=c,N=[...f],D=B,sr(_,b,I,k,N,t4(D))}F[e]=i;let s=sn(l,n);if(a=await o8({req:U,sessionName:n,action:i,scope:T,filePath:c,line:q[e]??0,step:e+1,tracePath:K,invoke:d}),B.push(...si(l,n,s)),!a.ok){return sa(a).forEach(e=>f.add(e)),x=a,R=i,M=e,P=c,C=[...f],E=B,sr(x,R,M,P,C,t4(E))}sa(a).forEach(e=>f.add(e)),H+=1}G&&H>0&&tQ(c,F,l.get(n));let j=t4(B);return{ok:!0,data:{replayed:F.length,healed:H,session:n,artifactPaths:[...f],...j?{snapshotDiagnostics:j}:{}}}}catch(t){let e=i(t);return L(e.code,e.message,f.size>0?{artifactPaths:[...f]}:void 0)}}function sr(e,t,r,a,n=[],i){if(e.ok)return e;let o=r+1;return{ok:!1,error:{code:e.error.code,message:`Replay failed at step ${o} (${ro(t)}): ${e.error.message}`,hint:e.error.hint,diagnosticId:e.error.diagnosticId,logPath:e.error.logPath,details:{...e.error.details??{},replayPath:a,step:o,action:t.command,positionals:t.positionals??[],artifactPaths:n,...i?{snapshotDiagnostics:i}:{}}}}}function sa(e){if(!e.ok){let t=e.error.details?.artifactPaths;return Array.isArray(t)?[...new Set(t.filter(e=>"string"==typeof e&&so(e)))]:[]}if(!e.data)return[];let t=[];if("string"==typeof e.data.path&&t.push(e.data.path),"string"==typeof e.data.outPath&&t.push(e.data.outPath),Array.isArray(e.data.artifacts))for(let r of e.data.artifacts){if(!r||"object"!=typeof r)continue;let e="string"==typeof r.localPath?r.localPath:void 0,a="string"==typeof r.path?r.path:void 0;e?t.push(e):a&&t.push(a)}return[...new Set(t.filter(e=>so(e)))]}function sn(e,t){return e.get(t)?.snapshotDiagnostics?.samples.length??0}function si(e,t,r){return e.get(t)?.snapshotDiagnostics?.samples.slice(r)??[]}function so(e){try{return t.statSync(e).isFile()}catch{return!1}}function ss(e){return"string"==typeof e?e.includes("${"):Array.isArray(e)?e.some(ss):!!e&&"object"==typeof e&&Object.values(e).some(ss)}async function sl(e){let{req:t,sessionName:a,logPath:n,sessionStore:i,artifactsDir:o,tracePath:s}=e;if(t.flags?.recordVideo!==!0)return;let l=i.get(a);if(!l||l.recording)return;let u=rh(l.device.platform),d=o?r.join(o,`recording${u}`):rg(l.device.platform);sd(s,{type:"video_recording_start",session:a,videoPath:d}),tb({phase:"replay_test_video_recording_start",data:{session:a,videoPath:d}});let p=await rm({req:{token:t.token,session:a,command:"record",positionals:["start",d],flags:{},meta:t.meta},sessionName:a,sessionStore:i,logPath:n});if(!p.ok)return sd(s,{type:"video_recording_start_failed",session:a,videoPath:d,errorCode:p.error.code}),p;let c=Date.now();return await rf(1e3),sd(s,{type:"video_preroll_done",session:a,durationMs:Date.now()-c,requestedDurationMs:1e3}),tb({phase:"replay_test_video_recording_preroll_done",durationMs:Date.now()-c,data:{session:a,requestedDurationMs:1e3}}),p}async function su(e){let{req:t,sessionName:r,logPath:a,sessionStore:n,tracePath:i,artifactPaths:o}=e;if(t.flags?.recordVideo!==!0||!n.get(r)?.recording)return;sd(i,{type:"video_tail_start",session:r,requestedDurationMs:3e3});let s=Date.now();await rf(3e3);let l=Date.now(),u=await rm({req:{token:t.token,session:r,command:"record",positionals:["stop"],flags:{},meta:t.meta},sessionName:r,sessionStore:n,logPath:a});return sa(u).forEach(e=>o.add(e)),sd(i,{type:"video_recording_stop",session:r,ok:u.ok,durationMs:Date.now()-l,tailDurationMs:l-s,errorCode:u.ok?void 0:u.error.code}),tb({phase:"replay_test_video_recording_stop",durationMs:Date.now()-l,data:{session:r,ok:u.ok,tailDurationMs:l-s}}),u}function sd(e,t){iA(e,{...t,ts:new Date().toISOString()})}async function sp(e){let{req:t,sessionName:r,logPath:a,sessionStore:n,leaseRegistry:i,invoke:o}=e;return"replay"===t.command?await st({req:t,sessionName:r,logPath:a,sessionStore:n,invoke:o}):"test"===t.command?await iL({req:t,sessionName:r,runReplay:async({filePath:e,sessionName:r,platform:i,target:s,requestId:l,artifactsDir:u,artifactPaths:d,tracePath:p,shard:c})=>{let f=function(e){let{platform:t,target:r,artifactsDir:a,shard:n}=e,i=function(e){if(e?.recordVideo!==!0)return e;let t={...e};return delete t.recordVideo,Object.keys(t).length>0?t:void 0}(e.parentFlags);if(void 0===t&&void 0===r&&void 0===a&&void 0===n)return i;var o={...i??{},...void 0!==t?{platform:t}:{},...void 0!==r?{target:r}:{},...void 0!==a?{artifactsDir:a}:{}};if(!n)return o;let s={...o??{},device:void 0,udid:void 0,serial:void 0,platform:n.device.platform,target:n.device.target,shardAll:void 0,shardSplit:void 0,shardCount:n.shardCount,shardIndex:n.shardIndex};return"android"===n.device.platform?{...s,serial:n.device.id}:{...s,udid:n.device.id}}({parentFlags:t.flags,platform:i,target:s,artifactsDir:u,shard:c}),m={req:t,sessionName:r,logPath:a,sessionStore:n,artifactsDir:u,tracePath:p},h=function(e){if(e.req.flags?.recordVideo===!0)return{beforeDispatch:async()=>await sl(e)}}(m);return await st({req:{...t,command:"replay",session:r,positionals:[e],flags:f,meta:{...t.meta??{},...l?{requestId:l}:{}},...t.internal||h?{internal:{...t.internal??{},...h?{openLifecycle:h}:{}}}:{}},sessionName:r,logPath:a,sessionStore:n,tracePath:p,invoke:async e=>{var t;let r=await sl(m);return r&&!r.ok?r:(t=await o(e),d&&sa(t).forEach(e=>d.add(e)),t)}})},finalizeAttempt:async({sessionName:e,artifactPaths:r,artifactsDir:i,tracePath:o})=>await su({req:t,sessionName:e,logPath:a,sessionStore:n,artifactsDir:i,tracePath:o,artifactPaths:r}),cleanupSession:async e=>{n.get(e)&&await ab({req:{token:t.token,session:e,command:"close",positionals:[],flags:{},meta:t.meta},sessionName:e,logPath:a,sessionStore:n,leaseRegistry:i})}}):null}async function sc(e){var t,r,a,n,i,o,s,l;let u,d,{req:p,sessionName:c,logPath:f,sessionStore:m}=e,h=p.positionals?.[0]??"";if("ios-runner"!==h)return L("INVALID_ARGS","prepare requires a subcommand: ios-runner");let g=m.get(c),w=p.flags??{},y=rN(ry.prepare,g,w);if(y)return y;let v=await rx({session:g,flags:w,ensureReady:!0});if(!ty(v.platform))return L("UNSUPPORTED_OPERATION","prepare ios-runner is only supported on Apple runner platforms");let A=Date.now(),S=await Y(v,(t=p,r=g,a=f,d=(n=t,"number"==typeof(u=n.flags?.timeoutMs)&&Number.isFinite(u)&&u>0?u:3e5),{verbose:t.flags?.verbose,logPath:a,traceLogPath:r?.trace?.outPath,cleanStaleBundles:!0,startupTimeoutMs:function(e){if("number"==typeof e&&Number.isFinite(e)&&!(e<=0))return Math.max(45e3,Math.floor(e))}(t.flags?.timeoutMs),requestId:t.meta?.requestId,buildTimeoutMs:d,healthTimeoutMs:Math.min(d,9e4),iosXctestrunFile:t.flags?.iosXctestrunFile,iosXctestDerivedDataPath:t.flags?.iosXctestDerivedDataPath,iosXctestEnvDir:t.flags?.iosXctestEnvDir}));return{ok:!0,data:(i=h,o=v,s=Math.max(0,Date.now()-A),l=S,{action:i,platform:o.platform,deviceId:o.id,deviceName:o.name,kind:o.kind,durationMs:s,...l,message:`Prepared Apple runner: ${o.name}`})}}async function sf(e){let{req:t,sessionName:r,logPath:a,sessionStore:n,command:i,positionals:o,recordPositionals:s,deriveNextSession:l}=e,u=n.get(r),d=t.flags??{},c=rN(i,u,d);if(c)return c;let f=await rx({session:u,flags:d,ensureReady:!0});if(!eV(i,f))return L("UNSUPPORTED_OPERATION",`${i} is not supported on this device`);let m=await p(f,i,o,t.flags?.out,{...eu(a,t.flags,u?.appBundleId,u?.trace?.outPath)});if(u){let e=l?await l(u,m,f):u;n.recordAction(e,{command:i,positionals:s??o,flags:t.flags??{},result:m??{}}),e!==u&&n.set(r,e)}return{ok:!0,data:m??{}}}async function sm(e){let{req:t,sessionName:r,logPath:a,sessionStore:n}=e,i=n.get(r),o=t.flags??{},s=rN(ry.clipboard,i,o);if(s)return s;let l=(t.positionals?.[0]??"").toLowerCase();if("read"!==l&&"write"!==l)return L("INVALID_ARGS","clipboard requires a subcommand: read or write");let u=await rx({session:i,flags:o,ensureReady:!0});if(!eV(ry.clipboard,u))return L("UNSUPPORTED_OPERATION","clipboard is not supported on this device");let d=await p(u,ry.clipboard,t.positionals??[],t.flags?.out,{...eu(a,t.flags,i?.appBundleId,i?.trace?.outPath)});return i&&n.recordAction(i,{command:t.command,positionals:t.positionals??[],flags:t.flags??{},result:d??{}}),{ok:!0,data:{platform:u.platform,...d??{}}}}async function sh(e){let{req:t,sessionName:r,logPath:a,sessionStore:n,leaseRegistry:i=new X,invoke:o,invokeReplayAction:s,androidAdbExecutor:l}=e;if("inventory"===g(t.command))return await aR({req:t,sessionName:r,sessionStore:n});if("runtime"===t.command)return await r4({req:t,sessionName:r,sessionStore:n});if("state"===g(t.command))return await aC({req:t,sessionName:r,sessionStore:n});if(t.command===ry.clipboard)return await sm({req:t,sessionName:r,logPath:a,sessionStore:n});if(t.command===ry.keyboard){let e=n.get(r),i=t.positionals?.[0]?.trim().toLowerCase();return e||"dismiss"!==i&&"enter"!==i&&"return"!==i||"ios"!==tA((t.flags??{}).platform)?await sf({req:t,sessionName:r,logPath:a,sessionStore:n,command:ry.keyboard,positionals:t.positionals??[]}):L("SESSION_NOT_FOUND","iOS keyboard action requires an active session so the target app stays foregrounded. Run open first.")}if("observability"===g(t.command))return await nw({req:t,sessionName:r,sessionStore:n,androidAdbExecutor:l});if(t.command===ry.prepare)return await sc({req:t,sessionName:r,logPath:a,sessionStore:n});if(t.command===ry.install||t.command===ry.reinstall)return await aD({req:t,command:t.command,sessionName:r,sessionStore:n,deployOps:t.command===ry.install?aN:ak});if(t.command===rw.installSource)return await rb({req:t,sessionName:r,sessionStore:n});if(t.command===rw.releaseMaterializedPaths)return await rI({req:t});if(t.command===ry.push){let e,i=t.positionals?.[0]?.trim(),o=t.positionals?.[1]?.trim();return i&&o?await sf({req:t,sessionName:r,logPath:a,sessionStore:n,command:ry.push,positionals:[i,"file"===(e=ev(o,{subject:"Push payload",cwd:t.meta?.cwd,expandPath:(e,t)=>ep.expandHome(e,t)})).kind?e.path:e.text],recordPositionals:[i,o]}):L("INVALID_ARGS","push requires <bundle|package> <payload.json|inline-json>")}return t.command===ry.triggerAppEvent?await sf({req:t,sessionName:r,logPath:a,sessionStore:n,command:ry.triggerAppEvent,positionals:t.positionals??[],deriveNextSession:async(e,t)=>{let r="string"==typeof t?.eventUrl?t.eventUrl:void 0,a=r?await ao(e.device,r,e.appBundleId,an)??e.appBundleId:e.appBundleId;return{...e,appBundleId:a}}}):t.command===ry.open?await aw({req:t,sessionName:r,logPath:a,sessionStore:n}):"replay"===g(t.command)?await sp({req:t,sessionName:r,logPath:a,sessionStore:n,leaseRegistry:i,invoke:s??o}):t.command===ry.batch?await ax(t,r,o):t.command===ry.close?await ab({req:t,sessionName:r,logPath:a,sessionStore:n,leaseRegistry:i}):null}export{rv as session_namespaceObject};