agent-device 0.17.5 → 0.17.6

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 (123) hide show
  1. package/README.md +2 -2
  2. package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.17.5.apk → agent-device-android-multitouch-helper-0.17.6.apk} +0 -0
  3. package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.17.6.apk.sha256 +1 -0
  4. package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.17.5.manifest.json → agent-device-android-multitouch-helper-0.17.6.manifest.json} +4 -4
  5. package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.17.5.apk → agent-device-android-snapshot-helper-0.17.6.apk} +0 -0
  6. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.17.6.apk.sha256 +1 -0
  7. package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.17.5.manifest.json → agent-device-android-snapshot-helper-0.17.6.manifest.json} +6 -6
  8. package/dist/src/2133.js +1 -0
  9. package/dist/src/2748.js +1 -0
  10. package/dist/src/{4012.js → 2892.js} +1 -1
  11. package/dist/src/2948.js +1 -0
  12. package/dist/src/2954.js +2 -0
  13. package/dist/src/{7651.js → 3006.js} +1 -1
  14. package/dist/src/314.js +1 -0
  15. package/dist/src/{8806.js → 3340.js} +5 -5
  16. package/dist/src/4291.js +2 -0
  17. package/dist/src/{7599.js → 432.js} +1 -1
  18. package/dist/src/4418.js +1 -0
  19. package/dist/src/{2403.js → 4428.js} +1 -1
  20. package/dist/src/4723.js +1 -0
  21. package/dist/src/5299.js +1 -0
  22. package/dist/src/{113.js → 5448.js} +1 -1
  23. package/dist/src/5484.js +1 -0
  24. package/dist/src/5628.js +1 -0
  25. package/dist/src/587.js +1 -0
  26. package/dist/src/6311.js +27 -0
  27. package/dist/src/6918.js +1 -0
  28. package/dist/src/7244.js +1 -0
  29. package/dist/src/7394.js +6 -0
  30. package/dist/src/8184.js +1 -0
  31. package/dist/src/8225.js +1 -0
  32. package/dist/src/{1974.js → 8275.js} +1 -1
  33. package/dist/src/8875.js +1 -0
  34. package/dist/src/{1352.js → 9581.js} +1 -1
  35. package/dist/src/9624.js +1 -0
  36. package/dist/src/9722.js +38 -0
  37. package/dist/src/9836.js +1 -0
  38. package/dist/src/9873.js +1 -0
  39. package/dist/src/9919.js +6 -0
  40. package/dist/src/android-adb.d.ts +3 -3
  41. package/dist/src/android-adb.js +1 -1
  42. package/dist/src/android-snapshot-helper.js +1 -1
  43. package/dist/src/android.js +1 -1
  44. package/dist/src/apple.js +1 -1
  45. package/dist/src/apps.js +6 -6
  46. package/dist/src/artifacts.js +1 -1
  47. package/dist/src/batch.d.ts +4 -4
  48. package/dist/src/batch.js +1 -1
  49. package/dist/src/{args.js → cli-help.js} +18 -18
  50. package/dist/src/cli-output.js +4 -30
  51. package/dist/src/cli.js +17 -17
  52. package/dist/src/command-surface.js +1 -1
  53. package/dist/src/contracts.d.ts +6 -6
  54. package/dist/src/contracts.js +1 -1
  55. package/dist/src/devices.js +1 -1
  56. package/dist/src/find.js +1 -1
  57. package/dist/src/finders.d.ts +1 -1
  58. package/dist/src/finders.js +1 -1
  59. package/dist/src/generic.js +8 -14
  60. package/dist/src/index.d.ts +28 -25
  61. package/dist/src/index.js +1 -1
  62. package/dist/src/input-actions.js +1 -1
  63. package/dist/src/input-actions~1.js +1 -1
  64. package/dist/src/install-source.js +1 -1
  65. package/dist/src/interaction.js +1 -1
  66. package/dist/src/internal/bin.js +5 -5
  67. package/dist/src/internal/companion-tunnel.js +1 -1
  68. package/dist/src/internal/daemon.js +1 -1
  69. package/dist/src/internal/png-worker.js +1 -1
  70. package/dist/src/internal/update-check-entry.js +1 -1
  71. package/dist/src/io.js +1 -1
  72. package/dist/src/lease.js +1 -1
  73. package/dist/src/linux.js +1 -1
  74. package/dist/src/metro.js +1 -1
  75. package/dist/src/notifications.js +1 -1
  76. package/dist/src/react-native.js +1 -1
  77. package/dist/src/record-trace-recording.js +2 -2
  78. package/dist/src/record-trace.js +1 -1
  79. package/dist/src/recording-provider.js +1 -1
  80. package/dist/src/remote-config.d.ts +5 -5
  81. package/dist/src/remote-config.js +1 -1
  82. package/dist/src/rslib-runtime.js +1 -1
  83. package/dist/src/selector-runtime.js +1 -1
  84. package/dist/src/selectors.d.ts +1 -1
  85. package/dist/src/selectors.js +1 -1
  86. package/dist/src/server.js +1 -1
  87. package/dist/src/session.js +7 -7
  88. package/dist/src/snapshot.js +2 -2
  89. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +5 -0
  90. package/package.json +14 -13
  91. package/server.json +3 -3
  92. package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.17.5.apk.sha256 +0 -1
  93. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.17.5.apk.sha256 +0 -1
  94. package/dist/src/1010.js +0 -1
  95. package/dist/src/123.js +0 -1
  96. package/dist/src/1231.js +0 -1
  97. package/dist/src/208.js +0 -1
  98. package/dist/src/221.js +0 -6
  99. package/dist/src/2415.js +0 -38
  100. package/dist/src/3675.js +0 -1
  101. package/dist/src/5611.js +0 -1
  102. package/dist/src/5827.js +0 -1
  103. package/dist/src/6088.js +0 -1
  104. package/dist/src/6133.js +0 -1
  105. package/dist/src/6629.js +0 -1
  106. package/dist/src/7556.js +0 -1
  107. package/dist/src/7719.js +0 -1
  108. package/dist/src/7847.js +0 -1
  109. package/dist/src/8133.js +0 -1
  110. package/dist/src/8656.js +0 -1
  111. package/dist/src/9010.js +0 -1
  112. package/dist/src/9471.js +0 -1
  113. package/dist/src/9542.js +0 -6
  114. package/dist/src/9616.js +0 -2
  115. package/dist/src/9639.js +0 -2
  116. package/dist/src/9671.js +0 -1
  117. package/dist/src/9818.js +0 -1
  118. package/dist/src/989.js +0 -1
  119. /package/dist/src/{2301.js → 4069.js} +0 -0
  120. /package/dist/src/{4829.js → 5560.js} +0 -0
  121. /package/dist/src/{4778.js → 6024.js} +0 -0
  122. /package/dist/src/{9152.js → 733.js} +0 -0
  123. /package/dist/src/{3267.js → 9612.js} +0 -0
@@ -1,4 +1,4 @@
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"./9152.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 R,ANDROID_FRAME_SAMPLE_METHOD as x,refreshSessionDeviceIfNeeded as M,buildAppleFrameSamplingMetadata as P,createRequestCanceledError as L,registerRequestAbort as O,errorResponse as E,IOS_SIMULATOR_POST_OPEN_SETTLE_MS as C,IOS_SIMULATOR_POST_CLOSE_SETTLE_MS as $,settleIosSimulator as V,buildSessionRecoveryHint as U,applyRuntimeHintsToApp as q,withKeyedLock as F,resolveTargetDevice as G,getAppLogPathMetadata as T,uniqueStrings as B,setSessionSnapshot as H,sampleAndroidMemoryPerf as K,shutdownDeviceTarget as j,ANDROID_HPROF_SNAPSHOT_DESCRIPTION as z,sampleAndroidCpuPerf as W,clearRuntimeHintsFromApp as J,ANDROID_HPROF_SNAPSHOT_METHOD as Y,startAppleXctracePerfCapture as X,buildAppleSamplingMetadata as Z,getSnapshotReferenceFrame as Q,clearAppLogFiles as ee,handleCloseCommand as et,prepareIosRunner as er,session_device_utils_hasExplicitSessionFlag as ea,readSessionNetworkCapture as en,cleanupRetainedMaterializedPaths as ei,isImplicitSessionScopeConflict as eo,resolveSessionRunnerLogPath as es,ANDROID_CPU_SAMPLE_DESCRIPTION as el,buildSnapshotState as eu,resolveLogBackend as ep,stopAndroidSimpleperfProfile as ed,context_contextFromFlags as ec,listDeviceInventory as ef,SessionStore as em,ANDROID_CPU_SAMPLE_METHOD as eh,buildAppleMemorySnapshotSupport as eg,stopAndroidPerfettoTrace as ew,isRequestCanceled as ey,resolveRequestTrackingId as ev,retainMaterializedPaths as eA,runAppLogDoctor as eS,resolvePayloadInput as eI,prepareUploadedArtifact as eb,resetAndroidFramePerfStats as e_,ANDROID_FRAME_SAMPLE_DESCRIPTION as ek,markRequestCanceled as eN,stopAppLog as eD,resolveImplicitSessionScope as eR,APPLE_MEMGRAPH_SNAPSHOT_METHOD as ex,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 eq,ANDROID_MEMORY_SAMPLE_METHOD as eF,getRequestSignal as eG,markAndroidSnapshotFreshness as eT,startAppLog as eB,emitRequestProgress as eH}from"./2415.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 eY,isPerfKind as eX,isPerfMemoryKind as eZ,pointInsideRect as eQ,successText as e0,clampGesturePoint as e1,resolveDeployResultTarget as e2,PERF_MEMORY_KIND_ERROR_MESSAGE as e3,PERF_KIND_ERROR_MESSAGE as e5,isPerfArea as e8,LOG_ACTION_VALUES as e6,withSuccessText as e4,clampToRange as e7,parseSessionSurface as e9,resolveInstallFromSourceResultTarget as te,readReactNativeOverlayActionNodes as tt,detectReactNativeOverlay as tr,PERF_SUBJECT_ERROR_MESSAGE as ta}from"./6133.js";import{isApplePlatform as tn,resolveAppleSimulatorSetPathForSelector as ti,normalizePlatformSelector as to,NETWORK_INCLUDE_MODES as ts,matchesPlatformSelector as tl}from"./9616.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"./8806.js";import{getDiagnosticsMeta as ty,emitDiagnostic as tv}from"./7599.js";import{runBatch as tA,mergeParentFlags as tS}from"./1231.js";import{assertResolvedAppsFilter as tI}from"./3675.js";import{listIosApps as tb}from"./apps.js";import{unsupportedCommand as t_,readEnvMap as tk,parseReplayScriptDetailed as tN,readReplayShellEnvSource as tD,normalizeCommandList as tR,normalizePlatform as tx,readReplayCliEnvEntries as tM,parseMaestroYamlDocuments as tP,parseAbsolutePoint as tL,readReplayScriptMetadata as tO,parseReplayCliEnvEntries as tE,collectReplayShellEnv as tC,support_action as t$,isPlainRecord as tV,requireAppId as tU,assertOnlyKeys as tq,resolveMaestroString as tF,requireStringValue as tG,parseMaestroPoint as tT,unsupportedMaestroSyntax as tB,readTimeoutMs as tH,writeReplayScript as tK,buildReplayVarScope as tj,resolveReplayAction as tz,mergeReplayVarScopeValues as tW}from"./2403.js";import{runCmdSync as tJ}from"./9818.js";import{readSnapshotDiagnosticsSummary as tY,summarizeSnapshotTimingSamples as tX,mergeSnapshotDiagnostics as tZ}from"./4012.js";import{splitSelectorFromArgs as tQ,extractNodeText as t0,findSnapshotAncestor as t1,isDescendantOfSnapshotNode as t2,parseSelectorChain as t3,tryParseSelectorChain as t5,splitIsSelectorArgs as t8,resolveSelectorChain as t6,buildSelectorChainForNode as t4,buildSnapshotNodeByIndex as t7,matchesSelector as t9,normalizeType as re}from"./7847.js";import{formatScriptActionSummary as rt,evaluateIsPredicate as rr,isTouchTargetCommand as ra}from"./123.js";import{normalizeText as rn}from"./7556.js";import{sleep as ri}from"./4829.js";import{buildSnapshotDisplayLines as ro}from"./5827.js";import{handleRecordCommand as rs}from"./record-trace-recording.js";import{INTERNAL_COMMANDS as rl,PUBLIC_COMMANDS as ru}from"./6088.js";import{trimRuntimeValue as rp}from"./8656.js";var rd={};async function rc(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 G(e.flags??{});return await eM(a),a}async function rf(e){let{prepared:t,retention:r,req:a,session:n,sessionName:i}=e;if(r.enabled)return await eA({archivePath:t.archivePath,installablePath:t.installablePath,tenantId:a.meta?.tenantId,sessionName:n?i:void 0,ttlMs:r.ttlMs})}function rm(e){return e?{...e.archivePath?{archivePath:e.archivePath}:{},installablePath:e.installablePath,materializationId:e.materializationId,materializationExpiresAt:e.expiresAt}:{}}async function rh(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:eb(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 rc({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 rf({prepared:e,retention:l,req:t,session:n,sessionName:r});let o=await i(s),p=e4(o,(u=o,`Installed: ${te(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 ei(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{...rm(t),bundleId:r.bundleId,...r.appName?{appName:r.appName}:{},launchTarget:r.bundleId}})}let{prepareAndroidInstallArtifact:c}=await import("./8806.js"),{installAndroidInstallablePathAndResolvePackageName:f}=await import("./8806.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("./8806.js"),a=r(t);return{...rm(e),packageName:t,...a?{appName:a}:{},launchTarget:t}})}catch(e){return{ok:!1,error:o(e)}}}async function rg(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 ei(e,t.meta?.tenantId),{ok:!0,data:{released:!0,materializationId:e}}}catch(e){return{ok:!1,error:o(e)}}}e.r(rd),e.d(rd,{handleSessionCommands:()=>oC});let rw=["platform","metroHost","metroPort","bundleUrl","launchUrl"];function ry(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>void 0!==e&&""!==e).length:0}function rv(e,t){if(void 0!==e){if("string"!=typeof e)throw new s("INVALID_ARGS",`Invalid open runtime ${t}: expected string.`);return rp(e)}}function rA(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 rS(e){if("ios"===e||"android"===e)return e}async function rI(e){let{replacedStoredRuntime:t,previousRuntime:r,runtime:a,session:n}=e;!t||!n?.appBundleId||!h(r)||h(a)||await J({device:n.device,appId:n.appBundleId})}async function rb(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 J({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=rS(to(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:rp(t?.metroHost),metroPort:rA(t?.metroPort),bundleUrl:rp(t?.bundleUrl),launchUrl:rp(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===ry(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 r_="open-command-roundtrip",rk="Not implemented for this platform in this release.";function rN(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 rD=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 rx(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 rM(e,t):await rP(e,t)}async function rM(e,t){try{let{resolveIosSimulatorDeepLinkBundleId:r}=await import("./apps.js");return await r(e,t)}catch{return}}async function rP(e,t){try{let{resolveIosApp:r}=await import("./apps.js");return await r(e,t)}catch{return}}async function rL(e,t){if(!("android"!==e.platform||!t||th(t)))try{let{resolveAndroidApp:r}=await import("./8806.js"),a=await r(e,t);return"package"===a.type?a.value:void 0}catch{return}}async function rO(e,t,r){if(r||"android"!==e.platform||!t||!th(t))return r;try{let{getAndroidAppState:t}=await import("./8806.js"),a=await t(e);return a.package?.trim()||r}catch{return r}}async function rE(e,t,r,a){return await rx(e,t,r)??await a(e,t)??("android"===e.platform&&t&&th(t)?r:void 0)}function rC(e){return E("INVALID_ARGS",e)}function r$(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=e9(r);if(!rD.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?e9(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 rV(e){let{shouldRelaunch:t,openTarget:r,surface:a,device:n}=e;return t?r&&th(r)?rC("open --relaunch does not support URL targets."):"app"!==a?rC("open --relaunch is supported only for app surfaces."):"android"===n.platform&&r&&"binary"===tp(r)?rC(tg(r)):null:null}async function rU(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=>!rw.includes(e));if(n)throw new s("INVALID_ARGS",`Invalid open runtime field: ${n}. Supported fields are ${rw.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:rv(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 rA(e)}}(t.metroPort),bundleUrl:rv(t.bundleUrl,"bundleUrl"),launchUrl:rv(t.launchUrl,"launchUrl")}}({runtime:t.runtime,sessionName:a,platform:rS(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=rS(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&&ry(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 rI({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 rE(t,a,n,rL),appName:i.appName??a}}let rF=new Map;async function rG(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 V(t,$)}async function rT(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=ec(t,r,l,u),delete a.launchConsole,delete a.launchArgs,a)})}async function rB(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 rG({device:d,closeTarget:e,outFlag:o.flags?.out,context:{...ec(u,o.flags,S??y?.appBundleId,A)}}),b.relaunchCloseDurationMs=Math.max(0,Date.now()-t)}let k=Date.now();await q({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},x=o.flags?.maestro?.prewarmRunnerBeforeOpen===!0;if(N&&S&&(b.runnerPrewarmKind="session",b.runnerPrewarmScheduled=!0,x)){i=eL(d,D);let e=Date.now();await i,b.runnerPrewarmWaited=!0,b.runnerPrewarmDurationMs=Math.max(0,Date.now()-e)}let M=Date.now(),P=await rH({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,{...ec(u,o.flags,S)}),b.openDispatchDurationMs=Math.max(0,Date.now()-M);let $=Date.now();if(await rT({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 rO(d,c,S),"android"===d.platform&&S&&await e_(d,S);let U=c?(t=S,{durationMs:Math.max(0,Date.now()-M),measuredAt:new Date().toISOString(),method:r_,appTarget:c,appBundleId:t}):void 0,F=Date.now();if(await V(d,C),b.postOpenSettleDurationMs=Math.max(0,Date.now()-F),ey(o.meta?.requestId)){let e=L();return E(e.code,e.message,e.details)}y&&eT(y,"open",y.snapshot);let G=rN({existingSession:O,sessionName:y?.name??_(o),sessionScope:y?.sessionScope??eR(o),device:d,surface:h,appBundleId:S,appName:m,saveScript:!!o.flags?.saveScript});void 0!==o.runtime&&(r=l,a=s,(n=w)&&(0===ry(n)?r.clearRuntimeHints(a):r.setRuntimeHints(a,n)));let T=l.ensureSessionDir(s),B=R(T,o.meta?.requestId??ty().requestId);b.totalDurationMs=Math.max(0,Date.now()-I);let H=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,...e0(`Opened: ${i??o??t}`)}}({sessionName:G.name,sessionStateDir:T,runnerLogPath:es(T),requestLogPath:B,appName:m,appBundleId:S,surface:h,startup:U,timing:b,device:d,runtime:w,runtimeHintCount:ry});return l.recordAction(G,{command:"open",positionals:f,flags:o.flags??{},runtime:void 0!==o.runtime?w:void 0,result:H}),l.set(s,G),{ok:!0,data:H}}async function rH(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=rN({existingSession:l,sessionName:l?.name??_(t),sessionScope:l?.sessionScope??eR(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 rK(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=r$(i.device,t.flags?.surface,s,i.surface);if("string"!=typeof l)return l;if(!s&&"app"===l)return e?rC("open --relaunch requires an app name or an active session app."):rC("Session already active. Close it first or pass a new --session name.");let u=rV({shouldRelaunch:e,openTarget:s,surface:l,device:i.device});if(u)return u;let p=await M(i.device),d=await rU({req:t,sessionName:r,sessionStore:n,device:p,surface:l,openTarget:s,existingSession:i});return"response"===d.type?d.response:await rB({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 rC("open --relaunch requires an app argument.");let l=function(e){let{shouldRelaunch:t,openTarget:r,platform:a}=e;return t?r&&th(r)?rC("open --relaunch does not support URL targets."):"android"===a&&r&&"binary"===tp(r)?rC(tg(r)):null:null}({shouldRelaunch:o,openTarget:s,platform:t.flags?.platform==="android"?"android":void 0});if(l)return l;let u=await G(t.flags??{}),p=r$(u,t.flags?.surface,s);if("string"!=typeof p)return p;let d=rV({shouldRelaunch:o,openTarget:s,surface:p,device:u});return d||await F(rF,u.id,async()=>{let e=n.toArray().find(e=>e.device.id===u.id);if(e)return eo(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:U(e,"device-in-use")});let i=await rU({req:t,sessionName:r,sessionStore:n,device:u,surface:p,openTarget:s});return"response"===i.type?i.response:await rB({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 rj={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("./8806.js");return await a(e,t,r)}},rz={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("./8806.js"),n=await a(e,r);return{package:n.packageName,appName:n.appName,launchTarget:n.launchTarget}}};async function rW(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?eb(c,r.meta?.tenantId):em.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=e4(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 rJ(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=eR(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:es(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=to(t.flags?.platform),a=ti({simulatorSetPath:tu(t.flags?.iosSimulatorDeviceSet),platform:r,target:t.flags?.target}),n=await ef({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?tn(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 tn(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 rX(e){let{ensureAndroidEmulatorBooted:t}=await import("./8806.js");return await t(e)}let rZ='iOS appstate requires an active session on the target device. Run open first (for example: open --session sim --platform ios --device "<name>" <app>).',rQ='macOS appstate requires an active session on the target device. Run open first (for example: open --session macos --platform macos "System Settings").';async function r0(e){let{req:t,sessionName:r,sessionStore:a}=e,n=a.get(r),i=t.flags??{},o=to(i.platform);if(!n&&ea(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=tn(n?.device.platform)&&c(i,n);if("ios"===o&&!l)return E("SESSION_NOT_FOUND",rZ);if("macos"===o&&!l)return E("SESSION_NOT_FOUND",rQ);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",rZ);if("macos"===u.platform)return E("SESSION_NOT_FOUND",rQ);let{getAndroidAppState:p}=await import("./8806.js"),d=await p(u);return{ok:!0,data:{platform:"android",package:d.package,activity:d.activity}}}async function r1(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"===(to(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 rX({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 rX({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 j(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 r0({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===r_&&t.push({durationMs:Math.max(0,Math.round(e.durationMs)),measuredAt:e.measuredAt,method:r_,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:r_,sampleCount:i.length,samples:i}:{available:!1,reason:"No startup sample captured yet. Run open <app|url> in this session first.",method:r_},{session:r.name,platform:r.device.platform,device:r.device.name,deviceId:r.device.id,metrics:{startup:s,...{fps:r8(),memory:{available:!1,reason:rk},cpu:{available:!1,reason:rk}}},sampling:{startup:{method:r_,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:eF,description:eP,unit:"kB"},cpu:{method:eh,description:el,unit:"percent"},fps:{method:x,description:ek,unit:"percent",primaryField:"droppedFramePercent",window:"since previous Android gfxinfo reset or app process start",resetsAfterRead:!0,relatedActionsLimit:12}}:Z(a.device)}});return ae(e)&&(e.appBundleId?"android"===e.device.platform?await r6(u,e,e.appBundleId,t):await r4(u,e,e.appBundleId):(n=u,l=at(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 r3(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:r8()},sampling:{fps:"android"===(a=r).device.platform?{method:x,description:ek,unit:"percent",primaryField:"droppedFramePercent",window:"since previous Android gfxinfo reset or app process start",resetsAfterRead:!0,relatedActionsLimit:12}:P(a.device)}};return ae(e)&&(e.appBundleId?await r9(n,e,e.appBundleId,t):n.metrics.fps={available:!1,reason:at(e)}),n}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,sampling:{memory:"android"===(a=r).device.platform?{method:eF,description:eP,unit:"kB",topConsumerLimit:5}:Z(a.device).memory,snapshot:"android"===r.device.platform?{method:Y,description:z,defaultKind:"android-hprof",artifactOnly:!0}:{method:ex,description:u,defaultKind:"memgraph",artifactOnly:!0}}};if(!ae(e)){if("snapshot"===t.action){let r=as(e,t.kind);return n.artifact=al(e,r),n.support=ap(n.artifact.support)??au(e),n}return n.metrics={memory:{available:!1,reason:rk}},n}return"sample"===t.action?n.metrics={memory:await an(e,t)}:(n.artifact=await ao(e,t),n.support=ap(n.artifact.support)??au(e)),n}function r8(){return{available:!1,reason:"Dropped-frame sampling is currently available only on Android app sessions and connected iOS device app sessions."}}async function r6(e,t,r,a){let n=await ar(t,r,a);r7(e,t,n)}async function r4(e,t,r){let a=await aa(t,r);r7(e,t,a)}function r7(e,t,r){e.metrics.memory=ac(r.memory),e.metrics.cpu=ac(r.cpu),e.metrics.fps=af(ac(r.fps),t)}async function r9(e,t,r,a){let n="android"===t.device.platform?await ad(eq(t.device,r,{adb:a.androidAdb})):await ad(g(t.device,r));e.metrics.fps=af(ac(n),t)}function ae(e){return"android"===e.device.platform||"ios"===e.device.platform||"macos"===e.device.platform}function at(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 ar(e,t,r){let a={adb:r.androidAdb},[n,i,o]=await Promise.allSettled([K(e.device,t,a),W(e.device,t,a),eq(e.device,t,a)]);return{memory:n,cpu:i,fps:o}}async function aa(e,t){let r=await ad(g(e.device,t)),a=await ad(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 an(e,t){return e.appBundleId?ac("android"===e.device.platform?await ad(K(e.device,e.appBundleId,{adb:t.androidAdb})):await ad(ai(e))):{available:!1,reason:at(e)}}async function ai(e){if(!e.appBundleId)throw new s("INVALID_ARGS",at(e));return(await eU(e.device,e.appBundleId)).memory}async function ao(e,t){if(!e.appBundleId)throw new s("INVALID_ARGS",at(e),{hint:"Run open <app> first so perf memory snapshot can resolve the app process."});let a=as(e,t.kind),n=function(e,t){if(e.out)return em.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?al(e,a):await I(e.device,e.appBundleId,n,{adb:t.androidAdb}):"memgraph"!==a?al(e,a):await w(e.device,e.appBundleId,n)}function as(e,t){return t||("android"===e.device.platform?"android-hprof":"memgraph")}function al(e,t){var r,a;let n=au(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 au(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."}:{...eg(e.device),androidHprof:!1,heapprofd:!1,heapprofdDecision:"Deferred because heapprofd is Android/Perfetto-specific and outside this memory artifact slice."}}function ap(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:void 0}async function ad(e){try{return{status:"fulfilled",value:await e}}catch(e){return{status:"rejected",reason:e}}}function ac(e){if("fulfilled"===e.status)return{available:!0,...e.value};let t=o(e.reason);return{available:!1,reason:t.message,error:t}}function af(e,t){var r,a;let n,i;if(!0!==e.available)return e;let o=(r=t.actions,n=am((a=e).windowStartedAt),i=am(a.windowEndedAt)??am(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 am(e){if("string"!=typeof e)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}async function ah(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=ag(i,1),m=ag(i,2),h=ag(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",ta)):(u=t,p=c,g=ag(u,1),w=ag(u,2),"start"!==(d=g)&&"stop"!==d?E("INVALID_ARGS","perf trace action must be start or stop"):eX(w)?"perfetto"!==w?E("INVALID_ARGS","perf trace requires --kind perfetto"):{ok:!0,area:"trace",action:g,kind:w,outPath:p}:E("INVALID_ARGS",e5)));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 av(e,v,v.appBundleId,y):await aA(e,v,v.appBundleId,y);return{ok:!0,data:t}}catch(e){return{ok:!1,error:o(e)}}}function ag(e,t){return(e.positionals?.[t]??"").toLowerCase()}function aw(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 ay(e,t,a){var n,i,o;let s;return t?em.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 av(e,t,r,a){if("start"===a.action){aS(t);let n=ay(e,a.outPath,"cpu.perf.data"),i=await l(t.device,r,n,{adb:e.androidAdbExecutor});return aw(e,i)}let n=ab(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=ay(e,a.outPath,"cpu-report.json");return await eC(t.device,n,r,{adb:e.androidAdbExecutor})}let i=aI(e,a.outPath,n),o=await ed(t.device,n,i,{adb:e.androidAdbExecutor});return aw(e,o)}async function aA(e,t,r,a){if("start"===a.action){aS(t);let n=ay(e,a.outPath,"app.perfetto-trace"),i=await A(t.device,r,n,{adb:e.androidAdbExecutor});return aw(e,i)}let n=ab(t,"trace",a.kind),i=aI(e,a.outPath,n),o=await ew(t.device,n,i,{adb:e.androidAdbExecutor});return aw(e,o)}function aS(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 aI(e,t,r){return t?ay(e,t,r.outPath):r.outPath}function ab(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 a_(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=ak(e[2],"perf cpu profile",!0);if(!t.ok)return t;let r=aN(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=ak(e[1],"perf trace",!1);if(!t.ok)return t;let r=aN(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 aD(e,t,n);if("stop"===n.action)return await aR(e,t,n);return await ax(e,t,n)}catch(e){return{ok:!1,error:o(e)}}}function ak(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 aN(e){return e?.toLowerCase()==="xctrace"?{ok:!0}:E("INVALID_ARGS","perf native collection currently supports --kind xctrace")}async function aD(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=aP(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=aL("started",i);return aM(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?em.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=aL("stopped",d);return aM(e,t,m),{ok:!0,data:m}}async function ax(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=aP(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:em.expandHome(o.value,e.req.meta?.cwd),outPath:i,mode:r.mode,template:t.applePerf?.lastProfileTemplate??r.template,appBundleId:t.appBundleId})};return aM(e,t,s),{ok:!0,data:s}}function aM(e,t,r){e.sessionStore.recordAction(t,{command:"perf",positionals:e.req.positionals??[],flags:e.req.flags??{},result:r})}function aP(e,t){if(t.outPath)return em.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 aL(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 aO=`logs requires ${e6.slice(0,-1).join(", ")}, or ${e6.at(-1)}`,aE=["dump","log"],aC=`network requires ${aE.join(" or ")}`,a$=`network include mode must be one of: ${ts.join(", ")}`,aV={path:({session:e,sessionName:t,sessionStore:r})=>(function(e,t,r){let a=r.resolveAppLogPath(t),n=T(a);return{ok:!0,data:{path:a,active:!!e.appLog,state:e.appLog?.getState()??"inactive",backend:e.appLog?.backend??ep(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})=>aB(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})=>aH(e,t,r,a),start:({session:e,sessionName:t,sessionStore:r})=>aK(e,t,r),stop:({session:e,sessionName:t,sessionStore:r})=>aj(e,t,r)};async function aU(e){let{req:t}=e;return"perf"===t.command?aq(e):"logs"===t.command?aT(e):"network"===t.command?az(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 ah({req:r,sessionName:a,sessionStore:n,session:l,androidAdbExecutor:i,area:u}):await a_(e,l);let p=function(e){var t,r,a,n,i,l,u,p,d,c;let f,m,h=e8(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",eY);let w=function(e){if(void 0!==e)return"string"==typeof e&&eX(e)?e:new s("INVALID_ARGS",e5)}(e.flags?.kind);if(w instanceof s)return{ok:!1,error:o(w)};let y=(t=h,r=g,("memory"===t?aG(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"):eZ(u)?void 0:E("INVALID_ARGS",e3):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 a_(e,l);try{return{ok:!0,data:await aF(e,l,p)}}catch(e){return{ok:!1,error:o(e)}}}async function aF(e,t,r){let{sessionName:a,sessionStore:n,androidAdbExecutor:i}=e;return"memory"===r.area?await r5(t,{action:function(e){if(aG(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 r3(t,{androidAdb:i}):await r2(t,{androidAdb:i})}function aG(e){return"sample"===e||"snapshot"===e}async function aT(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,e6.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",aO));return l.ok?await aV[l.action]({...e,session:s,restart:l.restart}):l}async function aB(e,t,r){let a=r.resolveAppLogPath(t),n=await eS(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 aH(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:ee(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=ee(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 aK(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 aj(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 az(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(!aE.includes(i))return E("INVALID_ARGS",aC);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 ts.includes(a)?{ok:!0,include:a}:E("INVALID_ARGS",a$)}(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,i=await en({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}}}function aW(e,t,r){var a,n;if(null==e)return t$("open",[tF(tU(t,"launchApp"),r)]);if("string"==typeof e)return t$("open",[tF(e,r)]);if(!tV(e))throw new s("INVALID_ARGS","launchApp expects a string or map.");tq(e,"launchApp",["appId","stopApp","clearState","clearKeychain","arguments","permissions","launchArguments"]),aZ(e,"permissions"),aZ(e,"clearKeychain");let i=tF("string"==typeof e.appId?e.appId:tU(t,"launchApp"),r),o=(a=e,n=r,[...aY(a.arguments,"launchApp.arguments",n),...aY(a.launchArguments,"launchApp.launchArguments",n)]),l=!0===e.clearState;return t$("open",[i],{...!l&&(!0===e.stopApp||o.length>0)?{relaunch:!0}:{},...l?{clearAppState:!0}:{},...o.length>0?{launchArgs:o}:{}})}function aJ(e,t,r){if(null==e)return t$("close",[tF(tU(t,"stopApp"),r)]);if("string"==typeof e)return t$("close",[tF(e,r)]);throw new s("INVALID_ARGS","stopApp expects a string appId or no value.")}function aY(e,t,r){if(null==e)return[];if("string"==typeof e)return[tF(e,r)];if(Array.isArray(e))return e.map((e,a)=>aX(e,`${t}[${a}]`,r));if(tV(e))return Object.entries(e).flatMap(([e,a])=>[tF(e,r),aX(a,`${t}.${e}`,r)]);throw new s("INVALID_ARGS",`${t} expects a string, list, or map.`)}function aX(e,t,r){if("string"==typeof e)return tF(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 aZ(e,t){if(void 0!==e[t])throw tB(`Maestro launchApp field "${t}" is not supported yet.`)}let aQ="__maestroRunScript",a0="__maestroAssertVisible",a1="__maestroAssertNotVisible",a2="__maestroPressEnter",a3="__maestroWaitForAnimationToEnd",a5="__maestroScrollUntilVisible",a8="__maestroSwipeScreen",a6="__maestroSwipeOn",a4="__maestroTapOn",a7="__maestroTapPointPercent";function a9(e){if(null==e)return t$("type",["\b".repeat(50)]);if("number"==typeof e&&Number.isInteger(e)&&e>0)return t$("type",["\b".repeat(e)]);if(!tV(e))throw new s("INVALID_ARGS","eraseText expects empty, a positive count, or a map.");if(tq(e,"eraseText",["charactersToErase"]),void 0===e.charactersToErase)return t$("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 t$("type",["\b".repeat(e.charactersToErase)])}function ne(e){return"number"==typeof e&&Number.isFinite(e)?String(Math.max(16,Math.floor(e))):void 0}function nt(e,t){let r=e.toLowerCase();switch(r){case"up":case"down":case"left":case"right":return r;default:throw tB(`Maestro ${t} must be UP, DOWN, LEFT, or RIGHT.`)}}function nr(e){return nt(e,"swipe direction")}function na(e,t,r=[],a){if("string"==typeof e)return nn(tF(e,a));if(!tV(e))throw new s("INVALID_ARGS",`${t} expects a string or selector map.`);tq(e,t,["id","text","enabled","selected",...r]);let n=[],i=[];if("boolean"==typeof e.enabled&&i.push(no("enabled",String(e.enabled))),"boolean"==typeof e.selected&&i.push(no("selected",String(e.selected))),"string"==typeof e.id&&n.push(no("id",tF(e.id,a)),...i),"string"==typeof e.text&&0===n.length)return nn(tF(e.text,a),i);if("string"==typeof e.label&&0===n.length&&n.push(no("label",tF(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 nn(e,t=[]){return[[no("label",e),...t].join(" "),[no("text",e),...t].join(" "),[no("id",e),...t].join(" ")].join(" || ")}function ni(e){let t=ne(e.duration);return t?[t]:[]}function no(e,t){return`${e}=${JSON.stringify(t)}`}function ns(e){var t,r;if(!tV(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 nl(e){let t=ns(e)??{};return{...t,maestro:{...t.maestro??{},allowNonHittableCoordinateFallback:!0}}}function nu(e){let t={doubleTap:!0};return tV(e)&&"number"==typeof e.delay&&Number.isInteger(e.delay)&&(t.intervalMs=Math.max(0,e.delay)),t}class np{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 nd(e,t,r){return{...t$(e,t),replayControl:r}}function nc(e,t,r){let a="string"==typeof e?tF(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 nf=`
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,isPerfKind as eY,isPerfMemoryKind as eZ,pointInsideRect as eQ,successText as e0,clampGesturePoint as e1,resolveDeployResultTarget as e3,PERF_MEMORY_KIND_ERROR_MESSAGE as e2,PERF_KIND_ERROR_MESSAGE as e5,isPerfArea as e4,LOG_ACTION_VALUES as e6,withSuccessText as e8,clampToRange as e7,parseSessionSurface as e9,resolveInstallFromSourceResultTarget as te,readReactNativeOverlayActionNodes as tt,detectReactNativeOverlay as tr,PERF_SUBJECT_ERROR_MESSAGE as ta}from"./9873.js";import{isApplePlatform as tn,resolveAppleSimulatorSetPathForSelector as ti,normalizePlatformSelector as to,NETWORK_INCLUDE_MODES as ts,matchesPlatformSelector as tl}from"./4291.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{unsupportedCommand as t_,readEnvMap as tk,parseReplayScriptDetailed as tN,readReplayShellEnvSource as tD,normalizeCommandList as tx,normalizePlatform as tR,readReplayCliEnvEntries as tM,parseMaestroYamlDocuments as tP,parseAbsolutePoint as tL,readReplayScriptMetadata as tO,parseReplayCliEnvEntries as tE,collectReplayShellEnv as tC,support_action as t$,isPlainRecord as tV,requireAppId as tU,assertOnlyKeys as tF,resolveMaestroString as tq,requireStringValue as tG,parseMaestroPoint as tT,unsupportedMaestroSyntax as tB,readTimeoutMs as tH,writeReplayScript as tK,buildReplayVarScope as tj,resolveReplayAction as tz,mergeReplayVarScopeValues as tW}from"./4428.js";import{runCmdSync as tJ}from"./8875.js";import{readSnapshotDiagnosticsSummary as tX,summarizeSnapshotTimingSamples as tY,mergeSnapshotDiagnostics as tZ}from"./2892.js";import{splitSelectorFromArgs as tQ,extractNodeText as t0,findSnapshotAncestor as t1,isDescendantOfSnapshotNode as t3,parseSelectorChain as t2,tryParseSelectorChain as t5,splitIsSelectorArgs as t4,resolveSelectorChain as t6,buildSelectorChainForNode as t8,buildSnapshotNodeByIndex as t7,matchesSelector as t9,normalizeType as re}from"./9836.js";import{formatScriptActionSummary as rt,evaluateIsPredicate as rr,isTouchTargetCommand as ra}from"./5299.js";import{normalizeText as rn}from"./587.js";import{sleep as ri}from"./5560.js";import{buildSnapshotDisplayLines as ro}from"./7244.js";import{handleRecordCommand as rs}from"./record-trace-recording.js";import{INTERNAL_COMMANDS as rl,PUBLIC_COMMANDS as ru}from"./2133.js";import{trimRuntimeValue as rp}from"./5628.js";var rd={};async function rc(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 rf(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 rm(e){return e?{...e.archivePath?{archivePath:e.archivePath}:{},installablePath:e.installablePath,materializationId:e.materializationId,materializationExpiresAt:e.expiresAt}:{}}async function rh(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 rc({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 rf({prepared:e,retention:l,req:t,session:n,sessionName:r});let o=await i(s),p=e8(o,(u=o,`Installed: ${te(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{...rm(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{...rm(e),packageName:t,...a?{appName:a}:{},launchTarget:t}})}catch(e){return{ok:!1,error:o(e)}}}async function rg(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(rd),e.d(rd,{handleSessionCommands:()=>oC});let rw=["platform","metroHost","metroPort","bundleUrl","launchUrl"];function ry(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>void 0!==e&&""!==e).length:0}function rv(e,t){if(void 0!==e){if("string"!=typeof e)throw new s("INVALID_ARGS",`Invalid open runtime ${t}: expected string.`);return rp(e)}}function rA(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 rS(e){if("ios"===e||"android"===e)return e}async function rI(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 rb(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=rS(to(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:rp(t?.metroHost),metroPort:rA(t?.metroPort),bundleUrl:rp(t?.bundleUrl),launchUrl:rp(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===ry(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 r_="open-command-roundtrip",rk="Not implemented for this platform in this release.";function rN(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 rD=new Set(["app","desktop","frontmost-app"]);async function rx(e){if("app"===e||"desktop"===e||"menubar"===e)return{};let t=await e$();return{appBundleId:t.bundleId,appName:t.appName}}async function rR(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 rM(e,t):await rP(e,t)}async function rM(e,t){try{let{resolveIosSimulatorDeepLinkBundleId:r}=await import("./apps.js");return await r(e,t)}catch{return}}async function rP(e,t){try{let{resolveIosApp:r}=await import("./apps.js");return await r(e,t)}catch{return}}async function rL(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 rO(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 rE(e,t,r,a){return await rR(e,t,r)??await a(e,t)??("android"===e.platform&&t&&th(t)?r:void 0)}function rC(e){return E("INVALID_ARGS",e)}function r$(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=e9(r);if(!rD.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?e9(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 rV(e){let{shouldRelaunch:t,openTarget:r,surface:a,device:n}=e;return t?r&&th(r)?rC("open --relaunch does not support URL targets."):"app"!==a?rC("open --relaunch is supported only for app surfaces."):"android"===n.platform&&r&&"binary"===tp(r)?rC(tg(r)):null:null}async function rU(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 rF({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=>!rw.includes(e));if(n)throw new s("INVALID_ARGS",`Invalid open runtime field: ${n}. Supported fields are ${rw.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:rv(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 rA(e)}}(t.metroPort),bundleUrl:rv(t.bundleUrl,"bundleUrl"),launchUrl:rv(t.launchUrl,"launchUrl")}}({runtime:t.runtime,sessionName:a,platform:rS(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=rS(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&&ry(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 rI({replacedStoredRuntime:r,previousRuntime:t,runtime:e,session:u})}return{type:"details",details:{appBundleId:p,appName:d,runtime:c.data.runtime}}}async function rF(e){let{device:t,surface:r,openTarget:a,existingAppBundleId:n}=e,i=await rx(r);return{appBundleId:i.appBundleId??await rE(t,a,n,rL),appName:i.appName??a}}let rq=new Map;async function rG(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 rT(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 rB(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 rG({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 rH({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 rT({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 rO(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:r_,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=rN({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===ry(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,...e0(`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:ry});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 rH(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=rN({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 rK(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=r$(i.device,t.flags?.surface,s,i.surface);if("string"!=typeof l)return l;if(!s&&"app"===l)return e?rC("open --relaunch requires an app name or an active session app."):rC("Session already active. Close it first or pass a new --session name.");let u=rV({shouldRelaunch:e,openTarget:s,surface:l,device:i.device});if(u)return u;let p=await M(i.device),d=await rU({req:t,sessionName:r,sessionStore:n,device:p,surface:l,openTarget:s,existingSession:i});return"response"===d.type?d.response:await rB({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 rC("open --relaunch requires an app argument.");let l=function(e){let{shouldRelaunch:t,openTarget:r,platform:a}=e;return t?r&&th(r)?rC("open --relaunch does not support URL targets."):"android"===a&&r&&"binary"===tp(r)?rC(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=r$(u,t.flags?.surface,s);if("string"!=typeof p)return p;let d=rV({shouldRelaunch:o,openTarget:s,surface:p,device:u});return d||await F(rq,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 rU({req:t,sessionName:r,sessionStore:n,device:u,surface:p,openTarget:s});return"response"===i.type?i.response:await rB({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 rj={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)}},rz={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 rW(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=e8(e,(f=e,`Installed: ${f.appName??e3(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 rJ(e,t,r){return await tA(e,t,r)}async function rX(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=to(t.flags?.platform),a=ti({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?tn(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 tn(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 rY(e){let{ensureAndroidEmulatorBooted:t}=await import("./3340.js");return await t(e)}let rZ='iOS appstate requires an active session on the target device. Run open first (for example: open --session sim --platform ios --device "<name>" <app>).',rQ='macOS appstate requires an active session on the target device. Run open first (for example: open --session macos --platform macos "System Settings").';async function r0(e){let{req:t,sessionName:r,sessionStore:a}=e,n=a.get(r),i=t.flags??{},o=to(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=tn(n?.device.platform)&&c(i,n);if("ios"===o&&!l)return E("SESSION_NOT_FOUND",rZ);if("macos"===o&&!l)return E("SESSION_NOT_FOUND",rQ);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",rZ);if("macos"===u.platform)return E("SESSION_NOT_FOUND",rQ);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 r1(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"===(to(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 rY({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 rY({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 r0({req:t,sessionName:r,sessionStore:a}):null}async function r3(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===r_&&t.push({durationMs:Math.max(0,Math.round(e.durationMs)),measuredAt:e.measuredAt,method:r_,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:r_,sampleCount:i.length,samples:i}:{available:!1,reason:"No startup sample captured yet. Run open <app|url> in this session first.",method:r_},{session:r.name,platform:r.device.platform,device:r.device.name,deviceId:r.device.id,metrics:{startup:s,...{fps:r4(),memory:{available:!1,reason:rk},cpu:{available:!1,reason:rk}}},sampling:{startup:{method:r_,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 ae(e)&&(e.appBundleId?"android"===e.device.platform?await r6(u,e,e.appBundleId,t):await r8(u,e,e.appBundleId):(n=u,l=at(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 r2(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:r4()},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 ae(e)&&(e.appBundleId?await r9(n,e,e.appBundleId,t):n.metrics.fps={available:!1,reason:at(e)}),n}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,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(!ae(e)){if("snapshot"===t.action){let r=as(e,t.kind);return n.artifact=al(e,r),n.support=ap(n.artifact.support)??au(e),n}return n.metrics={memory:{available:!1,reason:rk}},n}return"sample"===t.action?n.metrics={memory:await an(e,t)}:(n.artifact=await ao(e,t),n.support=ap(n.artifact.support)??au(e)),n}function r4(){return{available:!1,reason:"Dropped-frame sampling is currently available only on Android app sessions and connected iOS device app sessions."}}async function r6(e,t,r,a){let n=await ar(t,r,a);r7(e,t,n)}async function r8(e,t,r){let a=await aa(t,r);r7(e,t,a)}function r7(e,t,r){e.metrics.memory=ac(r.memory),e.metrics.cpu=ac(r.cpu),e.metrics.fps=af(ac(r.fps),t)}async function r9(e,t,r,a){let n="android"===t.device.platform?await ad(eF(t.device,r,{adb:a.androidAdb})):await ad(g(t.device,r));e.metrics.fps=af(ac(n),t)}function ae(e){return"android"===e.device.platform||"ios"===e.device.platform||"macos"===e.device.platform}function at(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 ar(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 aa(e,t){let r=await ad(g(e.device,t)),a=await ad(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 an(e,t){return e.appBundleId?ac("android"===e.device.platform?await ad(H(e.device,e.appBundleId,{adb:t.androidAdb})):await ad(ai(e))):{available:!1,reason:at(e)}}async function ai(e){if(!e.appBundleId)throw new s("INVALID_ARGS",at(e));return(await eU(e.device,e.appBundleId)).memory}async function ao(e,t){if(!e.appBundleId)throw new s("INVALID_ARGS",at(e),{hint:"Run open <app> first so perf memory snapshot can resolve the app process."});let a=as(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?al(e,a):await I(e.device,e.appBundleId,n,{adb:t.androidAdb}):"memgraph"!==a?al(e,a):await w(e.device,e.appBundleId,n)}function as(e,t){return t||("android"===e.device.platform?"android-hprof":"memgraph")}function al(e,t){var r,a;let n=au(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 au(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 ap(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:void 0}async function ad(e){try{return{status:"fulfilled",value:await e}}catch(e){return{status:"rejected",reason:e}}}function ac(e){if("fulfilled"===e.status)return{available:!0,...e.value};let t=o(e.reason);return{available:!1,reason:t.message,error:t}}function af(e,t){var r,a;let n,i;if(!0!==e.available)return e;let o=(r=t.actions,n=am((a=e).windowStartedAt),i=am(a.windowEndedAt)??am(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 am(e){if("string"!=typeof e)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}async function ah(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=ag(i,1),m=ag(i,2),h=ag(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",ta)):(u=t,p=c,g=ag(u,1),w=ag(u,2),"start"!==(d=g)&&"stop"!==d?E("INVALID_ARGS","perf trace action must be start or stop"):eY(w)?"perfetto"!==w?E("INVALID_ARGS","perf trace requires --kind perfetto"):{ok:!0,area:"trace",action:g,kind:w,outPath:p}:E("INVALID_ARGS",e5)));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 av(e,v,v.appBundleId,y):await aA(e,v,v.appBundleId,y);return{ok:!0,data:t}}catch(e){return{ok:!1,error:o(e)}}}function ag(e,t){return(e.positionals?.[t]??"").toLowerCase()}function aw(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 ay(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 av(e,t,r,a){if("start"===a.action){aS(t);let n=ay(e,a.outPath,"cpu.perf.data"),i=await l(t.device,r,n,{adb:e.androidAdbExecutor});return aw(e,i)}let n=ab(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=ay(e,a.outPath,"cpu-report.json");return await eC(t.device,n,r,{adb:e.androidAdbExecutor})}let i=aI(e,a.outPath,n),o=await ep(t.device,n,i,{adb:e.androidAdbExecutor});return aw(e,o)}async function aA(e,t,r,a){if("start"===a.action){aS(t);let n=ay(e,a.outPath,"app.perfetto-trace"),i=await A(t.device,r,n,{adb:e.androidAdbExecutor});return aw(e,i)}let n=ab(t,"trace",a.kind),i=aI(e,a.outPath,n),o=await eg(t.device,n,i,{adb:e.androidAdbExecutor});return aw(e,o)}function aS(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 aI(e,t,r){return t?ay(e,t,r.outPath):r.outPath}function ab(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 a_(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=ak(e[2],"perf cpu profile",!0);if(!t.ok)return t;let r=aN(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=ak(e[1],"perf trace",!1);if(!t.ok)return t;let r=aN(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 aD(e,t,n);if("stop"===n.action)return await ax(e,t,n);return await aR(e,t,n)}catch(e){return{ok:!1,error:o(e)}}}function ak(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 aN(e){return e?.toLowerCase()==="xctrace"?{ok:!0}:E("INVALID_ARGS","perf native collection currently supports --kind xctrace")}async function aD(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=aP(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=aL("started",i);return aM(e,t,o),{ok:!0,data:o}}async function ax(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=aL("stopped",d);return aM(e,t,m),{ok:!0,data:m}}async function aR(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=aP(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 aM(e,t,s),{ok:!0,data:s}}function aM(e,t,r){e.sessionStore.recordAction(t,{command:"perf",positionals:e.req.positionals??[],flags:e.req.flags??{},result:r})}function aP(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 aL(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 aO=`logs requires ${e6.slice(0,-1).join(", ")}, or ${e6.at(-1)}`,aE=["dump","log"],aC=`network requires ${aE.join(" or ")}`,a$=`network include mode must be one of: ${ts.join(", ")}`,aV={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})=>aB(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})=>aH(e,t,r,a),start:({session:e,sessionName:t,sessionStore:r})=>aK(e,t,r),stop:({session:e,sessionName:t,sessionStore:r})=>aj(e,t,r)};async function aU(e){let{req:t}=e;return"perf"===t.command?aF(e):"logs"===t.command?aT(e):"network"===t.command?az(e):null}async function aF(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 ah({req:r,sessionName:a,sessionStore:n,session:l,androidAdbExecutor:i,area:u}):await a_(e,l);let p=function(e){var t,r,a,n,i,l,u,p,d,c;let f,m,h=e4(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&&eY(e)?e:new s("INVALID_ARGS",e5)}(e.flags?.kind);if(w instanceof s)return{ok:!1,error:o(w)};let y=(t=h,r=g,("memory"===t?aG(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"):eZ(u)?void 0:E("INVALID_ARGS",e2):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 a_(e,l);try{return{ok:!0,data:await aq(e,l,p)}}catch(e){return{ok:!1,error:o(e)}}}async function aq(e,t,r){let{sessionName:a,sessionStore:n,androidAdbExecutor:i}=e;return"memory"===r.area?await r5(t,{action:function(e){if(aG(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 r2(t,{androidAdb:i}):await r3(t,{androidAdb:i})}function aG(e){return"sample"===e||"snapshot"===e}async function aT(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,e6.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",aO));return l.ok?await aV[l.action]({...e,session:s,restart:l.restart}):l}async function aB(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 aH(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 aK(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 aj(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 az(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(!aE.includes(i))return E("INVALID_ARGS",aC);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 ts.includes(a)?{ok:!0,include:a}:E("INVALID_ARGS",a$)}(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,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}}}function aW(e,t,r){var a,n;if(null==e)return t$("open",[tq(tU(t,"launchApp"),r)]);if("string"==typeof e)return t$("open",[tq(e,r)]);if(!tV(e))throw new s("INVALID_ARGS","launchApp expects a string or map.");tF(e,"launchApp",["appId","stopApp","clearState","clearKeychain","arguments","permissions","launchArguments"]),aZ(e,"permissions"),aZ(e,"clearKeychain");let i=tq("string"==typeof e.appId?e.appId:tU(t,"launchApp"),r),o=(a=e,n=r,[...aX(a.arguments,"launchApp.arguments",n),...aX(a.launchArguments,"launchApp.launchArguments",n)]),l=!0===e.clearState;return t$("open",[i],{...!l&&(!0===e.stopApp||o.length>0)?{relaunch:!0}:{},...l?{clearAppState:!0}:{},...o.length>0?{launchArgs:o}:{}})}function aJ(e,t,r){if(null==e)return t$("close",[tq(tU(t,"stopApp"),r)]);if("string"==typeof e)return t$("close",[tq(e,r)]);throw new s("INVALID_ARGS","stopApp expects a string appId or no value.")}function aX(e,t,r){if(null==e)return[];if("string"==typeof e)return[tq(e,r)];if(Array.isArray(e))return e.map((e,a)=>aY(e,`${t}[${a}]`,r));if(tV(e))return Object.entries(e).flatMap(([e,a])=>[tq(e,r),aY(a,`${t}.${e}`,r)]);throw new s("INVALID_ARGS",`${t} expects a string, list, or map.`)}function aY(e,t,r){if("string"==typeof e)return tq(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 aZ(e,t){if(void 0!==e[t])throw tB(`Maestro launchApp field "${t}" is not supported yet.`)}let aQ="__maestroRunScript",a0="__maestroAssertVisible",a1="__maestroAssertNotVisible",a3="__maestroPressEnter",a2="__maestroWaitForAnimationToEnd",a5="__maestroScrollUntilVisible",a4="__maestroSwipeScreen",a6="__maestroSwipeOn",a8="__maestroTapOn",a7="__maestroTapPointPercent";function a9(e){if(null==e)return t$("type",["\b".repeat(50)]);if("number"==typeof e&&Number.isInteger(e)&&e>0)return t$("type",["\b".repeat(e)]);if(!tV(e))throw new s("INVALID_ARGS","eraseText expects empty, a positive count, or a map.");if(tF(e,"eraseText",["charactersToErase"]),void 0===e.charactersToErase)return t$("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 t$("type",["\b".repeat(e.charactersToErase)])}function ne(e){return"number"==typeof e&&Number.isFinite(e)?String(Math.max(16,Math.floor(e))):void 0}function nt(e,t){let r=e.toLowerCase();switch(r){case"up":case"down":case"left":case"right":return r;default:throw tB(`Maestro ${t} must be UP, DOWN, LEFT, or RIGHT.`)}}function nr(e){return nt(e,"swipe direction")}function na(e,t,r=[],a){if("string"==typeof e)return nn(tq(e,a));if(!tV(e))throw new s("INVALID_ARGS",`${t} expects a string or selector map.`);tF(e,t,["id","text","enabled","selected",...r]);let n=[],i=[];if("boolean"==typeof e.enabled&&i.push(no("enabled",String(e.enabled))),"boolean"==typeof e.selected&&i.push(no("selected",String(e.selected))),"string"==typeof e.id&&n.push(no("id",tq(e.id,a)),...i),"string"==typeof e.text&&0===n.length)return nn(tq(e.text,a),i);if("string"==typeof e.label&&0===n.length&&n.push(no("label",tq(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 nn(e,t=[]){return[[no("label",e),...t].join(" "),[no("text",e),...t].join(" "),[no("id",e),...t].join(" ")].join(" || ")}function ni(e){let t=ne(e.duration);return t?[t]:[]}function no(e,t){return`${e}=${JSON.stringify(t)}`}function ns(e){var t,r;if(!tV(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 nl(e){let t=ns(e)??{};return{...t,maestro:{...t.maestro??{},allowNonHittableCoordinateFallback:!0}}}function nu(e){let t={doubleTap:!0};return tV(e)&&"number"==typeof e.delay&&Number.isInteger(e.delay)&&(t.intervalMs=Math.max(0,e.delay)),t}class np{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 nd(e,t,r){return{...t$(e,t),replayControl:r}}function nc(e,t,r){let a="string"==typeof e?tq(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 nf=`
2
2
  const fs = require('node:fs');
3
3
  const input = JSON.parse(fs.readFileSync(0, 'utf8'));
4
4
  if (typeof fetch !== 'function') {
@@ -19,10 +19,10 @@ fetch(input.url, {
19
19
  console.error(error && error.stack ? error.stack : String(error));
20
20
  process.exit(1);
21
21
  });
22
- `;function nm(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,nh)}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 nh(e,t){return"__proto__"===e||"constructor"===e||"prototype"===e?void 0:t}let ng={launchApp:({value:e,config:t,context:r})=>[aW(e,t,r)],tapOn:({value:e,context:t})=>[function(e,t){if("string"==typeof e)return t$(a4,[nn(tF(e,t))],nl(e));if(tV(e)&&"string"==typeof e.point){tq(e,"tapOn",["point","repeat","delay","optional","label"]);let t=tT(e.point);return"percent"===t.kind?t$(a7,[String(t.x),String(t.y)],ns(e)):t$("click",[String(t.x),String(t.y)],ns(e))}tV(e)&&tq(e,"tapOn",["id","text","childOf","enabled","index","selected","repeat","delay","optional","label"]);let r=nl(e);return t$(a4,[na(e,"tapOn",["repeat","delay","optional","label","index","childOf"],t),...function(e,t){if(!tV(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=na(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(tV(e)&&"string"==typeof e.point){tq(e,"doubleTapOn",["point","delay"]);let t=tL(e.point);return t$("click",[String(t.x),String(t.y)],nu(e))}return tV(e)&&tq(e,"doubleTapOn",["id","text","enabled","selected","delay"]),t$("click",[na(e,"doubleTapOn",["delay"],t)],nu(e))}(e,t)],longPressOn:({value:e,context:t})=>[function(e,t){if(tV(e)&&"string"==typeof e.point){tq(e,"longPressOn",["point"]);let t=tL(e.point);return t$("longpress",[String(t.x),String(t.y),"3000"])}return tV(e)&&tq(e,"longPressOn",["id","text","enabled","selected"]),t$("click",[na(e,"longPressOn",[],t)],{holdMs:3e3})}(e,t)],inputText:({value:e,context:t})=>[t$("type",[tF(function(e){if("string"==typeof e)return e;if(!tV(e))throw new s("INVALID_ARGS","inputText expects a string or map.");if(tq(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})=>[a9(e)],pasteText:({value:e,context:t,name:r})=>[t$("type",[tF(tG(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=tF((l=n,u=s,"string"==typeof l?l:tV(l)?(tq(l,u,["link"]),tG(`${u}.link`,l.link)):tG(u,l)),o),("ios"===o.platform||"android"===o.platform)&&i.appId?t$("open",[tF(tU(i,s),o),p],"ios"===o.platform?{maestro:{prewarmRunnerBeforeOpen:!0}}:void 0):t$("open",[p]))]},assertVisible:({value:e,context:t,name:r})=>[t$(a0,[na(e,r,[],t),"17000"])],assertNotVisible:({value:e,context:t,name:r})=>[t$(a1,[na(e,r,[],t)])],extendedWaitUntil:({value:e,context:t})=>(function(e,t){if(!tV(e))throw new s("INVALID_ARGS","extendedWaitUntil expects a map.");tq(e,"extendedWaitUntil",["visible","notVisible","timeout"]);let r=e.visible??e.notVisible;if(void 0===r)throw tB("Only Maestro extendedWaitUntil.visible/notVisible is supported.");let a=na(r,"extendedWaitUntil",[],t),n=String(tH(e,17e3));return void 0!==e.notVisible?[t$(a1,[a,n])]:[t$(a0,[a,n],{maestro:{allowAlreadyPastLoading:!0}})]})(e,t),takeScreenshot:({value:e,context:t,name:r})=>[t$("screenshot",[tF(tG(r,e),t)])],scroll:({value:e})=>[function(e){if(null!=e)throw tB("Maestro scroll options are not supported yet.");return t$("scroll",["down"])}(e)],scrollUntilVisible:({value:e,context:t})=>(function(e,t){if("string"==typeof e)return[t$(a5,[nn(tF(e,t)),"5000","down"])];if(!tV(e))throw new s("INVALID_ARGS","scrollUntilVisible expects a string or map.");tq(e,"scrollUntilVisible",["element","direction","timeout"]);let r=na(e.element,"scrollUntilVisible.element",[],t),a="string"==typeof e.direction?nt(e.direction,"scrollUntilVisible.direction"):"down";return[t$(a5,[r,String(tH(e,5e3)),a])]})(e,t),swipe:({value:e,context:t})=>[function(e,t){var r,a,n;let i;if(!tV(e))throw new s("INVALID_ARGS","swipe expects a map.");tq(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=nr("string"==typeof r.direction?r.direction:"up"),t$(a6,[na(a,"swipe.from",[],n),i,...ni(r)])):"string"==typeof e.direction?t$(a8,["direction",nr(e.direction),...ni(e)]):function(e){let{start:t,end:r}=function(e){if("string"==typeof e.start&&"string"==typeof e.end)return{start:tT(e.start),end:tT(e.end)};throw tB("Only Maestro swipe start/end coordinates are supported.")}(e);var a=t,n=r,i=ne(e.duration);if("absolute"===a.kind&&"absolute"===n.kind)return t$("swipe",[String(a.x),String(a.y),String(n.x),String(n.y),...i?[i]:[]]);if("percent"===a.kind&&"percent"===n.kind)return t$(a8,["percent",String(a.x),String(a.y),String(n.x),String(n.y),...i?[i]:[]]);throw tB("Maestro swipe start/end must both be absolute pixels or both be percentages.")}(e)}(e,t)],hideKeyboard:()=>[t$("keyboard",["dismiss"])],pressKey:({value:e})=>[function(e){let t=tG("pressKey",e).toLowerCase();if("back"===t)return t$("back");if("enter"===t||"return"===t)return t$(a2);if("home"===t)return t$("home");throw tB(`Maestro pressKey "${t}" is not supported yet.`)}(e)],back:()=>[t$("back")],waitForAnimationToEnd:({value:e})=>[t$(a3,[String(tH(e,15e3))])],stopApp:({value:e,config:t,context:r})=>[aJ(e,t,r)],runScript:({value:e,context:t})=>{let a;return[t$(aQ,[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:tF(e,t),env:{}};if(!tV(e))throw new s("INVALID_ARGS","runScript expects a file path string or map.");return tq(e,"runScript",["file","env"]),{file:tF(tG("runScript.file",e.file),t),env:Object.fromEntries(Object.entries(tk(e.env,"runScript.env")).map(([e,r])=>[e,tF(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(tF(e,r),r).actions;if(!tV(e))throw new s("INVALID_ARGS","runFlow expects a file path string or map.");tq(e,"runFlow",["file","commands","env","when","label"]);let i=function(e,t){var r,a;if(null==e)return{shouldRun:!0};if(!tV(e))throw new s("INVALID_ARGS","runFlow.when expects a map.");return(tq(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 np(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=tF(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:na(r.visible,"runFlow.when.visible",[],a)}:{},...void 0!==r.notVisible?{notVisibleSelector:na(r.notVisible,"runFlow.when.notVisible",[],a)}:{}})}}(e.when,r);if(!i.shouldRun)return[];let o={...r,env:{...r.env,...tk(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 tB("Maestro runFlow.when cannot combine visible and notVisible yet.");let n=r?"visible":"notVisible",i=r??a??"";return[nd("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(tF(e.file,r),r).actions;if(Array.isArray(e.commands))return n(tR(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,nv),repeat:({value:e,config:t,context:r,deps:a})=>(function(e,t,r,a,n){var i;if(!tV(e))throw new s("INVALID_ARGS","repeat expects a map.");if(tq(e,"repeat",["times","commands","while"]),void 0!==e.while)throw tB("Maestro repeat.while is not supported yet. Only deterministic repeat.times is supported.");let o=(i=e.times,nc(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=tR(e.commands);return Array.from({length:o}).flatMap(()=>n(l,t,r,a))})(e,t,r,a,nv),retry:({value:e,config:t,context:r,deps:a})=>(function(e,t,r,a,n){var i,o;if(!tV(e))throw new s("INVALID_ARGS","retry expects a map.");if(tq(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:nc(i,o,"retry.maxRetries")),u=n(tR(e.commands),t,r,a);return[nd("retry",[String(l)],{kind:"retry",maxRetries:l,actions:u})]})(e,t,r,a,nv)},nw={launchApp:(e,t)=>[aW(void 0,e,t)],scroll:()=>[t$("scroll",["down"])],hideKeyboard:()=>[t$("keyboard",["dismiss"])],eraseText:()=>[a9(void 0)],back:()=>[t$("back")],waitForAnimationToEnd:()=>[t$(a3,["15000"])],stopApp:(e,t)=>[aJ(void 0,e,t)]};function ny(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=nw[n])?a(i,o):t_(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=ng[u];return d?d({value:p,config:t,context:r,deps:a,name:u}):t_(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 nv(e,t,r,a){return e.flatMap((e,n)=>ny(e,t,n+1,r,a))}function nA(e,t){let{config:r,commands:a}=nS(tP(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=ny(r,t,a,n,{parseRunFlowFile:nI});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!==a2||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!==a4)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 nS(e){if(0===e.length)throw new s("INVALID_ARGS","Maestro flow is empty.");if(Array.isArray(e[0]))return{config:{},commands:tR(e[0])};let t=function(e){if(!tV(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}:{},...tV(e.env)?{env:tk(e.env,"env")}:{},...Array.isArray(e.onFlowStart)?{onFlowStart:tR(e.onFlowStart)}:{},...Array.isArray(e.onFlowComplete)?{onFlowComplete:tR(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:tR(r)}}function nI(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),nA(i,{...a,baseDir:r.dirname(n),visitedPaths:o})}let nb=/[*?[\]{}]/;function n_(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 nk(e,t){return"number"==typeof e?e:t}function nN(e,t){let r="number"==typeof e?e:t;return"number"!=typeof r?0:Math.max(0,Math.min(3,r))}function nD(e,a,n){var i,o;let l=em.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,!nb.test(i)&&(o=l,!nb.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 nR(e,t){let r=nx(e),a=nx(t);return r!==a?r-a:e.localeCompare(t)}function nx(e){return+(".ad"===r.extname(e))}function nM(e){return[...new Set(e.map(e=>r.normalize(e)))]}function nP(e){return"maestro"===e}let nL=["failed to start daemon","runner did not accept connection","xcodebuild exited early","device is offline","device offline","device unauthorized"];function nO(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(),nL.some(e=>o.includes(e))))}async function nE(e){let a,n,{filePath:i,sessionName:s,requestId:l,parentRequestId:u,timeoutMs:p,platform:d,target:c,artifactsDir:f,shard:m,runReplay:h,cleanupSession:g,finalizeAttempt:w}=e;O(l);let y=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),v=new Set,A=!1,S=Date.now(),I=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),nU(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:v,filePath:i,sessionName:s,requestId:l,timeoutMs:p,platform:d,target:c}),b=h({filePath:i,sessionName:s,platform:d,target:c,requestId:l,artifactsDir:f,artifactPaths:v,tracePath:I,shard:m}).catch(e=>({ok:!1,error:o(e)})).finally(()=>{y(),eO(l)});try{n="number"==typeof p?await Promise.race([b,new Promise(e=>{a=setTimeout(()=>{A=!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,[...v]))},p)})]):await b,nU(I,{type:"replay_test_attempt_stop",ts:new Date().toISOString(),session:s,ok:n.ok,timedOut:A,durationMs:Date.now()-S,errorCode:n.ok?void 0:n.error.code})}finally{var _,k,N;let e,t;a&&clearTimeout(a),A&&(await nC(b)||((_=n)&&!_.ok&&(_.error.details={..._.error.details??{},reason:"timeout_cleanup_pending",timeoutCleanupPending:!0}),tv({level:"warn",phase:"test_timeout_cleanup_race",data:{session:s,requestId:l,graceMs:2e3}}),n$({replayPromise:b,cleanupSession:g,sessionName:s,requestId:l})));let r=await nV({finalizeAttempt:w,sessionName:s,artifactPaths:v,artifactsDir:f,tracePath:I});n?.ok&&r&&!r.ok&&(k=n,N=`Replay test finalization failed: ${r.error.message}`,t=Array.isArray((e=k.data??={}).warnings)?e.warnings.filter(e=>"string"==typeof e):[],e.warnings=[...t,N]);let i=Date.now();try{nU(I,{type:"replay_test_cleanup_start",ts:new Date().toISOString(),session:s}),await g(s),nU(I,{type:"replay_test_cleanup_stop",ts:new Date().toISOString(),session:s,ok:!0,durationMs:Date.now()-i})}catch(t){let e=o(t);nU(I,{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 nC(e){return await Promise.race([e.then(()=>!0),n(2e3).then(()=>!1)])}async function n$(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 nV(e){let{finalizeAttempt:t,sessionName:r,artifactPaths:a,artifactsDir:n,tracePath:i}=e;if(!t)return;let s=Date.now();nU(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 nU(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 nU(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 nU(e,r){e&&t.appendFileSync(e,`${JSON.stringify(r)}
24
- `)}async function nq(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 nF(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,...nB(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),...nT(u.data?.snapshotDiagnostics),...function(e){return nB(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,...nB(u)}),{file:o.path,title:o.title,session:r.finalSessionName,status:"failed",durationMs:a,attempts:r.attempts,artifactsDir:t.testArtifactsDir,error:p,...nT((i=r.finalResponse,i?.ok?i.data?.snapshotDiagnostics:i?.error.details?.snapshotDiagnostics)),...function(e){return nB(e)}(u)}}(t,a,n,i)}async function nF(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:n_(a,n,r.path,i),artifactsDir:t.testArtifactsDir,...nB(l)})}(e,t);let r={finalSessionName:"",attempts:0,finalAttemptDurationMs:0,attemptFailures:[]};for(let d=0;d<=e.retries&&!ey(e.requestId);d+=1){var a,n,i,o,s,l,u,p;let c=await nG(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||ey(i.requestId)||nO(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,...nB(l.shard)})}return r}async function nG(e,a,n){var i;let{entry:o,sessionName:s,suiteInvocationId:l,caseIndex:u,requestId:p,timeoutMs:d,shard:c}=e,f=n+1,m=Date.now(),h=n_(s,l,o.path,u,n),g=r.join(a.testArtifactsDir,`attempt-${f}`);i=o.path,t.mkdirSync(g,{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,g);let w=function(e){let{requestId:t,suiteInvocationId:a,filePath:n,caseIndex:i,attemptIndex:o,shardIndex:s}=e,l=void 0===s?"":`:shard:${s+1}`;return ev(`${t??a}${l}:test:${i+1}:${r.basename(n)}:attempt:${o+1}`,a)}({requestId:p,suiteInvocationId:l,filePath:o.path,caseIndex:u,attemptIndex:n,shardIndex:c?.shardIndex}),y=await nE({filePath:o.path,sessionName:h,requestId:w,parentRequestId:p,timeoutMs:d,platform:o.metadata.platform,target:o.metadata.target,artifactsDir:g,shard:c,runReplay:e.runReplay,cleanupSession:e.cleanupSession,finalizeAttempt:e.finalizeAttempt}),v=Date.now()-m;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:y,filePath:o.path,sessionName:h,attempts:f,maxAttempts:a.maxAttempts,attemptArtifactsDir:g}),{response:y,sessionName:h,attempt:f,durationMs:v}}function nT(e){let t=tY(e);return t?{snapshotDiagnostics:t}:{}}function nB(e){return e?{shardIndex:e.shardIndex,shardCount:e.shardCount,deviceId:e.device.id}:{}}async function nH(e,t,r){let a=function(e){let t=nK(e?.shardAll,"--shard-all"),r=nK(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 nj(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 nK(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 nj(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 ef((a=e,f=tm(a?.androidDeviceAllowlist),{platform:a?.platform,target:a?.target,iosSimulatorSetPath:ti({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=nW(e),r=l.find(r=>nz(r,p)&&(r.id===e||nW(r.name)===t));if(!r)throw new s("DEVICE_NOT_FOUND",`No shard device matched ${e}`);return r})):n.filter(e=>{var t;return!!nz(t=e,o)&&("ios"===t.platform||"android"===t.platform)&&!1!==t.booted}).sort(nJ));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 nz(e,t){return!(!tl(e.platform,t?.platform)||t?.target&&(e.target??"mobile")!==t.target)}function nW(e){return e.toLowerCase().replace(/_/g," ").replace(/\s+/g," ").trim()}function nJ(e,t){return e.id.localeCompare(t.id)}async function nY(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 nX(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 nZ({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 n1({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=tZ(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 nX(e){var a,n,i,o;let l=function(e){let{inputs:a,cwd:n,platformFilter:i,replayBackend:o}=e,l=new Set(nP(o)?[".yaml",".yml",".ad"]:[".ad"]),u=function(e,a,n,i){if(!nP(i))return[...new Set(e.flatMap(e=>nD(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=em.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"}:nD(e,a,n)}(i,a,n);"file"===e.source?o.push(...e.paths):s.push("directory"===e.source?nM(e.paths):e.paths.map(e=>r.normalize(e)).sort(nR))}return nM([...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=tO(a),s=(d=a,c=e,nP(o)&&".ad"!==r.extname(c)?function(e){let{config:t}=nS(tP(e));return t.name}(d):void 0);if(!i){p.push({kind:"run",path:e,title:s,metadata:n});continue}if(!n.platform){nP(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 nH(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=em.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 nZ(e){return(await Promise.allSettled(e.shards.map(async t=>await nQ({...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:n0(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 nQ(e){let{shard:t,sessionName:r}=e;return await n2({...e,entries:t.entries,sessionName:n0(r,t),shard:t})}function n0(e,t){return`${e}:shard-${t.shardIndex+1}`}async function n1(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(ey(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 nq({entry:m,sessionName:r,suiteInvocationId:a,caseIndex:f-1,cwd:n,requestId:i,retries:nN(o?.retries,m.metadata.retries),timeoutMs:nk(o?.timeoutMs,m.metadata.timeoutMs),suiteArtifactsDir:s,suiteIndex:e+1,suiteTotal:l,runReplay:u,cleanupSession:p,finalizeAttempt:d});if(c.push(t),n3(t,o,i))break}return c}async function n2(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(ey(i))break;let{entry:t,suiteIndex:h}=m,g=await nq({entry:t,sessionName:r,suiteInvocationId:a,caseIndex:e,cwd:n,requestId:i,retries:nN(o?.retries,t.metadata.retries),timeoutMs:nk(o?.timeoutMs,t.metadata.timeoutMs),suiteArtifactsDir:s,suiteIndex:h,suiteTotal:l,shard:u,runReplay:p,cleanupSession:d,finalizeAttempt:c});if(f.push(g),n3(g,o,i))break}return f}function n3(e,t,r){return ey(r)||t?.failFast===!0||nO(e)}let n5={maestro:{parse:function(e,t={}){var a;let n;return nA(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:tx(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=tQ(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 n6(e){let{action:t,sessionName:r,logPath:a,sessionStore:n}=e;if(!(ra(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),ra(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&&n4(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}=t8(e.positionals);r&&t.push(r.selectorExpression)}if("wait"===e.command){let{selectorExpression:r}=n8(e.positionals??[]);r&&t.push(r)}return B(t).filter(e=>e.trim().length>0)})(t).map(e=>t5(e)).filter(e=>null!==e);if(0===o.length)return null;let s=ra(t.command)||"fill"===t.command,l=ra(t.command)||"fill"===t.command||"get"===t.command&&t.positionals?.[0]==="text",u=await n7(i,t,a,s,n);for(let e of o){let r=t6(u.nodes,e,{platform:i.device.platform,requireRect:s,requireUnique:!0,disambiguateAmbiguous:l});if(!r)continue;let a=t4(r.node,i.device.platform,{action:"fill"===t.command?"fill":ra(t.command)?"click":"get"}).join(" || ");if(ra(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&&n4(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}=t8(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 n4(e){return void 0!==e&&""!==e.trim()&&Number.isFinite(Number(e))}async function n7(e,t,r,a,n){let i=eu(await p(e.device,"snapshot",[],t.flags?.out,{...ec(r,{...t.flags??{},snapshotInteractiveOnly:a},e.appBundleId,e.trace?.outPath)}),{...t.flags??{},snapshotInteractiveOnly:a});return H(e,i),n.set(e.name,e),i}let n9=.35,ie=120,it=360,ir=8;function ia(e,t){return Math.round(Math.min(it,Math.max(ie,"number"==typeof e?e*n9:0,1.5*t)))}let ii=new WeakMap,io=new WeakMap,is=new WeakMap;function il(e,t,r){return{ok:!1,error:{code:e,message:t,...r?{details:r}:{}}}}async function iu(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=Q(ip(n.data)))&&ii.set(t,r)),n}function ip(e){return Array.isArray(e?.nodes)?e:void 0}function id(e,t){e&&io.set(e,{selector:t})}function ic(e){e&&is.delete(e)}let im=new Map([["button",0],["link",0],["textfield",0],["textview",0],["searchfield",0],["switch",0],["slider",0],["cell",1],["statictext",2]]);function ih(e,t,r,a,n,i={}){let o=iA(e,t,a);if(r.childOf){let t=iA(e,r.childOf,a);if(0===t.length)return{ok:!1,message:`Maestro childOf parent did not match: ${r.childOf}`};let n=t7(e.nodes);o=o.filter(r=>t.some(t=>t2(e.nodes,r,t,n)))}let s=iw({nodes:e.nodes,matches:o,platform:a}),l=ib(e.nodes,s.matches,r.index,iv(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 ig(e,t,r,a){let n=iA(e,t,r,{allowLeadingCompositeLabelMatch:!1}),i=iw({nodes:e.nodes,matches:n,platform:r}),o=ib(e.nodes,i.matches,void 0,iv(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 iw(e){let t=e.matches.filter(t=>rr({predicate:"visible",node:t,nodes:e.nodes,platform:e.platform}).pass),r=function(e,t,r){let a=tr(e);if(!a.detected||!a.redBox)return{matches:t,blockedByReactNativeOverlay:!1};let n=tt(a),i=n.filter(t=>rr({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 iy(e){return e?.platform==="android"?"android":"ios"}function iv(e){let t=t3(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 iA(e,t,r,a={}){for(let n of t3(t).selectors){let t=e.nodes.filter(e=>(function(e,t,r,a){return!!t9(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?t9(e,{raw:t.key,terms:[t]},r):iS((i=e,"id"===(o=t.key)?i.identifier:"label"===o?i.label:"value"===o?i.value:t0(i)),t.value,a)})(e,t,r,a))})(e,n,r,a));if(t.length>0)return t}return[]}function iS(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 iI(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 ib(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,R,x,M,P=t7(e),L=(l=e,u=t,p=P,d=a,c=r,f=n,m=i,x=(R=(D=u.map(e=>{var t;let r;return(r=iI(l,t=e,p))?{node:t,rect:r.rect,inheritedRect:r.inherited}:null}).filter(e=>!!e)).filter(e=>!e.inheritedRect)).length>0?R:D,d&&void 0===c?(h=x,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===iO(e.node,r));if(n.length>=2){let t=ik(e,n,r,a);if(t)return t}let i=t.filter(e=>1===iO(e.node,r));return n.length>0||i.length<2?null:ik(e,i,r,a)}(o,s,l,p)??i_(o,s,l,p):i_(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,R;if(a=t,n=r,!(("cell"===(S=re(a.node.type??""))||"other"===S||"scrollview"===S||"scroll-area"===S)&&!(a.rect.width<120)&&!(a.rect.height<32)&&!(a.rect.height>80)&&1>=iO(a.node,n)))return null;let x=(i=e,o=t,s=r,l=t7(e),i.filter(e=>{var t,r,a;let n;return e.index!==o.node.index&&!!e.rect&&t2(i,e,o.node,l)&&(t=e,r=o.rect,a=s,!("button"!==(n=re(t.type??""))&&"cell"!==n&&"other"!==n||1>=iO(t,a))&&!(t.rect.width<16)&&!(t.rect.height<16)&&!!iP(r,t.rect)&&ix(r,t.rect)>=.5)}).sort((e,t)=>e.rect.x-t.rect.x));if(0===x.length)return null;let M=(b=Math.floor((I=[...x.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,x.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"===re(h.node.type??"")&&1>=iO(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),R=N.some(e=>{var t;return t=u.rect,1>Math.abs(e.x-t.x)}),D&&!R?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,(iM(_.node)?null:t1(b,_.node,k,e=>{if(!iM(e))return null;let t=iI(b,e,k);return t&&function(e,t,r){var a,n;if(!iP(t,e)||(a=e,!((n=t).height<32||n.height>80||a.height<.75*n.height||.75>ix(a,n))&&!(n.width<240)&&n.width>=3*a.width))return!1;let i=iD(t),o=iD(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 i_(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===iO(e.node,r));if(l.length<2)return t;let u=t7(e),p=l.map(t=>({candidate:t,container:iN(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&&iL(t.container.rect,e.container.rect)>=.6)});if(d.length<2)return t;let c=(o=Math.max(...i=(n=d).map(e=>iD(e.container.rect))),(s=Math.min(...i))<=0||o<1.2*s?[]:n.filter(e=>iD(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=iN(e,r.node,a),i=n&&iP(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>iL(e.rect,r.rect)?1/0:Math.abs(e.index-r.index);if(iL(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=iO(e.node,r)-iO(t.node,r);if(0!==a)return a}let a=iR(e.node)-iR(t.node);if(0!==a)return a;let n=Number(e.inheritedRect)-Number(t.inheritedRect);if(0!==n)return n;let i=r&&iR(e.node)===iR(t.node)?iD(t.rect)-iD(e.rect):iD(e.rect)-iD(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 ik(e,t,r,a){let n=t7(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||!iP(i.rect,o.rect)||iD(i.rect)<2*iD(o.rect))&&t2(a,o.node,i.node,s)})});return i_(e,i,r,a)}function iN(e,t,r){return t1(e,t,r,e=>{let t;return!e.rect||"scrollview"!==(t=re(e.type??""))&&"scroll-area"!==t&&"list"!==t||e.rect.width<240||e.rect.height<320?null:e})}function iD(e){return e.width*e.height}function iR(e){return im.get(re(e.type??""))??3}function ix(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 iM(e){let t=re(e.type??"");return!0===e.hittable||"button"===t||"link"===t||"cell"===t||"textfield"===t||"searchfield"===t||"switch"===t||"slider"===t}function iP(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 iL(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(iD(e),iD(t)))}function iO(e,t){let r=[e.label,t0(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=>iS(e,t))?2:3}async function iE(e){let t=iz(e.positionals,{command:"assertVisible",defaultTimeoutMs:17e3});if(!t.ok)return t.response;let r=ij(e.baseReq,t.selector);return r?await iC(e,t,r):await iV(e,t)}async function iC(e,t,r){let a=Date.now(),n=await i$(e,t,r);if(n.ok){var i;if(i=e.baseReq,i.flags?.platform==="android"){let r=await iW(e,t.selector,"assertVisible");if(!r.visible){let n=iK(e.baseReq,t,r,a);return"return"===n.kind?n.response:await iV(e,t)}}return id(e.scope,t.selector),iX({ok:!0,data:{selector:t.selector,nativeWait:!0,query:r,response:n.data}},t.selector,a)}return await iU(e,t,n,a)}async function i$(e,t,r){return await e.invoke({...e.baseReq,command:"wait",positionals:[r,String(t.timeoutMs)]})}async function iV(e,t){let r,a,n=Date.now(),i=t.timeoutMs+1e3,o=!1;for(;;){let s=Date.now(),l=await iW(e,t.selector,"assertVisible");if(l.visible)return iX(l.response,t.selector,n);r=l.response,a=l.snapshot??a;let u=iK(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 ri(250)}let s=r??il("COMMAND_FAILED",`Expected visible but did not match: ${t.selector}`,{selector:t.selector,timeoutMs:t.timeoutMs}),l=await iq(e,t,a);return l||iZ(s,a,e.baseReq)}async function iU(e,t,r,a){let n=await iW(e,t.selector,"assertVisible");if(n.visible)return iX(n.response,t.selector,a);let i=iK(e.baseReq,t,n,a);if("return"===i.kind)return i.response;let o=await iq(e,t,n.snapshot);return o||iZ(r,n.snapshot,e.baseReq)}async function iq(e,t,r){if(e.baseReq.flags?.platform!=="android")return null;let a=function(e){if(!e)return;let t=is.get(e);return is.delete(e),t}(e.scope);return a?"tap"===a.kind?await iF(e,t,r,a):await iG(e,t,a):null}async function iF(e,t,r,a){if(!r)return null;let n=function(e,t,r){var a;let n,i=iy(e.baseReq.flags),o=Q(t),s=ih(t,r.selector,r.options??{},i,o,{promoteTapTarget:!0});if(s.ok)return{ok:!0,target:{kind:"point",point:eQ(s.rect)}};let l=iv(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 iB(e,n.target)).ok)?await iT(e,t,"retryTap"):null}async function iG(e,t,r){return(tv({level:"info",phase:"maestro_assert_visible_retry_swipe",data:{selector:t.selector,swipePositionals:r.positionals,timeoutMs:5e3}}),(await iH(e,r)).ok)?await iT(e,t,"retrySwipe"):null}async function iT(e,t,r){let a={...t,timeoutMs:Math.min(t.timeoutMs,5e3)},n=ij(e.baseReq,a.selector);if(!n)return await iV(e,a);let i=Date.now(),o=await i$(e,a,n);return o.ok?(id(e.scope,a.selector),iX({ok:!0,data:{selector:a.selector,nativeWait:!0,[r]:!0,query:n,response:o.data}},a.selector,i)):await iU(e,a,o,i)}async function iB(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 iH(e,t){return await e.invoke({...e.baseReq,command:"swipe",positionals:t.positionals})}function iK(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=iJ(iv(e));if(!iY(r))return!1;let a=t.nodes.flatMap(e=>[e.label,e.value,e.identifier]).filter(e=>!!e?.trim()).map(e=>iJ(e));return!a.some(e=>e.includes("something went wrong"))&&a.some(e=>e!==r&&!iY(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 ij(e,t){return e.flags?.platform!=="ios"&&e.flags?.platform!=="android"?null:iv(t)}function iz(e,t){let[r,a=String(t.defaultTimeoutMs)]=e;if(!r)return{ok:!1,response:il("INVALID_ARGS",`${t.command} requires a selector.`)};let n=Number(a);return!Number.isFinite(n)||n<0?{ok:!1,response:il("INVALID_ARGS",`${t.command} timeout must be a non-negative number.`)}:{ok:!0,selector:r,timeoutMs:n}}async function iW(e,t,r){let a=await iu(e);var n=e,i=t,o=r,s=a;if(!s.ok)return{visible:!1,response:s,infrastructureFailure:!0};let l=ip(s.data);if(!l)return{visible:!1,response:il("COMMAND_FAILED",`Unable to read snapshot data for ${o}.`),infrastructureFailure:!0};let u=ig(l,i,iy(n.baseReq.flags),Q(l));return u.ok?(id(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:il("COMMAND_FAILED",u.message,{selector:i}),infrastructureFailure:!1,snapshot:l}}function iJ(e){return e?.trim().toLowerCase().replace(/\u2026/g,"...")??""}function iY(e){return"loading"===e||"loading..."===e}function iX(e,t,r){return e.ok?{ok:!0,data:{selector:t,...e.data,waitedMs:Date.now()-r}}:e}function iZ(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)}
22
+ `;function nm(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,nh)}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 nh(e,t){return"__proto__"===e||"constructor"===e||"prototype"===e?void 0:t}let ng={launchApp:({value:e,config:t,context:r})=>[aW(e,t,r)],tapOn:({value:e,context:t})=>[function(e,t){if("string"==typeof e)return t$(a8,[nn(tq(e,t))],nl(e));if(tV(e)&&"string"==typeof e.point){tF(e,"tapOn",["point","repeat","delay","optional","label"]);let t=tT(e.point);return"percent"===t.kind?t$(a7,[String(t.x),String(t.y)],ns(e)):t$("click",[String(t.x),String(t.y)],ns(e))}tV(e)&&tF(e,"tapOn",["id","text","childOf","enabled","index","selected","repeat","delay","optional","label"]);let r=nl(e);return t$(a8,[na(e,"tapOn",["repeat","delay","optional","label","index","childOf"],t),...function(e,t){if(!tV(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=na(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(tV(e)&&"string"==typeof e.point){tF(e,"doubleTapOn",["point","delay"]);let t=tL(e.point);return t$("click",[String(t.x),String(t.y)],nu(e))}return tV(e)&&tF(e,"doubleTapOn",["id","text","enabled","selected","delay"]),t$("click",[na(e,"doubleTapOn",["delay"],t)],nu(e))}(e,t)],longPressOn:({value:e,context:t})=>[function(e,t){if(tV(e)&&"string"==typeof e.point){tF(e,"longPressOn",["point"]);let t=tL(e.point);return t$("longpress",[String(t.x),String(t.y),"3000"])}return tV(e)&&tF(e,"longPressOn",["id","text","enabled","selected"]),t$("click",[na(e,"longPressOn",[],t)],{holdMs:3e3})}(e,t)],inputText:({value:e,context:t})=>[t$("type",[tq(function(e){if("string"==typeof e)return e;if(!tV(e))throw new s("INVALID_ARGS","inputText expects a string or map.");if(tF(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})=>[a9(e)],pasteText:({value:e,context:t,name:r})=>[t$("type",[tq(tG(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=tq((l=n,u=s,"string"==typeof l?l:tV(l)?(tF(l,u,["link"]),tG(`${u}.link`,l.link)):tG(u,l)),o),("ios"===o.platform||"android"===o.platform)&&i.appId?t$("open",[tq(tU(i,s),o),p],"ios"===o.platform?{maestro:{prewarmRunnerBeforeOpen:!0}}:void 0):t$("open",[p]))]},assertVisible:({value:e,context:t,name:r})=>[t$(a0,[na(e,r,[],t),"17000"])],assertNotVisible:({value:e,context:t,name:r})=>[t$(a1,[na(e,r,[],t)])],extendedWaitUntil:({value:e,context:t})=>(function(e,t){if(!tV(e))throw new s("INVALID_ARGS","extendedWaitUntil expects a map.");tF(e,"extendedWaitUntil",["visible","notVisible","timeout"]);let r=e.visible??e.notVisible;if(void 0===r)throw tB("Only Maestro extendedWaitUntil.visible/notVisible is supported.");let a=na(r,"extendedWaitUntil",[],t),n=String(tH(e,17e3));return void 0!==e.notVisible?[t$(a1,[a,n])]:[t$(a0,[a,n],{maestro:{allowAlreadyPastLoading:!0}})]})(e,t),takeScreenshot:({value:e,context:t,name:r})=>[t$("screenshot",[tq(tG(r,e),t)])],scroll:({value:e})=>[function(e){if(null!=e)throw tB("Maestro scroll options are not supported yet.");return t$("scroll",["down"])}(e)],scrollUntilVisible:({value:e,context:t})=>(function(e,t){if("string"==typeof e)return[t$(a5,[nn(tq(e,t)),"5000","down"])];if(!tV(e))throw new s("INVALID_ARGS","scrollUntilVisible expects a string or map.");tF(e,"scrollUntilVisible",["element","direction","timeout"]);let r=na(e.element,"scrollUntilVisible.element",[],t),a="string"==typeof e.direction?nt(e.direction,"scrollUntilVisible.direction"):"down";return[t$(a5,[r,String(tH(e,5e3)),a])]})(e,t),swipe:({value:e,context:t})=>[function(e,t){var r,a,n;let i;if(!tV(e))throw new s("INVALID_ARGS","swipe expects a map.");tF(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=nr("string"==typeof r.direction?r.direction:"up"),t$(a6,[na(a,"swipe.from",[],n),i,...ni(r)])):"string"==typeof e.direction?t$(a4,["direction",nr(e.direction),...ni(e)]):function(e){let{start:t,end:r}=function(e){if("string"==typeof e.start&&"string"==typeof e.end)return{start:tT(e.start),end:tT(e.end)};throw tB("Only Maestro swipe start/end coordinates are supported.")}(e);var a=t,n=r,i=ne(e.duration);if("absolute"===a.kind&&"absolute"===n.kind)return t$("swipe",[String(a.x),String(a.y),String(n.x),String(n.y),...i?[i]:[]]);if("percent"===a.kind&&"percent"===n.kind)return t$(a4,["percent",String(a.x),String(a.y),String(n.x),String(n.y),...i?[i]:[]]);throw tB("Maestro swipe start/end must both be absolute pixels or both be percentages.")}(e)}(e,t)],hideKeyboard:()=>[t$("keyboard",["dismiss"])],pressKey:({value:e})=>[function(e){let t=tG("pressKey",e).toLowerCase();if("back"===t)return t$("back");if("enter"===t||"return"===t)return t$(a3);if("home"===t)return t$("home");throw tB(`Maestro pressKey "${t}" is not supported yet.`)}(e)],back:()=>[t$("back")],waitForAnimationToEnd:({value:e})=>[t$(a2,[String(tH(e,15e3))])],stopApp:({value:e,config:t,context:r})=>[aJ(e,t,r)],runScript:({value:e,context:t})=>{let a;return[t$(aQ,[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:tq(e,t),env:{}};if(!tV(e))throw new s("INVALID_ARGS","runScript expects a file path string or map.");return tF(e,"runScript",["file","env"]),{file:tq(tG("runScript.file",e.file),t),env:Object.fromEntries(Object.entries(tk(e.env,"runScript.env")).map(([e,r])=>[e,tq(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(tq(e,r),r).actions;if(!tV(e))throw new s("INVALID_ARGS","runFlow expects a file path string or map.");tF(e,"runFlow",["file","commands","env","when","label"]);let i=function(e,t){var r,a;if(null==e)return{shouldRun:!0};if(!tV(e))throw new s("INVALID_ARGS","runFlow.when expects a map.");return(tF(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 np(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=tq(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:na(r.visible,"runFlow.when.visible",[],a)}:{},...void 0!==r.notVisible?{notVisibleSelector:na(r.notVisible,"runFlow.when.notVisible",[],a)}:{}})}}(e.when,r);if(!i.shouldRun)return[];let o={...r,env:{...r.env,...tk(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 tB("Maestro runFlow.when cannot combine visible and notVisible yet.");let n=r?"visible":"notVisible",i=r??a??"";return[nd("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(tq(e.file,r),r).actions;if(Array.isArray(e.commands))return n(tx(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,nv),repeat:({value:e,config:t,context:r,deps:a})=>(function(e,t,r,a,n){var i;if(!tV(e))throw new s("INVALID_ARGS","repeat expects a map.");if(tF(e,"repeat",["times","commands","while"]),void 0!==e.while)throw tB("Maestro repeat.while is not supported yet. Only deterministic repeat.times is supported.");let o=(i=e.times,nc(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=tx(e.commands);return Array.from({length:o}).flatMap(()=>n(l,t,r,a))})(e,t,r,a,nv),retry:({value:e,config:t,context:r,deps:a})=>(function(e,t,r,a,n){var i,o;if(!tV(e))throw new s("INVALID_ARGS","retry expects a map.");if(tF(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:nc(i,o,"retry.maxRetries")),u=n(tx(e.commands),t,r,a);return[nd("retry",[String(l)],{kind:"retry",maxRetries:l,actions:u})]})(e,t,r,a,nv)},nw={launchApp:(e,t)=>[aW(void 0,e,t)],scroll:()=>[t$("scroll",["down"])],hideKeyboard:()=>[t$("keyboard",["dismiss"])],eraseText:()=>[a9(void 0)],back:()=>[t$("back")],waitForAnimationToEnd:()=>[t$(a2,["15000"])],stopApp:(e,t)=>[aJ(void 0,e,t)]};function ny(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=nw[n])?a(i,o):t_(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=ng[u];return d?d({value:p,config:t,context:r,deps:a,name:u}):t_(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 nv(e,t,r,a){return e.flatMap((e,n)=>ny(e,t,n+1,r,a))}function nA(e,t){let{config:r,commands:a}=nS(tP(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=ny(r,t,a,n,{parseRunFlowFile:nI});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!==a3||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!==a8)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 nS(e){if(0===e.length)throw new s("INVALID_ARGS","Maestro flow is empty.");if(Array.isArray(e[0]))return{config:{},commands:tx(e[0])};let t=function(e){if(!tV(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}:{},...tV(e.env)?{env:tk(e.env,"env")}:{},...Array.isArray(e.onFlowStart)?{onFlowStart:tx(e.onFlowStart)}:{},...Array.isArray(e.onFlowComplete)?{onFlowComplete:tx(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:tx(r)}}function nI(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),nA(i,{...a,baseDir:r.dirname(n),visitedPaths:o})}let nb=/[*?[\]{}]/;function n_(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 nk(e,t){return"number"==typeof e?e:t}function nN(e,t){let r="number"==typeof e?e:t;return"number"!=typeof r?0:Math.max(0,Math.min(3,r))}function nD(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,!nb.test(i)&&(o=l,!nb.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 nx(e,t){let r=nR(e),a=nR(t);return r!==a?r-a:e.localeCompare(t)}function nR(e){return+(".ad"===r.extname(e))}function nM(e){return[...new Set(e.map(e=>r.normalize(e)))]}function nP(e){return"maestro"===e}let nL=["failed to start daemon","runner did not accept connection","xcodebuild exited early","device is offline","device offline","device unauthorized"];function nO(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(),nL.some(e=>o.includes(e))))}async function nE(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),nU(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 _,nU(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 nC(_)||((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}}),n$({replayPromise:_,cleanupSession:w,sessionName:s,requestId:l})));let r=await nV({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{nU(b,{type:"replay_test_cleanup_start",ts:new Date().toISOString(),session:s}),await w(s),nU(b,{type:"replay_test_cleanup_stop",ts:new Date().toISOString(),session:s,ok:!0,durationMs:Date.now()-i})}catch(t){let e=o(t);nU(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 nC(e){return await Promise.race([e.then(()=>!0),n(2e3).then(()=>!1)])}async function n$(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 nV(e){let{finalizeAttempt:t,sessionName:r,artifactPaths:a,artifactsDir:n,tracePath:i}=e;if(!t)return;let s=Date.now();nU(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 nU(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 nU(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 nU(e,r){e&&t.appendFileSync(e,`${JSON.stringify(r)}
24
+ `)}async function nF(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 nq(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,...nB(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),...nT(u.data?.snapshotDiagnostics),...function(e){return nB(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,...nB(u)}),{file:o.path,title:o.title,session:r.finalSessionName,status:"failed",durationMs:a,attempts:r.attempts,artifactsDir:t.testArtifactsDir,error:p,...nT((i=r.finalResponse,i?.ok?i.data?.snapshotDiagnostics:i?.error.details?.snapshotDiagnostics)),...function(e){return nB(e)}(u)}}(t,a,n,i)}async function nq(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:n_(a,n,r.path,i),artifactsDir:t.testArtifactsDir,...nB(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 nG(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)||nO(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,...nB(l.shard)})}return r}async function nG(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=n_(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 nE({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,...nB(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 nT(e){let t=tX(e);return t?{snapshotDiagnostics:t}:{}}function nB(e){return e?{shardIndex:e.shardIndex,shardCount:e.shardCount,deviceId:e.device.id}:{}}async function nH(e,t,r){let a=function(e){let t=nK(e?.shardAll,"--shard-all"),r=nK(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 nj(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 nK(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 nj(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:ti({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=nW(e),r=l.find(r=>nz(r,p)&&(r.id===e||nW(r.name)===t));if(!r)throw new s("DEVICE_NOT_FOUND",`No shard device matched ${e}`);return r})):n.filter(e=>{var t;return!!nz(t=e,o)&&("ios"===t.platform||"android"===t.platform)&&!1!==t.booted}).sort(nJ));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 nz(e,t){return!(!tl(e.platform,t?.platform)||t?.target&&(e.target??"mobile")!==t.target)}function nW(e){return e.toLowerCase().replace(/_/g," ").replace(/\s+/g," ").trim()}function nJ(e,t){return e.id.localeCompare(t.id)}async function nX(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 nY(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 nZ({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 n1({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=tZ(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 nY(e){var a,n,i,o;let l=function(e){let{inputs:a,cwd:n,platformFilter:i,replayBackend:o}=e,l=new Set(nP(o)?[".yaml",".yml",".ad"]:[".ad"]),u=function(e,a,n,i){if(!nP(i))return[...new Set(e.flatMap(e=>nD(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"}:nD(e,a,n)}(i,a,n);"file"===e.source?o.push(...e.paths):s.push("directory"===e.source?nM(e.paths):e.paths.map(e=>r.normalize(e)).sort(nx))}return nM([...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=tO(a),s=(d=a,c=e,nP(o)&&".ad"!==r.extname(c)?function(e){let{config:t}=nS(tP(e));return t.name}(d):void 0);if(!i){p.push({kind:"run",path:e,title:s,metadata:n});continue}if(!n.platform){nP(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 nH(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 nZ(e){return(await Promise.allSettled(e.shards.map(async t=>await nQ({...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:n0(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 nQ(e){let{shard:t,sessionName:r}=e;return await n3({...e,entries:t.entries,sessionName:n0(r,t),shard:t})}function n0(e,t){return`${e}:shard-${t.shardIndex+1}`}async function n1(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 nF({entry:m,sessionName:r,suiteInvocationId:a,caseIndex:f-1,cwd:n,requestId:i,retries:nN(o?.retries,m.metadata.retries),timeoutMs:nk(o?.timeoutMs,m.metadata.timeoutMs),suiteArtifactsDir:s,suiteIndex:e+1,suiteTotal:l,runReplay:u,cleanupSession:p,finalizeAttempt:d});if(c.push(t),n2(t,o,i))break}return c}async function n3(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 nF({entry:t,sessionName:r,suiteInvocationId:a,caseIndex:e,cwd:n,requestId:i,retries:nN(o?.retries,t.metadata.retries),timeoutMs:nk(o?.timeoutMs,t.metadata.timeoutMs),suiteArtifactsDir:s,suiteIndex:h,suiteTotal:l,shard:u,runReplay:p,cleanupSession:d,finalizeAttempt:c});if(f.push(g),n2(g,o,i))break}return f}function n2(e,t,r){return ew(r)||t?.failFast===!0||nO(e)}let n5={maestro:{parse:function(e,t={}){var a;let n;return nA(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:tR(a.platform),env:{},envOverrides:a.env??{},visitedPaths:n}))}}};function n4(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=tQ(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 n6(e){let{action:t,sessionName:r,logPath:a,sessionStore:n}=e;if(!(ra(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),ra(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&&n8(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}=n4(e.positionals??[]);r&&t.push(r)}return T(t).filter(e=>e.trim().length>0)})(t).map(e=>t5(e)).filter(e=>null!==e);if(0===o.length)return null;let s=ra(t.command)||"fill"===t.command,l=ra(t.command)||"fill"===t.command||"get"===t.command&&t.positionals?.[0]==="text",u=await n7(i,t,a,s,n);for(let e of o){let r=t6(u.nodes,e,{platform:i.device.platform,requireRect:s,requireUnique:!0,disambiguateAmbiguous:l});if(!r)continue;let a=t8(r.node,i.device.platform,{action:"fill"===t.command?"fill":ra(t.command)?"click":"get"}).join(" || ");if(ra(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&&n8(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}=n4(t.positionals??[]),r=[a];return e&&r.push(e),{...t,positionals:r}}}return null}function n8(e){return void 0!==e&&""!==e.trim()&&Number.isFinite(Number(e))}async function n7(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 n9=.35,ie=120,it=360,ir=8;function ia(e,t){return Math.round(Math.min(it,Math.max(ie,"number"==typeof e?e*n9:0,1.5*t)))}let ii=new WeakMap,io=new WeakMap,is=new WeakMap;function il(e,t,r){return{ok:!1,error:{code:e,message:t,...r?{details:r}:{}}}}async function iu(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(ip(n.data)))&&ii.set(t,r)),n}function ip(e){return Array.isArray(e?.nodes)?e:void 0}function id(e,t){e&&io.set(e,{selector:t})}function ic(e){e&&is.delete(e)}let im=new Map([["button",0],["link",0],["textfield",0],["textview",0],["searchfield",0],["switch",0],["slider",0],["cell",1],["statictext",2]]);function ih(e,t,r,a,n,i={}){let o=iA(e,t,a);if(r.childOf){let t=iA(e,r.childOf,a);if(0===t.length)return{ok:!1,message:`Maestro childOf parent did not match: ${r.childOf}`};let n=t7(e.nodes);o=o.filter(r=>t.some(t=>t3(e.nodes,r,t,n)))}let s=iw({nodes:e.nodes,matches:o,platform:a}),l=ib(e.nodes,s.matches,r.index,iv(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 ig(e,t,r,a){let n=iA(e,t,r,{allowLeadingCompositeLabelMatch:!1}),i=iw({nodes:e.nodes,matches:n,platform:r}),o=ib(e.nodes,i.matches,void 0,iv(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 iw(e){let t=e.matches.filter(t=>rr({predicate:"visible",node:t,nodes:e.nodes,platform:e.platform}).pass),r=function(e,t,r){let a=tr(e);if(!a.detected||!a.redBox)return{matches:t,blockedByReactNativeOverlay:!1};let n=tt(a),i=n.filter(t=>rr({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 iy(e){return e?.platform==="android"?"android":"ios"}function iv(e){let t=t2(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 iA(e,t,r,a={}){for(let n of t2(t).selectors){let t=e.nodes.filter(e=>(function(e,t,r,a){return!!t9(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?t9(e,{raw:t.key,terms:[t]},r):iS((i=e,"id"===(o=t.key)?i.identifier:"label"===o?i.label:"value"===o?i.value:t0(i)),t.value,a)})(e,t,r,a))})(e,n,r,a));if(t.length>0)return t}return[]}function iS(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 iI(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 ib(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=t7(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=iI(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===iO(e.node,r));if(n.length>=2){let t=ik(e,n,r,a);if(t)return t}let i=t.filter(e=>1===iO(e.node,r));return n.length>0||i.length<2?null:ik(e,i,r,a)}(o,s,l,p)??i_(o,s,l,p):i_(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=re(a.node.type??""))||"other"===S||"scrollview"===S||"scroll-area"===S)&&!(a.rect.width<120)&&!(a.rect.height<32)&&!(a.rect.height>80)&&1>=iO(a.node,n)))return null;let R=(i=e,o=t,s=r,l=t7(e),i.filter(e=>{var t,r,a;let n;return e.index!==o.node.index&&!!e.rect&&t3(i,e,o.node,l)&&(t=e,r=o.rect,a=s,!("button"!==(n=re(t.type??""))&&"cell"!==n&&"other"!==n||1>=iO(t,a))&&!(t.rect.width<16)&&!(t.rect.height<16)&&!!iP(r,t.rect)&&iR(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"===re(h.node.type??"")&&1>=iO(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,(iM(_.node)?null:t1(b,_.node,k,e=>{if(!iM(e))return null;let t=iI(b,e,k);return t&&function(e,t,r){var a,n;if(!iP(t,e)||(a=e,!((n=t).height<32||n.height>80||a.height<.75*n.height||.75>iR(a,n))&&!(n.width<240)&&n.width>=3*a.width))return!1;let i=iD(t),o=iD(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 i_(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===iO(e.node,r));if(l.length<2)return t;let u=t7(e),p=l.map(t=>({candidate:t,container:iN(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&&iL(t.container.rect,e.container.rect)>=.6)});if(d.length<2)return t;let c=(o=Math.max(...i=(n=d).map(e=>iD(e.container.rect))),(s=Math.min(...i))<=0||o<1.2*s?[]:n.filter(e=>iD(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=iN(e,r.node,a),i=n&&iP(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>iL(e.rect,r.rect)?1/0:Math.abs(e.index-r.index);if(iL(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=iO(e.node,r)-iO(t.node,r);if(0!==a)return a}let a=ix(e.node)-ix(t.node);if(0!==a)return a;let n=Number(e.inheritedRect)-Number(t.inheritedRect);if(0!==n)return n;let i=r&&ix(e.node)===ix(t.node)?iD(t.rect)-iD(e.rect):iD(e.rect)-iD(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 ik(e,t,r,a){let n=t7(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||!iP(i.rect,o.rect)||iD(i.rect)<2*iD(o.rect))&&t3(a,o.node,i.node,s)})});return i_(e,i,r,a)}function iN(e,t,r){return t1(e,t,r,e=>{let t;return!e.rect||"scrollview"!==(t=re(e.type??""))&&"scroll-area"!==t&&"list"!==t||e.rect.width<240||e.rect.height<320?null:e})}function iD(e){return e.width*e.height}function ix(e){return im.get(re(e.type??""))??3}function iR(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 iM(e){let t=re(e.type??"");return!0===e.hittable||"button"===t||"link"===t||"cell"===t||"textfield"===t||"searchfield"===t||"switch"===t||"slider"===t}function iP(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 iL(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(iD(e),iD(t)))}function iO(e,t){let r=[e.label,t0(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=>iS(e,t))?2:3}async function iE(e){let t=iz(e.positionals,{command:"assertVisible",defaultTimeoutMs:17e3});if(!t.ok)return t.response;let r=ij(e.baseReq,t.selector);return r?await iC(e,t,r):await iV(e,t)}async function iC(e,t,r){let a=Date.now(),n=await i$(e,t,r);if(n.ok){var i;if(i=e.baseReq,i.flags?.platform==="android"){let r=await iW(e,t.selector,"assertVisible");if(!r.visible){let n=iK(e.baseReq,t,r,a);return"return"===n.kind?n.response:await iV(e,t)}}return id(e.scope,t.selector),iY({ok:!0,data:{selector:t.selector,nativeWait:!0,query:r,response:n.data}},t.selector,a)}return await iU(e,t,n,a)}async function i$(e,t,r){return await e.invoke({...e.baseReq,command:"wait",positionals:[r,String(t.timeoutMs)]})}async function iV(e,t){let r,a,n=Date.now(),i=t.timeoutMs+1e3,o=!1;for(;;){let s=Date.now(),l=await iW(e,t.selector,"assertVisible");if(l.visible)return iY(l.response,t.selector,n);r=l.response,a=l.snapshot??a;let u=iK(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 ri(250)}let s=r??il("COMMAND_FAILED",`Expected visible but did not match: ${t.selector}`,{selector:t.selector,timeoutMs:t.timeoutMs}),l=await iF(e,t,a);return l||iZ(s,a,e.baseReq)}async function iU(e,t,r,a){let n=await iW(e,t.selector,"assertVisible");if(n.visible)return iY(n.response,t.selector,a);let i=iK(e.baseReq,t,n,a);if("return"===i.kind)return i.response;let o=await iF(e,t,n.snapshot);return o||iZ(r,n.snapshot,e.baseReq)}async function iF(e,t,r){if(e.baseReq.flags?.platform!=="android")return null;let a=function(e){if(!e)return;let t=is.get(e);return is.delete(e),t}(e.scope);return a?"tap"===a.kind?await iq(e,t,r,a):await iG(e,t,a):null}async function iq(e,t,r,a){if(!r)return null;let n=function(e,t,r){var a;let n,i=iy(e.baseReq.flags),o=Z(t),s=ih(t,r.selector,r.options??{},i,o,{promoteTapTarget:!0});if(s.ok)return{ok:!0,target:{kind:"point",point:eQ(s.rect)}};let l=iv(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 iB(e,n.target)).ok)?await iT(e,t,"retryTap"):null}async function iG(e,t,r){return(tv({level:"info",phase:"maestro_assert_visible_retry_swipe",data:{selector:t.selector,swipePositionals:r.positionals,timeoutMs:5e3}}),(await iH(e,r)).ok)?await iT(e,t,"retrySwipe"):null}async function iT(e,t,r){let a={...t,timeoutMs:Math.min(t.timeoutMs,5e3)},n=ij(e.baseReq,a.selector);if(!n)return await iV(e,a);let i=Date.now(),o=await i$(e,a,n);return o.ok?(id(e.scope,a.selector),iY({ok:!0,data:{selector:a.selector,nativeWait:!0,[r]:!0,query:n,response:o.data}},a.selector,i)):await iU(e,a,o,i)}async function iB(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 iH(e,t){return await e.invoke({...e.baseReq,command:"swipe",positionals:t.positionals})}function iK(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=iJ(iv(e));if(!iX(r))return!1;let a=t.nodes.flatMap(e=>[e.label,e.value,e.identifier]).filter(e=>!!e?.trim()).map(e=>iJ(e));return!a.some(e=>e.includes("something went wrong"))&&a.some(e=>e!==r&&!iX(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 ij(e,t){return e.flags?.platform!=="ios"&&e.flags?.platform!=="android"?null:iv(t)}function iz(e,t){let[r,a=String(t.defaultTimeoutMs)]=e;if(!r)return{ok:!1,response:il("INVALID_ARGS",`${t.command} requires a selector.`)};let n=Number(a);return!Number.isFinite(n)||n<0?{ok:!1,response:il("INVALID_ARGS",`${t.command} timeout must be a non-negative number.`)}:{ok:!0,selector:r,timeoutMs:n}}async function iW(e,t,r){let a=await iu(e);var n=e,i=t,o=r,s=a;if(!s.ok)return{visible:!1,response:s,infrastructureFailure:!0};let l=ip(s.data);if(!l)return{visible:!1,response:il("COMMAND_FAILED",`Unable to read snapshot data for ${o}.`),infrastructureFailure:!0};let u=ig(l,i,iy(n.baseReq.flags),Z(l));return u.ok?(id(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:il("COMMAND_FAILED",u.message,{selector:i}),infrastructureFailure:!1,snapshot:l}}function iJ(e){return e?.trim().toLowerCase().replace(/\u2026/g,"...")??""}function iX(e){return"loading"===e||"loading..."===e}function iY(e,t,r){return e.ok?{ok:!0,data:{selector:t,...e.data,waitedMs:Date.now()-r}}:e}function iZ(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
26
  `);let o=ro(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 iQ(e){let t,r=iz(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 iW(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 ri(250)}return n>0?{ok:!0,data:{pass:!0,selector:r.selector,stableSamples:n,waitedMs:Date.now()-a,timeoutMs:r.timeoutMs}}:il("COMMAND_FAILED",`Expected not visible but matched: ${r.selector}`,{selector:r.selector,timeoutMs:r.timeoutMs,lastResponse:t})}async function i0(e){let t,r,a=Number(e.positionals[0]??15e3);if(!Number.isFinite(a)||a<0)return il("INVALID_ARGS","waitForAnimationToEnd timeout must be a number.");let n=Date.now();for(;Date.now()-n<a;){let n=await iu(e),i=function(e,t,r){let a=function(e){if(!e.ok)return null;let t=ip(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 ri(250)}return r?.ok===!1?r:{ok:!0,data:{stable:!1,timeoutMs:a}}}async function i1(e){var t,r,a;let[n,i="5000",o="down"]=e.positionals;if(!n)return il("INVALID_ARGS","scrollUntilVisible requires a selector.");let s=Number(i);if(!Number.isFinite(s)||s<=0)return il("INVALID_ARGS","scrollUntilVisible timeout must be a positive number.");let l=iv(n),u=Math.max(1,Math.ceil(s/500)),p=null;for(let t=0;t<u;t+=1){let r=await or(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}`}}:il("COMMAND_FAILED",`scrollUntilVisible timed out after ${a}ms for selector: ${r}`)}async function i2(e){let[t,r]=e.positionals,a=Number(t),n=Number(r);if(!Number.isFinite(a)||!Number.isFinite(n))return il("INVALID_ARGS","tapOn percentage point requires numeric x/y values.");let i=await iu(e);if(!i.ok)return i;let o=ip(i.data);if(!o)return il("COMMAND_FAILED","Unable to read snapshot data for Maestro percentage point tap.");let s=Q(o);if(!s)return il("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&&ic(e.scope),u}async function i3(e){let t=await i5(e);if(t)return t;let r=await i7(e);return r.ok?await i4(e,r,r.durationMs):r.response}async function i5(e){let[t,r,a]=e.positionals;if("direction"===t&&("left"===r||"right"===r)&&"android"!==iy(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 il("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:il("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 oa(e,o,l.value??{});if(!t.retry)return t.response;i=t.response,await ri(250)}return r=e,a=o,n=i,r.baseReq.flags?.maestro?.optional===!0?{ok:!0,data:{skipped:!0,optional:!0,selector:a}}:n??il("COMMAND_FAILED",`tapOn timed out for selector: ${a}`)}async function i6(e){let[t,r="up",a]=e.positionals;if(!t)return il("INVALID_ARGS","swipe.label requires a label selector.");let n=await os(e,t,{},"swipe.label",{promoteTapTarget:!1});if(!n.ok)return n.response;let i=function(e,t){let r=eQ(e.rect),a=e.frame,n=ia(a?.referenceWidth,e.rect.width),i=ia(a?.referenceHeight,e.rect.height),o=ir,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:e7(r.y-i,o,l)}};case"down":return{ok:!0,start:r,end:{x:r.x,y:e7(r.y+i,o,l)}};case"left":return{ok:!0,start:r,end:{x:e7(r.x-n,o,s),y:r.y}};case"right":return{ok:!0,start:r,end:{x:e7(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 i4(e,i,a):il("INVALID_ARGS",i.message)}async function i4(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&&is.set(a,n)),o}async function i7(e){var t;let r=((t=e.scope)?ii.get(t):void 0)??await i9(e);if(!r)return{ok:!1,response:il("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:il("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:e1({x:(l=eJ({direction:i,amount:.6,referenceWidth:o.referenceWidth,referenceHeight:o.referenceHeight})).x1,y:l.y1},o,8),end:e1({x:l.x2,y:l.y2},o,8),durationMs:s};case"left":case"right":return function(e,t,r,a){let n=ot(r,85,50,15,50),[i,o]="left"===e?[85,15]:[15,85],s=oe(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:il("INVALID_ARGS","Maestro swipe direction must be UP, DOWN, LEFT, or RIGHT.")}}}(n,r,iy(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:il("INVALID_ARGS","Maestro percentage swipe requires numeric points.")};let[u,p,d,c]=l,f=ot(r,u,p,d,c),m=oe(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,iy(e.baseReq.flags)):{ok:!1,response:il("INVALID_ARGS","Maestro screen swipe requires direction or percent.")}}async function i9(e){let t=await iu(e);if(t.ok)return Q(ip(t.data))}function oe(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 ot(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 or(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 oa(e,t,r){let a=iv(t),n=await on(e,t,r);return n.response.ok?{retry:!1,response:n.response}:n.targetResolved&&a?await oo(e,a):{retry:!0,response:n.response}}async function on(e,t,r){let a=await os(e,t,r,"tapOn",{promoteTapTarget:!0});return a.ok?await oi(e,t,a.target,r):{response:a.response,targetResolved:!1}}async function oi(e,t,r,a){let n=eQ(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)&&io.delete(o),s=e.scope,l={kind:"tap",selector:t,point:n,options:{...a}},s&&is.set(s,l)}return{response:i,targetResolved:!0}}async function oo(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)?(ic(e.scope),{retry:!1,response:r}):{retry:!0,response:r}}async function os(e,t,r,a,n){let i=await iu({...e,raw:!0});return function(e,t,r,a,n,i){if(!i.ok)return{ok:!1,response:i};let o=ip(i.data);if(!o)return{ok:!1,response:il("COMMAND_FAILED",`Unable to read snapshot data for ${a}.`)};let s=Q(o),l=iy(e.baseReq.flags),u=function(e,t,r,a){var n;let i=(n=e.scope)?io.get(n):void 0;if(!i)return;let o=ig(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=ih(o,t,r,l,s,{...n,preferredContext:u,requireOnScreen:!0});if(!p.ok){let e=iv(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,t0(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=iw({nodes:e.nodes,matches:i,platform:r}),s=ib(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:il("ELEMENT_NOT_FOUND",p.message,{selector:t,options:r,command:a})}}(e,t,r,a,n,i)}async function ol(e){switch(e.command){case a0:return await iE(e);case a1:return await iQ(e);case a2:return await ou(e);case a3:return await i0(e);case a5:return await i1(e);case a8:return await i3(e);case a6:return await i6(e);case a4:return await i8(e);case a7:return await i2(e);case aQ:return function(e){let[r]=e.positionals;if(!r)return il("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:nm,http:{post:(e,t)=>(function(e,t,r){let a=tJ(process.execPath,["-e",nf],{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 il(e.code,e.message,e.details)}}(e);default:return}}async function ou(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 op(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 od(e){let t;for(let r=0;r<=e.maxRetries;r+=1){let a=await op({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 oc(e){let t=await of(e,e.control);return t.ok?t.matched?await og(e):{ok:!0,data:{skipped:!0,condition:e.control.mode,selector:e.control.selector}}:t.response}async function of(e,t){if("visible"===t.mode)return await om(e,t);let r=await oh(e,t.selector);return r.ok?{ok:!0,matched:!r.matched}:{ok:!1,response:r.response}}async function om(e,t){let r=Date.now();for(;;){let a=await oh(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 ri(250)}}async function oh(e,t){var r,a;let n,i=await iu(e);return i.ok?(r=e,a=t,(n=ip(i.data))?{ok:!0,matched:ig(n,a,iy(r.baseReq.flags),Q(n)).ok}:{ok:!1,response:il("COMMAND_FAILED","Unable to read snapshot data for runFlow.when.")}):{ok:!1,response:i}}async function og(e){let t=await op({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 ow(e){let{req:t,sessionName:r,action:a,scope:n,filePath:i,line:o,step:s,tracePath:l,invoke:u}=e,p=tz(a,n,{file:i,line:o}),d=Date.now();oA(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 oy({req:t,sessionName:r,resolved:p,scope:n,line:o,step:s,invoke:u,invokeReplayAction:e=>ow({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 oA(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 oy(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 ov({control:n.replayControl,baseReq:d,line:o,step:s,invoke:l,invokeReplayAction:u})??await ol({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&&tW(i,e)}return c}async function ov(e){let{control:t,baseReq:r,line:a,step:n,invoke:i,invokeReplayAction:o}=e;if(t){switch(t.kind){case"retry":return await od({actions:t.actions,maxRetries:t.maxRetries,line:a,step:n,invokeReplayAction:o});case"maestroRunFlowWhen":return await oc({baseReq:r,control:t,line:a,step:n,invoke:i,invokeReplayAction:o})}return t}}function oA(e,r){e&&t.appendFileSync(e,`${JSON.stringify(r)}
28
- `)}async function oS(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,R,x,M,P,L,O;c=em.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=n5[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,{...tC(tD(a?.replayShellEnv)),...tE(tM(a?.replayEnv))})}),updateUnsupportedMessage:"replay -u is not supported for compat flow input. Convert to .ad first, then update that replay file."}:{...tN(e),metadata:tO(e)}}(e,a.flags,{sourcePath:c}),$=C.metadata,V=$.platform||$.target?{...a,flags:(m=a.flags,h=$,{...m??{},...void 0!==h.platform&&m?.platform===void 0?{platform:h.platform}:{},...void 0!==h.target&&m?.target===void 0?{target:h.target}:{}})}:a,U=C.actions,q=C.actionLines;if(a.flags?.replayUpdate===!0&&C.updateUnsupportedMessage)return E("INVALID_ARGS",C.updateUnsupportedMessage);if(a.flags?.replayUpdate===!0&&$.env&&Object.keys($.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(oD(t.flags)||oD(t.runtime))return!0}return!1}(U))return E("INVALID_ARGS","replay -u does not yet preserve ${VAR} substitutions. Resolve or inline the variables before running with -u.");let F=tj({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:V,sessionName:n,metadata:$,resolvedPath:c}),fileEnv:$.env,shellEnv:tC(tD(a.flags?.replayShellEnv)),cliEnv:tE(tM(a.flags?.replayEnv))}),G=a.flags?.replayUpdate===!0,T=u??l.get(n)?.trace?.outPath,B=[],H=0;for(let e=0;e<U.length;e+=1){let t=U[e];if(!t||"replay"===t.command)continue;let r=o_(l,n),a=await ow({req:V,sessionName:n,action:t,scope:F,filePath:c,line:q[e]??0,step:e+1,tracePath:T,invoke:p});if(B.push(...ok(l,n,r)),a.ok){ob(a).forEach(e=>f.add(e));continue}if(ob(a).forEach(e=>f.add(e)),!G){return g=a,w=t,y=e,v=c,A=[...f],S=B,oI(g,w,y,v,A,tX(S))}let i=await n6({action:t,sessionName:n,logPath:o,sessionStore:l});if(!i){return I=a,b=t,_=e,k=c,N=[...f],D=B,oI(I,b,_,k,N,tX(D))}U[e]=i;let s=o_(l,n);if(a=await ow({req:V,sessionName:n,action:i,scope:F,filePath:c,line:q[e]??0,step:e+1,tracePath:T,invoke:p}),B.push(...ok(l,n,s)),!a.ok){return ob(a).forEach(e=>f.add(e)),R=a,x=i,M=e,P=c,L=[...f],O=B,oI(R,x,M,P,L,tX(O))}ob(a).forEach(e=>f.add(e)),H+=1}G&&H>0&&tK(c,U,l.get(n));let K=tX(B);return{ok:!0,data:{replayed:U.length,healed:H,session:n,artifactPaths:[...f],...K?{snapshotDiagnostics:K}:{}}}}catch(t){let e=i(t);return E(e.code,e.message,f.size>0?{artifactPaths:[...f]}:void 0)}}function oI(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} (${rt(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 ob(e){if(!e.ok){let t=e.error.details?.artifactPaths;return Array.isArray(t)?[...new Set(t.filter(e=>"string"==typeof e&&oN(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=>oN(e)))]}function o_(e,t){return e.get(t)?.snapshotDiagnostics?.samples.length??0}function ok(e,t,r){return e.get(t)?.snapshotDiagnostics?.samples.slice(r)??[]}function oN(e){try{return t.statSync(e).isFile()}catch{return!1}}function oD(e){return"string"==typeof e?e.includes("${"):Array.isArray(e)?e.some(oD):!!e&&"object"==typeof e&&Object.values(e).some(oD)}async function oR(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`;oM(s,{type:"video_recording_start",session:a,videoPath:u}),tv({phase:"replay_test_video_recording_start",data:{session:a,videoPath:u}});let p=await rs({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 oM(s,{type:"video_recording_start_failed",session:a,videoPath:u,errorCode:p.error.code}),p;let d=Date.now();return await ri(1e3),oM(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 ox(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;oM(i,{type:"video_tail_start",session:r,requestedDurationMs:3e3});let s=Date.now();await ri(3e3);let l=Date.now(),u=await rs({req:{token:t.token,session:r,command:"record",positionals:["stop"],flags:{},meta:t.meta},sessionName:r,sessionStore:n,logPath:a});return ob(u).forEach(e=>o.add(e)),oM(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 oM(e,t){nU(e,{...t,ts:new Date().toISOString()})}async function oP(e){let{req:t,sessionName:r,logPath:a,sessionStore:n,invoke:i}=e;return"replay"===t.command?await oS({req:t,sessionName:r,logPath:a,sessionStore:n,invoke:i}):"test"===t.command?await nY({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 oR(e)}}(m);return await oS({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 oR(m);return r&&!r.ok?r:(t=await i(e),p&&ob(t).forEach(e=>p.add(e)),t)}})},finalizeAttempt:async({sessionName:e,artifactPaths:r,artifactsDir:i,tracePath:o})=>await ox({req:t,sessionName:e,logPath:a,sessionStore:n,artifactsDir:i,tracePath:o,artifactPaths:r}),cleanupSession:async e=>{n.get(e)&&await et({req:{token:t.token,session:e,command:"close",positionals:[],flags:{},meta:t.meta},sessionName:e,logPath:a,sessionStore:n})}}):null}async function oL(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(ru.prepare,w,y);if(v)return v;let A=await m({session:w,flags:y,ensureReady:!0});if(!tn(A.platform))return E("UNSUPPORTED_OPERATION","prepare ios-runner is only supported on Apple runner platforms");let S=Date.now(),I=await er(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)}));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 oO(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,{...ec(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 oE(e){let{req:t,sessionName:r,logPath:a,sessionStore:n}=e,i=n.get(r),o=t.flags??{},s=N(ru.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(ru.clipboard,u))return E("UNSUPPORTED_OPERATION","clipboard is not supported on this device");let d=await p(u,ru.clipboard,t.positionals??[],t.flags?.out,{...ec(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 oC(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 rb({req:t,sessionName:r,sessionStore:n});if("state"===y(t.command))return await r1({req:t,sessionName:r,sessionStore:n});if(t.command===ru.clipboard)return await oE({req:t,sessionName:r,logPath:a,sessionStore:n});if(t.command===ru.keyboard){let e=n.get(r),i=t.positionals?.[0]?.trim().toLowerCase();return e||"dismiss"!==i&&"enter"!==i&&"return"!==i||"ios"!==to((t.flags??{}).platform)?await oO({req:t,sessionName:r,logPath:a,sessionStore:n,command:ru.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 aU({req:t,sessionName:r,sessionStore:n,androidAdbExecutor:s});if(t.command===ru.prepare)return await oL({req:t,sessionName:r,logPath:a,sessionStore:n});if(t.command===ru.install||t.command===ru.reinstall)return await rW({req:t,command:t.command,sessionName:r,sessionStore:n,deployOps:t.command===ru.install?rz:rj});if(t.command===rl.installSource)return await rh({req:t,sessionName:r,sessionStore:n});if(t.command===rl.releaseMaterializedPaths)return await rg({req:t});if(t.command===ru.push){let e,i=t.positionals?.[0]?.trim(),o=t.positionals?.[1]?.trim();return i&&o?await oO({req:t,sessionName:r,logPath:a,sessionStore:n,command:ru.push,positionals:[i,"file"===(e=eI(o,{subject:"Push payload",cwd:t.meta?.cwd,expandPath:(e,t)=>em.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===ru.triggerAppEvent?await oO({req:t,sessionName:r,logPath:a,sessionStore:n,command:ru.triggerAppEvent,positionals:t.positionals??[],deriveNextSession:async(e,t)=>{let r="string"==typeof t?.eventUrl?t.eventUrl:void 0,a=r?await rE(e.device,r,e.appBundleId,rL)??e.appBundleId:e.appBundleId;return{...e,appBundleId:a}}}):t.command===ru.open?await rK({req:t,sessionName:r,logPath:a,sessionStore:n}):"replay"===y(t.command)?await oP({req:t,sessionName:r,logPath:a,sessionStore:n,invoke:o??i}):t.command===ru.batch?await rJ(t,r,i):t.command===ru.close?await et({req:t,sessionName:r,logPath:a,sessionStore:n}):null}export{rd as session_namespaceObject};
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 iQ(e){let t,r=iz(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 iW(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 ri(250)}return n>0?{ok:!0,data:{pass:!0,selector:r.selector,stableSamples:n,waitedMs:Date.now()-a,timeoutMs:r.timeoutMs}}:il("COMMAND_FAILED",`Expected not visible but matched: ${r.selector}`,{selector:r.selector,timeoutMs:r.timeoutMs,lastResponse:t})}async function i0(e){let t,r,a=Number(e.positionals[0]??15e3);if(!Number.isFinite(a)||a<0)return il("INVALID_ARGS","waitForAnimationToEnd timeout must be a number.");let n=Date.now();for(;Date.now()-n<a;){let n=await iu(e),i=function(e,t,r){let a=function(e){if(!e.ok)return null;let t=ip(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 ri(250)}return r?.ok===!1?r:{ok:!0,data:{stable:!1,timeoutMs:a}}}async function i1(e){var t,r,a;let[n,i="5000",o="down"]=e.positionals;if(!n)return il("INVALID_ARGS","scrollUntilVisible requires a selector.");let s=Number(i);if(!Number.isFinite(s)||s<=0)return il("INVALID_ARGS","scrollUntilVisible timeout must be a positive number.");let l=iv(n),u=Math.max(1,Math.ceil(s/500)),p=null;for(let t=0;t<u;t+=1){let r=await or(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}`}}:il("COMMAND_FAILED",`scrollUntilVisible timed out after ${a}ms for selector: ${r}`)}async function i3(e){let[t,r]=e.positionals,a=Number(t),n=Number(r);if(!Number.isFinite(a)||!Number.isFinite(n))return il("INVALID_ARGS","tapOn percentage point requires numeric x/y values.");let i=await iu(e);if(!i.ok)return i;let o=ip(i.data);if(!o)return il("COMMAND_FAILED","Unable to read snapshot data for Maestro percentage point tap.");let s=Z(o);if(!s)return il("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&&ic(e.scope),u}async function i2(e){let t=await i5(e);if(t)return t;let r=await i7(e);return r.ok?await i8(e,r,r.durationMs):r.response}async function i5(e){let[t,r,a]=e.positionals;if("direction"===t&&("left"===r||"right"===r)&&"android"!==iy(e.baseReq.flags))return await e.invoke({...e.baseReq,command:"gesture",positionals:["swipe",r,...a?[a]:[]]})}async function i4(e){var t,r,a,n;let i,[o,s]=e.positionals;if(!o)return il("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:il("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 oa(e,o,l.value??{});if(!t.retry)return t.response;i=t.response,await ri(250)}return r=e,a=o,n=i,r.baseReq.flags?.maestro?.optional===!0?{ok:!0,data:{skipped:!0,optional:!0,selector:a}}:n??il("COMMAND_FAILED",`tapOn timed out for selector: ${a}`)}async function i6(e){let[t,r="up",a]=e.positionals;if(!t)return il("INVALID_ARGS","swipe.label requires a label selector.");let n=await os(e,t,{},"swipe.label",{promoteTapTarget:!1});if(!n.ok)return n.response;let i=function(e,t){let r=eQ(e.rect),a=e.frame,n=ia(a?.referenceWidth,e.rect.width),i=ia(a?.referenceHeight,e.rect.height),o=ir,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:e7(r.y-i,o,l)}};case"down":return{ok:!0,start:r,end:{x:r.x,y:e7(r.y+i,o,l)}};case"left":return{ok:!0,start:r,end:{x:e7(r.x-n,o,s),y:r.y}};case"right":return{ok:!0,start:r,end:{x:e7(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 i8(e,i,a):il("INVALID_ARGS",i.message)}async function i8(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&&is.set(a,n)),o}async function i7(e){var t;let r=((t=e.scope)?ii.get(t):void 0)??await i9(e);if(!r)return{ok:!1,response:il("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:il("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:e1({x:(l=eJ({direction:i,amount:.6,referenceWidth:o.referenceWidth,referenceHeight:o.referenceHeight})).x1,y:l.y1},o,8),end:e1({x:l.x2,y:l.y2},o,8),durationMs:s};case"left":case"right":return function(e,t,r,a){let n=ot(r,85,50,15,50),[i,o]="left"===e?[85,15]:[15,85],s=oe(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:il("INVALID_ARGS","Maestro swipe direction must be UP, DOWN, LEFT, or RIGHT.")}}}(n,r,iy(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:il("INVALID_ARGS","Maestro percentage swipe requires numeric points.")};let[u,p,d,c]=l,f=ot(r,u,p,d,c),m=oe(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,iy(e.baseReq.flags)):{ok:!1,response:il("INVALID_ARGS","Maestro screen swipe requires direction or percent.")}}async function i9(e){let t=await iu(e);if(t.ok)return Z(ip(t.data))}function oe(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 ot(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 or(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 oa(e,t,r){let a=iv(t),n=await on(e,t,r);return n.response.ok?{retry:!1,response:n.response}:n.targetResolved&&a?await oo(e,a):{retry:!0,response:n.response}}async function on(e,t,r){let a=await os(e,t,r,"tapOn",{promoteTapTarget:!0});return a.ok?await oi(e,t,a.target,r):{response:a.response,targetResolved:!1}}async function oi(e,t,r,a){let n=eQ(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)&&io.delete(o),s=e.scope,l={kind:"tap",selector:t,point:n,options:{...a}},s&&is.set(s,l)}return{response:i,targetResolved:!0}}async function oo(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)?(ic(e.scope),{retry:!1,response:r}):{retry:!0,response:r}}async function os(e,t,r,a,n){let i=await iu({...e,raw:!0});return function(e,t,r,a,n,i){if(!i.ok)return{ok:!1,response:i};let o=ip(i.data);if(!o)return{ok:!1,response:il("COMMAND_FAILED",`Unable to read snapshot data for ${a}.`)};let s=Z(o),l=iy(e.baseReq.flags),u=function(e,t,r,a){var n;let i=(n=e.scope)?io.get(n):void 0;if(!i)return;let o=ig(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=ih(o,t,r,l,s,{...n,preferredContext:u,requireOnScreen:!0});if(!p.ok){let e=iv(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,t0(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=iw({nodes:e.nodes,matches:i,platform:r}),s=ib(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:il("ELEMENT_NOT_FOUND",p.message,{selector:t,options:r,command:a})}}(e,t,r,a,n,i)}async function ol(e){switch(e.command){case a0:return await iE(e);case a1:return await iQ(e);case a3:return await ou(e);case a2:return await i0(e);case a5:return await i1(e);case a4:return await i2(e);case a6:return await i6(e);case a8:return await i4(e);case a7:return await i3(e);case aQ:return function(e){let[r]=e.positionals;if(!r)return il("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:nm,http:{post:(e,t)=>(function(e,t,r){let a=tJ(process.execPath,["-e",nf],{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 il(e.code,e.message,e.details)}}(e);default:return}}async function ou(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 op(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 od(e){let t;for(let r=0;r<=e.maxRetries;r+=1){let a=await op({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 oc(e){let t=await of(e,e.control);return t.ok?t.matched?await og(e):{ok:!0,data:{skipped:!0,condition:e.control.mode,selector:e.control.selector}}:t.response}async function of(e,t){if("visible"===t.mode)return await om(e,t);let r=await oh(e,t.selector);return r.ok?{ok:!0,matched:!r.matched}:{ok:!1,response:r.response}}async function om(e,t){let r=Date.now();for(;;){let a=await oh(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 ri(250)}}async function oh(e,t){var r,a;let n,i=await iu(e);return i.ok?(r=e,a=t,(n=ip(i.data))?{ok:!0,matched:ig(n,a,iy(r.baseReq.flags),Z(n)).ok}:{ok:!1,response:il("COMMAND_FAILED","Unable to read snapshot data for runFlow.when.")}):{ok:!1,response:i}}async function og(e){let t=await op({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 ow(e){let{req:t,sessionName:r,action:a,scope:n,filePath:i,line:o,step:s,tracePath:l,invoke:u}=e,p=tz(a,n,{file:i,line:o}),d=Date.now();oA(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 oy({req:t,sessionName:r,resolved:p,scope:n,line:o,step:s,invoke:u,invokeReplayAction:e=>ow({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 oA(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 oy(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 ov({control:n.replayControl,baseReq:d,line:o,step:s,invoke:l,invokeReplayAction:u})??await ol({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&&tW(i,e)}return c}async function ov(e){let{control:t,baseReq:r,line:a,step:n,invoke:i,invokeReplayAction:o}=e;if(t){switch(t.kind){case"retry":return await od({actions:t.actions,maxRetries:t.maxRetries,line:a,step:n,invokeReplayAction:o});case"maestroRunFlowWhen":return await oc({baseReq:r,control:t,line:a,step:n,invoke:i,invokeReplayAction:o})}return t}}function oA(e,r){e&&t.appendFileSync(e,`${JSON.stringify(r)}
28
+ `)}async function oS(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=n5[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,{...tC(tD(a?.replayShellEnv)),...tE(tM(a?.replayEnv))})}),updateUnsupportedMessage:"replay -u is not supported for compat flow input. Convert to .ad first, then update that replay file."}:{...tN(e),metadata:tO(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(oD(t.flags)||oD(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=tj({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:tC(tD(a.flags?.replayShellEnv)),cliEnv:tE(tM(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=o_(l,n),a=await ow({req:U,sessionName:n,action:t,scope:G,filePath:c,line:q[e]??0,step:e+1,tracePath:B,invoke:p});if(H.push(...ok(l,n,r)),a.ok){ob(a).forEach(e=>f.add(e));continue}if(ob(a).forEach(e=>f.add(e)),!T){return g=a,w=t,y=e,v=c,A=[...f],S=H,oI(g,w,y,v,A,tY(S))}let i=await n6({action:t,sessionName:n,logPath:o,sessionStore:l});if(!i){return I=a,b=t,_=e,k=c,N=[...f],D=H,oI(I,b,_,k,N,tY(D))}F[e]=i;let s=o_(l,n);if(a=await ow({req:U,sessionName:n,action:i,scope:G,filePath:c,line:q[e]??0,step:e+1,tracePath:B,invoke:p}),H.push(...ok(l,n,s)),!a.ok){return ob(a).forEach(e=>f.add(e)),x=a,R=i,M=e,P=c,L=[...f],O=H,oI(x,R,M,P,L,tY(O))}ob(a).forEach(e=>f.add(e)),K+=1}T&&K>0&&tK(c,F,l.get(n));let j=tY(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 oI(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} (${rt(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 ob(e){if(!e.ok){let t=e.error.details?.artifactPaths;return Array.isArray(t)?[...new Set(t.filter(e=>"string"==typeof e&&oN(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=>oN(e)))]}function o_(e,t){return e.get(t)?.snapshotDiagnostics?.samples.length??0}function ok(e,t,r){return e.get(t)?.snapshotDiagnostics?.samples.slice(r)??[]}function oN(e){try{return t.statSync(e).isFile()}catch{return!1}}function oD(e){return"string"==typeof e?e.includes("${"):Array.isArray(e)?e.some(oD):!!e&&"object"==typeof e&&Object.values(e).some(oD)}async function ox(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`;oM(s,{type:"video_recording_start",session:a,videoPath:u}),tv({phase:"replay_test_video_recording_start",data:{session:a,videoPath:u}});let p=await rs({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 oM(s,{type:"video_recording_start_failed",session:a,videoPath:u,errorCode:p.error.code}),p;let d=Date.now();return await ri(1e3),oM(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 oR(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;oM(i,{type:"video_tail_start",session:r,requestedDurationMs:3e3});let s=Date.now();await ri(3e3);let l=Date.now(),u=await rs({req:{token:t.token,session:r,command:"record",positionals:["stop"],flags:{},meta:t.meta},sessionName:r,sessionStore:n,logPath:a});return ob(u).forEach(e=>o.add(e)),oM(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 oM(e,t){nU(e,{...t,ts:new Date().toISOString()})}async function oP(e){let{req:t,sessionName:r,logPath:a,sessionStore:n,invoke:i}=e;return"replay"===t.command?await oS({req:t,sessionName:r,logPath:a,sessionStore:n,invoke:i}):"test"===t.command?await nX({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 ox(e)}}(m);return await oS({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 ox(m);return r&&!r.ok?r:(t=await i(e),p&&ob(t).forEach(e=>p.add(e)),t)}})},finalizeAttempt:async({sessionName:e,artifactPaths:r,artifactsDir:i,tracePath:o})=>await oR({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 oL(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(ru.prepare,w,y);if(v)return v;let A=await m({session:w,flags:y,ensureReady:!0});if(!tn(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 oO(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 oE(e){let{req:t,sessionName:r,logPath:a,sessionStore:n}=e,i=n.get(r),o=t.flags??{},s=N(ru.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(ru.clipboard,u))return E("UNSUPPORTED_OPERATION","clipboard is not supported on this device");let d=await p(u,ru.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 oC(e){let{req:t,sessionName:r,logPath:a,sessionStore:n,invoke:i,invokeReplayAction:o,androidAdbExecutor:s}=e;if("inventory"===y(t.command))return await rX({req:t,sessionName:r,sessionStore:n});if("runtime"===t.command)return await rb({req:t,sessionName:r,sessionStore:n});if("state"===y(t.command))return await r1({req:t,sessionName:r,sessionStore:n});if(t.command===ru.clipboard)return await oE({req:t,sessionName:r,logPath:a,sessionStore:n});if(t.command===ru.keyboard){let e=n.get(r),i=t.positionals?.[0]?.trim().toLowerCase();return e||"dismiss"!==i&&"enter"!==i&&"return"!==i||"ios"!==to((t.flags??{}).platform)?await oO({req:t,sessionName:r,logPath:a,sessionStore:n,command:ru.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 aU({req:t,sessionName:r,sessionStore:n,androidAdbExecutor:s});if(t.command===ru.prepare)return await oL({req:t,sessionName:r,logPath:a,sessionStore:n});if(t.command===ru.install||t.command===ru.reinstall)return await rW({req:t,command:t.command,sessionName:r,sessionStore:n,deployOps:t.command===ru.install?rz:rj});if(t.command===rl.installSource)return await rh({req:t,sessionName:r,sessionStore:n});if(t.command===rl.releaseMaterializedPaths)return await rg({req:t});if(t.command===ru.push){let e,i=t.positionals?.[0]?.trim(),o=t.positionals?.[1]?.trim();return i&&o?await oO({req:t,sessionName:r,logPath:a,sessionStore:n,command:ru.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===ru.triggerAppEvent?await oO({req:t,sessionName:r,logPath:a,sessionStore:n,command:ru.triggerAppEvent,positionals:t.positionals??[],deriveNextSession:async(e,t)=>{let r="string"==typeof t?.eventUrl?t.eventUrl:void 0,a=r?await rE(e.device,r,e.appBundleId,rL)??e.appBundleId:e.appBundleId;return{...e,appBundleId:a}}}):t.command===ru.open?await rK({req:t,sessionName:r,logPath:a,sessionStore:n}):"replay"===y(t.command)?await oP({req:t,sessionName:r,logPath:a,sessionStore:n,invoke:o??i}):t.command===ru.batch?await rJ(t,r,i):t.command===ru.close?await ee({req:t,sessionName:r,logPath:a,sessionStore:n}):null}export{rd as session_namespaceObject};