agent-device 0.18.0 → 0.18.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -2
- package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.18.0.apk → agent-device-android-multitouch-helper-0.18.1.apk} +0 -0
- package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.18.1.apk.sha256 +1 -0
- package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.18.0.manifest.json → agent-device-android-multitouch-helper-0.18.1.manifest.json} +4 -4
- package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.18.0.apk → agent-device-android-snapshot-helper-0.18.1.apk} +0 -0
- package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.18.1.apk.sha256 +1 -0
- package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.18.0.manifest.json → agent-device-android-snapshot-helper-0.18.1.manifest.json} +6 -6
- package/apple-runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerApp.m +156 -0
- package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunner.xcodeproj/project.pbxproj +10 -16
- package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AXSnapshotFallback.swift +2 -0
- package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +3 -1
- package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandJournal.swift +2 -0
- package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+FlatSnapshotFiltering.swift +2 -4
- package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +9 -36
- package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScrollGesture.swift +2 -0
- package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SequenceExecution.swift +2 -0
- package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +2 -0
- package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +2 -0
- package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntry.swift +0 -1
- package/dist/src/1986.js +1 -0
- package/dist/src/2748.js +1 -1
- package/dist/src/2948.js +21 -21
- package/dist/src/314.js +1 -1
- package/dist/src/3340.js +8 -7
- package/dist/src/432.js +4 -4
- package/dist/src/4418.js +1 -1
- package/dist/src/4428.js +3 -3
- package/dist/src/485.js +1 -0
- package/dist/src/495.js +5 -0
- package/dist/src/5484.js +1 -1
- package/dist/src/587.js +1 -1
- package/dist/src/5913.js +4 -0
- package/dist/src/6849.js +1 -0
- package/dist/src/6918.js +1 -1
- package/dist/src/6967.js +1 -0
- package/dist/src/760.js +1 -0
- package/dist/src/7871.js +1 -0
- package/dist/src/8225.js +1 -1
- package/dist/src/8391.js +1 -0
- package/dist/src/8404.js +2 -0
- package/dist/src/8414.js +2 -0
- package/dist/src/8875.js +1 -1
- package/dist/src/8936.js +1 -1
- package/dist/src/9581.js +3 -3
- package/dist/src/9624.js +1 -1
- package/dist/src/9722.js +37 -32
- package/dist/src/android-adb.d.ts +19 -54
- package/dist/src/android-adb.js +1 -1
- package/dist/src/android.js +5 -5
- package/dist/src/apps.js +9 -11
- package/dist/src/audio-probe.js +1 -0
- package/dist/src/batch.d.ts +33 -25
- package/dist/src/batch.js +1 -1
- package/dist/src/cli-help.js +66 -16
- package/dist/src/cli.js +33 -21
- package/dist/src/contracts.d.ts +32 -122
- package/dist/src/contracts.js +1 -1
- package/dist/src/debug-symbols.js +3 -0
- package/dist/src/devices.js +1 -1
- package/dist/src/devices~1.js +1 -1
- package/dist/src/devices~2.js +1 -1
- package/dist/src/find.js +1 -1
- package/dist/src/finders.d.ts +2 -6
- package/dist/src/finders.js +1 -1
- package/dist/src/generic.js +1 -9
- package/dist/src/handler-utils.js +1 -0
- package/dist/src/index.d.ts +438 -171
- package/dist/src/index.js +1 -1
- package/dist/src/input-actions.js +1 -1
- package/dist/src/input-actions~1.js +1 -1
- package/dist/src/install-source.d.ts +0 -26
- package/dist/src/install-source.js +1 -1
- package/dist/src/interaction.js +1 -1
- package/dist/src/interactor.js +1 -0
- package/dist/src/internal/bin.js +1 -1
- package/dist/src/internal/companion-tunnel.js +1 -1
- package/dist/src/internal/png-worker.js +1 -1
- package/dist/src/lease.js +1 -1
- package/dist/src/linux.js +1 -1
- package/dist/src/metro.d.ts +10 -134
- package/dist/src/metro.js +1 -1
- package/dist/src/notifications.js +1 -1
- package/dist/src/react-native.js +1 -1
- package/dist/src/record-trace-recording.js +3 -3
- package/dist/src/record-trace.js +1 -1
- package/dist/src/remote-config.d.ts +14 -16
- package/dist/src/remote-config.js +1 -1
- package/dist/src/runner-sequence.js +1 -0
- package/dist/src/selector-runtime.js +1 -1
- package/dist/src/selectors.d.ts +7 -3
- package/dist/src/selectors.js +1 -1
- package/dist/src/server.js +2 -2
- package/dist/src/session.js +11 -11
- package/dist/src/simulator.js +2 -2
- package/dist/src/snapshot.js +2 -2
- package/dist/src/web.js +1 -1
- package/macos-helper/Sources/AgentDeviceMacOSHelper/AudioProbe.swift +297 -0
- package/macos-helper/Sources/AgentDeviceMacOSHelper/main.swift +30 -0
- package/package.json +15 -11
- package/server.json +2 -2
- package/android-multitouch-helper/README.md +0 -41
- package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.18.0.apk.sha256 +0 -1
- package/android-snapshot-helper/README.md +0 -88
- package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.18.0.apk.sha256 +0 -1
- package/dist/src/1848.js +0 -4
- package/dist/src/2577.js +0 -1
- package/dist/src/2954.js +0 -2
- package/dist/src/4291.js +0 -1
- package/dist/src/4723.js +0 -1
- package/dist/src/5341.js +0 -1
- package/dist/src/5910.js +0 -2
- package/dist/src/6024.js +0 -1
- package/dist/src/733.js +0 -1
- package/dist/src/7394.js +0 -6
- package/dist/src/8275.js +0 -2
- package/dist/src/9919.js +0 -6
- package/dist/src/android-snapshot-helper.d.ts +0 -359
- package/dist/src/android-snapshot-helper.js +0 -1
- package/dist/src/apple.js +0 -1
- package/dist/src/device-ready.js +0 -2
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerApp.swift +0 -17
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/AccentColor.colorset/Contents.json +0 -11
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/AppIcon.appiconset/Contents.json +0 -36
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/AppIcon.appiconset/logo.jpg +0 -0
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/Contents.json +0 -6
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/Logo.imageset/Contents.json +0 -21
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/Logo.imageset/logo.jpg +0 -0
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/PoweredBy.imageset/Contents.json +0 -21
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/PoweredBy.imageset/powered-by.png +0 -0
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/ContentView.swift +0 -34
- package/ios-runner/README.md +0 -53
- package/ios-runner/RUNNER_PROTOCOL.md +0 -76
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunner.xcodeproj/project.xcworkspace/contents.xcworkspacedata +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunner.xcodeproj/xcshareddata/xcschemes/AgentDeviceRunner.xcscheme +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/AgentDeviceRunnerUITests-Bridging-Header.h +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/AgentDeviceRunnerUITests.entitlements +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.h +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.m +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerObjCExceptionCatcher.h +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerObjCExceptionCatcher.m +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedGesture.h +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedGesture.m +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Environment.swift +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Exceptions.swift +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Lifecycle.swift +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScreenRecorder.swift +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SystemModal.swift +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Transport.swift +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TvRemote.swift +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests.xctestplan +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/RecordingScripts/recording-overlay.swift +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/RecordingScripts/recording-resize.swift +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/RecordingScripts/recording-trim.swift +0 -0
- /package/dist/src/{4069.js → 4917.js} +0 -0
- /package/dist/src/{9836.js → 893.js} +0 -0
package/dist/src/session.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{__webpack_require__ as e}from"./rslib-runtime.js";import t from"node:fs";import r from"node:path";import a from"node:vm";import{setTimeout as n}from"node:timers/promises";import{asAppError as i,normalizeError as o,AppError as s}from"./733.js";import{runXcrun as l,startAndroidSimpleperfProfile as u,APPLE_MEMGRAPH_SNAPSHOT_DESCRIPTION as d,dispatchCommand as p,sessionMatchesScope as c,appendAppLogMarker as f,sampleAppleFramePerf as m,captureAppleMemorySnapshot as h,getSessionCommandKind as g,inferFillText as w,startAndroidPerfettoTrace as y,stopIosRunnerSession as v,captureAndroidHeapSnapshot as A,stopAppleXctracePerfCapture as S,resolvePublicSessionName as _,writeAppleXctracePerfReport as b,stopSessionApplePerfCapture as I,resolveSessionRequestLogPath as k,cleanupUploadedArtifact as N,ANDROID_FRAME_SAMPLE_METHOD as D,buildAppleFrameSamplingMetadata as x,createRequestCanceledError as R,stopAppleRunnerForClose as M,registerRequestAbort as P,errorResponse as L,readReplayTestActionProgress as O,buildSessionRecoveryHint as C,releaseSessionLease as E,withKeyedLock as $,resolveTargetDevice as V,getAppLogPathMetadata as U,uniqueStrings as F,setSessionSnapshot as q,sampleAndroidMemoryPerf as T,ANDROID_HPROF_SNAPSHOT_DESCRIPTION as G,sampleAndroidCpuPerf as K,ANDROID_HPROF_SNAPSHOT_METHOD as B,startAppleXctracePerfCapture as H,getSnapshotReferenceFrame as j,buildAppleSamplingMetadata as z,cleanupRetainedMaterializedPathsForSession as W,clearAppLogFiles as J,LeaseRegistry as X,prepareIosRunner as Y,hasExplicitDeviceSelector as Z,stopSessionAndroidNativePerfCapture as Q,readSessionNetworkCapture as ee,cleanupRetainedMaterializedPaths as et,isImplicitSessionScopeConflict as er,resolveSessionRunnerLogPath as ea,ANDROID_CPU_SAMPLE_DESCRIPTION as en,buildSnapshotState as ei,resolveLogBackend as eo,resolveSessionLeaseForRequest as es,stopAndroidSimpleperfProfile as el,context_contextFromFlags as eu,listDeviceInventory as ed,SessionStore as ep,ANDROID_CPU_SAMPLE_METHOD as ec,buildAppleMemorySnapshotSupport as ef,stopAndroidPerfettoTrace as em,isRequestCanceled as eh,resolveRequestTrackingId as eg,retainMaterializedPaths as ew,runAppLogDoctor as ey,resolvePayloadInput as ev,prepareUploadedArtifact as eA,resetAndroidFramePerfStats as eS,ANDROID_FRAME_SAMPLE_DESCRIPTION as e_,listSessionSelectorConflicts as eb,stopSessionAppLog as eI,stopSessionAndroidSnapshotHelper as ek,withReplayTestActionProgress as eN,markRequestCanceled as eD,stopAppLog as ex,resolveImplicitSessionScope as eR,APPLE_MEMGRAPH_SNAPSHOT_METHOD as eM,ANDROID_MEMORY_SAMPLE_DESCRIPTION as eP,writeAndroidSimpleperfReport as eL,prewarmIosRunnerSession as eO,clearRequestCanceled as eC,buildSimctlArgsForDevice as eE,resolveFrontmostMacOsApp as e$,isCommandSupportedOnDevice as eV,sampleApplePerfMetrics as eU,sampleAndroidFramePerf as eF,ANDROID_MEMORY_SAMPLE_METHOD as eq,getRequestSignal as eT,markAndroidSnapshotFreshness as eG,startAppLog as eK,emitRequestProgress as eB}from"./9722.js";import{ensureDeviceReady as eH}from"./device-ready.js";import{isPerfAction as ej,isPerfSubject as ez,pointFromPercent as eW,PERF_AREA_ERROR_MESSAGE as eJ,buildSwipeGesturePlan as eX,PERF_ACTION_ERROR_MESSAGE as eY,buildSnapshotDisplayLines as eZ,isPerfKind as eQ,isPerfMemoryKind as e0,pointInsideRect as e1,successText as e3,clampGesturePoint as e2,resolveDeployResultTarget as e5,PERF_MEMORY_KIND_ERROR_MESSAGE as e4,PERF_KIND_ERROR_MESSAGE as e6,isPerfArea as e8,LOG_ACTION_VALUES as e7,withSuccessText as e9,clampToRange as te,parseSessionSurface as tt,resolveInstallFromSourceResultTarget as tr,readReactNativeOverlayActionNodes as ta,detectReactNativeOverlay as tn,PERF_SUBJECT_ERROR_MESSAGE as ti}from"./2948.js";import{trimRuntimeValue as to,resolveRuntimeTransportHints as ts}from"./8936.js";import{runAndroidAdb as tl,resolveIosSimulatorDeviceSetPath as tu,classifyAndroidAppTarget as td,resolveIosDeviceDeepLinkBundleId as tp,isInfrastructureBootFailureReason as tc,isWebUrl as tf,resolveAndroidSerialAllowlist as tm,isDeepLinkTarget as th,formatAndroidInstalledPackageRequiredMessage as tg,listAndroidApps as tw}from"./3340.js";import{isApplePlatform as ty,resolveAppleSimulatorSetPathForSelector as tv,normalizePlatformSelector as tA,matchesPlatformSelector as tS}from"./5910.js";import{getDiagnosticsMeta as t_,emitDiagnostic as tb}from"./432.js";import{shutdownSimulator as tI,getSimulatorState as tk}from"./simulator.js";import{runBatch as tN,mergeParentFlags as tD}from"./6918.js";import{assertResolvedAppsFilter as tx}from"./2748.js";import{listIosApps as tR}from"./apps.js";import{resolveWebProvider as tM}from"./provider.js";import{NETWORK_INCLUDE_MODES as tP}from"./4291.js";import{unsupportedCommand as tL,readEnvMap as tO,parseReplayScriptDetailed as tC,readReplayShellEnvSource as tE,normalizeCommandList as t$,normalizePlatform as tV,readReplayCliEnvEntries as tU,parseMaestroYamlDocuments as tF,parseAbsolutePoint as tq,readReplayScriptMetadata as tT,parseReplayCliEnvEntries as tG,collectReplayShellEnv as tK,support_action as tB,isPlainRecord as tH,requireAppId as tj,assertOnlyKeys as tz,resolveMaestroString as tW,requireStringValue as tJ,parseMaestroPoint as tX,unsupportedMaestroSyntax as tY,readTimeoutMs as tZ,writeReplayScript as tQ,buildReplayVarScope as t0,resolveReplayAction as t1,mergeReplayVarScopeValues as t3}from"./4428.js";import{runCmdSync as t2}from"./8875.js";import{readSnapshotDiagnosticsSummary as t5,summarizeSnapshotTimingSamples as t4,mergeSnapshotDiagnostics as t6}from"./1848.js";import{resolveSelectorChain as t8,extractNodeText as t7,findSnapshotAncestor as t9,isDescendantOfSnapshotNode as re,splitIsSelectorArgs as rt,buildSelectorChainForNode as rr,buildSnapshotNodeByIndex as ra,matchesSelector as rn,normalizeType as ri}from"./9836.js";import{formatScriptActionSummary as ro,evaluateIsPredicate as rs,isTouchTargetCommand as rl}from"./2577.js";import{splitSelectorFromArgs as ru,normalizeText as rd,tryParseSelectorChain as rp,parseSelectorChain as rc}from"./587.js";import{sleep as rf}from"./5560.js";import{handleRecordCommand as rm}from"./record-trace-recording.js";import{recordingExtensionForPlatform as rh,defaultRecordingPath as rg}from"./5643.js";import{INTERNAL_COMMANDS as rw,PUBLIC_COMMANDS as ry}from"./5341.js";var rv={};async function rA(e){var t;let r="ios"===(t=e.flags?.platform)||"android"===t?t:void 0;if(e.session){if(r&&e.session.device.platform!==r)throw new s("INVALID_ARGS",`install_from_source requested platform ${r}, but session is bound to ${e.session.device.platform}`);return await eH(e.session.device),e.session.device}if(!r)throw new s("INVALID_ARGS",'install_from_source requires platform "ios" or "android" when no session is provided');let a=await V(e.flags??{});return await eH(a),a}async function rS(e){let{prepared:t,retention:r,req:a,session:n,sessionName:i}=e;if(r.enabled)return await ew({archivePath:t.archivePath,installablePath:t.installablePath,tenantId:a.meta?.tenantId,sessionName:n?i:void 0,ttlMs:r.ttlMs})}function r_(e){return e?{...e.archivePath?{archivePath:e.archivePath}:{},installablePath:e.installablePath,materializationId:e.materializationId,materializationExpiresAt:e.expiresAt}:{}}async function rb(e){let{req:t,sessionName:r,sessionStore:a}=e,n=a.get(r);try{let e,i,o=(e=function(e){let t=e.meta?.installSource;if(!t)throw new s("INVALID_ARGS","install_from_source requires a source payload");switch(t.kind){case"url":if(!t.url||0===t.url.trim().length)throw new s("INVALID_ARGS","install_from_source url source requires a non-empty url");return t;case"path":if(!t.path||0===t.path.trim().length)throw new s("INVALID_ARGS","install_from_source path source requires a non-empty path");return t;case"github-actions-artifact":throw new s("UNSUPPORTED_OPERATION","install_from_source github-actions-artifact sources require a compatible remote daemon");default:throw new s("UNSUPPORTED_OPERATION",`install_from_source ${String(t.kind)} sources require a compatible remote daemon`)}}(t),(i=t.meta?.uploadedArtifactId)&&"path"===e.kind?{source:{kind:"path",path:eA(i,t.meta?.tenantId)},cleanup:()=>{N(i)}}:{source:e,cleanup:()=>{}}),l=function(e){let t=e.meta?.retainMaterializedPaths===!0,r=e.meta?.materializedPathRetentionMs;if(!t)return{enabled:!1};if(void 0!==r&&r<=0)throw new s("INVALID_ARGS","install_from_source retentionMs must be a positive integer");return{enabled:!0,ttlMs:r}}(t),u=await rA({session:n,flags:t.flags});if(!eV("install",u))return L("UNSUPPORTED_OPERATION","install_from_source is not supported on this device");let d=eT(t.meta?.requestId),p=async(e,i)=>{let s;try{var u;s=await rS({prepared:e,retention:l,req:t,session:n,sessionName:r});let o=await i(s),d=e9(o,(u=o,`Installed: ${tr(u)}`));return!function(e){let{session:t,sessionStore:r,req:a,data:n}=e;t&&r.recordAction(t,{command:"install_source",positionals:[],flags:a.flags??{},result:n})}({session:n,sessionStore:a,req:t,data:d}),{ok:!0,data:d}}catch(e){throw s&&await et(s.materializationId,t.meta?.tenantId).catch(()=>{}),e}finally{await e.cleanup(),o.cleanup()}};if("ios"===u.platform){let{installIosInstallablePath:e}=await import("./apps.js"),{prepareIosInstallArtifact:t}=await import("./apps.js"),r=await t(o.source,{signal:d});return await p(r,async t=>{if(await e(u,r.installablePath),!r.bundleId)throw new s("COMMAND_FAILED","Installed iOS app identity could not be resolved from the artifact");return{...r_(t),bundleId:r.bundleId,...r.appName?{appName:r.appName}:{},launchTarget:r.bundleId}})}let{prepareAndroidInstallArtifact:c}=await import("./3340.js"),{installAndroidInstallablePathAndResolvePackageName:f}=await import("./3340.js"),m=await c(o.source,{signal:d});return await p(m,async e=>{let t=await f(u,m.installablePath,m.packageName);if(!t)throw new s("COMMAND_FAILED","Installed Android app identity could not be resolved from the artifact or device state");let{inferAndroidAppName:r}=await import("./3340.js"),a=r(t);return{...r_(e),packageName:t,...a?{appName:a}:{},launchTarget:t}})}catch(e){return{ok:!1,error:o(e)}}}async function rI(e){let{req:t}=e;try{let e=t.meta?.materializationId?.trim();if(!e)throw new s("INVALID_ARGS","release_materialized_paths requires a materializationId");return await et(e,t.meta?.tenantId),{ok:!0,data:{released:!0,materializationId:e}}}catch(e){return{ok:!1,error:o(e)}}}function rk(e){return"ios"===e.platform&&"simulator"===e.kind}function rN(e,t,r){return t||Z(r)?null:L("INVALID_ARGS",`${e} requires an active session or an explicit device selector (e.g. --platform ios).`)}async function rD(e,t){rk(e)&&!(t<=0)&&await new Promise(e=>setTimeout(e,t))}async function rx(e){let t=Z(e.flags)||!e.session?await V(e.flags??{}):await rR(e.session.device);return!1!==e.ensureReady&&await eH(t),t}async function rR(e){if("ios"!==e.platform||"simulator"!==e.kind||"darwin"!==process.platform)return e;let t={platform:"ios",target:e.target,udid:e.id,...e.simulatorSetPath?{iosSimulatorDeviceSet:e.simulatorSetPath}:{}};try{return await V(t)}catch(e){if(!(e instanceof s)||"DEVICE_NOT_FOUND"!==e.code)throw e}return await V({platform:"ios",target:e.target,device:e.name,...e.simulatorSetPath?{iosSimulatorDeviceSet:e.simulatorSetPath}:{}})}function rM(e){let t=e.flags?.device?.trim();return t||(e.resolvedDevice?.platform==="android"&&"emulator"===e.resolvedDevice.kind?e.resolvedDevice.name:e.sessionDevice?.platform==="android"&&"emulator"===e.sessionDevice.kind?e.sessionDevice.name:void 0)}e.r(rv),e.d(rv,{handleSessionCommands:()=>sh});let rP="shared_prefs/ReactNativeDevPrefs.xml",rL="debug_http_host",rO="dev_server_https",rC="RCT_jsLocation",rE="RCT_packager_scheme",r$="React Native runtime hints require adb run-as access to the app sandbox. Verify the app is debuggable and the selected package/device are correct.",rV='<?xml version="1.0" encoding="utf-8" standalone="yes" ?>\n<map>\n</map>\n';function rU(e){return void 0!==ts(e)}async function rF(e){let{device:t,appId:r,runtime:a}=e;if(!r)return;let n=ts(a);if(n){if("android"===t.platform)return void await rT(t,r,n);"ios"===t.platform&&"simulator"===t.kind&&await rH(t,r,n)}}async function rq(e){let{device:t,appId:r}=e;if(r){if("android"===t.platform)return void await rG(t,r);"ios"===t.platform&&"simulator"===t.kind&&await rj(t,r)}}async function rT(e,t,r){var a,n,i,o,s,l;let u,d;rX(t);let p=(a=await rK(e,t),n=rL,i=`${r.host}:${r.port}`,u=` <string name="${rY(n)}">${rY(i)}</string>`,rW(rJ(a,n),u));o=p,s=rO,l="https"===r.scheme,d=` <boolean name="${rY(s)}" value="${l?"true":"false"}" />`,p=rW(rJ(o,s),d),await rB(e,t,p)}async function rG(e,t){rX(t);let r=await rK(e,t),a=rJ(r,rL),n=rJ(a,rO);n!==r&&await rB(e,t,n)}async function rK(e,t){let r=await tl(e,["shell","run-as",t,"cat",rP],{allowFailure:!0});return 0!==r.exitCode?rV:rz(r.stdout)}async function rB(e,t,r){let a=["shell","run-as",t,"id"],n=await tl(e,a,{allowFailure:!0});if(0!==n.exitCode){let e=rZ(n.stdout,n.stderr);throw new s("COMMAND_FAILED",e?`Failed to access Android app sandbox for ${t}`:`Failed to probe Android app sandbox for ${t}`,{package:t,cmd:"adb",args:a,stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode,hint:e?r$:"adb shell run-as probe failed. Check adb connectivity and that the device is reachable. Inspect stderr/details for more information."})}try{await tl(e,["shell","run-as",t,"mkdir","-p","shared_prefs"]),await tl(e,["shell","run-as",t,"tee",rP],{stdin:r.trimEnd()})}catch(a){let e=i(a);if("TOOL_MISSING"===e.code)throw e;let r=rZ("string"==typeof e.details?.stdout?e.details.stdout:"","string"==typeof e.details?.stderr?e.details.stderr:"");throw new s("COMMAND_FAILED",r?`Failed to access Android app sandbox for ${t}`:`Failed to write Android runtime hints for ${t}`,{...e.details??{},package:t,cmd:"adb",phase:"write-runtime-hints",hint:r?r$:"adb run-as succeeded, but writing ReactNativeDevPrefs.xml failed. Inspect stderr/details for the failing shell command."},e)}}async function rH(e,t,r){await l(eE(e,["spawn",e.id,"defaults","write",t,rC,"-string",`${r.host}:${r.port}`])),await l(eE(e,["spawn",e.id,"defaults","write",t,rE,"-string",r.scheme]))}async function rj(e,t){await l(eE(e,["spawn",e.id,"defaults","delete",t,rC]),{allowFailure:!0}),await l(eE(e,["spawn",e.id,"defaults","delete",t,rE]),{allowFailure:!0})}function rz(e){let t=e.trim();return t.includes("<map")&&t.includes("</map>")?`${t}
|
|
2
|
-
`:
|
|
3
|
-
</map>`)}function
|
|
4
|
-
${t}`.toLowerCase();return["run-as: package not debuggable","run-as: permission denied","run-as: package is unknown","run-as: unknown package","is unknown","is not an application","could not set capabilities"].some(e=>r.includes(e))}let rQ=["platform","metroHost","metroPort","bundleUrl","launchUrl"];function r0(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>void 0!==e&&""!==e).length:0}function r1(e,t){if(void 0!==e){if("string"!=typeof e)throw new s("INVALID_ARGS",`Invalid open runtime ${t}: expected string.`);return to(e)}}function r3(e){if(void 0!==e){if(!Number.isInteger(e)||e<1||e>65535)throw new s("INVALID_ARGS",`Invalid runtime metroPort: ${String(e)}. Use an integer between 1 and 65535.`);return e}}function r2(e){if("ios"===e||"android"===e)return e}async function r5(e){let{replacedStoredRuntime:t,previousRuntime:r,runtime:a,session:n}=e;!t||!n?.appBundleId||!rU(r)||rU(a)||await rq({device:n.device,appId:n.appBundleId})}async function r4(e){var t,r;let{req:a,sessionName:n,sessionStore:i}=e,o=(a.positionals?.[0]??"show").toLowerCase(),s=i.get(n),l=i.getRuntimeHints(n);if(!["set","show","clear"].includes(o))return L("INVALID_ARGS","runtime requires set, show, or clear");if("clear"===o){rU(l)&&s?.appBundleId&&await rq({device:s.device,appId:s.appBundleId});let e=i.clearRuntimeHints(n);return{ok:!0,data:{session:n,cleared:e}}}if("show"===o)return{ok:!0,data:{session:n,configured:!!l,runtime:l}};let u=r2(tA(a.flags?.platform)??l?.platform??s?.device.platform);if(!u)return L("INVALID_ARGS","runtime set only supports iOS and Android sessions. Pass --platform ios|android or open an iOS/Android session first.");if(s&&s.device.platform!==u)return L("INVALID_ARGS",`runtime set targets ${u}, but session "${n}" is already bound to ${s.device.platform}.`);let d={platform:(t=a.flags,r={platform:u,metroHost:to(t?.metroHost),metroPort:r3(t?.metroPort),bundleUrl:to(t?.bundleUrl),launchUrl:to(t?.launchUrl)}).platform??l?.platform,metroHost:r.metroHost??l?.metroHost,metroPort:r.metroPort??l?.metroPort,bundleUrl:r.bundleUrl??l?.bundleUrl,launchUrl:r.launchUrl??l?.launchUrl};return 0===r0(d)?L("INVALID_ARGS","runtime set requires at least one hint such as --metro-host, --metro-port, --bundle-url, or --launch-url."):(i.setRuntimeHints(n,d),{ok:!0,data:{session:n,configured:!0,runtime:d}})}let r6="open-command-roundtrip",r8="Not implemented for this platform in this release.";function r7(e){let{existingSession:t,sessionName:r,sessionScope:a,device:n,surface:i,appBundleId:o,appName:s,saveScript:l}=e;return t?{...t,device:n,surface:i,appBundleId:o,appName:s,recordSession:t.recordSession||l,snapshot:void 0}:{name:r,sessionScope:a,device:n,createdAt:Date.now(),surface:i,appBundleId:o,appName:s,recordSession:l,actions:[]}}let r9=new Set(["app","desktop","frontmost-app"]);async function ae(e){if("app"===e||"desktop"===e||"menubar"===e)return{};let t=await e$();return{appBundleId:t.bundleId,appName:t.appName}}async function at(e,t,r){if(("ios"===e.platform||"macos"===e.platform)&&t)return th(t)?"macos"===e.platform?void 0:"device"===e.kind?tp(r,t):tf(t)?void 0:r??await ar(e,t):await aa(e,t)}async function ar(e,t){try{let{resolveIosSimulatorDeepLinkBundleId:r}=await import("./apps.js");return await r(e,t)}catch{return}}async function aa(e,t){try{let{resolveIosApp:r}=await import("./apps.js");return await r(e,t)}catch{return}}async function an(e,t){if(!("android"!==e.platform||!t||th(t)))try{let{resolveAndroidApp:r}=await import("./3340.js"),a=await r(e,t);return"package"===a.type?a.value:void 0}catch{return}}async function ai(e,t,r){if(r||"android"!==e.platform||!t||!th(t))return r;try{let{getAndroidAppState:t}=await import("./3340.js"),a=await t(e);return a.package?.trim()||r}catch{return r}}async function ao(e,t,r,a){return await at(e,t,r)??await a(e,t)??("android"===e.platform&&t&&th(t)?r:void 0)}function as(e){return L("INVALID_ARGS",e)}function al(e,t,r,a){try{return function(e){let{device:t,surfaceFlag:r,openTarget:a,existingSurface:n}=e;if(("macos"===t.platform||"linux"===t.platform)&&!r)return n??"app";if("linux"===t.platform){if(!r)return"app";let e=tt(r);if(!r9.has(e))throw new s("INVALID_ARGS",`Linux supports --surface app, desktop, and frontmost-app (got "${r}")`);if("app"!==e&&a)throw new s("INVALID_ARGS",`open --surface ${e} does not accept an app target`);return e}if("macos"!==t.platform){if(r)throw new s("INVALID_ARGS","surface is only supported on macOS and Linux");return"app"}let i=r?tt(r):"app";if("app"!==i&&"menubar"!==i&&a)throw new s("INVALID_ARGS",`open --surface ${i} does not accept an app target`);return i}({device:e,surfaceFlag:t,openTarget:r,existingSurface:a})}catch(e){return L(e instanceof s?e.code:"INVALID_ARGS",String(e.message))}}function au(e){let{shouldRelaunch:t,openTarget:r,surface:a,device:n}=e;return t?r&&th(r)?as("open --relaunch does not support URL targets."):"app"!==a?as("open --relaunch is supported only for app surfaces."):"android"===n.platform&&r&&"binary"===td(r)?as(tg(r)):null:null}async function ad(e){let{req:t,sessionName:r,sessionStore:a,device:n,surface:o,openTarget:l,existingSession:u}=e;await eH(n,{deviceHub:t.flags?.deviceHub===!0});let{appBundleId:d,appName:p}=await ap({device:n,surface:o,openTarget:l,existingAppBundleId:u?.appBundleId}),c=function(e){try{return{ok:!0,data:function(e){let{req:t,sessionStore:r,sessionName:a,device:n}=e,i=r.getRuntimeHints(a),o=function(e){let{runtime:t,sessionName:r,platform:a}=e;if(void 0===t)return;if(!t||"object"!=typeof t||Array.isArray(t))throw new s("INVALID_ARGS","open runtime must be an object.");let n=Object.keys(t).find(e=>!rQ.includes(e));if(n)throw new s("INVALID_ARGS",`Invalid open runtime field: ${n}. Supported fields are ${rQ.join(", ")}.`);return{platform:function(e,t,r){if(void 0===e)return r;if("ios"!==e&&"android"!==e)throw new s("INVALID_ARGS",`Invalid open runtime platform: ${String(e)}. Use "ios" or "android".`);if(r&&e!==r)throw new s("INVALID_ARGS",`open runtime targets ${e}, but session "${t}" is bound to ${r}.`);return e}(t.platform,r,a),metroHost:r1(t.metroHost,"metroHost"),metroPort:function(e){if(void 0!==e){if("number"!=typeof e)throw new s("INVALID_ARGS","Invalid open runtime metroPort: expected integer.");return r3(e)}}(t.metroPort),bundleUrl:r1(t.bundleUrl,"bundleUrl"),launchUrl:r1(t.launchUrl,"launchUrl")}}({runtime:t.runtime,sessionName:a,platform:r2(n.platform)});return void 0===t.runtime?{runtime:function(e,t,r){let a=e.getRuntimeHints(t);if(!a)return;let n=r?.platform,i=r2(n);if(a.platform&&r&&!i)throw new s("INVALID_ARGS",`Session runtime hints are only supported on iOS and Android sessions, but session "${t}" is bound to ${n}.`);if(a.platform&&i&&a.platform!==i)throw new s("INVALID_ARGS",`Session runtime hints target ${a.platform}, but session "${t}" is bound to ${n}. Clear the runtime hints or use a different session.`);return i&&a.platform!==i?{...a,platform:i}:a}(r,a,n),previousRuntime:i,replacedStoredRuntime:!1}:{runtime:o&&r0(o)>0?o:void 0,previousRuntime:i,replacedStoredRuntime:!0}}(e)}}catch(t){let e=i(t);return L(e.code,e.message,e.details)}}({req:t,sessionStore:a,sessionName:r,device:n});if(!c.ok)return{type:"response",response:c};if(u){let{runtime:e,previousRuntime:t,replacedStoredRuntime:r}=c.data;await r5({replacedStoredRuntime:r,previousRuntime:t,runtime:e,session:u})}return{type:"details",details:{appBundleId:d,appName:p,runtime:c.data.runtime}}}async function ap(e){let{device:t,surface:r,openTarget:a,existingAppBundleId:n}=e,i=await ae(r);return{appBundleId:i.appBundleId??await ao(t,a,n,an),appName:i.appName??a}}let ac=new Map;async function af(e){let{device:t,closeTarget:r,outFlag:a,context:n}=e;"android"!==t.platform&&await v(t.id),await p(t,"close",[r],a,n),await rD(t,300)}async function am(e){var t,r;let a,{runtime:n,device:i,req:o,logPath:s,appBundleId:l,traceLogPath:u,openPositionals:d}=e,c=n?.launchUrl;if(!c||0===d.length||d.length>1)return;let f=d[0]?.trim();!f||th(f)||await p(i,"open",[c],o.flags?.out,{...(t=s,r=o.flags,a=eu(t,r,l,u),delete a.launchConsole,delete a.launchArgs,a)})}async function ah(e){var t,r,a,n;let i,{req:o,sessionName:s,sessionStore:l,logPath:u,device:d,openTarget:c,openPositionals:f,appName:m,surface:h,appBundleId:g,runtime:w,existingSession:y}=e,v=o.flags?.relaunch===!0,A=y?.trace?.outPath,S=g,b=Date.now(),I={};if(v&&c){let e=S??c,t=Date.now();await af({device:d,closeTarget:e,outFlag:o.flags?.out,context:{...eu(u,o.flags,S??y?.appBundleId,A)}}),I.relaunchCloseDurationMs=Math.max(0,Date.now()-t)}let N=Date.now();await rF({device:d,appId:S,runtime:w}),I.runtimeHintsDurationMs=Math.max(0,Date.now()-N);let D="ios"===d.platform&&"app"===h&&f.length>0,x={verbose:o.flags?.verbose,logPath:u,traceLogPath:A,requestId:o.meta?.requestId,runnerLeaseContext:eu(u,o.flags,S,A,o.meta?.requestId,o.meta).runnerLeaseContext,iosXctestrunFile:o.flags?.iosXctestrunFile,iosXctestDerivedDataPath:o.flags?.iosXctestDerivedDataPath,iosXctestEnvDir:o.flags?.iosXctestEnvDir},M=o.flags?.maestro?.prewarmRunnerBeforeOpen===!0;if(D&&S&&(I.runnerPrewarmKind="session",I.runnerPrewarmScheduled=!0,M)){i=eO(d,{...x,propagateError:!0});let e=Date.now();await i,I.runnerPrewarmWaited=!0,I.runnerPrewarmDurationMs=Math.max(0,Date.now()-e)}let P=Date.now(),O=await ag({req:o,sessionName:s,sessionStore:l,device:d,surface:h,sessionAppBundleId:S,appName:m,existingSession:y});if("response"===O.type)return O.response;let C=O.session??y;await p(d,"open",f,o.flags?.out,{...eu(u,o.flags,S)}),I.openDispatchDurationMs=Math.max(0,Date.now()-P);let E=Date.now();if(await am({runtime:w,device:d,req:o,logPath:u,appBundleId:S,traceLogPath:A,openPositionals:f}),I.launchUrlDurationMs=Math.max(0,Date.now()-E),D&&S&&!i&&(i=eO(d,x)),v&&i&&!0!==I.runnerPrewarmWaited){let e=Date.now();await i,I.runnerPrewarmWaited=!0,I.runnerPrewarmDurationMs=Math.max(0,Date.now()-e)}else i&&!0!==I.runnerPrewarmWaited&&(I.runnerPrewarmWaited=!1);S=await ai(d,c,S),"android"===d.platform&&S&&await eS(d,S);let $=c?(t=S,{durationMs:Math.max(0,Date.now()-P),measuredAt:new Date().toISOString(),method:r6,appTarget:c,appBundleId:t}):void 0,V=Date.now();if(await rD(d,300),I.postOpenSettleDurationMs=Math.max(0,Date.now()-V),eh(o.meta?.requestId)){let e=R();return L(e.code,e.message,e.details)}y&&eG(y,"open",y.snapshot);let U=r7({existingSession:C,sessionName:y?.name??_(o),sessionScope:y?.sessionScope??eR(o),device:d,surface:h,appBundleId:S,appName:m,saveScript:!!o.flags?.saveScript});U.lease=es({req:o,existingLease:y?.lease}),void 0!==o.runtime&&(r=l,a=s,(n=w)&&(0===r0(n)?r.clearRuntimeHints(a):r.setRuntimeHints(a,n)));let F=l.ensureSessionDir(s),q=k(F,o.meta?.requestId??t_().requestId);I.totalDurationMs=Math.max(0,Date.now()-b);let T=function(e){let{sessionName:t,sessionStateDir:r,runnerLogPath:a,requestLogPath:n,appName:i,appBundleId:o,surface:s,startup:l,timing:u,device:d,runtime:p,runtimeHintCount:c}=e,f={session:t,surface:s,sessionStateDir:r,runnerLogPath:a,requestLogPath:n};return i&&(f.appName=i),o&&(f.appBundleId=o),l&&(f.startup=l),u&&(f.timing=u),p&&c(p)>0&&(f.runtime=p),d&&(f.platform=d.platform,f.target=d.target??"mobile",f.device=d.name,f.id=d.id,f.kind=d.kind,"android"===d.platform&&(f.serial=d.id)),d?.platform==="ios"&&(f.device_udid=d.id,f.ios_simulator_device_set=d.simulatorSetPath??null),{...f,...e3(`Opened: ${i??o??t}`)}}({sessionName:U.name,sessionStateDir:F,runnerLogPath:ea(F),requestLogPath:q,appName:m,appBundleId:S,surface:h,startup:$,timing:I,device:d,runtime:w,runtimeHintCount:r0});return l.recordAction(U,{command:"open",positionals:f,flags:o.flags??{},runtime:void 0!==o.runtime?w:void 0,result:T}),l.set(s,U),{ok:!0,data:T}}async function ag(e){let{req:t,sessionName:r,sessionStore:a,device:n,surface:i,sessionAppBundleId:o,appName:s,existingSession:l}=e,u=t.internal?.openLifecycle?.beforeDispatch;if(!u)return{type:"session",session:l};let d=r7({existingSession:l,sessionName:l?.name??_(t),sessionScope:l?.sessionScope??eR(t),device:n,surface:i,appBundleId:o,appName:s,saveScript:!!t.flags?.saveScript});d.lease=es({req:t,existingLease:l?.lease}),a.set(r,d);let p=await u(d);return p&&!p.ok?{type:"response",response:p}:{type:"session",session:a.get(r)??d}}async function aw(e){let{req:t,sessionName:r,logPath:a,sessionStore:n}=e,i=n.get(r);if(i){let e=t.flags?.relaunch===!0,o=t.positionals?.[0],s=o??(e?i.appName:void 0),l=al(i.device,t.flags?.surface,s,i.surface);if("string"!=typeof l)return l;if(!s&&"app"===l)return e?as("open --relaunch requires an app name or an active session app."):as("Session already active. Close it first or pass a new --session name.");let u=au({shouldRelaunch:e,openTarget:s,surface:l,device:i.device});if(u)return u;let d=await rR(i.device),p=await ad({req:t,sessionName:r,sessionStore:n,device:d,surface:l,openTarget:s,existingSession:i});return"response"===p.type?p.response:await ah({req:t,sessionName:r,sessionStore:n,logPath:a,device:d,openTarget:s,openPositionals:o?t.positionals??[]:s?[s]:[],appBundleId:p.details.appBundleId,appName:p.details.appName,runtime:p.details.runtime,surface:l,existingSession:i})}let o=t.flags?.relaunch===!0,s=t.positionals?.[0];if(o&&!s)return as("open --relaunch requires an app argument.");let l=function(e){let{shouldRelaunch:t,openTarget:r,platform:a}=e;return t?r&&th(r)?as("open --relaunch does not support URL targets."):"android"===a&&r&&"binary"===td(r)?as(tg(r)):null:null}({shouldRelaunch:o,openTarget:s,platform:t.flags?.platform==="android"?"android":void 0});if(l)return l;let u=await V(t.flags??{}),d=al(u,t.flags?.surface,s);if("string"!=typeof d)return d;let p=au({shouldRelaunch:o,openTarget:s,surface:d,device:u});return p||await $(ac,u.id,async()=>{let e=n.toArray().find(e=>e.device.id===u.id);if(e)return er(t,e)?L("DEVICE_IN_USE","Device is already in use by another workspace session.",{deviceId:u.id,deviceName:u.name,hint:"Use a different device selector, wait for the other workspace to close its session, or run agent-device devices to choose another target."}):L("DEVICE_IN_USE",`Device is already in use by session "${e.name}".`,{session:e.name,deviceId:u.id,deviceName:u.name,hint:C(e,"device-in-use")});let i=await ad({req:t,sessionName:r,sessionStore:n,device:u,surface:d,openTarget:s});return"response"===i.type?i.response:await ah({req:t,sessionName:r,sessionStore:n,logPath:a,device:u,openTarget:s,openPositionals:t.positionals??[],appBundleId:i.details.appBundleId,appName:i.details.appName,runtime:i.details.runtime,surface:d})})}async function ay(e){if(!1===e.booted)return{success:!0,exitCode:0,stdout:"",stderr:""};try{return rk(e)?await av(e):await aS(e)}catch(t){let e=o(t);return{success:!1,exitCode:-1,stdout:"",stderr:e.message,error:e}}}async function av(e){let t=await tI(e);return t.success?t:"Shutdown"===await aA(e)?{...t,success:!0,exitCode:0}:t}async function aA(e){try{return await tk(e)}catch{return null}}async function aS(e){let t=await tl(e,["emu","kill"],{allowFailure:!0,timeoutMs:15e3});return{success:0===t.exitCode,exitCode:t.exitCode,stdout:String(t.stdout??""),stderr:String(t.stderr??"")}}async function a_(e){let{device:t,shutdownRequested:r}=e;if(r&&(rk(t)||"android"===t.platform&&"emulator"===t.kind))return await ay(t)}async function ab(e){let{req:t,sessionName:r,logPath:a,sessionStore:n,leaseRegistry:i}=e,o=n.get(r);if(!o)return await aI(t,a);try{var s,l,u;(await eI(o),await I(o),await Q(o),await ek(o),s=t,l=o,u=s,(u.positionals?.length??0)>0||"web"===l.device.platform)&&(ty(o.device.platform)&&!rk(o.device)&&await M(o),await p(o.device,"close",t.positionals??[],t.flags?.out,{...eu(a,t.flags,o.appBundleId,o.trace?.outPath)}),await rD(o.device,300));ty(o.device.platform)&&(!rk(o.device)||t.flags?.shutdown||o.recording)?await M(o):ty(o.device.platform)&&tb({level:"debug",phase:"ios_runner_retained_after_close",data:{session:o.name,deviceId:o.device.id}});let e=n.getRuntimeHints(r);rU(e)&&o.appBundleId&&await rq({device:o.device,appId:o.appBundleId}).catch(()=>{}),n.recordAction(o,{command:"close",positionals:t.positionals??[],flags:t.flags??{},result:{session:o.name,...e3(`Closed: ${o.name}`)}}),t.flags?.saveScript&&(o.recordSession=!0),n.writeSessionLog(o),await W(r).catch(()=>{})}finally{E({session:o,leaseRegistry:i}),n.delete(r)}let d=await a_({device:o.device,shutdownRequested:t.flags?.shutdown});return d?{ok:!0,data:e9({session:o.name,shutdown:d},`Closed: ${o.name}`)}:{ok:!0,data:{session:o.name,...e3(`Closed: ${o.name}`)}}}async function aI(e,t){if(!e.positionals||0===e.positionals.length)return L("SESSION_NOT_FOUND","No active session");let r=await rx({session:void 0,flags:e.flags,ensureReady:!0});return await p(r,"close",e.positionals,e.flags?.out,{...eu(t,e.flags)}),await rD(r,300),{ok:!0,data:{app:e.positionals[0],...e3(`Closed: ${e.positionals[0]}`)}}}let ak={ios:async(e,t,r)=>{let{reinstallIosApp:a}=await import("./apps.js");return await a(e,t,r)},android:async(e,t,r)=>{let{reinstallAndroidApp:a}=await import("./3340.js");return await a(e,t,r)}},aN={ios:async(e,t,r)=>{let{installIosApp:a}=await import("./apps.js"),n=await a(e,r,{appIdentifierHint:t});return{bundleId:n.bundleId,appName:n.appName,launchTarget:n.launchTarget}},android:async(e,t,r)=>{let{installAndroidApp:a}=await import("./3340.js"),n=await a(e,r);return{package:n.packageName,appName:n.appName,launchTarget:n.launchTarget}}};async function aD(e){let{req:r,command:a,sessionName:n,sessionStore:i,deployOps:o}=e,s=i.get(n),l=r.flags??{},u=rN(a,s,l);if(u)return u;let d=r.positionals?.[0]?.trim(),p=r.positionals?.[1]?.trim();if(!d||!p)return L("INVALID_ARGS",`${a} requires: ${a} <app> <path-to-app-binary>`);let c=r.meta?.uploadedArtifactId;try{var f;let e,n=c?eA(c,r.meta?.tenantId):ep.expandHome(p);if(!t.existsSync(n))return L("INVALID_ARGS",`App binary not found: ${n}`);let u=await rx({session:s,flags:l,ensureReady:!1});if(!eV(a,u))return L("UNSUPPORTED_OPERATION",`${a} is not supported on this device`);if("ios"===u.platform){let t=await o.ios(u,d,n),r=t.bundleId;e=r?{app:d,appPath:n,platform:"ios",appId:r,bundleId:r,appName:t.appName,launchTarget:t.launchTarget}:{app:d,appPath:n,platform:"ios",appName:t.appName,launchTarget:t.launchTarget}}else{let t=await o.android(u,d,n),r=t.package;e=r?{app:d,appPath:n,platform:"android",appId:r,package:r,packageName:r,appName:t.appName,launchTarget:t.launchTarget}:{app:d,appPath:n,platform:"android",appName:t.appName,launchTarget:t.launchTarget}}let m=e9(e,(f=e,`Installed: ${f.appName??e5(f)}`));return s&&i.recordAction(s,{command:a,positionals:r.positionals??[],flags:r.flags??{},result:m??{}}),{ok:!0,data:m}}finally{c&&N(c)}}async function ax(e,t,r){return await tN(e,t,r)}async function aR(e){let{req:t,sessionName:r,sessionStore:a}=e;if("session_list"===t.command){let e=eR(t);return{ok:!0,data:{sessions:a.toArray().filter(t=>c(t,e)).map(e=>{let t=a.resolveSessionDir(e.name);return{name:e.name,sessionStateDir:t,runnerLogPath:ea(t),platform:e.device.platform,target:e.device.target??"mobile",surface:e.surface??"app",device:e.device.name,id:e.device.id,device_id:e.device.id,createdAt:e.createdAt,..."ios"===e.device.platform&&{device_udid:e.device.id,ios_simulator_device_set:e.device.simulatorSetPath??null}}})}}}if("devices"===t.command)try{let e=tm(t.flags?.androidDeviceAllowlist),r=tA(t.flags?.platform),a=tv({simulatorSetPath:tu(t.flags?.iosSimulatorDeviceSet),platform:r,target:t.flags?.target}),n=await ed({platform:r,target:t.flags?.target,deviceName:t.flags?.device,udid:t.flags?.udid,serial:t.flags?.serial,iosSimulatorSetPath:a,androidSerialAllowlist:e?Array.from(e).sort():void 0}),i=r?n.filter(e=>{var t,a;return t=e,!(a=r)||("apple"===a?ty(t.platform):t.platform===a)}):n,o=(t.flags?.target?i.filter(e=>(e.target??"mobile")===t.flags?.target):i).map(({simulatorSetPath:e,...t})=>t);return{ok:!0,data:{devices:o}}}catch(t){let e=i(t);return L(e.code,e.message,e.details)}if("apps"===t.command){let e=a.get(r),n=t.flags??{},i=rN(t.command,e,n);if(i)return i;let o=await rx({session:e,flags:n,ensureReady:!0});if(!eV("apps",o))return L("UNSUPPORTED_OPERATION","apps is not supported on this device");let s=tx(t.flags?.appsFilter);return ty(o.platform)?{ok:!0,data:{apps:(await tR(o,s)).map(e=>e.name&&e.name!==e.bundleId?`${e.name} (${e.bundleId})`:e.bundleId)}}:{ok:!0,data:{apps:(await tw(o,s)).map(e=>e.name&&e.name!==e.package?`${e.name} (${e.package})`:e.package)}}}return null}async function aM(e){let{ensureAndroidEmulatorBooted:t}=await import("./3340.js");return await t(e)}let aP='iOS appstate requires an active session on the target device. Run open first (for example: open --session sim --platform ios --device "<name>" <app>).',aL='macOS appstate requires an active session on the target device. Run open first (for example: open --session macos --platform macos "System Settings").';async function aO(e){let{req:t,sessionName:r,sessionStore:a}=e,n=a.get(r),i=t.flags??{},o=tA(i.platform);if(!n&&"string"==typeof i?.session&&i.session.trim().length>0)return L("SESSION_NOT_FOUND","ios"===o?`No active session "${r}". Run open with --session ${r} first.`:`No active session "${r}". Run open with --session ${r} first, or omit --session to query by device selector.`);let s=rN("appstate",n,i);if(s)return s;let l=ty(n?.device.platform)&&!!n&&0===eb(n,i).length;if("ios"===o&&!l)return L("SESSION_NOT_FOUND",aP);if("macos"===o&&!l)return L("SESSION_NOT_FOUND",aL);if(l&&n){let e=n.appName??n.appBundleId;if(!n.appName&&!n.appBundleId){if("macos"===n.device.platform&&n.surface&&"app"!==n.surface&&"frontmost-app"!==n.surface)return{ok:!0,data:{platform:n.device.platform,appName:n.surface,appBundleId:n.appBundleId,source:"session",surface:n.surface}};let e="macos"===n.device.platform?"macOS":"iOS";return L("COMMAND_FAILED",`No foreground app is tracked for this ${e} session. Open an app in the session, then retry appstate.`)}return{ok:!0,data:{platform:n.device.platform,appName:e??"unknown",appBundleId:n.appBundleId,source:"session",surface:n.surface??"app",..."ios"===n.device.platform?{device_udid:n.device.id,ios_simulator_device_set:n.device.simulatorSetPath??null}:{}}}}let u=await rx({session:n,flags:i,ensureReady:!0});if("ios"===u.platform)return L("SESSION_NOT_FOUND",aP);if("macos"===u.platform)return L("SESSION_NOT_FOUND",aL);if("web"===u.platform)return L("UNSUPPORTED_OPERATION","appstate is not supported on web.");let{getAndroidAppState:d}=await import("./3340.js"),p=await d(u);return{ok:!0,data:{platform:"android",package:p.package,activity:p.activity}}}async function aC(e){let{req:t,sessionName:r,sessionStore:a}=e;if("boot"===t.command){let e,n=a.get(r),o=t.flags??{},s=rN(t.command,n,o);if(s)return s;let l="android"===(tA(o.platform)??n?.device.platform),u=!0===o.headless;if(u&&!l)return L("INVALID_ARGS","boot --headless is supported only for Android emulators.");let d=rM({flags:o,sessionDevice:n?.device}),p=l&&!!d,c=!1;try{e=await rx({session:n,flags:o,ensureReady:!1})}catch(r){let t=i(r);if(l&&u&&!d&&"DEVICE_NOT_FOUND"===t.code)return L("INVALID_ARGS","boot --headless requires --device <avd-name> (or an Android emulator session target).");if(!p||"DEVICE_NOT_FOUND"!==t.code||!d)throw r;e=await aM({avdName:d,serial:o.serial,headless:u}),c=!0}if(o.target&&(e.target??"mobile")!==o.target)return L("DEVICE_NOT_FOUND",`No ${e.platform} device found matching --target ${o.target}.`);if(l&&u){if("android"!==e.platform||"emulator"!==e.kind)return L("INVALID_ARGS","boot --headless is supported only for Android emulators.");if(!c){let t=rM({flags:o,sessionDevice:n?.device,resolvedDevice:e});if(!t)return L("INVALID_ARGS","boot --headless requires --device <avd-name> (or an Android emulator session target).");e=await aM({avdName:t,serial:o.serial,headless:!0})}await eH(e)}else("android"!==e.platform||!0!==e.booted)&&await eH(e);return eV("boot",e)?{ok:!0,data:{platform:e.platform,target:e.target??"mobile",device:e.name,id:e.id,kind:e.kind,booted:!0}}:L("UNSUPPORTED_OPERATION","boot is not supported on this device")}if("shutdown"===t.command){var n;let e,i=a.get(r),o=t.flags??{},s=rN(t.command,i,o);if(s)return s;let l=await rx({ensureReady:!1,flags:o,session:i});if(!eV("shutdown",l))return L("UNSUPPORTED_OPERATION","shutdown is supported only for Apple simulators and Android emulators.");if(i&&i.device.platform===l.platform&&i.device.id===l.id)return L("DEVICE_IN_USE","Cannot shut down an active session device directly. Use close --shutdown to end the session and turn off the simulator/emulator.",{hint:`Run agent-device close --shutdown --session ${r}`,session:r,platform:l.platform,target:l.target??"mobile",device:l.name,id:l.id,kind:l.kind});let u=await ay(l);return u.success?{ok:!0,data:{platform:l.platform,target:l.target??"mobile",device:l.name,id:l.id,kind:l.kind,shutdown:u}}:L(u.error?.code??"COMMAND_FAILED",(n=u,(e=n.error?.message??n.stderr.trim()).length>0?e:"Shutdown failed"),{platform:l.platform,target:l.target??"mobile",device:l.name,id:l.id,kind:l.kind,shutdown:u})}return"appstate"===t.command?await aO({req:t,sessionName:r,sessionStore:a}):null}async function aE(e,t={}){var r,a,n;let i,o,s,l,u=(s=(o=(i=function(e){let t=[];for(let r of e){if("open"!==r.command)continue;let e=r.result?.startup;e&&"object"==typeof e&&"number"==typeof e.durationMs&&Number.isFinite(e.durationMs)&&"string"==typeof e.measuredAt&&0!==e.measuredAt.trim().length&&e.method===r6&&t.push({durationMs:Math.max(0,Math.round(e.durationMs)),measuredAt:e.measuredAt,method:r6,appTarget:"string"==typeof e.appTarget&&e.appTarget.length>0?e.appTarget:void 0,appBundleId:"string"==typeof e.appBundleId&&e.appBundleId.length>0?e.appBundleId:void 0})}return t.slice(-20)}((r=e).actions)).at(-1))?{available:!0,lastDurationMs:o.durationMs,lastMeasuredAt:o.measuredAt,method:r6,sampleCount:i.length,samples:i}:{available:!1,reason:"No startup sample captured yet. Run open <app|url> in this session first.",method:r6},{session:r.name,platform:r.device.platform,device:r.device.name,deviceId:r.device.id,metrics:{startup:s,...{fps:aU(),memory:{available:!1,reason:r8},cpu:{available:!1,reason:r8}}},sampling:{startup:{method:r6,description:"Elapsed wall-clock time around dispatching the open command for the active session app target.",unit:"ms"},..."android"===(a=r).device.platform?{memory:{method:eq,description:eP,unit:"kB"},cpu:{method:ec,description:en,unit:"percent"},fps:{method:D,description:e_,unit:"percent",primaryField:"droppedFramePercent",window:"since previous Android gfxinfo reset or app process start",resetsAfterRead:!0,relatedActionsLimit:12}}:z(a.device)}});return aK(e)&&(e.appBundleId?"android"===e.device.platform?await aF(u,e,e.appBundleId,t):await aq(u,e,e.appBundleId):(n=u,l=aB(e),n.metrics.fps={available:!1,reason:l},n.metrics.memory={available:!1,reason:l},n.metrics.cpu={available:!1,reason:l})),u}async function a$(e,t={}){var r,a;let n={session:(r=e).name,platform:r.device.platform,device:r.device.name,deviceId:r.device.id,metrics:{fps:aU()},sampling:{fps:"android"===(a=r).device.platform?{method:D,description:e_,unit:"percent",primaryField:"droppedFramePercent",window:"since previous Android gfxinfo reset or app process start",resetsAfterRead:!0,relatedActionsLimit:12}:x(a.device)}};return aK(e)&&(e.appBundleId?await aG(n,e,e.appBundleId,t):n.metrics.fps={available:!1,reason:aB(e)}),n}async function aV(e,t){var r,a;let n={session:(r=e).name,platform:r.device.platform,device:r.device.name,deviceId:r.device.id,sampling:{memory:"android"===(a=r).device.platform?{method:eq,description:eP,unit:"kB",topConsumerLimit:5}:z(a.device).memory,snapshot:"android"===r.device.platform?{method:B,description:G,defaultKind:"android-hprof",artifactOnly:!0}:{method:eM,description:d,defaultKind:"memgraph",artifactOnly:!0}}};if(!aK(e)){if("snapshot"===t.action){let r=aX(e,t.kind);return n.artifact=aY(e,r),n.support=aQ(n.artifact.support)??aZ(e),n}return n.metrics={memory:{available:!1,reason:r8}},n}return"sample"===t.action?n.metrics={memory:await az(e,t)}:(n.artifact=await aJ(e,t),n.support=aQ(n.artifact.support)??aZ(e)),n}function aU(){return{available:!1,reason:"Dropped-frame sampling is currently available only on Android app sessions and connected iOS device app sessions."}}async function aF(e,t,r,a){let n=await aH(t,r,a);aT(e,t,n)}async function aq(e,t,r){let a=await aj(t,r);aT(e,t,a)}function aT(e,t,r){e.metrics.memory=a1(r.memory),e.metrics.cpu=a1(r.cpu),e.metrics.fps=a3(a1(r.fps),t)}async function aG(e,t,r,a){let n="android"===t.device.platform?await a0(eF(t.device,r,{adb:a.androidAdb})):await a0(m(t.device,r));e.metrics.fps=a3(a1(n),t)}function aK(e){return"android"===e.device.platform||"ios"===e.device.platform||"macos"===e.device.platform}function aB(e){return"android"===e.device.platform?"No Android app package is associated with this session. Run open <app> first.":"No Apple app bundle ID is associated with this session. Run open <app> first."}async function aH(e,t,r){let a={adb:r.androidAdb},[n,i,o]=await Promise.allSettled([T(e.device,t,a),K(e.device,t,a),eF(e.device,t,a)]);return{memory:n,cpu:i,fps:o}}async function aj(e,t){let r=await a0(m(e.device,t)),a=await a0(eU(e.device,t));if("fulfilled"===a.status){let e=a.value;return{memory:{status:"fulfilled",value:e.memory},cpu:{status:"fulfilled",value:e.cpu},fps:r}}return{memory:{status:"rejected",reason:a.reason},cpu:{status:"rejected",reason:a.reason},fps:r}}async function az(e,t){return e.appBundleId?a1("android"===e.device.platform?await a0(T(e.device,e.appBundleId,{adb:t.androidAdb})):await a0(aW(e))):{available:!1,reason:aB(e)}}async function aW(e){if(!e.appBundleId)throw new s("INVALID_ARGS",aB(e));return(await eU(e.device,e.appBundleId)).memory}async function aJ(e,t){if(!e.appBundleId)throw new s("INVALID_ARGS",aB(e),{hint:"Run open <app> first so perf memory snapshot can resolve the app process."});let a=aX(e,t.kind),n=function(e,t){if(e.out)return ep.expandHome(e.out,e.cwd);let a=new Date().toISOString().replace(/[:.]/g,"-"),n=e.sessionStore.ensureSessionDir(e.sessionName);return r.join(n,"artifacts",`memory-${t}-${a}.${"android-hprof"===t?"hprof":"memgraph"===t?"memgraph":"artifact"}`)}(t,a);return"android"===e.device.platform?"android-hprof"!==a?aY(e,a):await A(e.device,e.appBundleId,n,{adb:t.androidAdb}):"memgraph"!==a?aY(e,a):await h(e.device,e.appBundleId,n)}function aX(e,t){return t||("android"===e.device.platform?"android-hprof":"memgraph")}function aY(e,t){var r,a;let n=aZ(e),i=(r=e,a=t,"android"===r.device.platform?{reason:`Android perf memory snapshot supports android-hprof, not ${a}.`,hint:"Use perf memory snapshot --kind android-hprof for Android Java heap artifacts."}:"ios"===r.device.platform||"macos"===r.device.platform?{reason:`Apple perf memory snapshot supports memgraph, not ${a}.`,hint:"Use perf memory snapshot --kind memgraph for supported Apple app sessions."}:{reason:`Memory snapshot artifacts are not supported on ${r.device.platform}.`,hint:"Use perf memory sample where supported, or run the snapshot against Android, iOS simulator, or macOS."});return{available:!1,kind:t,reason:i.reason,hint:i.hint,support:n}}function aZ(e){return"android"===e.device.platform?{platform:e.device.platform,defaultKind:"android-hprof",androidHprof:!0,memgraph:!1,heapprofd:!1,heapprofdDecision:"Deferred until Android Perfetto/heapprofd plumbing is available in the perf trace slice."}:"ios"!==e.device.platform&&"macos"!==e.device.platform?{platform:e.device.platform,defaultKind:"memgraph",androidHprof:!1,memgraph:!1,heapprofd:!1,reason:"Memory snapshot artifacts are available only on Android, iOS simulator, and macOS.",hint:"Use perf memory sample where supported, or switch to a platform with memory artifact support.",heapprofdDecision:"Deferred because heapprofd is Android/Perfetto-specific and outside this memory artifact slice."}:{...ef(e.device),androidHprof:!1,heapprofd:!1,heapprofdDecision:"Deferred because heapprofd is Android/Perfetto-specific and outside this memory artifact slice."}}function aQ(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:void 0}async function a0(e){try{return{status:"fulfilled",value:await e}}catch(e){return{status:"rejected",reason:e}}}function a1(e){if("fulfilled"===e.status)return{available:!0,...e.value};let t=o(e.reason);return{available:!1,reason:t.message,error:t}}function a3(e,t){var r,a;let n,i;if(!0!==e.available)return e;let o=(r=t.actions,n=a2((a=e).windowStartedAt),i=a2(a.windowEndedAt)??a2(a.measuredAt),void 0===n||void 0===i?[]:r.filter(e=>e.ts>=n&&e.ts<=i).map(e=>({command:e.command,at:new Date(e.ts).toISOString(),offsetMs:Math.max(0,Math.round(e.ts-n)),target:function(e){let t=e.result;if(t)for(let e of["refLabel","ref","appName","appBundleId"]){let r=t[e];if("string"==typeof r&&r.length>0)return r}}(e)})).slice(-12));return 0===o.length?e:{...e,relatedActions:o}}function a2(e){if("string"!=typeof e)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}async function a5(e){var t,r,a,n,i,s,l,u,d,p;let c,f,m,h,g,w,y=(t=e.req,r=e.area,c=(a=t,n=r,"string"==typeof a.flags?.out&&a.flags.out.length>0?a.flags.out:(a.positionals??[])["cpu"===n?5:4]||void 0),"cpu"===r?(i=t,s=c,f=a4(i,1),m=a4(i,2),h=a4(i,3),ez(f)?"start"!==(l=m)&&"stop"!==l&&"report"!==l?L("INVALID_ARGS","perf cpu profile action must be start, stop, or report"):"simpleperf"!==h?L("INVALID_ARGS","perf cpu profile requires --kind simpleperf"):{ok:!0,area:"cpu",subject:f,action:m,kind:h,outPath:s}:L("INVALID_ARGS",ti)):(u=t,d=c,g=a4(u,1),w=a4(u,2),"start"!==(p=g)&&"stop"!==p?L("INVALID_ARGS","perf trace action must be start or stop"):eQ(w)?"perfetto"!==w?L("INVALID_ARGS","perf trace requires --kind perfetto"):{ok:!0,area:"trace",action:g,kind:w,outPath:d}:L("INVALID_ARGS",e6)));if(!y.ok)return y;let{session:v}=e;if("android"!==v.device.platform)return L("UNSUPPORTED_OPERATION","Android native perf collectors are supported only on Android sessions.");if(!v.appBundleId)return L("COMMAND_FAILED","No Android app package is associated with this session.",{hint:"Run open <app> first so perf can resolve the package and process identity."});try{let t="cpu"===y.area?await a7(e,v,v.appBundleId,y):await a9(e,v,v.appBundleId,y);return{ok:!0,data:t}}catch(e){return{ok:!1,error:o(e)}}}function a4(e,t){return(e.positionals?.[t]??"").toLowerCase()}function a6(e,t){var r;return e.sessionStore.set(e.sessionName,{...e.session,nativePerf:{android:t}}),{action:(r=t).action,platform:"android",type:r.type,kind:r.kind,packageName:r.packageName,appPid:r.appPid,profilerPid:r.profilerPid,state:r.state,startedAt:new Date(r.startedAt).toISOString(),stoppedAt:"number"==typeof r.stoppedAt?new Date(r.stoppedAt).toISOString():void 0,durationMs:r.durationMs,outPath:r.outPath,sizeBytes:r.sizeBytes,remotePath:r.remotePath,method:r.method,summary:r.summary,message:r.message}}function a8(e,t,a){var n,i,o;let s;return t?ep.expandHome(t,e.req.meta?.cwd):(n=e.sessionStore,i=e.sessionName,o=a,s=new Date().toISOString().replace(/[:.]/g,"-"),r.join(n.ensureSessionDir(i),`${s}-${o}`))}async function a7(e,t,r,a){if("start"===a.action){ne(t);let n=a8(e,a.outPath,"cpu.perf.data"),i=await u(t.device,r,n,{adb:e.androidAdbExecutor});return a6(e,i)}let n=nr(t,"cpu-profile",a.kind);if("report"===a.action){await function(e){if("running"===e.state)throw new s("COMMAND_FAILED","Stop the Android Simpleperf CPU profile before generating a report.",{hint:"Run perf cpu profile stop --kind simpleperf, then retry perf cpu profile report --kind simpleperf."})}(n);let r=a8(e,a.outPath,"cpu-report.json");return await eL(t.device,n,r,{adb:e.androidAdbExecutor})}let i=nt(e,a.outPath,n),o=await el(t.device,n,i,{adb:e.androidAdbExecutor});return a6(e,o)}async function a9(e,t,r,a){if("start"===a.action){ne(t);let n=a8(e,a.outPath,"app.perfetto-trace"),i=await y(t.device,r,n,{adb:e.androidAdbExecutor});return a6(e,i)}let n=nr(t,"trace",a.kind),i=nt(e,a.outPath,n),o=await em(t.device,n,i,{adb:e.androidAdbExecutor});return a6(e,o)}function ne(e){let t=e.nativePerf?.android;if(t?.state==="running")throw new s("COMMAND_FAILED",`Android ${t.kind} ${t.type} is already running for this session.`,{hint:"cpu-profile"===t.type?"Run perf cpu profile stop --kind simpleperf before starting another Android native perf capture.":"Run perf trace stop --kind perfetto before starting another Android native perf capture."})}function nt(e,t,r){return t?a8(e,t,r.outPath):r.outPath}function nr(e,t,r){let a=e.nativePerf?.android;if(a?.type===t&&a.kind===r)return a;throw new s("COMMAND_FAILED",`No Android ${r} ${t} is active for this session.`,{hint:"cpu-profile"===t?"Run perf cpu profile start --kind simpleperf first, then stop or report in the same session.":"Run perf trace start --kind perfetto first, then stop in the same session."})}async function na(e,t){let r,a,n=(r=e.req.positionals??[],"cpu"===(a=r[0]?.toLowerCase())?function(e){if(e[1]?.toLowerCase()!=="profile")return L("INVALID_ARGS","perf cpu requires profile");let t=nn(e[2],"perf cpu profile",!0);if(!t.ok)return t;let r=ni(e[3]);return r.ok?{ok:!0,area:"cpu",mode:"cpu-profile",action:t.value,kind:"xctrace",template:e[4]||void 0,outPath:e[5]||void 0,tracePath:e[6]||void 0}:r}(r):"trace"===a?function(e){let t=nn(e[1],"perf trace",!1);if(!t.ok)return t;let r=ni(e[2]);return r.ok?{ok:!0,area:"trace",mode:"trace",action:t.value,kind:"xctrace",template:e[3]||void 0,outPath:e[4]||void 0,tracePath:e[5]||void 0}:r}(r):L("INVALID_ARGS",eJ));if(!n.ok)return n;if("android"===t.device.platform)return L("UNSUPPORTED_OPERATION","Android native profiling belongs to the Android perf rollout; Apple xctrace perf supports iOS and macOS sessions only.");if("ios"!==t.device.platform&&"macos"!==t.device.platform)return L("UNSUPPORTED_OPERATION",`Apple xctrace perf is not supported on ${t.device.platform}.`);if(!t.appBundleId)return L("INVALID_ARGS","Apple xctrace perf requires an active app session. Run open <app> first.");try{if("start"===n.action)return await no(e,t,n);if("stop"===n.action)return await ns(e,t,n);return await nl(e,t,n)}catch(e){return{ok:!1,error:o(e)}}}function nn(e,t,r){let a=e?.toLowerCase();return"start"===a||"stop"===a||r&&"report"===a?{ok:!0,value:a}:L("INVALID_ARGS",r?`${t} requires start, stop, or report`:`${t} requires start or stop`)}function ni(e){return e?.toLowerCase()==="xctrace"?{ok:!0}:L("INVALID_ARGS","perf native collection currently supports --kind xctrace")}async function no(e,t,r){if(t.applePerf?.active)return L("INVALID_ARGS","Apple xctrace perf capture already in progress");let a=r.template??("cpu-profile"===r.mode?"Time Profiler":"Animation Hitches"),n=nd(e,r),i=await H({device:t.device,appBundleId:t.appBundleId,mode:r.mode,template:a,outPath:n});t.applePerf={...t.applePerf??{},active:i},e.sessionStore.set(e.sessionName,t);let o=np("started",i);return nu(e,t,o),{ok:!0,data:o}}async function ns(e,t,r){var a,n,o,s,l,u,d;let p,c=t.applePerf?.active;if(!c)return L("INVALID_ARGS","no active Apple xctrace perf capture");let f=r.outPath?ep.expandHome(r.outPath,e.req.meta?.cwd):c.outPath;try{p=await S(c,f)}catch(r){throw a=r,i(a).details?.captureCleanedUp===!0&&(n=e,(o=t).applePerf={...o.applePerf??{},active:void 0},n.sessionStore.set(n.sessionName,o)),r}s=e,l=t,u=p,l.applePerf={...l.applePerf??{},active:void 0,lastMode:u.mode,..."cpu-profile"===(d=u).mode?{lastProfileTracePath:d.outPath,lastProfileTemplate:d.template}:{lastTracePath:d.outPath}},s.sessionStore.set(s.sessionName,l);let m=np("stopped",p);return nu(e,t,m),{ok:!0,data:m}}async function nl(e,t,r){var a;let n;if("cpu-profile"!==r.mode)return L("INVALID_ARGS","perf trace does not support report");if(t.applePerf?.active)return L("INVALID_ARGS","perf cpu profile report requires a stopped profile trace; stop the active capture first.");let i=nd(e,r),o=(a=t,(n=r.tracePath??a.applePerf?.lastProfileTracePath??a.applePerf?.active?.outPath)?{ok:!0,value:n}:L("INVALID_ARGS","perf cpu profile report requires a stopped profile trace or tracePath option"));if(!o.ok)return o;let s={perf:"reported",...await b({tracePath:ep.expandHome(o.value,e.req.meta?.cwd),outPath:i,mode:r.mode,template:t.applePerf?.lastProfileTemplate??r.template,appBundleId:t.appBundleId})};return nu(e,t,s),{ok:!0,data:s}}function nu(e,t,r){e.sessionStore.recordAction(t,{command:"perf",positionals:e.req.positionals??[],flags:e.req.flags??{},result:r})}function nd(e,t){if(t.outPath)return ep.expandHome(t.outPath,e.req.meta?.cwd);let r=e.sessionStore.ensureSessionDir(e.sessionName),a=new Date().toISOString().replace(/[:.]/g,"-"),n="report"===t.action?"json":"trace";return`${r}/perf-${t.mode}-${a}.${n}`}function np(e,t){return{perf:e,kind:t.kind,mode:t.mode,template:t.template,outPath:t.outPath,appBundleId:t.appBundleId,deviceId:t.deviceId,platform:t.platform,targetPids:t.targetPids,targetProcesses:t.targetProcesses,startedAt:t.startedAt,endedAt:t.endedAt}}let nc=`logs requires ${e7.slice(0,-1).join(", ")}, or ${e7.at(-1)}`,nf=["dump","log"],nm=`network requires ${nf.join(" or ")}`,nh=`network include mode must be one of: ${tP.join(", ")}`,ng={path:({session:e,sessionName:t,sessionStore:r})=>(function(e,t,r){let a=r.resolveAppLogPath(t),n=U(a);return{ok:!0,data:{path:a,active:!!e.appLog,state:e.appLog?.getState()??"inactive",backend:e.appLog?.backend??eo(e.device),sizeBytes:n.sizeBytes,modifiedAt:n.modifiedAt,startedAt:e.appLog?.startedAt?new Date(e.appLog.startedAt).toISOString():void 0,hint:'Grep the file for token-efficient debugging, e.g. grep -n "Error\\|Exception" <path>'}}})(e,t,r),doctor:({session:e,sessionName:t,sessionStore:r})=>n_(e,t,r),mark:({req:e,sessionName:t,sessionStore:r})=>{var a,n,i;let o,s;return a=e,n=t,i=r,o=a.positionals?.slice(1).join(" ")??"",f(s=i.resolveAppLogPath(n),o),{ok:!0,data:{path:s,marked:!0}}},clear:({session:e,sessionName:t,sessionStore:r,restart:a})=>nb(e,t,r,a),start:({session:e,sessionName:t,sessionStore:r})=>nI(e,t,r),stop:({session:e,sessionName:t,sessionStore:r})=>nk(e,t,r)};async function nw(e){let{req:t}=e;return"perf"===t.command?ny(e):"logs"===t.command?nS(e):"network"===t.command?nN(e):null}async function ny(e){var t;let{req:r,sessionName:a,sessionStore:n,androidAdbExecutor:i}=e,l=n.get(a);if(!l)return L("SESSION_NOT_FOUND","perf requires an active session. Run open first.");let u=(r.positionals?.[0]??"metrics").toLowerCase();if("cpu"===(t=u)||"trace"===t)return"android"===l.device.platform?await a5({req:r,sessionName:a,sessionStore:n,session:l,androidAdbExecutor:i,area:u}):await na(e,l);let d=function(e){var t,r,a,n,i,l,u,d,p,c;let f,m,h=e8(f=(e.positionals?.[0]??"metrics").toString().toLowerCase())?f:void 0;if(!h)return L("INVALID_ARGS",eJ);if("cpu"===h||"trace"===h)return{ok:!0,native:!0};let g=ej(m=(e.positionals?.[1]??"sample").toString().toLowerCase())?m:void 0;if(!g)return L("INVALID_ARGS",eY);let w=function(e){if(void 0!==e)return"string"==typeof e&&eQ(e)?e:new s("INVALID_ARGS",e6)}(e.flags?.kind);if(w instanceof s)return{ok:!1,error:o(w)};let y=(t=h,r=g,("memory"===t?nA(r)?void 0:L("INVALID_ARGS","perf memory requires sample or snapshot"):"sample"!==r?L("INVALID_ARGS","perf metrics and perf frames only support sample"):void 0)??(a=e,n=h,i=g,l=w,function(e,t,r){if(e&&("memory"!==t||"snapshot"!==r))return L("INVALID_ARGS","--out is only supported with perf memory snapshot")}(a.flags?.out,n,i)??(u=l,d=n,p=i,u?"memory"!==d||"snapshot"!==p?L("INVALID_ARGS","--kind is only supported with perf memory snapshot"):e0(u)?void 0:L("INVALID_ARGS",e4):void 0)));return y||{ok:!0,native:!1,area:h,action:g,kind:w,out:"string"==typeof(c=e.flags?.out)&&c.length>0?c:void 0}}(r);if(!d.ok)return d;if(d.native)return await na(e,l);try{return{ok:!0,data:await nv(e,l,d)}}catch(e){return{ok:!1,error:o(e)}}}async function nv(e,t,r){let{sessionName:a,sessionStore:n,androidAdbExecutor:i}=e;return"memory"===r.area?await aV(t,{action:function(e){if(nA(e))return e;throw new s("INVALID_ARGS","perf memory requires sample or snapshot")}(r.action),kind:r.kind,out:r.out,cwd:e.req.meta?.cwd,sessionName:a,sessionStore:n,androidAdb:i}):"frames"===r.area?await a$(t,{androidAdb:i}):await aE(t,{androidAdb:i})}function nA(e){return"sample"===e||"snapshot"===e}async function nS(e){var t;let r,a,{req:n,sessionName:i,sessionStore:o}=e,s=o.get(i);if(!s)return L("SESSION_NOT_FOUND","logs requires an active session");if(!eV("logs",s.device))return L("UNSUPPORTED_OPERATION","logs is not supported on this device");let l=(t=n,r=(t.positionals?.[0]??"path").toLowerCase(),a=!!t.flags?.restart,e7.includes(r)?a&&"clear"!==r?L("INVALID_ARGS","logs --restart is only supported with logs clear"):{ok:!0,action:r,restart:a}:L("INVALID_ARGS",nc));return l.ok?await ng[l.action]({...e,session:s,restart:l.restart}):l}async function n_(e,t,r){let a=r.resolveAppLogPath(t),n=await ey(e.device,e.appBundleId);return{ok:!0,data:{path:a,active:!!e.appLog,state:e.appLog?.getState()??"inactive",checks:n.checks,notes:n.notes}}}async function nb(e,t,r,a){if(e.appLog&&!a)return L("INVALID_ARGS","logs clear requires logs to be stopped first; run logs stop");let n=r.resolveAppLogPath(t);if(!a)return{ok:!0,data:J(n)};let i=e.appBundleId;if(!i)return L("INVALID_ARGS","logs clear --restart requires an app session; run open <app> first");e.appLog&&await ex(e.appLog);let s=J(n),l=r.resolveAppLogPidPath(t);try{let a=await eK(e.device,i,n,l);return r.set(t,{...e,appLog:{platform:e.device.platform,backend:a.backend,outPath:n,startedAt:a.startedAt,getState:a.getState,stop:a.stop,wait:a.wait}}),{ok:!0,data:{...s,restarted:!0}}}catch(a){return r.set(t,{...e,appLog:void 0}),{ok:!1,error:o(a)}}}async function nI(e,t,r){if(e.appLog)return L("INVALID_ARGS","app log already streaming; run logs stop first");if(!e.appBundleId)return L("INVALID_ARGS","logs start requires an app session; run open <app> first");let a=r.resolveAppLogPath(t),n=r.resolveAppLogPidPath(t);try{let i=await eK(e.device,e.appBundleId,a,n);return r.set(t,{...e,appLog:{platform:e.device.platform,backend:i.backend,outPath:a,startedAt:i.startedAt,getState:i.getState,stop:i.stop,wait:i.wait}}),{ok:!0,data:{path:a,started:!0}}}catch(e){return{ok:!1,error:o(e)}}}async function nk(e,t,r){if(!e.appLog)return L("INVALID_ARGS","no app log stream active");let a=e.appLog.outPath;return await ex(e.appLog),r.set(t,{...e,appLog:void 0}),{ok:!0,data:{path:a,stopped:!0}}}async function nN(e){let t=function(e){let{req:t,sessionName:r,sessionStore:a}=e,n=a.get(r);if(!n)return L("SESSION_NOT_FOUND","network requires an active session");if(!eV("network",n.device))return L("UNSUPPORTED_OPERATION","network is not supported on this device");let i=(t.positionals?.[0]??"dump").toLowerCase();if(!nf.includes(i))return L("INVALID_ARGS",nm);let o=t.positionals?.[1]?Number.parseInt(t.positionals[1],10):25;if(!Number.isInteger(o)||o<1||o>200)return L("INVALID_ARGS","network dump limit must be an integer in range 1..200");let s=function(e){let t=e.positionals?.[2]?.toLowerCase(),r=e.flags?.networkInclude;if(t&&r&&t!==r)return L("INVALID_ARGS","network include mode was provided both positionally and via --include with different values");let a=(r??t??"summary").toLowerCase();return tP.includes(a)?{ok:!0,include:a}:L("INVALID_ARGS",nh)}(t);return s.ok?{ok:!0,session:n,maxEntries:o,include:s.include}:s}(e);if(!t.ok)return t;let{include:r,maxEntries:a,session:n}=t;if("web"===n.device.platform)return await nD({include:r,maxEntries:a});let i=await ee({device:n.device,appBundleId:n.appBundleId,appLogState:n.appLog?.getState(),appLogStartedAt:n.appLog?.startedAt,appLogPath:e.sessionStore.resolveAppLogPath(e.sessionName),maxEntries:a,include:r,maxPayloadChars:2048,maxScanLines:4e3});return{ok:!0,data:{...i.dump,active:!!n.appLog,state:n.appLog?.getState()??"inactive",backend:i.backend,notes:i.notes}}}async function nD(e){let t=tM();if(!t.dumpNetwork)return L("UNSUPPORTED_OPERATION","network is not supported by this web provider");try{let r=await t.dumpNetwork({include:e.include,limit:e.maxEntries});return{ok:!0,data:{entries:r.entries,active:!0,state:"active",backend:r.backend??"agent-browser",include:e.include,matchedLines:r.entries.length,scannedLines:r.entries.length,limits:{maxEntries:e.maxEntries,maxPayloadChars:2048,maxScanLines:r.entries.length},notes:r.notes}}}catch(e){return{ok:!1,error:o(e)}}}function nx(e,t,r){var a,n;if(null==e)return tB("open",[tW(tj(t,"launchApp"),r)]);if("string"==typeof e)return tB("open",[tW(e,r)]);if(!tH(e))throw new s("INVALID_ARGS","launchApp expects a string or map.");tz(e,"launchApp",["appId","stopApp","clearState","clearKeychain","arguments","permissions","launchArguments"]),nL(e,"permissions"),nL(e,"clearKeychain");let i=tW("string"==typeof e.appId?e.appId:tj(t,"launchApp"),r),o=(a=e,n=r,[...nM(a.arguments,"launchApp.arguments",n),...nM(a.launchArguments,"launchApp.launchArguments",n)]),l=!0===e.clearState;return tB("open",[i],{...!l&&(!0===e.stopApp||o.length>0)?{relaunch:!0}:{},...l?{clearAppState:!0}:{},...o.length>0?{launchArgs:o}:{}})}function nR(e,t,r){if(null==e)return tB("close",[tW(tj(t,"stopApp"),r)]);if("string"==typeof e)return tB("close",[tW(e,r)]);throw new s("INVALID_ARGS","stopApp expects a string appId or no value.")}function nM(e,t,r){if(null==e)return[];if("string"==typeof e)return[tW(e,r)];if(Array.isArray(e))return e.map((e,a)=>nP(e,`${t}[${a}]`,r));if(tH(e))return Object.entries(e).flatMap(([e,a])=>[tW(e,r),nP(a,`${t}.${e}`,r)]);throw new s("INVALID_ARGS",`${t} expects a string, list, or map.`)}function nP(e,t,r){if("string"==typeof e)return tW(e,r);if("number"==typeof e||"boolean"==typeof e)return String(e);throw new s("INVALID_ARGS",`${t} must be a string, number, or boolean.`)}function nL(e,t){if(void 0!==e[t])throw tY(`Maestro launchApp field "${t}" is not supported yet.`)}let nO="__maestroRunScript",nC="__maestroAssertVisible",nE="__maestroAssertNotVisible",n$="__maestroPressEnter",nV="__maestroWaitForAnimationToEnd",nU="__maestroScrollUntilVisible",nF="__maestroSwipeScreen",nq="__maestroSwipeOn",nT="__maestroTapOn",nG="__maestroTapPointPercent";function nK(e){if(null==e)return tB("type",["\b".repeat(50)]);if("number"==typeof e&&Number.isInteger(e)&&e>0)return tB("type",["\b".repeat(e)]);if(!tH(e))throw new s("INVALID_ARGS","eraseText expects empty, a positive count, or a map.");if(tz(e,"eraseText",["charactersToErase"]),void 0===e.charactersToErase)return tB("type",["\b".repeat(50)]);if("number"!=typeof e.charactersToErase||!Number.isInteger(e.charactersToErase)||e.charactersToErase<=0)throw new s("INVALID_ARGS","eraseText.charactersToErase must be a positive integer.");return tB("type",["\b".repeat(e.charactersToErase)])}function nB(e){return"number"==typeof e&&Number.isFinite(e)?String(Math.max(16,Math.floor(e))):void 0}function nH(e,t){let r=e.toLowerCase();switch(r){case"up":case"down":case"left":case"right":return r;default:throw tY(`Maestro ${t} must be UP, DOWN, LEFT, or RIGHT.`)}}function nj(e){return nH(e,"swipe direction")}function nz(e,t,r=[],a){if("string"==typeof e)return nW(tW(e,a));if(!tH(e))throw new s("INVALID_ARGS",`${t} expects a string or selector map.`);tz(e,t,["id","text","enabled","selected",...r]);let n=[],i=[];if("boolean"==typeof e.enabled&&i.push(nX("enabled",String(e.enabled))),"boolean"==typeof e.selected&&i.push(nX("selected",String(e.selected))),"string"==typeof e.id&&n.push(nX("id",tW(e.id,a)),...i),"string"==typeof e.text&&0===n.length)return nW(tW(e.text,a),i);if("string"==typeof e.label&&0===n.length&&n.push(nX("label",tW(e.label,a)),...i),0===n.length&&i.length>0&&n.push(...i),0===n.length)throw new s("INVALID_ARGS",`${t} selector map must include one of id, text, label, enabled, or selected.`);return n.join(" ")}function nW(e,t=[]){return[[nX("label",e),...t].join(" "),[nX("text",e),...t].join(" "),[nX("id",e),...t].join(" ")].join(" || ")}function nJ(e){let t=nB(e.duration);return t?[t]:[]}function nX(e,t){return`${e}=${JSON.stringify(t)}`}function nY(e){var t,r;if(!tH(e))return;let a={},n="number"==typeof(t=e.repeat)&&Number.isInteger(t)&&t>0?t:void 0,i="number"==typeof(r=e.delay)&&Number.isInteger(r)&&r>=0?r:void 0;return n&&n>1&&(a.count=n),void 0!==i&&(a.intervalMs=i),!0===e.optional&&(a.maestro={optional:!0}),Object.keys(a).length>0?a:void 0}function nZ(e){let t=nY(e)??{};return{...t,maestro:{...t.maestro??{},allowNonHittableCoordinateFallback:!0}}}function nQ(e){let t={doubleTap:!0};return tH(e)&&"number"==typeof e.delay&&Number.isInteger(e.delay)&&(t.intervalMs=Math.max(0,e.delay)),t}class n0{index=0;tokens;context;constructor(e,t){this.tokens=e,this.context=t}parse(){let e=this.parseOr();if(this.peek())throw new s("INVALID_ARGS","Unsupported trailing runFlow.when.true expression.");return e}parseOr(){let e=this.parseAnd();for(;this.consumeOperator("||");)e=this.parseAnd()||e;return e}parseAnd(){let e=this.parsePrimary();for(;this.consumeOperator("&&");)e=this.parsePrimary()&&e;return e}parsePrimary(){let e=this.peek();if(!e)throw new s("INVALID_ARGS","Incomplete runFlow.when.true expression.");if("boolean"===e.type)return this.index+=1,e.value;if("paren"===e.type&&"("===e.value){this.index+=1;let e=this.parseOr();if(!this.consumeParen(")"))throw new s("INVALID_ARGS","Unclosed runFlow.when.true parenthesis.");return e}return this.parsePlatformComparison()}parsePlatformComparison(){this.expectPlatform();let e=this.expectEqualityOperator(),t=this.expectString().toLowerCase(),r=this.context.platform;return"=="===e?r===t:r!==t}expectPlatform(){if(this.peek()?.type!=="platform")throw new s("INVALID_ARGS","runFlow.when.true supports maestro.platform comparisons.");this.index+=1}expectEqualityOperator(){let e=this.peek();if(e?.type==="operator"&&("=="===e.value||"!="===e.value))return this.index+=1,e.value;throw new s("INVALID_ARGS","runFlow.when.true comparison requires == or !=.")}expectString(){let e=this.peek();if(e?.type==="string")return this.index+=1,e.value;throw new s("INVALID_ARGS","runFlow.when.true comparison requires a string literal.")}consumeOperator(e){let t=this.peek();return t?.type==="operator"&&t.value===e&&(this.index+=1,!0)}consumeParen(e){let t=this.peek();return t?.type==="paren"&&t.value===e&&(this.index+=1,!0)}peek(){return this.tokens[this.index]}}function n1(e,t,r){return{...tB(e,t),replayControl:r}}function n3(e,t,r){let a="string"==typeof e?tW(e,t):e,n="number"==typeof a?a:"string"==typeof a&&/^\d+$/.test(a)?Number(a):void 0;if(void 0===n||!Number.isInteger(n)||n<0)throw new s("INVALID_ARGS",`${r} must be a non-negative integer or \${VAR} resolving to one.`);return n}let n2=`
|
|
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{access as i}from"node:fs/promises";import{asAppError as o,normalizeError as s,AppError as l}from"./485.js";import{runXcrun as u,installProviderDeviceInstallablePath as d,LOCAL_DEVICE_INVENTORY_PLATFORM_SELECTORS as p,APPLE_MEMGRAPH_SNAPSHOT_DESCRIPTION as c,dispatchCommand as f,sessionMatchesScope as m,appendAppLogMarker as h,countDeviceInventoryByGroup as g,startAndroidSimpleperfProfile as w,installProviderDeviceApp as v,sampleAppleFramePerf as y,captureAppleMemorySnapshot as A,isHostSystemAudioProbeDevice as b,getSessionCommandKind as S,inferFillText as _,startAndroidPerfettoTrace as I,stopIosRunnerSession as k,captureAndroidHeapSnapshot as N,stopAppleXctracePerfCapture as D,resolvePublicSessionName as x,writeAppleXctracePerfReport as R,registerBuiltinPlatformPlugins as M,stopSessionApplePerfCapture as P,cleanupUploadedArtifact as L,resolveSessionRequestLogPath as O,ANDROID_FRAME_SAMPLE_METHOD as $,buildAppleFrameSamplingMetadata as C,createRequestCanceledError as E,stopAppleRunnerForClose as V,isActiveProviderDevice as F,registerRequestAbort as q,errorResponse as T,runHostSystemAudioProbeCommand as U,readReplayTestActionProgress as G,configureProviderPortReverse as H,releaseSessionLease as K,removeProviderPortReverse as B,withKeyedLock as j,buildSessionRecoveryHint as z,resolveTargetDevice as W,getAppLogPathMetadata as J,sampleAndroidMemoryPerf as Y,requireCommandSupported as X,uniqueStrings as Q,setSessionSnapshot as Z,stopSessionAudioProbe as ee,ANDROID_HPROF_SNAPSHOT_DESCRIPTION as et,sampleAndroidCpuPerf as er,ANDROID_HPROF_SNAPSHOT_METHOD as ea,buildDeviceInventoryRequestFromFlags as en,startAppleXctracePerfCapture as ei,buildAppleSamplingMetadata as eo,cleanupRetainedMaterializedPathsForSession as es,clearAppLogFiles as el,tryGetPlugin as eu,getSnapshotReferenceFrame as ed,prepareIosRunner as ep,hasExplicitDeviceSelector as ec,stopSessionAndroidNativePerfCapture as ef,readSessionNetworkCapture as em,cleanupRetainedMaterializedPaths as eh,isImplicitSessionScopeConflict as eg,resolveSessionRunnerLogPath as ew,ANDROID_CPU_SAMPLE_DESCRIPTION as ev,buildSnapshotState as ey,resolveLogBackend as eA,resolveSessionLeaseForRequest as eb,stopAndroidSimpleperfProfile as eS,context_contextFromFlags as e_,listDeviceInventory as eI,SessionStore as ek,ANDROID_CPU_SAMPLE_METHOD as eN,buildAppleMemorySnapshotSupport as eD,stopAndroidPerfettoTrace as ex,isRequestCanceled as eR,resolveRequestTrackingId as eM,retainMaterializedPaths as eP,runAppLogDoctor as eL,resolvePayloadInput as eO,prepareUploadedArtifact as e$,LeaseRegistry as eC,resetAndroidFramePerfStats as eE,listSessionSelectorConflicts as eV,stopSessionAppLog as eF,stopSessionAndroidSnapshotHelper as eq,withReplayTestActionProgress as eT,ANDROID_FRAME_SAMPLE_DESCRIPTION as eU,markRequestCanceled as eG,stopAppLog as eH,resolveImplicitSessionScope as eK,APPLE_MEMGRAPH_SNAPSHOT_METHOD as eB,ANDROID_MEMORY_SAMPLE_DESCRIPTION as ej,writeAndroidSimpleperfReport as ez,prewarmIosRunnerSession as eW,clearRequestCanceled as eJ,buildSimctlArgsForDevice as eY,resolveFrontmostMacOsApp as eX,isCommandSupportedOnDevice as eQ,sampleApplePerfMetrics as eZ,sampleAndroidFramePerf as e0,ANDROID_MEMORY_SAMPLE_METHOD as e1,getRequestSignal as e3,markAndroidSnapshotFreshness as e2,startAppLog as e5,emitRequestProgress as e4}from"./9722.js";import{ensureDeviceReady as e8,buildAppleRunnerRequestOptions as e6,buildAppleRunnerSessionOptions as e7,createAppleRunnerCachePrewarmOnColdBoot as e9,createAppleRunnerCacheColdBootPrewarmForOpen as te}from"./8414.js";import{isPerfAction as tt,isPerfSubject as tr,pointFromPercent as ta,PERF_AREA_ERROR_MESSAGE as tn,buildSwipeGesturePlan as ti,PERF_ACTION_ERROR_MESSAGE as to,buildSnapshotDisplayLines as ts,formatDoctorCheckDetailLines as tl,isPerfKind as tu,isPerfMemoryKind as td,pointInsideRect as tp,successText as tc,clampGesturePoint as tf,resolveDeployResultTarget as tm,PERF_MEMORY_KIND_ERROR_MESSAGE as th,PERF_KIND_ERROR_MESSAGE as tg,isPerfArea as tw,formatDoctorCheckSummaryLine as tv,LOG_ACTION_VALUES as ty,withSuccessText as tA,clampToRange as tb,parseSessionSurface as tS,resolveInstallFromSourceResultTarget as t_,readReactNativeOverlayActionNodes as tI,detectReactNativeOverlay as tk,PERF_SUBJECT_ERROR_MESSAGE as tN}from"./2948.js";import{recordSessionAction as tD}from"./handler-utils.js";import{trimRuntimeValue as tx,resolveRuntimeTransportHints as tR}from"./8936.js";import{resolveAndroidAdbExecutor as tM,runAndroidAdb as tP,resolveIosSimulatorDeviceSetPath as tL,classifyAndroidAppTarget as tO,resolveIosDeviceDeepLinkBundleId as t$,isInfrastructureBootFailureReason as tC,Deadline as tE,isWebUrl as tV,resolveAndroidSerialAllowlist as tF,isDeepLinkTarget as tq,formatAndroidInstalledPackageRequiredMessage as tT,listAndroidApps as tU}from"./3340.js";import{isApplePlatform as tG,resolveAppleSimulatorSetPathForSelector as tH,matchesDeviceSelector as tK,NETWORK_INCLUDE_MODES as tB,isMobilePlatform as tj,matchesPlatformSelector as tz}from"./6849.js";import{getDiagnosticsMeta as tW,emitDiagnostic as tJ}from"./432.js";import{shutdownSimulator as tY,getSimulatorState as tX}from"./simulator.js";import{runBatch as tQ,mergeParentFlags as tZ}from"./6918.js";import{assertResolvedAppsFilter as t0}from"./2748.js";import{listIosApps as t1}from"./apps.js";import{resolveWebProvider as t3}from"./provider.js";import{unsupportedCommand as t2,readEnvMap as t5,parseReplayScriptDetailed as t4,readReplayShellEnvSource as t8,normalizeCommandList as t6,normalizePlatform as t7,readReplayCliEnvEntries as t9,parseMaestroYamlDocuments as re,parseAbsolutePoint as rt,readReplayScriptMetadata as rr,parseReplayCliEnvEntries as ra,collectReplayShellEnv as rn,support_action as ri,isPlainRecord as ro,requireAppId as rs,assertOnlyKeys as rl,resolveMaestroString as ru,requireStringValue as rd,parseMaestroPoint as rp,unsupportedMaestroSyntax as rc,readTimeoutMs as rf,writeReplayScript as rm,buildReplayVarScope as rh,resolveReplayAction as rg,mergeReplayVarScopeValues as rw}from"./4428.js";import{runCmdSync as rv,runCmd as ry}from"./8875.js";import{readSnapshotDiagnosticsSummary as rA,summarizeSnapshotTimingSamples as rb,mergeSnapshotDiagnostics as rS}from"./5913.js";import{resolveSelectorChain as r_,extractNodeText as rI,findSnapshotAncestor as rk,isDescendantOfSnapshotNode as rN,splitIsSelectorArgs as rD,buildSelectorChainForNode as rx,buildSnapshotNodeByIndex as rR,matchesSelector as rM,normalizeType as rP}from"./893.js";import{formatScriptActionSummary as rL,evaluateIsPredicate as rO,isTouchTargetCommand as r$}from"./7871.js";import{splitSelectorFromArgs as rC,normalizeText as rE,tryParseSelectorChain as rV,parseSelectorChain as rF}from"./587.js";import{sleep as rq}from"./5560.js";import{handleRecordCommand as rT}from"./record-trace-recording.js";import{recordingExtensionForPlatform as rU,defaultRecordingPath as rG}from"./5643.js";import{detectProjectRuntimeKind as rH}from"./760.js";import{INTERNAL_COMMANDS as rK,PUBLIC_COMMANDS as rB}from"./1986.js";import{readVersion as rj}from"./1404.js";var rz={};async function rW(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 l("INVALID_ARGS",`install_from_source requested platform ${r}, but session is bound to ${e.session.device.platform}`);return await e8(e.session.device),e.session.device}if(!r)throw new l("INVALID_ARGS",'install_from_source requires platform "ios" or "android" when no session is provided');let a=await W(e.flags??{});return await e8(a),a}async function rJ(e){let{prepared:t,retention:r,req:a,session:n,sessionName:i}=e;if(r.enabled)return await eP({archivePath:t.archivePath,installablePath:t.installablePath,tenantId:a.meta?.tenantId,sessionName:n?i:void 0,ttlMs:r.ttlMs})}function rY(e){return e?{...e.archivePath?{archivePath:e.archivePath}:{},installablePath:e.installablePath,materializationId:e.materializationId,materializationExpiresAt:e.expiresAt}:{}}async function rX(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 l("INVALID_ARGS","install_from_source requires a source payload");switch(t.kind){case"url":if(!t.url||0===t.url.trim().length)throw new l("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 l("INVALID_ARGS","install_from_source path source requires a non-empty path");return t;case"github-actions-artifact":throw new l("UNSUPPORTED_OPERATION","install_from_source github-actions-artifact sources require a compatible remote daemon");default:throw new l("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:e$(i,t.meta?.tenantId)},cleanup:()=>{L(i)}}:{source:e,cleanup:()=>{}}),s=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 l("INVALID_ARGS","install_from_source retentionMs must be a positive integer");return{enabled:!0,ttlMs:r}}(t),u=await rW({session:n,flags:t.flags}),d=X("install",u,{message:"install_from_source is not supported on this device"});if(d)return d;let p=e3(t.meta?.requestId);if("ios"===u.platform){let{prepareIosInstallArtifact:e}=await import("./apps.js"),i=await e(o.source,{signal:p});return await rQ({prepared:i,retention:s,req:t,resolvedSourceCleanup:()=>o.cleanup(),session:n,sessionName:r,sessionStore:a,buildResult:async e=>await rZ(u,i,e)})}let{prepareAndroidInstallArtifact:c}=await import("./3340.js"),f=await c(o.source,{signal:p});return await rQ({prepared:f,retention:s,req:t,resolvedSourceCleanup:()=>o.cleanup(),session:n,sessionName:r,sessionStore:a,buildResult:async e=>await r0(u,f,e)})}catch(e){return{ok:!1,error:s(e)}}}async function rQ(e){let t;try{var r;t=await rJ(e);let a=await e.buildResult(t),n=tA(a,(r=a,`Installed: ${t_(r)}`));return!function(e){let{session:t,sessionStore:r,req:a,data:n}=e;tD(r,t,a,"install_source",n,{positionals:[]})}({session:e.session,sessionStore:e.sessionStore,req:e.req,data:n}),{ok:!0,data:n}}catch(r){throw t&&await eh(t.materializationId,e.req.meta?.tenantId).catch(()=>{}),r}finally{await e.prepared.cleanup(),e.resolvedSourceCleanup()}}async function rZ(e,t,r){var a,n,i;let o,s,u=await d(e,t.installablePath,{appIdentifierHint:t.bundleId});if(!u){let{installIosInstallablePath:r}=await import("./apps.js");await r(e,t.installablePath)}return a=t,n=u,i=r,o=function(e,t){let r=t?.bundleId??e.bundleId;if(r)return r;throw new l("COMMAND_FAILED","Installed iOS app identity could not be resolved from the artifact")}(a,n),s=n?.appName??a.appName,{...rY(i),bundleId:o,...r1(s),launchTarget:n?.launchTarget??o}}async function r0(e,t,r){let a=await d(e,t.installablePath,{packageNameHint:t.packageName}),n=await r3(e,t,a),{inferAndroidAppName:i}=await import("./3340.js"),o=i(n);return{...rY(r),packageName:n,...r1(a?.appName??o),launchTarget:a?.launchTarget??n}}function r1(e){return e?{appName:e}:{}}async function r3(e,t,r){let a=r?.packageName??r?.launchTarget;if(a)return a;let{installAndroidInstallablePathAndResolvePackageName:n}=await import("./3340.js"),i=await n(e,t.installablePath,t.packageName);if(!i)throw new l("COMMAND_FAILED","Installed Android app identity could not be resolved from the artifact or device state");return i}async function r2(e){let{req:t}=e;try{let e=t.meta?.materializationId?.trim();if(!e)throw new l("INVALID_ARGS","release_materialized_paths requires a materializationId");return await eh(e,t.meta?.tenantId),{ok:!0,data:{released:!0,materializationId:e}}}catch(e){return{ok:!1,error:s(e)}}}function r5(e){return"ios"===e.platform&&"simulator"===e.kind}function r4(e,t,r){return t||ec(r)?null:T("INVALID_ARGS",`${e} requires an active session or an explicit device selector (e.g. --platform ios).`)}async function r8(e,t){r5(e)&&!(t<=0)&&await new Promise(e=>setTimeout(e,t))}async function r6(e){let t=ec(e.flags)||!e.session?await W(e.flags??{},{allowStoppedAndroidAvdPlaceholders:e.allowStoppedAndroidAvdPlaceholders}):await r7(e.session.device);return!1!==e.ensureReady&&await e8(t),t}async function r7(e){if("ios"!==e.platform||"simulator"!==e.kind||"darwin"!==process.platform)return e;let t={platform:"ios",target:e.target,udid:e.id,...e.simulatorSetPath?{iosSimulatorDeviceSet:e.simulatorSetPath}:{}};try{return await W(t)}catch(e){if(!(e instanceof l)||"DEVICE_NOT_FOUND"!==e.code)throw e}return await W({platform:"ios",target:e.target,device:e.name,...e.simulatorSetPath?{iosSimulatorDeviceSet:e.simulatorSetPath}:{}})}function r9(e){let t=e.flags?.device?.trim();return t||(e.resolvedDevice?.platform==="android"&&"emulator"===e.resolvedDevice.kind?e.resolvedDevice.name:e.sessionDevice?.platform==="android"&&"emulator"===e.sessionDevice.kind?e.sessionDevice.name:void 0)}e.r(rz),e.d(rz,{handleSessionCommands:()=>lS});let ae="shared_prefs/ReactNativeDevPrefs.xml",at="debug_http_host",ar="dev_server_https",aa="RCT_jsLocation",an="RCT_packager_scheme",ai="React Native runtime hints require adb run-as access to the app sandbox. Verify the app is debuggable and the selected package/device are correct.",ao='<?xml version="1.0" encoding="utf-8" standalone="yes" ?>\n<map>\n</map>\n';function as(e){return void 0!==tR(e)}async function al(e){let{device:t,appId:r,runtime:a}=e;if(F(t)||!r)return;let n=tR(a);if(n){if("android"===t.platform)return void await ad(t,r,n);"ios"===t.platform&&"simulator"===t.kind&&await am(t,r,n)}}async function au(e){let{device:t,appId:r}=e;if(r){if("android"===t.platform)return void await ap(t,r);"ios"===t.platform&&"simulator"===t.kind&&await ah(t,r)}}async function ad(e,t,r){var a,n,i,o,s,l;let u,d;ay(t);let p=(a=await ac(e,t),n=at,i=`${r.host}:${r.port}`,u=` <string name="${aA(n)}">${aA(i)}</string>`,aw(av(a,n),u));o=p,s=ar,l="https"===r.scheme,d=` <boolean name="${aA(s)}" value="${l?"true":"false"}" />`,p=aw(av(o,s),d),await af(e,t,p)}async function ap(e,t){ay(t);let r=await ac(e,t),a=av(r,at),n=av(a,ar);n!==r&&await af(e,t,n)}async function ac(e,t){let r=await tP(e,["shell","run-as",t,"cat",ae],{allowFailure:!0});return 0!==r.exitCode?ao:ag(r.stdout)}async function af(e,t,r){let a=["shell","run-as",t,"id"],n=await tP(e,a,{allowFailure:!0});if(0!==n.exitCode){let e=ab(n.stdout,n.stderr);throw new l("COMMAND_FAILED",e?`Failed to access Android app sandbox for ${t}`:`Failed to probe Android app sandbox for ${t}`,{package:t,cmd:"adb",args:a,stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode,hint:e?ai:"adb shell run-as probe failed. Check adb connectivity and that the device is reachable. Inspect stderr/details for more information."})}try{await tP(e,["shell","run-as",t,"mkdir","-p","shared_prefs"]),await tP(e,["shell","run-as",t,"tee",ae],{stdin:r.trimEnd()})}catch(a){let e=o(a);if("TOOL_MISSING"===e.code)throw e;let r=ab("string"==typeof e.details?.stdout?e.details.stdout:"","string"==typeof e.details?.stderr?e.details.stderr:"");throw new l("COMMAND_FAILED",r?`Failed to access Android app sandbox for ${t}`:`Failed to write Android runtime hints for ${t}`,{...e.details??{},package:t,cmd:"adb",phase:"write-runtime-hints",hint:r?ai:"adb run-as succeeded, but writing ReactNativeDevPrefs.xml failed. Inspect stderr/details for the failing shell command."},e)}}async function am(e,t,r){await u(eY(e,["spawn",e.id,"defaults","write",t,aa,"-string",`${r.host}:${r.port}`])),await u(eY(e,["spawn",e.id,"defaults","write",t,an,"-string",r.scheme]))}async function ah(e,t){await u(eY(e,["spawn",e.id,"defaults","delete",t,aa]),{allowFailure:!0}),await u(eY(e,["spawn",e.id,"defaults","delete",t,an]),{allowFailure:!0})}function ag(e){let t=e.trim();return t.includes("<map")&&t.includes("</map>")?`${t}
|
|
2
|
+
`:ao}function aw(e,t){return ag(e).replace("</map>",`${t}
|
|
3
|
+
</map>`)}function av(e,t){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return ag(e).replace(RegExp(`^\\s*<string name="${r}">[\\s\\S]*?<\\/string>\\n?`,"m"),"").replace(RegExp(`^\\s*<boolean name="${r}" value="(?:true|false)"\\s*\\/?>\\n?`,"m"),"")}function ay(e){if("binary"!==tO(e))return;let t=tT(e);throw new l("INVALID_ARGS",t,{package:e,hint:t})}function aA(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function ab(e,t){let r=`${e}
|
|
4
|
+
${t}`.toLowerCase();return["run-as: package not debuggable","run-as: permission denied","run-as: package is unknown","run-as: unknown package","is unknown","is not an application","could not set capabilities"].some(e=>r.includes(e))}let aS=["platform","metroHost","metroPort","bundleUrl","launchUrl"];function a_(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>void 0!==e&&""!==e).length:0}function aI(e,t){if(void 0!==e){if("string"!=typeof e)throw new l("INVALID_ARGS",`Invalid open runtime ${t}: expected string.`);return tx(e)}}function ak(e){if(void 0!==e){if(!Number.isInteger(e)||e<1||e>65535)throw new l("INVALID_ARGS",`Invalid runtime metroPort: ${String(e)}. Use an integer between 1 and 65535.`);return e}}function aN(e){if("ios"===e||"android"===e)return e}async function aD(e){let{replacedStoredRuntime:t,previousRuntime:r,runtime:a,session:n}=e;!t||!n?.appBundleId||!as(r)||as(a)||await au({device:n.device,appId:n.appBundleId})}async function ax(e){var t,r,a;let{req:n,sessionName:i,sessionStore:o}=e,s=(n.positionals?.[0]??"show").toLowerCase();if("port-reverse"===(t=s)||"port-reverse-remove"===t)return await aM(n,s);if("set"!==(r=s)&&"show"!==r&&"clear"!==r)return T("INVALID_ARGS","runtime requires set, show, clear, port-reverse, or port-reverse-remove");let l=o.get(i),u=o.getRuntimeHints(i);return"clear"===s?await aR(i,o,l,u):"show"===s?{ok:!0,data:{session:i,configured:!!(a=u),runtime:a}}:function(e){var t,r;let{req:a,sessionName:n,sessionStore:i,session:o,current:s}=e,l=aN(a.flags?.platform??s?.platform??o?.device.platform);if(!l)return T("INVALID_ARGS","runtime set only supports iOS and Android sessions. Pass --platform ios|android or open an iOS/Android session first.");if(o&&o.device.platform!==l)return T("INVALID_ARGS",`runtime set targets ${l}, but session "${n}" is already bound to ${o.device.platform}.`);let u={platform:(t=a.flags,r={platform:l,metroHost:tx(t?.metroHost),metroPort:ak(t?.metroPort),bundleUrl:tx(t?.bundleUrl),launchUrl:tx(t?.launchUrl)}).platform??s?.platform,metroHost:r.metroHost??s?.metroHost,metroPort:r.metroPort??s?.metroPort,bundleUrl:r.bundleUrl??s?.bundleUrl,launchUrl:r.launchUrl??s?.launchUrl};return 0===a_(u)?T("INVALID_ARGS","runtime set requires at least one hint such as --metro-host, --metro-port, --bundle-url, or --launch-url."):(i.setRuntimeHints(n,u),{ok:!0,data:{session:n,configured:!0,runtime:u}})}({req:n,sessionName:i,sessionStore:o,session:l,current:u})}async function aR(e,t,r,a){as(a)&&r?.appBundleId&&await au({device:r.device,appId:r.appBundleId});let n=t.clearRuntimeHints(e);return{ok:!0,data:{session:e,cleared:n}}}async function aM(e,t){let r=function(e){var t,r;let a,n,i,o,s=(t=e,a=t.flags?.leaseId,n=t.flags?.leaseProvider,a?n?{ok:!0,leaseId:a,provider:n}:{ok:!1,response:T("INVALID_ARGS","runtime port-reverse requires a lease provider.")}:{ok:!1,response:T("INVALID_ARGS","runtime port-reverse requires a resolved remote lease.")});if(!s.ok)return s;let l=(r=e,i=aL(r.flags?.devicePort),o=aL(r.flags?.hostPort??r.flags?.devicePort),i&&o?{ok:!0,devicePort:i,hostPort:o}:{ok:!1,response:T("INVALID_ARGS","runtime port-reverse requires numeric devicePort and hostPort values from 1 to 65535.")});if(!l.ok)return l;let u=e.flags?.portReverseName?.trim()||"runtime";return{ok:!0,options:{leaseId:s.leaseId,provider:s.provider,devicePort:l.devicePort,hostPort:l.hostPort,name:u}}}(e);if(!r.ok)return r.response;let a=await aP(t,r.options);return a?{ok:!0,data:{action:t,...a}}:T("UNSUPPORTED_OPERATION","No active provider device runtime supports port reverse for this lease.")}async function aP(e,t){return"port-reverse"===e?await H(t):await B(t)}function aL(e){if("number"==typeof e&&Number.isInteger(e)&&!(e<1)&&!(e>65535))return e}let aO="open-command-roundtrip",a$="Not implemented for this platform in this release.";function aC(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 aE=new Set(["app","desktop","frontmost-app"]);async function aV(e){if("app"===e||"desktop"===e||"menubar"===e)return{};let t=await eX();return{appBundleId:t.bundleId,appName:t.appName}}async function aF(e,t,r){if(tG(e.platform)&&t)return tq(t)?"macos"===e.platform?void 0:"device"===e.kind?t$(r,t):tV(t)?void 0:r??await aq(e,t):await aT(e,t)}async function aq(e,t){try{let{resolveIosSimulatorDeepLinkBundleId:r}=await import("./apps.js");return await r(e,t)}catch{return}}async function aT(e,t){try{let{resolveIosApp:r}=await import("./apps.js");return await r(e,t)}catch{return}}async function aU(e,t){if(!("android"!==e.platform||!t||tq(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 aG(e,t,r){if(r||"android"!==e.platform||!t||!tq(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 aH(e,t,r,a){return await aF(e,t,r)??await a(e,t)??("android"===e.platform&&t&&tq(t)?r:void 0)}function aK(e){return T("INVALID_ARGS",e)}function aB(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=tS(r);if(!aE.has(e))throw new l("INVALID_ARGS",`Linux supports --surface app, desktop, and frontmost-app (got "${r}")`);if("app"!==e&&a)throw new l("INVALID_ARGS",`open --surface ${e} does not accept an app target`);return e}if("macos"!==t.platform){if(r)throw new l("INVALID_ARGS","surface is only supported on macOS and Linux");return"app"}let i=r?tS(r):"app";if("app"!==i&&"menubar"!==i&&a)throw new l("INVALID_ARGS",`open --surface ${i} does not accept an app target`);return i}({device:e,surfaceFlag:t,openTarget:r,existingSurface:a})}catch(e){return T(e instanceof l?e.code:"INVALID_ARGS",String(e.message))}}function aj(e){let{shouldRelaunch:t,openTarget:r,surface:a,device:n}=e;return t?r&&tq(r)?aK("open --relaunch does not support URL targets."):"app"!==a?aK("open --relaunch is supported only for app surfaces."):"android"===n.platform&&r&&"binary"===tO(r)?aK(tT(r)):null:null}async function az(e){let{req:t,sessionName:r,sessionStore:a,device:n,surface:i,openTarget:s,existingSession:u,onIosSimulatorColdBootStart:d}=e;await e8(n,{deviceHub:t.flags?.deviceHub===!0,onIosSimulatorColdBootStart:d});let{appBundleId:p,appName:c}=await aW({device:n,surface:i,openTarget:s,existingAppBundleId:u?.appBundleId}),f=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 l("INVALID_ARGS","open runtime must be an object.");let n=Object.keys(t).find(e=>!aS.includes(e));if(n)throw new l("INVALID_ARGS",`Invalid open runtime field: ${n}. Supported fields are ${aS.join(", ")}.`);return{platform:function(e,t,r){if(void 0===e)return r;if("ios"!==e&&"android"!==e)throw new l("INVALID_ARGS",`Invalid open runtime platform: ${String(e)}. Use "ios" or "android".`);if(r&&e!==r)throw new l("INVALID_ARGS",`open runtime targets ${e}, but session "${t}" is bound to ${r}.`);return e}(t.platform,r,a),metroHost:aI(t.metroHost,"metroHost"),metroPort:function(e){if(void 0!==e){if("number"!=typeof e)throw new l("INVALID_ARGS","Invalid open runtime metroPort: expected integer.");return ak(e)}}(t.metroPort),bundleUrl:aI(t.bundleUrl,"bundleUrl"),launchUrl:aI(t.launchUrl,"launchUrl")}}({runtime:t.runtime,sessionName:a,platform:aN(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=aN(n);if(a.platform&&r&&!i)throw new l("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 l("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&&a_(o)>0?o:void 0,previousRuntime:i,replacedStoredRuntime:!0}}(e)}}catch(t){let e=o(t);return T(e.code,e.message,e.details)}}({req:t,sessionStore:a,sessionName:r,device:n});if(!f.ok)return{type:"response",response:f};if(u){let{runtime:e,previousRuntime:t,replacedStoredRuntime:r}=f.data;await aD({replacedStoredRuntime:r,previousRuntime:t,runtime:e,session:u})}return{type:"details",details:{appBundleId:p,appName:c,runtime:f.data.runtime}}}async function aW(e){let{device:t,surface:r,openTarget:a,existingAppBundleId:n}=e,i=await aV(r);return{appBundleId:i.appBundleId??await aH(t,a,n,aU),appName:i.appName??a}}let aJ=new Map;async function aY(e){let{device:t,closeTarget:r,outFlag:a,context:n}=e;"android"!==t.platform&&await k(t.id),await f(t,"close",[r],a,n),await r8(t,300)}async function aX(e){var t,r;let a,{runtime:n,device:i,req:o,logPath:s,appBundleId:l,traceLogPath:u,openPositionals:d}=e,p=n?.launchUrl;if(!p||0===d.length||d.length>1)return;let c=d[0]?.trim();!c||tq(c)||await f(i,"open",[p],o.flags?.out,{...(t=s,r=o.flags,a=e_(t,r,l,u),delete a.launchConsole,delete a.launchArgs,a)})}async function aQ(e){var t,r,a,n;let i,{req:o,sessionName:s,sessionStore:l,logPath:u,device:d,openTarget:p,openPositionals:c,appName:m,surface:h,appBundleId:g,runtime:w,existingSession:v}=e,y=o.flags?.relaunch===!0,A=v?.trace?.outPath,b=g,S=Date.now(),_={};if(y&&p){let e=b??p,t=Date.now();await aY({device:d,closeTarget:e,outFlag:o.flags?.out,context:{...e_(u,o.flags,b??v?.appBundleId,A)}}),_.relaunchCloseDurationMs=Math.max(0,Date.now()-t)}let I=Date.now();await al({device:d,appId:b,runtime:w}),_.runtimeHintsDurationMs=Math.max(0,Date.now()-I);let k="ios"===d.platform&&"app"===h&&c.length>0,N=e7({req:o,logPath:u,appBundleId:b,traceLogPath:A}),D=o.flags?.maestro?.prewarmRunnerBeforeOpen===!0;if(k&&b&&(_.runnerPrewarmKind="session",_.runnerPrewarmScheduled=!0,D)){i=eW(d,{...N,propagateError:!0});let e=Date.now();await i,_.runnerPrewarmWaited=!0,_.runnerPrewarmDurationMs=Math.max(0,Date.now()-e)}let R=Date.now(),M=await aZ({req:o,sessionName:s,sessionStore:l,device:d,surface:h,sessionAppBundleId:b,appName:m,existingSession:v});if("response"===M.type)return M.response;let P=M.session??v;await f(d,"open",c,o.flags?.out,{...e_(u,o.flags,b)}),_.openDispatchDurationMs=Math.max(0,Date.now()-R);let L=Date.now();if(await aX({runtime:w,device:d,req:o,logPath:u,appBundleId:b,traceLogPath:A,openPositionals:c}),_.launchUrlDurationMs=Math.max(0,Date.now()-L),k&&b&&!i&&(i=eW(d,N)),y&&i&&!0!==_.runnerPrewarmWaited){let e=Date.now();await i,_.runnerPrewarmWaited=!0,_.runnerPrewarmDurationMs=Math.max(0,Date.now()-e)}else i&&!0!==_.runnerPrewarmWaited&&(_.runnerPrewarmWaited=!1);b=await aG(d,p,b),"android"===d.platform&&b&&await eE(d,b);let $=p?(t=b,{durationMs:Math.max(0,Date.now()-R),measuredAt:new Date().toISOString(),method:aO,appTarget:p,appBundleId:t}):void 0,C=Date.now();if(await r8(d,300),_.postOpenSettleDurationMs=Math.max(0,Date.now()-C),eR(o.meta?.requestId)){let e=E();return T(e.code,e.message,e.details)}v&&e2(v,"open",v.snapshot);let V=aC({existingSession:P,sessionName:v?.name??x(o),sessionScope:v?.sessionScope??eK(o),device:d,surface:h,appBundleId:b,appName:m,saveScript:!!o.flags?.saveScript});V.lease=eb({req:o,existingLease:v?.lease}),void 0!==o.runtime&&(r=l,a=s,(n=w)&&(0===a_(n)?r.clearRuntimeHints(a):r.setRuntimeHints(a,n)));let F=l.ensureSessionDir(s),q=O(F,o.meta?.requestId??tW().requestId);_.totalDurationMs=Math.max(0,Date.now()-S);let U=function(e){let{sessionName:t,sessionStateDir:r,runnerLogPath:a,requestLogPath:n,appName:i,appBundleId:o,surface:s,startup:l,timing:u,device:d,runtime:p,runtimeHintCount:c}=e,f={session:t,surface:s,sessionStateDir:r,runnerLogPath:a,requestLogPath:n};return i&&(f.appName=i),o&&(f.appBundleId=o),l&&(f.startup=l),u&&(f.timing=u),p&&c(p)>0&&(f.runtime=p),d&&(f.platform=d.platform,f.target=d.target??"mobile",f.device=d.name,f.id=d.id,f.kind=d.kind,"android"===d.platform&&(f.serial=d.id)),d?.platform==="ios"&&(f.device_udid=d.id,f.ios_simulator_device_set=d.simulatorSetPath??null),{...f,...tc(`Opened: ${i??o??t}`)}}({sessionName:V.name,sessionStateDir:F,runnerLogPath:ew(F),requestLogPath:q,appName:m,appBundleId:b,surface:h,startup:$,timing:_,device:d,runtime:w,runtimeHintCount:a_});return l.recordAction(V,{command:"open",positionals:c,flags:o.flags??{},runtime:void 0!==o.runtime?w:void 0,result:U}),l.set(s,V),{ok:!0,data:U}}async function aZ(e){let{req:t,sessionName:r,sessionStore:a,device:n,surface:i,sessionAppBundleId:o,appName:s,existingSession:l}=e,u=t.internal?.openLifecycle?.beforeDispatch;if(!u)return{type:"session",session:l};let d=aC({existingSession:l,sessionName:l?.name??x(t),sessionScope:l?.sessionScope??eK(t),device:n,surface:i,appBundleId:o,appName:s,saveScript:!!t.flags?.saveScript});d.lease=eb({req:t,existingLease:l?.lease}),a.set(r,d);let p=await u(d);return p&&!p.ok?{type:"response",response:p}:{type:"session",session:a.get(r)??d}}async function a0(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=aB(i.device,t.flags?.surface,s,i.surface);if("string"!=typeof l)return l;if(!s&&"app"===l)return e?aK("open --relaunch requires an app name or an active session app."):aK("Session already active. Close it first or pass a new --session name.");let u=aj({shouldRelaunch:e,openTarget:s,surface:l,device:i.device});if(u)return u;let d=await r7(i.device),p=await az({req:t,sessionName:r,sessionStore:n,device:d,surface:l,openTarget:s,existingSession:i,onIosSimulatorColdBootStart:te({req:t,logPath:a,device:d,surface:l,openTarget:s,traceLogPath:i.trace?.outPath})});return"response"===p.type?p.response:await aQ({req:t,sessionName:r,sessionStore:n,logPath:a,device:d,openTarget:s,openPositionals:o?t.positionals??[]:s?[s]:[],appBundleId:p.details.appBundleId,appName:p.details.appName,runtime:p.details.runtime,surface:l,existingSession:i})}let o=t.flags?.relaunch===!0,s=t.positionals?.[0];if(o&&!s)return aK("open --relaunch requires an app argument.");let l=function(e){let{shouldRelaunch:t,openTarget:r,platform:a}=e;return t?r&&tq(r)?aK("open --relaunch does not support URL targets."):"android"===a&&r&&"binary"===tO(r)?aK(tT(r)):null:null}({shouldRelaunch:o,openTarget:s,platform:t.flags?.platform==="android"?"android":void 0});if(l)return l;let u=await W(t.flags??{}),d=aB(u,t.flags?.surface,s);if("string"!=typeof d)return d;let p=aj({shouldRelaunch:o,openTarget:s,surface:d,device:u});return p||await j(aJ,u.id,async()=>{let e=n.toArray().find(e=>e.device.id===u.id);if(e)return eg(t,e)?T("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."}):T("DEVICE_IN_USE",`Device is already in use by session "${e.name}".`,{session:e.name,deviceId:u.id,deviceName:u.name,hint:z(e,"device-in-use")});let i=await az({req:t,sessionName:r,sessionStore:n,device:u,surface:d,openTarget:s,onIosSimulatorColdBootStart:te({req:t,logPath:a,device:u,surface:d,openTarget:s})});return"response"===i.type?i.response:await aQ({req:t,sessionName:r,sessionStore:n,logPath:a,device:u,openTarget:s,openPositionals:t.positionals??[],appBundleId:i.details.appBundleId,appName:i.details.appName,runtime:i.details.runtime,surface:d})})}async function a1(e){if(!1===e.booted)return{success:!0,exitCode:0,stdout:"",stderr:""};try{return r5(e)?await a3(e):await a5(e)}catch(t){let e=s(t);return{success:!1,exitCode:-1,stdout:"",stderr:e.message,error:e}}}async function a3(e){let t=await tY(e);return t.success?t:"Shutdown"===await a2(e)?{...t,success:!0,exitCode:0}:t}async function a2(e){try{return await tX(e)}catch{return null}}async function a5(e){let t=await tP(e,["emu","kill"],{allowFailure:!0,timeoutMs:15e3});return{success:0===t.exitCode,exitCode:t.exitCode,stdout:String(t.stdout??""),stderr:String(t.stderr??"")}}async function a4(e){let{device:t,shutdownRequested:r}=e;if(r&&(r5(t)||"android"===t.platform&&"emulator"===t.kind))return await a1(t)}async function a8(e){let t,{req:r,sessionName:a,logPath:n,sessionStore:i,leaseRegistry:o,leaseLifecycleProvider:s}=e,l=i.get(a);if(!l)return await a6(r,n);try{var u,d,p;(await eF(l),await ee(l,"session-close"),await P(l),await ef(l),await eq(l),u=r,d=l,p=u,(p.positionals?.length??0)>0||"web"===d.device.platform)&&(tG(l.device.platform)&&!r5(l.device)&&await V(l),await f(l.device,"close",r.positionals??[],r.flags?.out,{...e_(n,r.flags,l.appBundleId,l.trace?.outPath)}),await r8(l.device,300));tG(l.device.platform)&&(!r5(l.device)||r.flags?.shutdown||l.recording)?await V(l):tG(l.device.platform)&&tJ({level:"debug",phase:"ios_runner_retained_after_close",data:{session:l.name,deviceId:l.device.id}});let e=i.getRuntimeHints(a);as(e)&&l.appBundleId&&await au({device:l.device,appId:l.appBundleId}).catch(()=>{}),tD(i,l,r,"close",{session:l.name,...tc(`Closed: ${l.name}`)}),r.flags?.saveScript&&(l.recordSession=!0),i.writeSessionLog(l),await es(a).catch(()=>{})}finally{try{t=await K({session:l,leaseRegistry:o,leaseLifecycleProvider:s})}finally{i.delete(a)}}let c=await a4({device:l.device,shutdownRequested:r.flags?.shutdown});return c?{ok:!0,data:tA({session:l.name,shutdown:c,...t?{provider:t}:{}},`Closed: ${l.name}`)}:{ok:!0,data:{session:l.name,...tc(`Closed: ${l.name}`),...t?{provider:t}:{}}}}async function a6(e,t){if(!e.positionals||0===e.positionals.length)return T("SESSION_NOT_FOUND","No active session");let r=await r6({session:void 0,flags:e.flags,ensureReady:!0});return await f(r,"close",e.positionals,e.flags?.out,{...e_(t,e.flags)}),await r8(r,300),{ok:!0,data:{app:e.positionals[0],...tc(`Closed: ${e.positionals[0]}`)}}}let a7={ios:async(e,t,r)=>{let a=await v(e,t,r,{relaunch:!0,appIdentifierHint:t});if(a)return{bundleId:a.bundleId??a.launchTarget??t};let{reinstallIosApp:n}=await import("./apps.js");return await n(e,t,r)},android:async(e,t,r)=>{let a=await v(e,t,r,{relaunch:!0,packageNameHint:t});if(a)return{package:a.packageName??a.launchTarget??t};let{reinstallAndroidApp:n}=await import("./3340.js");return await n(e,t,r)}},a9={ios:async(e,t,r)=>{let a=await v(e,t,r,{appIdentifierHint:t});if(a)return{bundleId:a.bundleId,appName:a.appName,launchTarget:a.launchTarget};let{installIosApp:n}=await import("./apps.js"),i=await n(e,r,{appIdentifierHint:t});return{bundleId:i.bundleId,appName:i.appName,launchTarget:i.launchTarget}},android:async(e,t,r)=>{let a=await v(e,t,r,{packageNameHint:t});if(a)return{package:a.packageName,appName:a.appName,launchTarget:a.launchTarget};let{installAndroidApp:n}=await import("./3340.js"),i=await n(e,r);return{package:i.packageName,appName:i.appName,launchTarget:i.launchTarget}}};async function ne(e){let{req:r,command:a,sessionName:n,sessionStore:i,deployOps:o}=e,s=i.get(n),l=r.flags??{},u=r4(a,s,l);if(u)return u;let d=function(e,t){let r=t[0]?.trim(),a=t[1]?.trim();if("install"===e){let e=a??r;return e?{ok:!0,app:a?r??"":"",appPathInput:e}:{ok:!1,response:T("INVALID_ARGS","install requires: install <path-to-app-binary>")}}return r&&a?{ok:!0,app:r,appPathInput:a}:{ok:!1,response:T("INVALID_ARGS","reinstall requires: reinstall <app> <path-to-app-binary>")}}(a,r.positionals??[]);if(!d.ok)return d.response;let{app:p,appPathInput:c}=d,f=r.meta?.uploadedArtifactId;try{var m,h,g,w,v,y,A;let e,n,u=f?e$(f,r.meta?.tenantId):ek.expandHome(c);if(!t.existsSync(u))return T("INVALID_ARGS",`App binary not found: ${u}`);let d=await r6({session:s,flags:l,ensureReady:!1}),b=X(a,d);if(b)return b;let S="ios"===d.platform?(m=p,h=u,e=(g=await o.ios(d,p,u)).bundleId,{app:m||e||g.launchTarget||h,appPath:h,platform:"ios",...e?{appId:e,bundleId:e}:{},appName:g.appName,launchTarget:g.launchTarget}):(w=p,v=u,n=(y=await o.android(d,p,u)).package,{app:w||n||y.launchTarget||v,appPath:v,platform:"android",...n?{appId:n,package:n,packageName:n}:{},appName:y.appName,launchTarget:y.launchTarget}),_=tA(S,(A=S,`Installed: ${A.appName??tm(A)}`));return tD(i,s,r,a,_),{ok:!0,data:_}}finally{f&&L(f)}}async function nt(e,t,r){return await tQ(e,t,r)}async function nr(e){let{req:t,sessionName:r,sessionStore:a}=e;if("session_list"===t.command){let e=eK(t);return{ok:!0,data:{sessions:a.toArray().filter(t=>m(t,e)).map(e=>{let t=a.resolveSessionDir(e.name);return{name:e.name,sessionStateDir:t,runnerLogPath:ew(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=tF(t.flags?.androidDeviceAllowlist),r=t.flags?.platform,a=tH({simulatorSetPath:tL(t.flags?.iosSimulatorDeviceSet),platform:r,target:t.flags?.target}),n=await eI({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?tG(t.platform):t.platform===a)}):n,o=(t.flags?.target?i.filter(e=>(e.target??"mobile")===t.flags?.target):i).map(({simulatorSetPath:e,appleOs:t,...r})=>r);return{ok:!0,data:{devices:o}}}catch(t){let e=o(t);return T(e.code,e.message,e.details)}if("apps"===t.command){let e=a.get(r),n=t.flags??{},i=r4(t.command,e,n);if(i)return i;let o=await r6({session:e,flags:n,ensureReady:!0}),s=X("apps",o);if(s)return s;let l=t0(t.flags?.appsFilter);return tG(o.platform)?{ok:!0,data:{apps:(await t1(o,l)).map(e=>e.name&&e.name!==e.bundleId?`${e.name} (${e.bundleId})`:e.bundleId)}}:{ok:!0,data:{apps:(await tU(o,l)).map(e=>e.name&&e.name!==e.package?`${e.name} (${e.package})`:e.package)}}}return null}async function na(e){let{ensureAndroidEmulatorBooted:t}=await import("./3340.js");return await t(e)}let nn='iOS appstate requires an active session on the target device. Run open first (for example: open --session sim --platform ios --device "<name>" <app>).',ni='macOS appstate requires an active session on the target device. Run open first (for example: open --session macos --platform macos "System Settings").';async function no(e){let{req:t,sessionName:r,sessionStore:a}=e,n=a.get(r),i=t.flags??{},o=i.platform;if(!n&&"string"==typeof i?.session&&i.session.trim().length>0)return T("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=r4("appstate",n,i);if(s)return s;let l=tG(n?.device.platform)&&!!n&&0===eV(n,i).length;if("ios"===o&&!l)return T("SESSION_NOT_FOUND",nn);if("macos"===o&&!l)return T("SESSION_NOT_FOUND",ni);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 T("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 r6({session:n,flags:i,ensureReady:!0});if("ios"===u.platform)return T("SESSION_NOT_FOUND",nn);if("macos"===u.platform)return T("SESSION_NOT_FOUND",ni);if("web"===u.platform)return T("UNSUPPORTED_OPERATION","appstate is not supported on web.");let{getAndroidAppState:d}=await import("./3340.js"),p=await d(u);return{ok:!0,data:{platform:"android",package:p.package,activity:p.activity}}}async function ns(e){let{req:t,sessionName:r,logPath:a,sessionStore:n}=e;if("boot"===t.command){let e,i=n.get(r),s=t.flags??{},l=r4(t.command,i,s);if(l)return l;let u="android"===(s.platform??i?.device.platform),d=!0===s.headless;if(d&&!u)return T("INVALID_ARGS","boot --headless is supported only for Android emulators.");let p=r9({flags:s,sessionDevice:i?.device}),c=u&&!!p,f=!1;try{e=await r6({session:i,flags:s,ensureReady:!1,allowStoppedAndroidAvdPlaceholders:!0})}catch(r){let t=o(r);if(u&&d&&!p&&"DEVICE_NOT_FOUND"===t.code)return T("INVALID_ARGS","boot --headless requires --device <avd-name> (or an Android emulator session target).");if(!c||"DEVICE_NOT_FOUND"!==t.code||!p)throw r;e=await na({avdName:p,serial:s.serial,headless:d}),f=!0}if(s.target&&(e.target??"mobile")!==s.target)return T("DEVICE_NOT_FOUND",`No ${e.platform} device found matching --target ${s.target}.`);if(u&&d){if("android"!==e.platform||"emulator"!==e.kind)return T("INVALID_ARGS","boot --headless is supported only for Android emulators.");if(!f){let t=r9({flags:s,sessionDevice:i?.device,resolvedDevice:e});if(!t)return T("INVALID_ARGS","boot --headless requires --device <avd-name> (or an Android emulator session target).");e=await na({avdName:t,serial:s.serial,headless:!0})}await e8(e)}else"android"===e.platform&&"emulator"===e.kind&&!0!==e.booted?(e=await na({avdName:e.name,serial:s.serial,headless:!1}),await e8(e)):("android"!==e.platform||!0!==e.booted)&&await e8(e,{onIosSimulatorColdBootStart:e9({req:t,logPath:a,device:e,enabled:!0})});let m=X("boot",e);return m||{ok:!0,data:{platform:e.platform,target:e.target??"mobile",device:e.name,id:e.id,kind:e.kind,booted:!0}}}if("shutdown"===t.command){var i;let e,a=n.get(r),o=t.flags??{},s=r4(t.command,a,o);if(s)return s;let l=await r6({ensureReady:!1,flags:o,session:a}),u=X("shutdown",l,{message:"shutdown is supported only for Apple simulators and Android emulators."});if(u)return u;if(a&&a.device.platform===l.platform&&a.device.id===l.id)return T("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 d=await a1(l);return d.success?{ok:!0,data:{platform:l.platform,target:l.target??"mobile",device:l.name,id:l.id,kind:l.kind,shutdown:d}}:T(d.error?.code??"COMMAND_FAILED",(i=d,(e=i.error?.message??i.stderr.trim()).length>0?e:"Shutdown failed"),{platform:l.platform,target:l.target??"mobile",device:l.name,id:l.id,kind:l.kind,shutdown:d})}return"appstate"===t.command?await no({req:t,sessionName:r,sessionStore:n}):null}async function nl(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===aO&&t.push({durationMs:Math.max(0,Math.round(e.durationMs)),measuredAt:e.measuredAt,method:aO,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:aO,sampleCount:i.length,samples:i}:{available:!1,reason:"No startup sample captured yet. Run open <app|url> in this session first.",method:aO},{session:r.name,platform:r.device.platform,device:r.device.name,deviceId:r.device.id,metrics:{startup:s,...{fps:np(),memory:{available:!1,reason:a$},cpu:{available:!1,reason:a$}}},sampling:{startup:{method:aO,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:e1,description:ej,unit:"kB"},cpu:{method:eN,description:ev,unit:"percent"},fps:{method:$,description:eU,unit:"percent",primaryField:"droppedFramePercent",window:"since previous Android gfxinfo reset or app process start",resetsAfterRead:!0,relatedActionsLimit:12}}:eo(a.device)}});return ng(e)&&(e.appBundleId?"android"===e.device.platform?await nc(u,e,e.appBundleId,t):await nf(u,e,e.appBundleId):(n=u,l=nw(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 nu(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:np()},sampling:{fps:"android"===(a=r).device.platform?{method:$,description:eU,unit:"percent",primaryField:"droppedFramePercent",window:"since previous Android gfxinfo reset or app process start",resetsAfterRead:!0,relatedActionsLimit:12}:C(a.device)}};return ng(e)&&(e.appBundleId?await nh(n,e,e.appBundleId,t):n.metrics.fps={available:!1,reason:nw(e)}),n}async function nd(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:e1,description:ej,unit:"kB",topConsumerLimit:5}:eo(a.device).memory,snapshot:"android"===r.device.platform?{method:ea,description:et,defaultKind:"android-hprof",artifactOnly:!0}:{method:eB,description:c,defaultKind:"memgraph",artifactOnly:!0}}};if(!ng(e)){if("snapshot"===t.action){let r=n_(e,t.kind);return n.artifact=nI(e,r),n.support=nN(n.artifact.support)??nk(e),n}return n.metrics={memory:{available:!1,reason:a$}},n}return"sample"===t.action?n.metrics={memory:await nA(e,t)}:(n.artifact=await nS(e,t),n.support=nN(n.artifact.support)??nk(e)),n}function np(){return{available:!1,reason:"Dropped-frame sampling is currently available only on Android app sessions and connected iOS device app sessions."}}async function nc(e,t,r,a){let n=await nv(t,r,a);nm(e,t,n)}async function nf(e,t,r){let a=await ny(t,r);nm(e,t,a)}function nm(e,t,r){e.metrics.memory=nx(r.memory),e.metrics.cpu=nx(r.cpu),e.metrics.fps=nR(nx(r.fps),t)}async function nh(e,t,r,a){let n="android"===t.device.platform?await nD(e0(t.device,r,{adb:a.androidAdb})):await nD(y(t.device,r));e.metrics.fps=nR(nx(n),t)}function ng(e){return eu(e.device.platform)?.perf?.supportsMetrics(e.device)??!1}function nw(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 nv(e,t,r){let a={adb:r.androidAdb},[n,i,o]=await Promise.allSettled([Y(e.device,t,a),er(e.device,t,a),e0(e.device,t,a)]);return{memory:n,cpu:i,fps:o}}async function ny(e,t){let r=await nD(y(e.device,t)),a=await nD(eZ(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 nA(e,t){return e.appBundleId?nx("android"===e.device.platform?await nD(Y(e.device,e.appBundleId,{adb:t.androidAdb})):await nD(nb(e))):{available:!1,reason:nw(e)}}async function nb(e){if(!e.appBundleId)throw new l("INVALID_ARGS",nw(e));return(await eZ(e.device,e.appBundleId)).memory}async function nS(e,t){if(!e.appBundleId)throw new l("INVALID_ARGS",nw(e),{hint:"Run open <app> first so perf memory snapshot can resolve the app process."});let a=n_(e,t.kind),n=function(e,t){if(e.out)return ek.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?nI(e,a):await N(e.device,e.appBundleId,n,{adb:t.androidAdb}):"memgraph"!==a?nI(e,a):await A(e.device,e.appBundleId,n)}function n_(e,t){return t||("android"===e.device.platform?"android-hprof":"memgraph")}function nI(e,t){var r,a;let n=nk(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."}:tG(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 nk(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."}:tG(e.device.platform)?{...eD(e.device),androidHprof:!1,heapprofd:!1,heapprofdDecision:"Deferred because heapprofd is Android/Perfetto-specific and outside this memory artifact slice."}:{platform:e.device.platform,defaultKind:"memgraph",androidHprof:!1,memgraph:!1,heapprofd:!1,reason:"Memory snapshot artifacts are available only on Android, iOS simulator, and macOS.",hint:"Use perf memory sample where supported, or switch to a platform with memory artifact support.",heapprofdDecision:"Deferred because heapprofd is Android/Perfetto-specific and outside this memory artifact slice."}}function nN(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:void 0}async function nD(e){try{return{status:"fulfilled",value:await e}}catch(e){return{status:"rejected",reason:e}}}function nx(e){if("fulfilled"===e.status)return{available:!0,...e.value};let t=s(e.reason);return{available:!1,reason:t.message,error:t}}function nR(e,t){var r,a;let n,i;if(!0!==e.available)return e;let o=(r=t.actions,n=nM((a=e).windowStartedAt),i=nM(a.windowEndedAt)??nM(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 nM(e){if("string"!=typeof e)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}async function nP(e){var t,r,a,n,i,o,l,u,d,p;let c,f,m,h,g,w,v=(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,o=c,f=nL(i,1),m=nL(i,2),h=nL(i,3),tr(f)?"start"!==(l=m)&&"stop"!==l&&"report"!==l?T("INVALID_ARGS","perf cpu profile action must be start, stop, or report"):"simpleperf"!==h?T("INVALID_ARGS","perf cpu profile requires --kind simpleperf"):{ok:!0,area:"cpu",subject:f,action:m,kind:h,outPath:o}:T("INVALID_ARGS",tN)):(u=t,d=c,g=nL(u,1),w=nL(u,2),"start"!==(p=g)&&"stop"!==p?T("INVALID_ARGS","perf trace action must be start or stop"):tu(w)?"perfetto"!==w?T("INVALID_ARGS","perf trace requires --kind perfetto"):{ok:!0,area:"trace",action:g,kind:w,outPath:d}:T("INVALID_ARGS",tg)));if(!v.ok)return v;let{session:y}=e;if("android"!==y.device.platform)return T("UNSUPPORTED_OPERATION","Android native perf collectors are supported only on Android sessions.");if(!y.appBundleId)return T("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"===v.area?await nC(e,y,y.appBundleId,v):await nE(e,y,y.appBundleId,v);return{ok:!0,data:t}}catch(e){return{ok:!1,error:s(e)}}}function nL(e,t){return(e.positionals?.[t]??"").toLowerCase()}function nO(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 n$(e,t,a){var n,i,o;let s;return t?ek.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 nC(e,t,r,a){if("start"===a.action){nV(t);let n=n$(e,a.outPath,"cpu.perf.data"),i=await w(t.device,r,n,{adb:e.androidAdbExecutor});return nO(e,i)}let n=nq(t,"cpu-profile",a.kind);if("report"===a.action){await function(e){if("running"===e.state)throw new l("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=n$(e,a.outPath,"cpu-report.json");return await ez(t.device,n,r,{adb:e.androidAdbExecutor})}let i=nF(e,a.outPath,n),o=await eS(t.device,n,i,{adb:e.androidAdbExecutor});return nO(e,o)}async function nE(e,t,r,a){if("start"===a.action){nV(t);let n=n$(e,a.outPath,"app.perfetto-trace"),i=await I(t.device,r,n,{adb:e.androidAdbExecutor});return nO(e,i)}let n=nq(t,"trace",a.kind),i=nF(e,a.outPath,n),o=await ex(t.device,n,i,{adb:e.androidAdbExecutor});return nO(e,o)}function nV(e){let t=e.nativePerf?.android;if(t?.state==="running")throw new l("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 nF(e,t,r){return t?n$(e,t,r.outPath):r.outPath}function nq(e,t,r){let a=e.nativePerf?.android;if(a?.type===t&&a.kind===r)return a;throw new l("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 nT(e){if(!b(e))return;let{macOsScreenCaptureKitAudioProbeBackend:t}=await import("./audio-probe.js");return t}M();let nU=["probe"],nG=["start","status","stop"],nH=`audio probe requires ${nG.join(", ")}`;async function nK(e){let t=function(e){var t;let r,a=(r=(t=e).sessionStore.get(t.sessionName))?eQ("audio",r.device)?{ok:!0,session:r}:T("UNSUPPORTED_OPERATION","audio is supported for web browser sessions, macOS sessions, iOS simulators, and Android emulators on macOS hosts"):T("SESSION_NOT_FOUND","audio requires an active session");if(!a.ok)return a;let n=function(e){let t,r;if(t=(e.positionals?.[0]??"probe").toLowerCase(),nU.includes(t)?!"probe":!void 0)return T("INVALID_ARGS","audio requires probe");let a=(r=(e.positionals?.[1]??"status").toLowerCase(),nG.includes(r)?r:void 0);return a?{ok:!0,probeAction:a}:T("INVALID_ARGS",nH)}(e.req);if(!n.ok)return n;let i=function(e,t){if("start"!==t&&e.positionals&&e.positionals.length>2)return T("INVALID_ARGS","audio probe duration and bucket are only supported with audio probe start");let r=nj(e.positionals?.[2],{defaultValue:1e4,min:100,max:12e4,message:"audio probe duration must be an integer in range 100..120000 ms"});if(r instanceof Error)return T("INVALID_ARGS",r.message);let a=nj(e.positionals?.[3],{defaultValue:1e3,min:100,max:1e4,message:"audio probe bucket must be an integer in range 100..10000 ms"});return a instanceof Error?T("INVALID_ARGS",a.message):{ok:!0,timing:{durationMs:r,bucketMs:a}}}(e.req,n.probeAction);return i.ok?{ok:!0,session:a.session,probeAction:n.probeAction,...i.timing}:i}(e);if(!t.ok)return t;let r=await nT(t.session.device);if(r)return await nB(e,t,r);let a=t3();if(!a.probeAudio)return T("UNSUPPORTED_OPERATION","audio is not supported by this web provider");try{return{ok:!0,data:await a.probeAudio({action:t.probeAction,durationMs:t.durationMs,bucketMs:t.bucketMs})}}catch(e){return{ok:!1,error:s(e)}}}async function nB(e,t,r){try{return{ok:!0,data:await U({session:t.session,sessionName:e.sessionName,sessionStore:e.sessionStore,backend:r,probeAction:t.probeAction,durationMs:t.durationMs,bucketMs:t.bucketMs})}}catch(e){return{ok:!1,error:s(e)}}}function nj(e,t){if(void 0===e)return t.defaultValue;let r=Number.parseInt(e,10);return!Number.isInteger(r)||String(r)!==e||r<t.min||r>t.max?Error(t.message):r}async function nz(e,t){let r,a,n=(r=e.req.positionals??[],"cpu"===(a=r[0]?.toLowerCase())?function(e){if(e[1]?.toLowerCase()!=="profile")return T("INVALID_ARGS","perf cpu requires profile");let t=nW(e[2],"perf cpu profile",!0);if(!t.ok)return t;let r=nJ(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=nW(e[1],"perf trace",!1);if(!t.ok)return t;let r=nJ(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):T("INVALID_ARGS",tn));if(!n.ok)return n;if("android"===t.device.platform)return T("UNSUPPORTED_OPERATION","Android native profiling belongs to the Android perf rollout; Apple xctrace perf supports iOS and macOS sessions only.");if(!tG(t.device.platform))return T("UNSUPPORTED_OPERATION",`Apple xctrace perf is not supported on ${t.device.platform}.`);if(!t.appBundleId)return T("INVALID_ARGS","Apple xctrace perf requires an active app session. Run open <app> first.");try{if("start"===n.action)return await nY(e,t,n);if("stop"===n.action)return await nX(e,t,n);return await nQ(e,t,n)}catch(e){return{ok:!1,error:s(e)}}}function nW(e,t,r){let a=e?.toLowerCase();return"start"===a||"stop"===a||r&&"report"===a?{ok:!0,value:a}:T("INVALID_ARGS",r?`${t} requires start, stop, or report`:`${t} requires start or stop`)}function nJ(e){return e?.toLowerCase()==="xctrace"?{ok:!0}:T("INVALID_ARGS","perf native collection currently supports --kind xctrace")}async function nY(e,t,r){if(t.applePerf?.active)return T("INVALID_ARGS","Apple xctrace perf capture already in progress");let a=r.template??("cpu-profile"===r.mode?"Time Profiler":"Animation Hitches"),n=n0(e,r),i=await ei({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=n1("started",i);return nZ(e,t,o),{ok:!0,data:o}}async function nX(e,t,r){var a,n,i,s,l,u,d;let p,c=t.applePerf?.active;if(!c)return T("INVALID_ARGS","no active Apple xctrace perf capture");let f=r.outPath?ek.expandHome(r.outPath,e.req.meta?.cwd):c.outPath;try{p=await D(c,f)}catch(r){throw a=r,o(a).details?.captureCleanedUp===!0&&(n=e,(i=t).applePerf={...i.applePerf??{},active:void 0},n.sessionStore.set(n.sessionName,i)),r}s=e,l=t,u=p,l.applePerf={...l.applePerf??{},active:void 0,lastMode:u.mode,..."cpu-profile"===(d=u).mode?{lastProfileTracePath:d.outPath,lastProfileTemplate:d.template}:{lastTracePath:d.outPath}},s.sessionStore.set(s.sessionName,l);let m=n1("stopped",p);return nZ(e,t,m),{ok:!0,data:m}}async function nQ(e,t,r){var a;let n;if("cpu-profile"!==r.mode)return T("INVALID_ARGS","perf trace does not support report");if(t.applePerf?.active)return T("INVALID_ARGS","perf cpu profile report requires a stopped profile trace; stop the active capture first.");let i=n0(e,r),o=(a=t,(n=r.tracePath??a.applePerf?.lastProfileTracePath??a.applePerf?.active?.outPath)?{ok:!0,value:n}:T("INVALID_ARGS","perf cpu profile report requires a stopped profile trace or tracePath option"));if(!o.ok)return o;let s={perf:"reported",...await R({tracePath:ek.expandHome(o.value,e.req.meta?.cwd),outPath:i,mode:r.mode,template:t.applePerf?.lastProfileTemplate??r.template,appBundleId:t.appBundleId})};return nZ(e,t,s),{ok:!0,data:s}}function nZ(e,t,r){tD(e.sessionStore,t,e.req,"perf",r)}function n0(e,t){if(t.outPath)return ek.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 n1(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 n3=`logs requires ${ty.slice(0,-1).join(", ")}, or ${ty.at(-1)}`,n2=["dump","log"],n5=`network requires ${n2.join(" or ")}`,n4=`network include mode must be one of: ${tB.join(", ")}`,n8={path:({session:e,sessionName:t,sessionStore:r})=>(function(e,t,r){let a=r.resolveAppLogPath(t),n=J(a);return{ok:!0,data:{path:a,active:!!e.appLog,state:e.appLog?.getState()??"inactive",backend:e.appLog?.backend??eA(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})=>ir(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(" ")??"",h(s=i.resolveAppLogPath(n),o),{ok:!0,data:{path:s,marked:!0}}},clear:({session:e,sessionName:t,sessionStore:r,restart:a})=>ia(e,t,r,a),start:({session:e,sessionName:t,sessionStore:r})=>ii(e,t,r),stop:({session:e,sessionName:t,sessionStore:r})=>io(e,t,r)};async function n6(e){let{req:t}=e;return"perf"===t.command?n7(e):"logs"===t.command?it(e):"network"===t.command?is(e):"audio"===t.command?await nK(e):null}async function n7(e){var t;let{req:r,sessionName:a,sessionStore:n,androidAdbExecutor:i}=e,o=n.get(a);if(!o)return T("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"===o.device.platform?await nP({req:r,sessionName:a,sessionStore:n,session:o,androidAdbExecutor:i,area:u}):await nz(e,o);let d=function(e){var t,r,a,n,i,o,u,d,p,c;let f,m,h=tw(f=(e.positionals?.[0]??"metrics").toString().toLowerCase())?f:void 0;if(!h)return T("INVALID_ARGS",tn);if("cpu"===h||"trace"===h)return{ok:!0,native:!0};let g=tt(m=(e.positionals?.[1]??"sample").toString().toLowerCase())?m:void 0;if(!g)return T("INVALID_ARGS",to);let w=function(e){if(void 0!==e)return"string"==typeof e&&tu(e)?e:new l("INVALID_ARGS",tg)}(e.flags?.kind);if(w instanceof l)return{ok:!1,error:s(w)};let v=(t=h,r=g,("memory"===t?ie(r)?void 0:T("INVALID_ARGS","perf memory requires sample or snapshot"):"sample"!==r?T("INVALID_ARGS","perf metrics and perf frames only support sample"):void 0)??(a=e,n=h,i=g,o=w,function(e,t,r){if(e&&("memory"!==t||"snapshot"!==r))return T("INVALID_ARGS","--out is only supported with perf memory snapshot")}(a.flags?.out,n,i)??(u=o,d=n,p=i,u?"memory"!==d||"snapshot"!==p?T("INVALID_ARGS","--kind is only supported with perf memory snapshot"):td(u)?void 0:T("INVALID_ARGS",th):void 0)));return v||{ok:!0,native:!1,area:h,action:g,kind:w,out:"string"==typeof(c=e.flags?.out)&&c.length>0?c:void 0}}(r);if(!d.ok)return d;if(d.native)return await nz(e,o);try{return{ok:!0,data:await n9(e,o,d)}}catch(e){return{ok:!1,error:s(e)}}}async function n9(e,t,r){let{sessionName:a,sessionStore:n,androidAdbExecutor:i}=e;return"memory"===r.area?await nd(t,{action:function(e){if(ie(e))return e;throw new l("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 nu(t,{androidAdb:i}):await nl(t,{androidAdb:i})}function ie(e){return"sample"===e||"snapshot"===e}async function it(e){var t;let r,a,{req:n,sessionName:i,sessionStore:o}=e,s=o.get(i);if(!s)return T("SESSION_NOT_FOUND","logs requires an active session");let l=X("logs",s.device);if(l)return l;let u=(t=n,r=(t.positionals?.[0]??"path").toLowerCase(),a=!!t.flags?.restart,ty.includes(r)?a&&"clear"!==r?T("INVALID_ARGS","logs --restart is only supported with logs clear"):{ok:!0,action:r,restart:a}:T("INVALID_ARGS",n3));return u.ok?await n8[u.action]({...e,session:s,restart:u.restart}):u}async function ir(e,t,r){let a=r.resolveAppLogPath(t),n=await eL(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 ia(e,t,r,a){if(e.appLog&&!a)return T("INVALID_ARGS","logs clear requires logs to be stopped first; run logs stop");let n=r.resolveAppLogPath(t);if(!a)return{ok:!0,data:el(n)};let i=e.appBundleId;if(!i)return T("INVALID_ARGS","logs clear --restart requires an app session; run open <app> first");e.appLog&&await eH(e.appLog);let o=el(n),l=r.resolveAppLogPidPath(t);try{let a=await e5(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:{...o,restarted:!0}}}catch(a){return r.set(t,{...e,appLog:void 0}),{ok:!1,error:s(a)}}}async function ii(e,t,r){if(e.appLog)return T("INVALID_ARGS","app log already streaming; run logs stop first");if(!e.appBundleId)return T("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 e5(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:s(e)}}}async function io(e,t,r){if(!e.appLog)return T("INVALID_ARGS","no app log stream active");let a=e.appLog.outPath;return await eH(e.appLog),r.set(t,{...e,appLog:void 0}),{ok:!0,data:{path:a,stopped:!0}}}async function is(e){let t=function(e){let{req:t,sessionName:r,sessionStore:a}=e,n=a.get(r);if(!n)return T("SESSION_NOT_FOUND","network requires an active session");let i=X("network",n.device);if(i)return i;let o=(t.positionals?.[0]??"dump").toLowerCase();if(!n2.includes(o))return T("INVALID_ARGS",n5);let s=t.positionals?.[1]?Number.parseInt(t.positionals[1],10):25;if(!Number.isInteger(s)||s<1||s>200)return T("INVALID_ARGS","network dump limit must be an integer in range 1..200");let l=function(e){let t=e.positionals?.[2]?.toLowerCase(),r=e.flags?.networkInclude;if(t&&r&&t!==r)return T("INVALID_ARGS","network include mode was provided both positionally and via --include with different values");let a=(r??t??"summary").toLowerCase();return tB.includes(a)?{ok:!0,include:a}:T("INVALID_ARGS",n4)}(t);return l.ok?{ok:!0,session:n,maxEntries:s,include:l.include}:l}(e);if(!t.ok)return t;let{include:r,maxEntries:a,session:n}=t;if("web"===n.device.platform)return await il({include:r,maxEntries:a});let i=await em({device:n.device,appBundleId:n.appBundleId,appLogState:n.appLog?.getState(),appLogStartedAt:n.appLog?.startedAt,appLogPath:e.sessionStore.resolveAppLogPath(e.sessionName),maxEntries:a,include:r,maxPayloadChars:2048,maxScanLines:4e3});return{ok:!0,data:{...i.dump,active:!!n.appLog,state:n.appLog?.getState()??"inactive",backend:i.backend,notes:i.notes}}}async function il(e){let t=t3();if(!t.dumpNetwork)return T("UNSUPPORTED_OPERATION","network is not supported by this web provider");try{let r=await t.dumpNetwork({include:e.include,limit:e.maxEntries});return{ok:!0,data:{entries:r.entries,active:!0,state:"active",backend:r.backend??"agent-browser",include:e.include,matchedLines:r.entries.length,scannedLines:r.entries.length,limits:{maxEntries:e.maxEntries,maxPayloadChars:2048,maxScanLines:r.entries.length},notes:r.notes}}}catch(e){return{ok:!1,error:s(e)}}}function iu(e,t,r){var a,n;if(null==e)return ri("open",[ru(rs(t,"launchApp"),r)]);if("string"==typeof e)return ri("open",[ru(e,r)]);if(!ro(e))throw new l("INVALID_ARGS","launchApp expects a string or map.");rl(e,"launchApp",["appId","stopApp","clearState","clearKeychain","arguments","permissions","launchArguments"]),im(e,"permissions"),im(e,"clearKeychain");let i=ru("string"==typeof e.appId?e.appId:rs(t,"launchApp"),r),o=(a=e,n=r,[...ip(a.arguments,"launchApp.arguments",n),...ip(a.launchArguments,"launchApp.launchArguments",n)]),s=!0===e.clearState;return ri("open",[i],{...!s&&(!0===e.stopApp||o.length>0)?{relaunch:!0}:{},...s?{clearAppState:!0}:{},...o.length>0?{launchArgs:o}:{}})}function id(e,t,r){if(null==e)return ri("close",[ru(rs(t,"stopApp"),r)]);if("string"==typeof e)return ri("close",[ru(e,r)]);throw new l("INVALID_ARGS","stopApp expects a string appId or no value.")}function ip(e,t,r){if(null==e)return[];if("string"==typeof e)return[ru(e,r)];if(Array.isArray(e))return e.map((e,a)=>ic(e,`${t}[${a}]`,r));if(ro(e))return Object.entries(e).flatMap(([e,a])=>[ru(e,r),ic(a,`${t}.${e}`,r)]);throw new l("INVALID_ARGS",`${t} expects a string, list, or map.`)}function ic(e,t,r){if("string"==typeof e)return ru(e,r);if("number"==typeof e||"boolean"==typeof e)return String(e);throw new l("INVALID_ARGS",`${t} must be a string, number, or boolean.`)}function im(e,t){if(void 0!==e[t])throw rc(`Maestro launchApp field "${t}" is not supported yet.`)}let ih="__maestroRunScript",ig="__maestroAssertVisible",iw="__maestroAssertNotVisible",iv="__maestroPressEnter",iy="__maestroWaitForAnimationToEnd",iA="__maestroScrollUntilVisible",ib="__maestroSwipeScreen",iS="__maestroSwipeOn",i_="__maestroTapOn",iI="__maestroTapPointPercent";function ik(e){if(null==e)return ri("type",["\b".repeat(50)]);if("number"==typeof e&&Number.isInteger(e)&&e>0)return ri("type",["\b".repeat(e)]);if(!ro(e))throw new l("INVALID_ARGS","eraseText expects empty, a positive count, or a map.");if(rl(e,"eraseText",["charactersToErase"]),void 0===e.charactersToErase)return ri("type",["\b".repeat(50)]);if("number"!=typeof e.charactersToErase||!Number.isInteger(e.charactersToErase)||e.charactersToErase<=0)throw new l("INVALID_ARGS","eraseText.charactersToErase must be a positive integer.");return ri("type",["\b".repeat(e.charactersToErase)])}function iN(e){return"number"==typeof e&&Number.isFinite(e)?String(Math.max(16,Math.floor(e))):void 0}function iD(e,t){let r=e.toLowerCase();switch(r){case"up":case"down":case"left":case"right":return r;default:throw rc(`Maestro ${t} must be UP, DOWN, LEFT, or RIGHT.`)}}function ix(e){return iD(e,"swipe direction")}function iR(e,t,r=[],a){if("string"==typeof e)return iM(ru(e,a));if(!ro(e))throw new l("INVALID_ARGS",`${t} expects a string or selector map.`);rl(e,t,["id","text","enabled","selected",...r]);let n=[],i=[];if("boolean"==typeof e.enabled&&i.push(iL("enabled",String(e.enabled))),"boolean"==typeof e.selected&&i.push(iL("selected",String(e.selected))),"string"==typeof e.id&&n.push(iL("id",ru(e.id,a)),...i),"string"==typeof e.text&&0===n.length)return iM(ru(e.text,a),i);if("string"==typeof e.label&&0===n.length&&n.push(iL("label",ru(e.label,a)),...i),0===n.length&&i.length>0&&n.push(...i),0===n.length)throw new l("INVALID_ARGS",`${t} selector map must include one of id, text, label, enabled, or selected.`);return n.join(" ")}function iM(e,t=[]){return[[iL("label",e),...t].join(" "),[iL("text",e),...t].join(" "),[iL("id",e),...t].join(" ")].join(" || ")}function iP(e){let t=iN(e.duration);return t?[t]:[]}function iL(e,t){return`${e}=${JSON.stringify(t)}`}function iO(e){var t,r;if(!ro(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 i$(e){let t=iO(e)??{};return{...t,maestro:{...t.maestro??{},allowNonHittableCoordinateFallback:!0}}}function iC(e){let t={doubleTap:!0};return ro(e)&&"number"==typeof e.delay&&Number.isInteger(e.delay)&&(t.intervalMs=Math.max(0,e.delay)),t}class iE{index=0;tokens;context;constructor(e,t){this.tokens=e,this.context=t}parse(){let e=this.parseOr();if(this.peek())throw new l("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 l("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 l("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 l("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 l("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 l("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 iV(e,t,r){return{...ri(e,t),replayControl:r}}function iF(e,t,r){let a="string"==typeof e?ru(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 l("INVALID_ARGS",`${r} must be a non-negative integer or \${VAR} resolving to one.`);return n}let iq=`
|
|
5
5
|
const fs = require('node:fs');
|
|
6
6
|
const input = JSON.parse(fs.readFileSync(0, 'utf8'));
|
|
7
7
|
if (typeof fetch !== 'function') {
|
|
@@ -22,10 +22,10 @@ fetch(input.url, {
|
|
|
22
22
|
console.error(error && error.stack ? error.stack : String(error));
|
|
23
23
|
process.exit(1);
|
|
24
24
|
});
|
|
25
|
-
`;function n5(e){if("string"!=typeof e)throw new s("COMMAND_FAILED",`Maestro runScript json() expected a string body, received ${typeof e}.`);if(0===e.trim().length)throw new s("COMMAND_FAILED","Maestro runScript json() received an empty body. Check the preceding http response status and setup server output.");try{return JSON.parse(e,n4)}catch(t){throw new s("COMMAND_FAILED",`Maestro runScript json() could not parse response body: ${t instanceof Error?t.message:String(t)}`,{bodyPreview:e.slice(0,1e3)},t instanceof Error?t:void 0)}}function n4(e,t){return"__proto__"===e||"constructor"===e||"prototype"===e?void 0:t}let n6={launchApp:({value:e,config:t,context:r})=>[nx(e,t,r)],tapOn:({value:e,context:t})=>[function(e,t){if("string"==typeof e)return tB(nT,[nW(tW(e,t))],nZ(e));if(tH(e)&&"string"==typeof e.point){tz(e,"tapOn",["point","repeat","delay","optional","label"]);let t=tX(e.point);return"percent"===t.kind?tB(nG,[String(t.x),String(t.y)],nY(e)):tB("click",[String(t.x),String(t.y)],nY(e))}tH(e)&&tz(e,"tapOn",["id","text","childOf","enabled","index","selected","repeat","delay","optional","label"]);let r=nZ(e);return tB(nT,[nz(e,"tapOn",["repeat","delay","optional","label","index","childOf"],t),...function(e,t){if(!tH(e))return[];let r={};if(void 0!==e.index){if("number"!=typeof e.index||!Number.isInteger(e.index)||e.index<0)throw new s("INVALID_ARGS","tapOn.index must be a non-negative integer.");r.index=e.index}return void 0!==e.childOf&&(r.childOf=nz(e.childOf,"tapOn.childOf",[],t)),Object.keys(r).length>0?[JSON.stringify(r)]:[]}(e,t)],r)}(e,t)],doubleTapOn:({value:e,context:t})=>[function(e,t){if(tH(e)&&"string"==typeof e.point){tz(e,"doubleTapOn",["point","delay"]);let t=tq(e.point);return tB("click",[String(t.x),String(t.y)],nQ(e))}return tH(e)&&tz(e,"doubleTapOn",["id","text","enabled","selected","delay"]),tB("click",[nz(e,"doubleTapOn",["delay"],t)],nQ(e))}(e,t)],longPressOn:({value:e,context:t})=>[function(e,t){if(tH(e)&&"string"==typeof e.point){tz(e,"longPressOn",["point"]);let t=tq(e.point);return tB("longpress",[String(t.x),String(t.y),"3000"])}return tH(e)&&tz(e,"longPressOn",["id","text","enabled","selected"]),tB("click",[nz(e,"longPressOn",[],t)],{holdMs:3e3})}(e,t)],inputText:({value:e,context:t})=>[tB("type",[tW(function(e){if("string"==typeof e)return e;if(!tH(e))throw new s("INVALID_ARGS","inputText expects a string or map.");if(tz(e,"inputText",["text","label"]),"string"!=typeof e.text)throw new s("INVALID_ARGS","inputText map requires a string text field.");return e.text}(e),t)])],eraseText:({value:e})=>[nK(e)],pasteText:({value:e,context:t,name:r})=>[tB("type",[tW(tJ(r,e),t)])],openLink:({value:e,config:t,context:r,name:a})=>{var n,i,o,s,l,u;let d;return[(n=e,i=t,o=r,s=a,d=tW((l=n,u=s,"string"==typeof l?l:tH(l)?(tz(l,u,["link"]),tJ(`${u}.link`,l.link)):tJ(u,l)),o),("ios"===o.platform||"android"===o.platform)&&i.appId?tB("open",[tW(tj(i,s),o),d],"ios"===o.platform?{maestro:{prewarmRunnerBeforeOpen:!0}}:void 0):tB("open",[d]))]},assertVisible:({value:e,context:t,name:r})=>[tB(nC,[nz(e,r,[],t),"17000"])],assertNotVisible:({value:e,context:t,name:r})=>[tB(nE,[nz(e,r,[],t)])],extendedWaitUntil:({value:e,context:t})=>(function(e,t){if(!tH(e))throw new s("INVALID_ARGS","extendedWaitUntil expects a map.");tz(e,"extendedWaitUntil",["visible","notVisible","timeout"]);let r=e.visible??e.notVisible;if(void 0===r)throw tY("Only Maestro extendedWaitUntil.visible/notVisible is supported.");let a=nz(r,"extendedWaitUntil",[],t),n=String(tZ(e,17e3));return void 0!==e.notVisible?[tB(nE,[a,n])]:[tB(nC,[a,n],{maestro:{allowAlreadyPastLoading:!0}})]})(e,t),takeScreenshot:({value:e,context:t,name:r})=>[tB("screenshot",[tW(tJ(r,e),t)])],scroll:({value:e})=>[function(e){if(null!=e)throw tY("Maestro scroll options are not supported yet.");return tB("scroll",["down"])}(e)],scrollUntilVisible:({value:e,context:t})=>(function(e,t){if("string"==typeof e)return[tB(nU,[nW(tW(e,t)),"5000","down"])];if(!tH(e))throw new s("INVALID_ARGS","scrollUntilVisible expects a string or map.");tz(e,"scrollUntilVisible",["element","direction","timeout"]);let r=nz(e.element,"scrollUntilVisible.element",[],t),a="string"==typeof e.direction?nH(e.direction,"scrollUntilVisible.direction"):"down";return[tB(nU,[r,String(tZ(e,5e3)),a])]})(e,t),swipe:({value:e,context:t})=>[function(e,t){var r,a,n;let i;if(!tH(e))throw new s("INVALID_ARGS","swipe expects a map.");tz(e,"swipe",["start","end","direction","duration","from","label"]);let o=e.from??("string"==typeof e.label?e.label:void 0);return void 0!==o?(r=e,a=o,n=t,i=nj("string"==typeof r.direction?r.direction:"up"),tB(nq,[nz(a,"swipe.from",[],n),i,...nJ(r)])):"string"==typeof e.direction?tB(nF,["direction",nj(e.direction),...nJ(e)]):function(e){let{start:t,end:r}=function(e){if("string"==typeof e.start&&"string"==typeof e.end)return{start:tX(e.start),end:tX(e.end)};throw tY("Only Maestro swipe start/end coordinates are supported.")}(e);var a=t,n=r,i=nB(e.duration);if("absolute"===a.kind&&"absolute"===n.kind)return tB("swipe",[String(a.x),String(a.y),String(n.x),String(n.y),...i?[i]:[]]);if("percent"===a.kind&&"percent"===n.kind)return tB(nF,["percent",String(a.x),String(a.y),String(n.x),String(n.y),...i?[i]:[]]);throw tY("Maestro swipe start/end must both be absolute pixels or both be percentages.")}(e)}(e,t)],hideKeyboard:()=>[tB("keyboard",["dismiss"])],pressKey:({value:e})=>[function(e){let t=tJ("pressKey",e).toLowerCase();if("back"===t)return tB("back");if("enter"===t||"return"===t)return tB(n$);if("home"===t)return tB("home");throw tY(`Maestro pressKey "${t}" is not supported yet.`)}(e)],back:()=>[tB("back")],waitForAnimationToEnd:({value:e})=>[tB(nV,[String(tZ(e,15e3))])],stopApp:({value:e,config:t,context:r})=>[nR(e,t,r)],runScript:({value:e,context:t})=>{let a;return[tB(nO,[function(e,t){if(r.isAbsolute(e))return e;if(!t.baseDir)throw new s("INVALID_ARGS","runScript file paths require replay input to have a source path.");return r.resolve(t.baseDir,e)}((a=function(e,t){if("string"==typeof e)return{file:tW(e,t),env:{}};if(!tH(e))throw new s("INVALID_ARGS","runScript expects a file path string or map.");return tz(e,"runScript",["file","env"]),{file:tW(tJ("runScript.file",e.file),t),env:Object.fromEntries(Object.entries(tO(e.env,"runScript.env")).map(([e,r])=>[e,tW(r,t)]))}}(e,t)).file,t)],{...Object.keys(a.env).length>0?{maestro:{runScriptEnv:a.env}}:{}})]},runFlow:({value:e,config:t,context:r,deps:a})=>(function(e,t,r,a,n){if("string"==typeof e)return a.parseRunFlowFile(tW(e,r),r).actions;if(!tH(e))throw new s("INVALID_ARGS","runFlow expects a file path string or map.");tz(e,"runFlow",["file","commands","env","when","label"]);let i=function(e,t){var r,a;if(null==e)return{shouldRun:!0};if(!tH(e))throw new s("INVALID_ARGS","runFlow.when expects a map.");return(tz(e,"runFlow.when",["platform","visible","notVisible","true"]),!function(e,t){if(void 0!==e.true&&!function(e,t){let r;if("boolean"==typeof e)return e;if("string"!=typeof e)throw new s("INVALID_ARGS","runFlow.when.true expects a boolean or expression string.");return new n0(function(e){let t=[],r=0;for(;r<e.length;){var a,n;let i=e.slice(r),o=(a=i,/^\s+/.exec(a)?.[0].length??0);if(o>0){r+=o;continue}let l=function(e){let t="maestro.platform";return e.startsWith(t)?{token:{type:"platform"},length:t.length}:null}(n=i)??function(e){let t=/^(==|!=|&&|\|\|)/.exec(e)?.[1];return t?{token:{type:"operator",value:t},length:t.length}:null}(n)??function(e){let t=e[0];return"("===t||")"===t?{token:{type:"paren",value:t},length:1}:null}(n)??function(e){let t=/^(['"])(.*?)\1/.exec(e);return t?{token:{type:"string",value:t[2]??""},length:t[0].length}:null}(n)??function(e){let t=/^(true|false)\b/.exec(e)?.[1];return t?{token:{type:"boolean",value:"true"===t},length:t.length}:null}(n);if(l){t.push(l.token),r+=l.length;continue}throw new s("INVALID_ARGS",`Unsupported runFlow.when.true expression near "${i.slice(0,24)}".`)}return t}((r=tW(e,t).trim()).startsWith("${")&&r.endsWith("}")?r.slice(2,-1).trim():r),{platform:t.platform}).parse()}(e.true,t))return!1;if(void 0===e.platform)return!0;let r=function(e,t){if("string"!=typeof e)throw new s("INVALID_ARGS",`${t} expects Android, iOS, or Web.`);let r=e.trim().toLowerCase();if("android"===r||"ios"===r||"web"===r)return r;throw new s("INVALID_ARGS",`${t} expects Android, iOS, or Web.`)}(e.platform,"runFlow.when.platform");if(!t.platform)throw new s("INVALID_ARGS","Maestro runFlow.when.platform requires replay to be run with --platform ios|android.");return r===t.platform}(e,t))?{shouldRun:!1}:{shouldRun:!0,...(r=e,a=t,{...void 0!==r.visible?{visibleSelector:nz(r.visible,"runFlow.when.visible",[],a)}:{},...void 0!==r.notVisible?{notVisibleSelector:nz(r.notVisible,"runFlow.when.notVisible",[],a)}:{}})}}(e.when,r);if(!i.shouldRun)return[];let o={...r,env:{...r.env,...tO(e.env,"runFlow.env"),...r.envOverrides}};return function(e,t){let{visibleSelector:r,notVisibleSelector:a}=t;if(!r&&!a)return e;if(r&&a)throw tY("Maestro runFlow.when cannot combine visible and notVisible yet.");let n=r?"visible":"notVisible",i=r??a??"";return[n1("runFlow.when",[n,i],{kind:"maestroRunFlowWhen",mode:n,selector:i,actions:e})]}(function(e,t,r,a,n){if("string"==typeof e.file)return a.parseRunFlowFile(tW(e.file,r),r).actions;if(Array.isArray(e.commands))return n(t$(e.commands),t,r,a);throw new s("INVALID_ARGS","runFlow map requires either file or commands.")}(e,t,o,a,n),i)})(e,t,r,a,n9),repeat:({value:e,config:t,context:r,deps:a})=>(function(e,t,r,a,n){var i;if(!tH(e))throw new s("INVALID_ARGS","repeat expects a map.");if(tz(e,"repeat",["times","commands","while"]),void 0!==e.while)throw tY("Maestro repeat.while is not supported yet. Only deterministic repeat.times is supported.");let o=(i=e.times,n3(i,r,"repeat.times"));if(!Array.isArray(e.commands))throw new s("INVALID_ARGS","repeat requires a commands list.");if(o>1e3)throw new s("INVALID_ARGS","repeat.times must be <= 1000 for deterministic replay expansion.");let l=t$(e.commands);return Array.from({length:o}).flatMap(()=>n(l,t,r,a))})(e,t,r,a,n9),retry:({value:e,config:t,context:r,deps:a})=>(function(e,t,r,a,n){var i,o;if(!tH(e))throw new s("INVALID_ARGS","retry expects a map.");if(tz(e,"retry",["maxRetries","commands"]),!Array.isArray(e.commands))throw new s("INVALID_ARGS","retry requires a commands list.");let l=(i=e.maxRetries,o=r,void 0===i?1:n3(i,o,"retry.maxRetries")),u=n(t$(e.commands),t,r,a);return[n1("retry",[String(l)],{kind:"retry",maxRetries:l,actions:u})]})(e,t,r,a,n9)},n8={launchApp:(e,t)=>[nx(void 0,e,t)],scroll:()=>[tB("scroll",["down"])],hideKeyboard:()=>[tB("keyboard",["dismiss"])],eraseText:()=>[nK(void 0)],back:()=>[tB("back")],waitForAnimationToEnd:()=>[tB(nV,["15000"])],stopApp:(e,t)=>[nR(void 0,e,t)]};function n7(e,t,r,a,n){try{return function(e,t,r,a){if("string"==typeof e){var n,i,o;let a;return n=e,i=t,o=r,(a=n8[n])?a(i,o):tL(n)}let l=Object.entries(e);if(1!==l.length)throw new s("INVALID_ARGS","Maestro command maps must contain exactly one command.");let[u,d]=l[0],p=n6[u];return p?p({value:d,config:t,context:r,deps:a,name:u}):tL(u)}(e,t,a,n)}catch(e){if(e instanceof s&&!/\bline \d+\b/.test(e.message))throw new s(e.code,`${e.message} (line ${r})`,e.details);throw e}}function n9(e,t,r,a){return e.flatMap((e,n)=>n7(e,t,n+1,r,a))}function ie(e,t){let{config:r,commands:a}=it(tF(e)),n={...t,env:{...t.env,...r.env??{},...t.envOverrides}},{actions:i,actionLines:o}=function(e){let{config:t,commands:r,commandLines:a,context:n}=e,i=[...t.onFlowStart??[],...r,...t.onFlowComplete??[]],o=[...Array.from({length:t.onFlowStart?.length??0},()=>1),...a,...Array.from({length:t.onFlowComplete?.length??0},()=>a.at(-1)??1)],s=[],l=[];for(let[e,r]of i.entries()){let a=o[e]??e+1,i=n7(r,t,a,n,{parseRunFlowFile:ir});s.push(...i),i.forEach(()=>l.push(a))}return function(e,t){let r=[],a=[];for(let n=0;n<e.length;n+=1){let i=e[n],o=function(e,t,r){var a;let n=function(e,t,r){let a=e[r],n=e[r+1],i=e[r+2];if(i?.command!==n$||a.flags?.maestro?.optional===!0)return null;let o=function(e){if(e?.command!=="type"||e.flags&&Object.keys(e.flags).length>0)return null;let[t,...r]=e.positionals??[];return r.length>0||"string"!=typeof t?null:t}(n),s=function(e){if(e?.command!==nT)return null;let[t,...r]=e.positionals??[];return r.length>0||"string"!=typeof t?null:t}(a);return n&&null!==o&&null!==s?{action:a,nextAction:n,pressEnterAction:i,tapSelector:s,typedAfterTap:o,line:t[r]??1}:null}(e,t,r);if(!n)return null;let{action:i,nextAction:o,pressEnterAction:s,tapSelector:l,typedAfterTap:u,line:d}=n;return(a=l,/\b(input|textfield|textarea|field|email|password|username|search|query)\b/i.test(a.replace(/([a-z])([A-Z])/g,"$1 $2")))?{actions:[{...i,command:"wait",positionals:[l,"30000"]},{...o,command:"fill",positionals:[l,u],flags:i.flags},s],actionLines:[d,d,t[r+2]??d],consumed:3}:{actions:[function(e){let t={...e.flags?.maestro??{}};return delete t.allowNonHittableCoordinateFallback,{...e,flags:{...e.flags??{},maestro:{...t}}}}(i)],actionLines:[d],consumed:1}}(e,t,n);if(o){r.push(...o.actions),a.push(...o.actionLines),n+=o.consumed-1;continue}r.push(i),a.push(t[n]??1)}return{actions:r,actionLines:a}}(s,l)}({config:r,commands:a,commandLines:function(e){let t=e.split(/\r?\n/),r=t.findIndex(e=>"---"===e.trim()),a=-1===r?0:r+1,n=[];for(let e=a;e<t.length;e+=1)/^-\s+/.test(t[e]??"")&&n.push(e+1);return n}(e),context:n});return{actions:i,actionLines:o,metadata:{env:r.env}}}function it(e){if(0===e.length)throw new s("INVALID_ARGS","Maestro flow is empty.");if(Array.isArray(e[0]))return{config:{},commands:t$(e[0])};let t=function(e){if(!tH(e))throw new s("INVALID_ARGS","Maestro flow config must be a YAML map.");return{..."string"==typeof e.name&&e.name.length>0?{name:e.name}:{},..."string"==typeof e.appId&&e.appId.length>0?{appId:e.appId}:{},...tH(e.env)?{env:tO(e.env,"env")}:{},...Array.isArray(e.onFlowStart)?{onFlowStart:t$(e.onFlowStart)}:{},...Array.isArray(e.onFlowComplete)?{onFlowComplete:t$(e.onFlowComplete)}:{}}}(e[0]),r=e[1];if(!Array.isArray(r))throw new s("INVALID_ARGS","Maestro flow must contain a command list after the YAML document separator.");return{config:t,commands:t$(r)}}function ir(e,a){let n=function(e,t){if(r.isAbsolute(e))return e;if(!t.baseDir)throw new s("INVALID_ARGS","runFlow file paths require replay input to have a source path.");return r.resolve(t.baseDir,e)}(e,a);if(a.visitedPaths.has(n))throw new s("INVALID_ARGS",`Maestro runFlow cycle detected at ${n}.`);let i=t.readFileSync(n,"utf8"),o=new Set(a.visitedPaths);return o.add(n),ie(i,{...a,baseDir:r.dirname(n),visitedPaths:o})}let ia=/[*?[\]{}]/;function ii(e,t,a,n,i=0){let o=r.basename(a,r.extname(a)).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return`${e}:test:${t}:${n+1}${o?`-${o}`:""}:attempt-${i+1}`}function io(e,t){return"number"==typeof e?e:t}function is(e,t){let r="number"==typeof e?e:t;return"number"!=typeof r?0:Math.max(0,Math.min(3,r))}function il(e,a,n){var i,o;let l=ep.expandHome(e,a);if(t.existsSync(l)){let a=t.statSync(l);if(a.isDirectory())return{paths:[...n].map(e=>`**/*${e}`).flatMap(e=>t.globSync(e,{cwd:l}).map(e=>r.join(l,e))),source:"directory"};if(a.isFile()){if(!n.has(r.extname(l)))throw new s("INVALID_ARGS",`test does not support this file type: ${e}`);return{paths:[l],source:"file"}}return{paths:[],source:"file"}}if(i=e,!ia.test(i)&&(o=l,!ia.test(o)))throw new s("INVALID_ARGS",`test input not found: ${e}`);let u=r.isAbsolute(l)?l:e;return{paths:t.globSync(u,{cwd:r.isAbsolute(l)?void 0:a}).map(e=>r.isAbsolute(e)?e:r.resolve(a,e)).filter(e=>n.has(r.extname(e))&&function(e){try{return t.statSync(e).isFile()}catch{return!1}}(e)),source:"glob"}}function iu(e,t){let r=id(e),a=id(t);return r!==a?r-a:e.localeCompare(t)}function id(e){return+(".ad"===r.extname(e))}function ip(e){return[...new Set(e.map(e=>r.normalize(e)))]}function ic(e){return"maestro"===e}let im=["failed to start daemon","runner did not accept connection","xcodebuild exited early","device is offline","device offline","device unauthorized"];function ih(e){var t,r,a,n;let i,o,s="ok"in(t=e)?t.ok?null:t.error:"failed"===t.status?t.error:null;return!!s&&(r=s.details,"timeout_cleanup_pending"===(i="string"==typeof r?.reason?r.reason:"")||!!i&&tc(i)||(a=s.code,n=s.message,o=`${a}
|
|
26
|
-
${n}`.toLowerCase(),
|
|
27
|
-
`)}async function
|
|
28
|
-
`;t.writeFileSync(m,h),i.ok||t.writeFileSync(r.join(d,"failure.txt"),h)}({response:A,filePath:o.path,sessionName:w,attempts:h,maxAttempts:a.maxAttempts,attemptArtifactsDir:y}),{response:A,sessionName:w,attempt:h,durationMs:S}}function iI(e){let t=t5(e);return t?{snapshotDiagnostics:t}:{}}function ik(e){return e?{shardIndex:e.shardIndex,shardCount:e.shardCount,deviceId:e.device.id}:{}}async function iN(e,t,r){let a=function(e){let t=iD(e?.shardAll,"--shard-all"),r=iD(e?.shardSplit,"--shard-split");if(void 0!==t&&void 0!==r)throw new s("INVALID_ARGS","--shard-all and --shard-split are mutually exclusive");return void 0!==t?{kind:"all",count:t}:void 0!==r?{kind:"split",count:r}:void 0}(e);if(!a||0===t.length)return;let n=await ix(e,a.count);return{mode:a.kind,shardCount:a.count,total:r+("all"===a.kind?t.length*a.count:t.length),shards:n.map((e,r)=>({shardIndex:r,shardCount:a.count,device:e,entries:"all"===a.kind?t:t.filter((e,t)=>t%a.count===r)}))}}function iD(e,t){if(void 0!==e){if("number"!=typeof e||!Number.isInteger(e)||e<1)throw new s("INVALID_ARGS",`${t} requires a positive integer`);return e}}async function ix(e,t){var r,a,n,i,o,l,u,d,p;let c,f,m=(r=e,"string"!=typeof(c=r?.device)||0===c.trim().length?[]:c.split(",").map(e=>e.trim()).filter(Boolean)),h=(n=await ed((a=e,f=tm(a?.androidDeviceAllowlist),{platform:a?.platform,target:a?.target,iosSimulatorSetPath:tv({simulatorSetPath:tu(a?.iosSimulatorDeviceSet),platform:a?.platform,target:a?.target}),androidSerialAllowlist:f?Array.from(f).sort():void 0})),i=m,o=e,i.length>0?(l=n,u=i,d=o,u.map(e=>{let t=iM(e),r=l.find(r=>iR(r,d)&&(r.id===e||iM(r.name)===t));if(!r)throw new s("DEVICE_NOT_FOUND",`No shard device matched ${e}`);return r})):n.filter(e=>{var t;return!!iR(t=e,o)&&("ios"===t.platform||"android"===t.platform)&&!1!==t.booted}).sort(iP));if(h.length<t){throw new s("DEVICE_NOT_FOUND",`test sharding requires ${(p=t,`${p} device${1===p?"":"s"}`)}, but only ${h.length} matched`)}return h.slice(0,t)}function iR(e,t){return!(!tS(e.platform,t?.platform)||t?.target&&(e.target??"mobile")!==t.target)}function iM(e){return e.toLowerCase().replace(/_/g," ").replace(/\s+/g," ").trim()}function iP(e,t){return e.id.localeCompare(t.id)}async function iL(e){let{req:t,sessionName:r,runReplay:a,cleanupSession:n,finalizeAttempt:o}=e;if((t.positionals?.length??0)===0)return L("INVALID_ARGS","test requires at least one path or glob");try{var s,l,u,d;let e,i,p,c,f,m,h=Date.now(),g=await iO(t);s=g,eB({type:"replay-test-suite",status:"start",total:s.total,runnable:s.runnable.length,skipped:s.entries.length-s.runnable.length,artifactsDir:s.suiteArtifactsDir,shardMode:s.shardPlan?.mode,shardCount:s.shardPlan?.shardCount});let w=g.shardPlan?function(e){let{entries:t,total:r}=e,a=[];for(let[e,n]of t.entries())"skip"===n.kind&&(eB({type:"replay-test",file:n.path,status:"skip",index:e+1,total:r,message:n.message}),a.push({file:n.path,status:"skipped",durationMs:0,reason:n.reason,message:n.message}));return a}({entries:g.entries,total:g.total}):[];g.shardPlan?w.push(...await iC({shards:g.shardPlan.shards,sessionName:r,suiteInvocationId:g.suiteInvocationId,cwd:t.meta?.cwd,requestId:t.meta?.requestId,flags:t.flags,suiteArtifactsDir:g.suiteArtifactsDir,suiteTotal:g.total,runReplay:a,cleanupSession:n,finalizeAttempt:o})):w.push(...await iV({discoveryEntries:g.entries,sessionName:r,suiteInvocationId:g.suiteInvocationId,cwd:t.meta?.cwd,requestId:t.meta?.requestId,flags:t.flags,suiteArtifactsDir:g.suiteArtifactsDir,suiteTotal:g.total,runReplay:a,cleanupSession:n,finalizeAttempt:o}));let y=(l=g.total,u=w,d=Date.now()-h,e=u.filter(e=>"passed"===e.status).length,p=(i=u.filter(e=>"failed"===e.status)).length,c=u.filter(e=>"skipped"===e.status).length,f=e+p,m=t6(u.map(e=>"skipped"===e.status?void 0:e.snapshotDiagnostics)),{total:l,executed:f,passed:e,failed:p,skipped:c,notRun:Math.max(0,l-f-c),durationMs:d,failures:i,tests:u,...m?{snapshotDiagnostics:m}:{}});return{ok:!0,data:y}}catch(t){let e=i(t);return L(e.code,e.message)}}async function iO(e){var a,n,i,o;let l=function(e){let{inputs:a,cwd:n,platformFilter:i,replayBackend:o}=e,l=new Set(ic(o)?[".yaml",".yml",".ad"]:[".ad"]),u=function(e,a,n,i){if(!ic(i))return[...new Set(e.flatMap(e=>il(e,a,n).paths))].map(e=>r.normalize(e)).sort((e,t)=>e.localeCompare(t));let o=[],s=[];for(let i of e){let e=function(e,a,n){let i=ep.expandHome(e,a);return t.existsSync(i)&&t.statSync(i).isDirectory()?{paths:function e(a,n){let i=[],o=t.opendirSync(a);try{let t;for(;null!==(t=o.readSync());){let o=r.join(a,t.name);t.isDirectory()?i.push(...e(o,n)):t.isFile()&&n.has(r.extname(t.name))&&i.push(o)}}finally{o.closeSync()}return i}(i,n),source:"directory"}:il(e,a,n)}(i,a,n);"file"===e.source?o.push(...e.paths):s.push("directory"===e.source?ip(e.paths):e.paths.map(e=>r.normalize(e)).sort(iu))}return ip([...o,...s.flat()])}(a,n??process.cwd(),l,o),d=[];for(let e of u){var p,c,f,m;let a=t.readFileSync(e,"utf8"),n=tT(a),s=(p=a,c=e,ic(o)&&".ad"!==r.extname(c)?function(e){let{config:t}=it(tF(e));return t.name}(p):void 0);if(!i){d.push({kind:"run",path:e,title:s,metadata:n});continue}if(!n.platform){ic(o)?d.push({kind:"run",path:e,title:s,metadata:n}):d.push({kind:"skip",path:e,reason:"skipped-by-filter",message:`missing platform metadata for --platform ${i}`});continue}f=i,m=n.platform,("apple"===f?"apple"===m||"ios"===m||"macos"===m:m===f)&&d.push({kind:"run",path:e,title:s,metadata:n})}if(0===d.filter(e=>"run"===e.kind).length){let e=i?` for --platform ${i}`:"";throw new s("INVALID_ARGS",`No replay tests matched${e}.`)}return d}({inputs:(n=e).positionals??[],cwd:n.meta?.cwd,platformFilter:n.flags?.platform,replayBackend:n.flags?.replayBackend}),u=l.flatMap((e,t)=>"run"===e.kind?[{entry:e,suiteIndex:t+1}]:[]),d=l.length-u.length,p=(a=e.meta?.requestId,(a?.trim()||`${process.pid}-${Date.now().toString(36)}`).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"suite"),c=await iN(e.flags,u,d);return{entries:l,runnable:u,shardPlan:c,suiteInvocationId:p,suiteArtifactsDir:(i=e,o=p,function(e){let{artifactsDir:t,cwd:a,suiteInvocationId:n}=e,i=ep.expandHome(t??".agent-device/test-artifacts",a);return r.join(i,n)}({artifactsDir:"string"==typeof i.flags?.artifactsDir?i.flags.artifactsDir:void 0,cwd:i.meta?.cwd,suiteInvocationId:o})),total:c?.total??l.length}}async function iC(e){return(await Promise.allSettled(e.shards.map(async t=>await iE({...e,shard:t})))).flatMap((t,r)=>{var a,n;let i;if("fulfilled"===t.status)return t.value;let s=e.shards[r];return s?[(a=s,n=e.sessionName,i=o(t.reason),{file:a.entries[0]?.entry.path??`shard-${a.shardIndex+1}`,session:i$(n,a),status:"failed",durationMs:0,attempts:1,error:{code:i.code,message:i.message,hint:i.hint,diagnosticId:i.diagnosticId,logPath:i.logPath,details:i.details},shardIndex:a.shardIndex,shardCount:a.shardCount,deviceId:a.device.id})]:[]})}async function iE(e){let{shard:t,sessionName:r}=e;return await iU({...e,entries:t.entries,sessionName:i$(r,t),shard:t})}function i$(e,t){return`${e}:shard-${t.shardIndex+1}`}async function iV(e){let{discoveryEntries:t,sessionName:r,suiteInvocationId:a,cwd:n,requestId:i,flags:o,suiteArtifactsDir:s,suiteTotal:l,runReplay:u,cleanupSession:d,finalizeAttempt:p}=e,c=[],f=0;for(let[e,m]of t.entries()){if(eh(i))break;if("skip"===m.kind){eB({type:"replay-test",file:m.path,status:"skip",index:e+1,total:l,message:m.message}),c.push({file:m.path,status:"skipped",durationMs:0,reason:m.reason,message:m.message});continue}f+=1;let t=await iS({entry:m,sessionName:r,suiteInvocationId:a,caseIndex:f-1,cwd:n,requestId:i,retries:is(o?.retries,m.metadata.retries),timeoutMs:io(o?.timeoutMs,m.metadata.timeoutMs),suiteArtifactsDir:s,suiteIndex:e+1,suiteTotal:l,runReplay:u,cleanupSession:d,finalizeAttempt:p});if(c.push(t),iF(t,o,i))break}return c}async function iU(e){let{entries:t,sessionName:r,suiteInvocationId:a,cwd:n,requestId:i,flags:o,suiteArtifactsDir:s,suiteTotal:l,shard:u,runReplay:d,cleanupSession:p,finalizeAttempt:c}=e,f=[];for(let[e,m]of t.entries()){if(eh(i))break;let{entry:t,suiteIndex:h}=m,g=await iS({entry:t,sessionName:r,suiteInvocationId:a,caseIndex:e,cwd:n,requestId:i,retries:is(o?.retries,t.metadata.retries),timeoutMs:io(o?.timeoutMs,t.metadata.timeoutMs),suiteArtifactsDir:s,suiteIndex:h,suiteTotal:l,shard:u,runReplay:d,cleanupSession:p,finalizeAttempt:c});if(f.push(g),iF(g,o,i))break}return f}function iF(e,t,r){return eh(r)||t?.failFast===!0||ih(e)}let iq={maestro:{parse:function(e,t={}){var a;let n;return ie(e,(n=(a=t).visitedPaths??new Set,a.sourcePath&&n.add(r.resolve(a.sourcePath)),{baseDir:a.sourcePath?r.dirname(a.sourcePath):void 0,platform:tV(a.platform),env:{},envOverrides:a.env??{},visitedPaths:n}))}}};function iT(e){if(0===e.length)return{selectorExpression:null,selectorTimeout:null};let t=e[e.length-1],r=void 0!==t&&/^\d+$/.test(t)?t:null,a=ru(null!==r?e.slice(0,-1):e.slice());return!a||a.rest.length>0?{selectorExpression:null,selectorTimeout:null}:{selectorExpression:a.selectorExpression,selectorTimeout:r}}async function iG(e){let{action:t,sessionName:r,logPath:a,sessionStore:n}=e;if(!(rl(t.command)||["fill","get","is","wait"].includes(t.command)))return null;let i=n.get(r);if(!i)return null;let o=(function(e){let t=[],r=Array.isArray(e.result?.selectorChain)&&e.result?.selectorChain.every(e=>"string"==typeof e)?e.result.selectorChain:[];if(t.push(...r),rl(e.command)){let r=function(e){let t=e.positionals??[];if("longpress"!==e.command)return t;let r=t.at(-1);return t.length>1&&iK(r)?t.slice(0,-1):t}(e),a=r[0]??"";a&&!a.startsWith("@")&&t.push(r.join(" "))}if("fill"===e.command){let r=e.positionals?.[0]??"";r&&!r.startsWith("@")&&Number.isNaN(Number(r))&&t.push(r)}if("get"===e.command){let r=e.positionals?.[1]??"";r&&!r.startsWith("@")&&t.push(e.positionals.slice(1).join(" "))}if("is"===e.command){let{split:r}=rt(e.positionals);r&&t.push(r.selectorExpression)}if("wait"===e.command){let{selectorExpression:r}=iT(e.positionals??[]);r&&t.push(r)}return F(t).filter(e=>e.trim().length>0)})(t).map(e=>rp(e)).filter(e=>null!==e);if(0===o.length)return null;let s=rl(t.command)||"fill"===t.command,l=rl(t.command)||"fill"===t.command||"get"===t.command&&t.positionals?.[0]==="text",u=await iB(i,t,a,s,n);for(let e of o){let r=t8(u.nodes,e,{platform:i.device.platform,requireRect:s,requireUnique:!0,disambiguateAmbiguous:l});if(!r)continue;let a=rr(r.node,i.device.platform,{action:"fill"===t.command?"fill":rl(t.command)?"click":"get"}).join(" || ");if(rl(t.command))return{...t,positionals:"longpress"===t.command?function(e,t){let r="number"==typeof e.result?.durationMs?String(e.result.durationMs):function(e){let t=e.at(-1);return e.length>1&&iK(t)?t:void 0}(e.positionals??[]);return r?[t,r]:[t]}(t,a):[a]};if("fill"===t.command){let e=w(t);if(!e)continue;return{...t,positionals:[a,e]}}if("get"===t.command){let e=t.positionals?.[0];if("text"!==e&&"attrs"!==e)continue;return{...t,positionals:[e,a]}}if("is"===t.command){let{predicate:e,split:r}=rt(t.positionals);if(!e)continue;let n=r?.rest.join(" ").trim()??"",i=[e,a];return"text"===e&&n.length>0&&i.push(n),{...t,positionals:i}}if("wait"===t.command){let{selectorTimeout:e}=iT(t.positionals??[]),r=[a];return e&&r.push(e),{...t,positionals:r}}}return null}function iK(e){return void 0!==e&&""!==e.trim()&&Number.isFinite(Number(e))}async function iB(e,t,r,a,n){let i=ei(await p(e.device,"snapshot",[],t.flags?.out,{...eu(r,{...t.flags??{},snapshotInteractiveOnly:a},e.appBundleId,e.trace?.outPath)}),{...t.flags??{},snapshotInteractiveOnly:a});return q(e,i),n.set(e.name,e),i}let iH=.35,ij=120,iz=360,iW=8;function iJ(e,t){return Math.round(Math.min(iz,Math.max(ij,"number"==typeof e?e*iH:0,1.5*t)))}let iX=new WeakMap,iY=new WeakMap,iZ=new WeakMap;function iQ(e,t,r){return{ok:!1,error:{code:e,message:t,...r?{details:r}:{}}}}async function i0(e){var t;let r,a=!0===e.raw||"1"===process.env.AGENT_DEVICE_MAESTRO_RAW_SNAPSHOTS,n=await e.invoke({...e.baseReq,command:"snapshot",positionals:[],flags:{...e.baseReq.flags,noRecord:!0,...a?{snapshotRaw:!0}:{}}});return n.ok&&e.scope&&(t=e.scope,(r=j(i1(n.data)))&&iX.set(t,r)),n}function i1(e){return Array.isArray(e?.nodes)?e:void 0}function i3(e,t){e&&iY.set(e,{selector:t})}function i2(e){e&&iZ.delete(e)}let i5=new Map([["button",0],["link",0],["textfield",0],["textview",0],["searchfield",0],["switch",0],["slider",0],["cell",1],["statictext",2]]);function i4(e,t,r,a,n,i={}){let o=oe(e,t,a);if(r.childOf){let t=oe(e,r.childOf,a);if(0===t.length)return{ok:!1,message:`Maestro childOf parent did not match: ${r.childOf}`};let n=ra(e.nodes);o=o.filter(r=>t.some(t=>re(e.nodes,r,t,n)))}let s=i8({nodes:e.nodes,matches:o,platform:a}),l=oa(e.nodes,s.matches,r.index,i9(t),n,!0===i.requireOnScreen,i.promoteTapTarget,i.preferredContext);if(!l){let e=r.index??0;return{ok:!1,message:s.blockedByReactNativeOverlay?`React Native overlay is covering app content: ${t}`:o.length>0&&0===s.matches.length?`Maestro selector matched ${o.length} element(s), but none were visible: ${t}`:`Maestro selector did not match index ${e}: ${t}`}}return{ok:!0,node:l.node,rect:l.rect}}function i6(e,t,r,a){let n=oe(e,t,r,{allowLeadingCompositeLabelMatch:!1}),i=i8({nodes:e.nodes,matches:n,platform:r}),o=oa(e.nodes,i.matches,void 0,i9(t),a,!0);return o?{ok:!0,node:o.node,rect:o.rect,matches:i.matches.length}:{ok:!1,message:i.blockedByReactNativeOverlay?`React Native overlay is covering app content: ${t}`:n.length>0?`Maestro selector matched ${n.length} element(s), but none were visible: ${t}`:`Maestro selector did not match: ${t}`}}function i8(e){let t=e.matches.filter(t=>rs({predicate:"visible",node:t,nodes:e.nodes,platform:e.platform}).pass),r=function(e,t,r){let a=tn(e);if(!a.detected||!a.redBox)return{matches:t,blockedByReactNativeOverlay:!1};let n=ta(a),i=n.filter(t=>rs({predicate:"visible",node:t,nodes:e,platform:r}).pass);if(0===i.length)return 0===n.length?{matches:[],blockedByReactNativeOverlay:!0}:{matches:t,blockedByReactNativeOverlay:!1};let o=new Set(i.map(e=>e.index)),s=t.filter(e=>o.has(e.index));return{matches:s,blockedByReactNativeOverlay:t.length>0&&0===s.length}}(e.nodes,t,e.platform);return{matches:r.matches,blockedByReactNativeOverlay:r.blockedByReactNativeOverlay}}function i7(e){return e?.platform==="android"?"android":"ios"}function i9(e){let t=rc(e).selectors.flatMap(e=>e.terms);if(0===t.length||!t.some(e=>"label"===e.key||"text"===e.key)||!t.every(e=>["label","text","id"].includes(e.key)))return null;let r=t.map(e=>"string"==typeof e.value?e.value:""),a=r[0];return a&&r.every(e=>e===a)?a:null}function oe(e,t,r,a={}){for(let n of rc(t).selectors){let t=e.nodes.filter(e=>(function(e,t,r,a){return!!rn(e,t,r)||t.terms.every(t=>(function(e,t,r,a){var n,i,o;return"string"!=typeof t.value||"id"!==(n=t.key)&&"label"!==n&&"text"!==n&&"value"!==n?rn(e,{raw:t.key,terms:[t]},r):ot((i=e,"id"===(o=t.key)?i.identifier:"label"===o?i.label:"value"===o?i.value:t7(i)),t.value,a)})(e,t,r,a))})(e,n,r,a));if(t.length>0)return t}return[]}function ot(e,t,r={}){var a;let n=e??"",i=rd(n),o=rd(t);if(i===o||!1!==r.allowLeadingCompositeLabelMatch&&function(e,t){if(!e||!t||!e.startsWith(t))return!1;let r=e.at(t.length);return","===r||":"===r||";"===r}(i,o))return!0;if(a=t,!/(?:\.\*|\.\+|\[[^\]]+\]|\([^)]*\)|\||\^|\$|\\[dDsSwWbB])/.test(a))return!1;try{return new RegExp(t).test(n)}catch{return!1}}function or(e,t,r){if(t.rect&&t.rect.width>0&&t.rect.height>0)return{rect:t.rect,inherited:!1};if(t.rect)return null;let a=function(e,t,r){let a=t;for(;"number"==typeof a.parentIndex&&(a=r.get(a.parentIndex)??e[a.parentIndex]);)if(a.rect)return a.rect.width>0&&a.rect.height>0?a.rect:null;return null}(e,t,r);return a?{rect:a,inherited:!0}:null}function oa(e,t,r,a,n,i=!1,o=!1,s){var l,u,d,p,c,f,m,h,g,w,y,v,A,S,_,b,I,k,N;let D,x,R,M,P=ra(e),L=(l=e,u=t,d=P,p=a,c=r,f=n,m=i,R=(x=(D=u.map(e=>{var t;let r;return(r=or(l,t=e,d))?{node:t,rect:r.rect,inheritedRect:r.inherited}:null}).filter(e=>!!e)).filter(e=>!e.inheritedRect)).length>0?x:D,p&&void 0===c?(h=R,g=f,w=m,M=h.filter(e=>{var t,r;let a,n;return t=e.rect,r=g,a=r?.referenceWidth??1/0,n=r?.referenceHeight??1/0,t.x<a&&t.y<n&&t.x+t.width>0&&t.y+t.height>0}),w||M.length>0?M:h):D),O=function(e,t,r,a,n,i){var o,s,l,u,d,p,c;if(void 0!==r)return t[r]??null;let f=(o=e,s=t,l=a,u=n,d=i,u&&l?function(e,t,r,a){let n=t.filter(e=>0===of(e.node,r));if(n.length>=2){let t=oi(e,n,r,a);if(t)return t}let i=t.filter(e=>1===of(e.node,r));return n.length>0||i.length<2?null:oi(e,i,r,a)}(o,s,l,d)??on(o,s,l,d):on(o,s,l,d));return(p=f,c=a,n&&c&&p)?function(e,t,r){var a,n,i,o,s,l,u,d,p,c,f,m,h,g,w,y,v,A;let S,_,b,I,k,N,D,x;if(a=t,n=r,!(("cell"===(S=ri(a.node.type??""))||"other"===S||"scrollview"===S||"scroll-area"===S)&&!(a.rect.width<120)&&!(a.rect.height<32)&&!(a.rect.height>80)&&1>=of(a.node,n)))return null;let R=(i=e,o=t,s=r,l=ra(e),i.filter(e=>{var t,r,a;let n;return e.index!==o.node.index&&!!e.rect&&re(i,e,o.node,l)&&(t=e,r=o.rect,a=s,!("button"!==(n=ri(t.type??""))&&"cell"!==n&&"other"!==n||1>=of(t,a))&&!(t.rect.width<16)&&!(t.rect.height<16)&&!!op(r,t.rect)&&ou(r,t.rect)>=.5)}).sort((e,t)=>e.rect.x-t.rect.x));if(0===R.length)return null;let M=(b=Math.floor((_=[...R.map(e=>e.rect.width)].sort((e,t)=>e-t)).length/2),_[b]??0),P=function(e,t){let r=[],a=e.x,n=e.x+e.width;for(let i of t){let t=Math.max(e.x,i.x),o=Math.min(n,i.x+i.width);t>a&&r.push({x:a,width:t-a}),a=Math.max(a,o)}return n>a&&r.push({x:a,width:n-a}),r}(t.rect,R.map(e=>e.rect)),L=(u=t,d=r,p=P,c=M,N=p.filter(e=>{var t,r;return t=e.width,r=c,!(t<24)&&!(r<24)&&t>=.4*r&&t<=1.6*r}),D=(f=u,m=d,I=p.find(e=>1>Math.abs(e.x-f.rect.x)),k=Math.max(48,Math.min(220,8*m.length+24)),(h=f,g=m,w=I,y=k,w&&"scrollview"===ri(h.node.type??"")&&1>=of(h.node,g)&&h.rect.width>=240&&h.rect.height>=32&&h.rect.height<=80&&w.width<=.55*h.rect.width&&w.width>=.6*y)?{x:f.rect.x,width:Math.min(k,I.width)}:null),x=N.some(e=>{var t;return t=u.rect,1>Math.abs(e.x-t.x)}),D&&!x?D:1===N.length?N[0]??null:D);return L?(v=t,A=L,{...v,rect:{x:A.x,y:v.rect.y,width:A.width,height:v.rect.height}}):null}(e,f,a)??f:f}(e,L,r,a,o,s);return y=e,v=O,A=P,S=o,_=n,v?S?(b=y,I=v,k=A,N=_,(od(I.node)?null:t9(b,I.node,k,e=>{if(!od(e))return null;let t=or(b,e,k);return t&&function(e,t,r){var a,n;if(!op(t,e)||(a=e,!((n=t).height<32||n.height>80||a.height<.75*n.height||.75>ou(a,n))&&!(n.width<240)&&n.width>=3*a.width))return!1;let i=os(t),o=os(e);if(o>0&&i>30*o)return!1;if(r){let e=r.referenceWidth*r.referenceHeight;if(e>0&&i>.5*e)return!1}return!0}(I.rect,t.rect,N)?{node:e,rect:t.rect}:null}))??{node:v.node,rect:v.rect}):{node:v.node,rect:v.rect}:null}function on(e,t,r,a){return(function(e,t,r,a){var n;let i,o,s;if(!r||t.length<2)return t;let l=t.filter(e=>0===of(e.node,r));if(l.length<2)return t;let u=ra(e),d=l.map(t=>({candidate:t,container:oo(e,t.node,u)})).filter(e=>!!e.container);if(d.length<2||d.length!==l.length)return t;let p=d.filter(e=>{var t;return t=e,d.some(e=>e!==t&&t.container.index!==e.container.index&&oc(t.container.rect,e.container.rect)>=.6)});if(p.length<2)return t;let c=(o=Math.max(...i=(n=p).map(e=>os(e.container.rect))),(s=Math.min(...i))<=0||o<1.2*s?[]:n.filter(e=>os(e.container.rect)===o).map(e=>e.candidate));if(c.length>0)return c;let f=function(e,t,r,a){if(!r)return[];let n=oo(e,r.node,a),i=n&&op(n.rect,r.rect)?n:null,o=t.map(e=>({entry:e,score:function(e,t,r){if(r)return e.index===r.index?0:.6>oc(e.rect,r.rect)?1/0:Math.abs(e.index-r.index);if(oc(e.rect,t.rect)>=.6)return 0;let a=e.index-t.node.index;return a>=0?a:1e5+Math.abs(a)}(e.container,r,i)})),s=Math.min(...o.map(e=>e.score));return Number.isFinite(s)?o.filter(e=>e.score===s).map(e=>e.entry.candidate):[]}(e,p,a,u);if(f.length>0)return f;let m=Math.max(...p.map(e=>e.container.index)),h=p.filter(e=>e.container.index===m).map(e=>e.candidate);return h.length>0?h:t})(e,t,r,a).sort((e,t)=>(function(e,t,r){var a,n;let i=function(e,t,r){if(r){let a=of(e.node,r)-of(t.node,r);if(0!==a)return a}let a=ol(e.node)-ol(t.node);if(0!==a)return a;let n=Number(e.inheritedRect)-Number(t.inheritedRect);if(0!==n)return n;let i=r&&ol(e.node)===ol(t.node)?os(t.rect)-os(e.rect):os(e.rect)-os(t.rect);return 0!==i?i:0}(e,t,r);if(0!==i)return i;if(a=e.rect,n=t.rect,Math.round(a.x)!==Math.round(n.x)||Math.round(a.y)!==Math.round(n.y)||Math.round(a.width)!==Math.round(n.width)||Math.round(a.height)!==Math.round(n.height))return e.node.index-t.node.index;let o=(t.node.depth??0)-(e.node.depth??0);return 0!==o?o:t.node.index-e.node.index})(e,t,r))[0]??null}function oi(e,t,r,a){let n=ra(e),i=t.filter(r=>{var a;return(a=r).rect.width>=16&&a.rect.width<=260&&a.rect.height>=24&&a.rect.height<=80&&t.some(t=>{var a,i,o,s;return a=e,i=t,o=r,s=n,!(i.node.index===o.node.index||!op(i.rect,o.rect)||os(i.rect)<2*os(o.rect))&&re(a,o.node,i.node,s)})});return on(e,i,r,a)}function oo(e,t,r){return t9(e,t,r,e=>{let t;return!e.rect||"scrollview"!==(t=ri(e.type??""))&&"scroll-area"!==t&&"list"!==t||e.rect.width<240||e.rect.height<320?null:e})}function os(e){return e.width*e.height}function ol(e){return i5.get(ri(e.type??""))??3}function ou(e,t){let r=Math.max(e.y,t.y);return Math.max(0,Math.min(e.y+e.height,t.y+t.height)-r)/Math.max(1,Math.min(e.height,t.height))}function od(e){let t=ri(e.type??"");return!0===e.hittable||"button"===t||"link"===t||"cell"===t||"textfield"===t||"searchfield"===t||"switch"===t||"slider"===t}function op(e,t){return t.x>=e.x-1&&t.y>=e.y-1&&t.x+t.width<=e.x+e.width+1&&t.y+t.height<=e.y+e.height+1}function oc(e,t){let r=Math.max(e.x,t.x),a=Math.min(e.x+e.width,t.x+t.width),n=Math.max(e.y,t.y);return Math.max(0,a-r)*Math.max(0,Math.min(e.y+e.height,t.y+t.height)-n)/Math.max(1,Math.min(os(e),os(t)))}function of(e,t){let r=[e.label,t7(e),e.identifier,e.value].filter(e=>!!e);return r.some(e=>e===t)?0:r.some(e=>rd(e)===rd(t))?1:r.some(e=>ot(e,t))?2:3}async function om(e){let t=oD(e.positionals,{command:"assertVisible",defaultTimeoutMs:17e3});if(!t.ok)return t.response;let r=oN(e.baseReq,t.selector);return r?await oh(e,t,r):await ow(e,t)}async function oh(e,t,r){let a=Date.now(),n=await og(e,t,r);if(n.ok){var i;if(i=e.baseReq,i.flags?.platform==="android"){let r=await ox(e,t.selector,"assertVisible");if(!r.visible){let n=ok(e.baseReq,t,r,a);return"return"===n.kind?n.response:await ow(e,t)}}return i3(e.scope,t.selector),oP({ok:!0,data:{selector:t.selector,nativeWait:!0,query:r,response:n.data}},t.selector,a)}return await oy(e,t,n,a)}async function og(e,t,r){return await e.invoke({...e.baseReq,command:"wait",positionals:[r,String(t.timeoutMs)]})}async function ow(e,t){let r,a,n=Date.now(),i=t.timeoutMs+1e3,o=!1;for(;;){let s=Date.now(),l=await ox(e,t.selector,"assertVisible");if(l.visible)return oP(l.response,t.selector,n);r=l.response,a=l.snapshot??a;let u=ok(e.baseReq,t,l,n);if("return"===u.kind)return u.response;let d=function(e){var t,r,a,n;return Date.now()-e.startedAt<e.deadlineMs?"wait":(t=e.capturedAfterDeadline,r=e.captureStartedAt,a=e.startedAt,n=e.deadlineMs,!t&&r-a<n)?"capture-again":"finish"}({captureStartedAt:s,capturedAfterDeadline:o,startedAt:n,deadlineMs:i});if("capture-again"===d){o=!0;continue}if("finish"===d)break;await rf(250)}let s=r??iQ("COMMAND_FAILED",`Expected visible but did not match: ${t.selector}`,{selector:t.selector,timeoutMs:t.timeoutMs}),l=await ov(e,t,a);return l||oL(s,a,e.baseReq)}async function oy(e,t,r,a){let n=await ox(e,t.selector,"assertVisible");if(n.visible)return oP(n.response,t.selector,a);let i=ok(e.baseReq,t,n,a);if("return"===i.kind)return i.response;let o=await ov(e,t,n.snapshot);return o||oL(r,n.snapshot,e.baseReq)}async function ov(e,t,r){if(e.baseReq.flags?.platform!=="android")return null;let a=function(e){if(!e)return;let t=iZ.get(e);return iZ.delete(e),t}(e.scope);return a?"tap"===a.kind?await oA(e,t,r,a):await oS(e,t,a):null}async function oA(e,t,r,a){if(!r)return null;let n=function(e,t,r){var a;let n,i=i7(e.baseReq.flags),o=j(t),s=i4(t,r.selector,r.options??{},i,o,{promoteTapTarget:!0});if(s.ok)return{ok:!0,target:{kind:"point",point:e1(s.rect)}};let l=i9(r.selector);return l&&(a=t,(n=l.trim().toLowerCase())&&a.nodes.some(e=>[e.label,e.value,e.identifier].some(e=>e?.trim().toLowerCase().includes(n))))?{ok:!0,target:{kind:"text",query:l}}:{ok:!1}}(e,r,a);return n.ok&&(tb({level:"info",phase:"maestro_assert_visible_retry_tap",data:{selector:t.selector,tapSelector:a.selector,originalPoint:a.point,retryTarget:n.target,timeoutMs:5e3}}),(await ob(e,n.target)).ok)?await o_(e,t,"retryTap"):null}async function oS(e,t,r){return(tb({level:"info",phase:"maestro_assert_visible_retry_swipe",data:{selector:t.selector,swipePositionals:r.positionals,timeoutMs:5e3}}),(await oI(e,r)).ok)?await o_(e,t,"retrySwipe"):null}async function o_(e,t,r){let a={...t,timeoutMs:Math.min(t.timeoutMs,5e3)},n=oN(e.baseReq,a.selector);if(!n)return await ow(e,a);let i=Date.now(),o=await og(e,a,n);return o.ok?(i3(e.scope,a.selector),oP({ok:!0,data:{selector:a.selector,nativeWait:!0,[r]:!0,query:n,response:o.data}},a.selector,i)):await oy(e,a,o,i)}async function ob(e,t){return"text"===t.kind?await e.invoke({...e.baseReq,command:"find",positionals:[t.query,"click"],flags:{...e.baseReq.flags,findFirst:!0,postGestureStabilization:!0}}):await e.invoke({...e.baseReq,command:"click",positionals:[String(t.point.x),String(t.point.y)],flags:{...e.baseReq.flags,postGestureStabilization:!0}})}async function oI(e,t){return await e.invoke({...e.baseReq,command:"swipe",positionals:t.positionals})}function ok(e,t,r,a){var n,i,o,s,l,u,d;return!(n=r.response).ok&&"COMMAND_FAILED"===n.error.code&&n.error.message.includes("React Native overlay")?{kind:"return",response:r.response}:(i=e,o=t.selector,s=r.snapshot,i.flags?.maestro?.allowAlreadyPastLoading===!0&&void 0!==s&&function(e,t){let r=oR(i9(e));if(!oM(r))return!1;let a=t.nodes.flatMap(e=>[e.label,e.value,e.identifier]).filter(e=>!!e?.trim()).map(e=>oR(e));return!a.some(e=>e.includes("something went wrong"))&&a.some(e=>e!==r&&!oM(e))}(o,s))?{kind:"return",response:(l=t.selector,u=t.timeoutMs,d=a,{ok:!0,data:{selector:l,alreadyPastLoading:!0,waitedMs:Date.now()-d,timeoutMs:u}})}:{kind:"continue"}}function oN(e,t){return e.flags?.platform!=="ios"&&e.flags?.platform!=="android"?null:i9(t)}function oD(e,t){let[r,a=String(t.defaultTimeoutMs)]=e;if(!r)return{ok:!1,response:iQ("INVALID_ARGS",`${t.command} requires a selector.`)};let n=Number(a);return!Number.isFinite(n)||n<0?{ok:!1,response:iQ("INVALID_ARGS",`${t.command} timeout must be a non-negative number.`)}:{ok:!0,selector:r,timeoutMs:n}}async function ox(e,t,r){let a=await i0(e);var n=e,i=t,o=r,s=a;if(!s.ok)return{visible:!1,response:s,infrastructureFailure:!0};let l=i1(s.data);if(!l)return{visible:!1,response:iQ("COMMAND_FAILED",`Unable to read snapshot data for ${o}.`),infrastructureFailure:!0};let u=i6(l,i,i7(n.baseReq.flags),j(l));return u.ok?(i3(n.scope,i),{visible:!0,response:{ok:!0,data:{selector:i,matches:u.matches,nodeIndex:u.node.index,nodeType:u.node.type,nodeLabel:u.node.label,nodeIdentifier:u.node.identifier,rect:u.rect}}}):{visible:!1,response:iQ("COMMAND_FAILED",u.message,{selector:i}),infrastructureFailure:!1,snapshot:l}}function oR(e){return e?.trim().toLowerCase().replace(/\u2026/g,"...")??""}function oM(e){return"loading"===e||"loading..."===e}function oP(e,t,r){return e.ok?{ok:!0,data:{selector:t,...e.data,waitedMs:Date.now()-r}}:e}function oL(e,a,n){var i;if(e.ok||!a)return e;let o="string"==typeof n.flags?.artifactsDir?n.flags.artifactsDir:void 0;if(!o)return e;let s=function(e,a){try{t.mkdirSync(a,{recursive:!0});let n=r.join(a,"failure-snapshot.json"),i=r.join(a,"failure-snapshot.txt");t.writeFileSync(n,`${JSON.stringify(e,null,2)}
|
|
29
|
-
`);let o=
|
|
30
|
-
`),[n,i]}catch{return[]}}(a,o);return 0===s.length?e:{ok:!1,error:{...e.error,details:{...e.error.details??{},artifactPaths:[...new Set([...Array.isArray(i=e.error.details?.artifactPaths)?i.filter(e=>"string"==typeof e):[],...s])]}}}}async function oO(e){let t,r=oD(e.positionals,{command:"assertNotVisible",defaultTimeoutMs:3e3});if(!r.ok)return r.response;let a=Date.now(),n=0;for(;Date.now()-a<=r.timeoutMs;){let i=await ox(e,r.selector,"assertNotVisible");if(!i.visible&&i.infrastructureFailure)return i.response;if(i.visible)n=0,t=i.response;else{n+=1;let e=Date.now()-a;if(n>=2||e>=r.timeoutMs)return{ok:!0,data:{pass:!0,selector:r.selector,stableSamples:n,waitedMs:e,timeoutMs:r.timeoutMs}}}await rf(250)}return n>0?{ok:!0,data:{pass:!0,selector:r.selector,stableSamples:n,waitedMs:Date.now()-a,timeoutMs:r.timeoutMs}}:iQ("COMMAND_FAILED",`Expected not visible but matched: ${r.selector}`,{selector:r.selector,timeoutMs:r.timeoutMs,lastResponse:t})}async function oC(e){let t,r,a=Number(e.positionals[0]??15e3);if(!Number.isFinite(a)||a<0)return iQ("INVALID_ARGS","waitForAnimationToEnd timeout must be a number.");let n=Date.now();for(;Date.now()-n<a;){let n=await i0(e),i=function(e,t,r){let a=function(e){if(!e.ok)return null;let t=i1(e.data);return t?JSON.stringify(t.nodes.map(e=>({index:e.index,parentIndex:e.parentIndex,type:e.type,identifier:e.identifier,label:e.label,value:e.value,rect:e.rect?{x:Math.round(e.rect.x),y:Math.round(e.rect.y),width:Math.round(e.rect.width),height:Math.round(e.rect.height)}:void 0}))):null}(e);return e.ok?a?t===a?{done:!0,response:{ok:!0,data:{stable:!0,timeoutMs:r}}}:{done:!1,signature:a}:{done:!0,response:e}:{done:!1}}(n,t,a);if(i.done)return i.response;t=i.signature??t,r=n,await rf(250)}return r?.ok===!1?r:{ok:!0,data:{stable:!1,timeoutMs:a}}}async function oE(e){var t,r,a;let[n,i="5000",o="down"]=e.positionals;if(!n)return iQ("INVALID_ARGS","scrollUntilVisible requires a selector.");let s=Number(i);if(!Number.isFinite(s)||s<=0)return iQ("INVALID_ARGS","scrollUntilVisible timeout must be a positive number.");let l=i9(n),u=Math.max(1,Math.ceil(s/500)),d=null;for(let t=0;t<u;t+=1){let r=await oj(e,n,l,Math.min(500,Math.max(1,s-500*t)));if(r.ok)return r;if(d=r,t===u-1)break;let a=await e.invoke({...e.baseReq,command:"scroll",positionals:[o]});if(!a.ok)return a}return t=d,r=n,a=s,t?{ok:!1,error:{...t.error,message:`scrollUntilVisible timed out after ${a}ms for selector: ${r}. Last wait: ${t.error.message}`}}:iQ("COMMAND_FAILED",`scrollUntilVisible timed out after ${a}ms for selector: ${r}`)}async function o$(e){let[t,r]=e.positionals,a=Number(t),n=Number(r);if(!Number.isFinite(a)||!Number.isFinite(n))return iQ("INVALID_ARGS","tapOn percentage point requires numeric x/y values.");let i=await i0(e);if(!i.ok)return i;let o=i1(i.data);if(!o)return iQ("COMMAND_FAILED","Unable to read snapshot data for Maestro percentage point tap.");let s=j(o);if(!s)return iQ("COMMAND_FAILED","Unable to resolve screen size for Maestro percentage point tap.");let l=eW(s,a,n),u=await e.invoke({...e.baseReq,command:"click",positionals:[String(l.x),String(l.y)],flags:{...e.baseReq.flags,postGestureStabilization:!0}});return u.ok&&i2(e.scope),u}async function oV(e){let t=await oU(e);if(t)return t;let r=await oG(e);return r.ok?await oT(e,r,r.durationMs):r.response}async function oU(e){let[t,r,a]=e.positionals;if("direction"===t&&("left"===r||"right"===r)&&"android"!==i7(e.baseReq.flags))return await e.invoke({...e.baseReq,command:"gesture",positionals:["swipe",r,...a?[a]:[]]})}async function oF(e){var t,r,a,n;let i,[o,s]=e.positionals;if(!o)return iQ("INVALID_ARGS","tapOn requires a selector.");let l=function(e){if(!e)return{ok:!0,value:null};try{let t=JSON.parse(e);return{ok:!0,value:t}}catch{return{ok:!1,response:iQ("INVALID_ARGS","tapOn runtime options must be valid JSON.")}}}(s);if(!l.ok)return l.response;let u=Date.now(),d=(t=e,t.baseReq.flags?.maestro?.optional===!0?3e3:3e4);for(;Date.now()-u<d;){let t=await oz(e,o,l.value??{});if(!t.retry)return t.response;i=t.response,await rf(250)}return r=e,a=o,n=i,r.baseReq.flags?.maestro?.optional===!0?{ok:!0,data:{skipped:!0,optional:!0,selector:a}}:n??iQ("COMMAND_FAILED",`tapOn timed out for selector: ${a}`)}async function oq(e){let[t,r="up",a]=e.positionals;if(!t)return iQ("INVALID_ARGS","swipe.label requires a label selector.");let n=await oY(e,t,{},"swipe.label",{promoteTapTarget:!1});if(!n.ok)return n.response;let i=function(e,t){let r=e1(e.rect),a=e.frame,n=iJ(a?.referenceWidth,e.rect.width),i=iJ(a?.referenceHeight,e.rect.height),o=iW,s=a?a.referenceWidth-o:r.x+n,l=a?a.referenceHeight-o:r.y+i;switch(t.toLowerCase()){case"up":return{ok:!0,start:r,end:{x:r.x,y:te(r.y-i,o,l)}};case"down":return{ok:!0,start:r,end:{x:r.x,y:te(r.y+i,o,l)}};case"left":return{ok:!0,start:r,end:{x:te(r.x-n,o,s),y:r.y}};case"right":return{ok:!0,start:r,end:{x:te(r.x+n,o,s),y:r.y}};default:return{ok:!1,message:"swipe.label direction must be up, down, left, or right."}}}(n.target,r);return i.ok?await oT(e,i,a):iQ("INVALID_ARGS",i.message)}async function oT(e,t,r){var a,n;let i=[String(t.start.x),String(t.start.y),String(t.end.x),String(t.end.y),...r?[r]:[]],o=await e.invoke({...e.baseReq,command:"swipe",positionals:i});return o.ok&&(a=e.scope,n={kind:"swipe",positionals:i},a&&iZ.set(a,n)),o}async function oG(e){var t;let r=((t=e.scope)?iX.get(t):void 0)??await oK(e);if(!r)return{ok:!1,response:iQ("COMMAND_FAILED","Unable to resolve screen size for Maestro swipe.")};let[a,...n]=e.positionals;return"direction"===a?function(e,t,r){let[a,n]=e;if(!a)return{ok:!1,response:iQ("INVALID_ARGS","Maestro direction swipe requires a direction.")};switch(a){case"up":case"down":var i,o,s;let l;return i=a,o=t,s=n,{ok:!0,start:e2({x:(l=eX({direction:i,amount:.6,referenceWidth:o.referenceWidth,referenceHeight:o.referenceHeight})).x1,y:l.y1},o,8),end:e2({x:l.x2,y:l.y2},o,8),durationMs:s};case"left":case"right":return function(e,t,r,a){let n=oH(r,85,50,15,50),[i,o]="left"===e?[85,15]:[15,85],s=oB(r,t,i,50,o,50);return{ok:!0,start:eW(t,i,n.startY,{marginPx:s}),end:eW(t,o,n.endY,{marginPx:s}),durationMs:a}}(a,t,r,n);default:return{ok:!1,response:iQ("INVALID_ARGS","Maestro swipe direction must be UP, DOWN, LEFT, or RIGHT.")}}}(n,r,i7(e.baseReq.flags)):"percent"===a?function(e,t,r){let[a,n,i,o,s]=e,l=[a,n,i,o].map(Number);if(l.some(e=>!Number.isFinite(e)))return{ok:!1,response:iQ("INVALID_ARGS","Maestro percentage swipe requires numeric points.")};let[u,d,p,c]=l,f=oH(r,u,d,p,c),m=oB(r,t,u,d,p,c);return{ok:!0,start:eW(t,u,f.startY,{marginPx:m}),end:eW(t,p,f.endY,{marginPx:m}),durationMs:s}}(n,r,i7(e.baseReq.flags)):{ok:!1,response:iQ("INVALID_ARGS","Maestro screen swipe requires direction or percent.")}}async function oK(e){let t=await i0(e);if(t.ok)return j(i1(t.data))}function oB(e,t,r,a,n,i){return"ios"!==e||a!==i||30>Math.abs(n-r)?1:Math.max(1,Math.round(.15*t.referenceWidth))}function oH(e,t,r,a,n){return"android"!==e||r!==n||50!==r||30>Math.abs(a-t)?{startY:r,endY:n}:{startY:65,endY:65}}async function oj(e,t,r,a){let n=await e.invoke({...e.baseReq,command:"wait",positionals:[t,String(a)]});return n.ok||!r?n:await e.invoke({...e.baseReq,command:"find",positionals:[r,"wait",String(a)]})}async function oz(e,t,r){let a=i9(t),n=await oW(e,t,r);return n.response.ok?{retry:!1,response:n.response}:n.targetResolved&&a?await oX(e,a):{retry:!0,response:n.response}}async function oW(e,t,r){let a=await oY(e,t,r,"tapOn",{promoteTapTarget:!0});return a.ok?await oJ(e,t,a.target,r):{response:a.response,targetResolved:!1}}async function oJ(e,t,r,a){let n=e1(r.rect);tb({level:"debug",phase:"maestro_tap_target",data:{selector:t,node:{index:r.node.index,type:r.node.type,label:r.node.label,value:r.node.value,identifier:r.node.identifier,visibleToUser:r.node.visibleToUser},rect:r.rect,point:n}});let i=await e.invoke({...e.baseReq,command:"click",positionals:[String(n.x),String(n.y)],flags:{...e.baseReq.flags,postGestureStabilization:!0}});if(i.ok){var o,s,l;(o=e.scope)&&iY.delete(o),s=e.scope,l={kind:"tap",selector:t,point:n,options:{...a}},s&&iZ.set(s,l)}return{response:i,targetResolved:!0}}async function oX(e,t){let r=await e.invoke({...e.baseReq,command:"find",positionals:[t,"click"],flags:{...e.baseReq.flags,findFirst:!0,postGestureStabilization:!0}});return(tb({level:r.ok?"info":"debug",phase:"maestro_fuzzy_tap_fallback",data:{query:t,ok:r.ok}}),r.ok)?(i2(e.scope),{retry:!1,response:r}):{retry:!0,response:r}}async function oY(e,t,r,a,n){let i=await i0({...e,raw:!0});return function(e,t,r,a,n,i){if(!i.ok)return{ok:!1,response:i};let o=i1(i.data);if(!o)return{ok:!1,response:iQ("COMMAND_FAILED",`Unable to read snapshot data for ${a}.`)};let s=j(o),l=i7(e.baseReq.flags),u=function(e,t,r,a){var n;let i=(n=e.scope)?iY.get(n):void 0;if(!i)return;let o=i6(t,i.selector,r,a);if(o.ok)return tb({level:"debug",phase:"maestro_preferred_context",data:{selector:i.selector,node:{index:o.node.index,type:o.node.type,label:o.node.label,value:o.node.value,identifier:o.node.identifier},rect:o.rect}}),{node:o.node,rect:o.rect}}(e,o,l,s),d=i4(o,t,r,l,s,{...n,preferredContext:u,requireOnScreen:!0});if(!d.ok){let e=i9(t);if(e){let t=function(e,t,r,a,n={}){let i=function(e,t){let r=rd(t);if(!r)return[];let a=[],n=[];for(let t of e.nodes){let e=[t.label,t7(t),t.identifier,t.value].filter(e=>!!e).map(e=>rd(e));e.some(e=>e===r)?a.push(t):e.some(e=>e.includes(r))&&n.push(t)}return a.length>0?a:n}(e,t),o=i8({nodes:e.nodes,matches:i,platform:r}),s=oa(e.nodes,o.matches,void 0,t,a,!0===n.requireOnScreen,n.promoteTapTarget,n.preferredContext);return s?{ok:!0,node:s.node,rect:s.rect}:{ok:!1,message:`Maestro fuzzy text did not match: ${t}`}}(o,e,l,s,{...n,preferredContext:u,requireOnScreen:!0});if(t.ok)return{ok:!0,target:{node:t.node,rect:t.rect,frame:s}}}}return d.ok?{ok:!0,target:{node:d.node,rect:d.rect,frame:s}}:{ok:!1,response:iQ("ELEMENT_NOT_FOUND",d.message,{selector:t,options:r,command:a})}}(e,t,r,a,n,i)}async function oZ(e){switch(e.command){case nC:return await om(e);case nE:return await oO(e);case n$:return await oQ(e);case nV:return await oC(e);case nU:return await oE(e);case nF:return await oV(e);case nq:return await oq(e);case nT:return await oF(e);case nG:return await o$(e);case nO:return function(e){let[r]=e.positionals;if(!r)return iQ("INVALID_ARGS","runScript requires a file path.");try{let n=function(e){let{scriptPath:r,env:n}=e,i=t.readFileSync(r,"utf8"),o=Object.create(null);try{var l,u;a.runInNewContext(i,(l=n,u=o,{...l,output:u,json:n5,http:{post:(e,t)=>(function(e,t,r){let a=t2(process.execPath,["-e",n2],{stdin:JSON.stringify({method:e,url:t,headers:r?.headers??{},body:r?.body??""}),timeoutMs:3e4,allowFailure:!0});if(0!==a.exitCode){let r;throw new s("COMMAND_FAILED",`Maestro runScript http.${e.toLowerCase()} failed for ${t}: ${(r=a.stderr.trim()).length>0?r.slice(0,1e3):"request process exited without stderr"}`,{exitCode:a.exitCode,stderr:a.stderr})}try{return JSON.parse(a.stdout)}catch(r){throw new s("COMMAND_FAILED",`Maestro runScript http.${e.toLowerCase()} returned invalid JSON for ${t}`,{stdout:a.stdout.slice(0,1e3),stderr:a.stderr.slice(0,1e3)},r instanceof Error?r:void 0)}})("POST",e,t)}}),{filename:r,timeout:3e4})}catch(e){throw new s("COMMAND_FAILED",`Maestro runScript failed for ${r}: ${e instanceof Error?e.message:String(e)}`,{scriptPath:r},e instanceof Error?e:void 0)}return function(e,t){for(let r of Object.keys(e))if(r.includes("."))throw new s("INVALID_ARGS",`Maestro runScript output key cannot contain ".": ${r}`,{scriptPath:t,key:r})}(o,r),Object.fromEntries(Object.entries(o).map(([e,t])=>{var r;return[`output.${e}`,(r=t,"string"==typeof r?r:"number"==typeof r||"boolean"==typeof r?String(r):JSON.stringify(r))]}))}({scriptPath:r,env:{...e.scope.values,...e.baseReq.flags?.maestro?.runScriptEnv??{}}});return{ok:!0,data:{outputEnv:n}}}catch(t){let e=i(t);return iQ(e.code,e.message,e.details)}}(e);default:return}}async function oQ(e){let t=await e.invoke({...e.baseReq,command:"keyboard",positionals:["enter"]});return t.ok?t:await e.invoke({...e.baseReq,command:"type",positionals:["\n"]})}async function o0(e){for(let[t,r]of e.actions.entries()){let a=await e.invokeReplayAction({action:r,line:e.line,step:e.step+t/1e3});if(!a.ok)return a}return{ok:!0,data:{ran:e.actions.length}}}async function o1(e){let t;for(let r=0;r<=e.maxRetries;r+=1){let a=await o0({actions:e.actions,line:e.line,step:e.step+r,invokeReplayAction:e.invokeReplayAction});if(a.ok)return{ok:!0,data:{attempts:r+1,retried:r>0}};t=a}return t??{ok:!1,error:{code:"COMMAND_FAILED",message:"retry commands failed."}}}async function o3(e){let t=await o2(e,e.control);return t.ok?t.matched?await o6(e):{ok:!0,data:{skipped:!0,condition:e.control.mode,selector:e.control.selector}}:t.response}async function o2(e,t){if("visible"===t.mode)return await o5(e,t);let r=await o4(e,t.selector);return r.ok?{ok:!0,matched:!r.matched}:{ok:!1,response:r.response}}async function o5(e,t){let r=Date.now();for(;;){let a=await o4(e,t.selector);if(!a.ok)return{ok:!1,response:a.response};if(a.matched)return{ok:!0,matched:!0};if(Date.now()-r>=3e3)return{ok:!0,matched:!1};await rf(250)}}async function o4(e,t){var r,a;let n,i=await i0(e);return i.ok?(r=e,a=t,(n=i1(i.data))?{ok:!0,matched:i6(n,a,i7(r.baseReq.flags),j(n)).ok}:{ok:!1,response:iQ("COMMAND_FAILED","Unable to read snapshot data for runFlow.when.")}):{ok:!1,response:i}}async function o6(e){let t=await o0({actions:e.control.actions,line:e.line,step:e.step,invokeReplayAction:e.invokeReplayAction});return t.ok?{ok:!0,data:{ran:t.data?.ran,condition:e.control.mode,selector:e.control.selector}}:t}async function o8(e){let{req:t,sessionName:r,action:a,scope:n,filePath:i,line:o,step:s,tracePath:l,invoke:u}=e,d=t1(a,n,{file:i,line:o}),p=Date.now();se(l,{type:"replay_action_start",ts:new Date(p).toISOString(),replayPath:i,line:o,step:s,command:d.command,positionals:d.positionals??[]});let c=await o7({req:t,sessionName:r,resolved:d,scope:n,line:o,step:s,invoke:u,invokeReplayAction:e=>o8({req:t,sessionName:r,action:e.action,scope:n,filePath:i,line:e.line,step:e.step,tracePath:l,invoke:u})}),f=Date.now();return se(l,{type:"replay_action_stop",ts:new Date(f).toISOString(),replayPath:i,line:o,step:s,command:d.command,ok:c.ok,durationMs:f-p,resultTiming:c.ok?function(e){if(!e||"object"!=typeof e||Array.isArray(e))return;let t=e.timing;if(!(!t||"object"!=typeof t||Array.isArray(t)))return Object.fromEntries(Object.entries(t).filter(([,e])=>{let t=typeof e;return"number"===t||"string"===t||"boolean"===t}))}(c.data):void 0,errorCode:c.ok?void 0:c.error.code}),c}async function o7(e){var t;let{req:r,sessionName:a,resolved:n,scope:i,line:o,step:s,invoke:l,invokeReplayAction:u}=e,d=(t=r.flags,tD(t,{...n.flags??{}})),p={token:r.token,session:a,flags:d,runtime:n.runtime,meta:r.meta,internal:r.internal},c=await o9({control:n.replayControl,baseReq:p,line:o,step:s,invoke:l,invokeReplayAction:u})??await oZ({command:n.command,baseReq:p,positionals:n.positionals??[],scope:i,line:o,step:s,invoke:l,invokeReplayAction:u})??await l({...p,command:n.command,positionals:n.positionals??[]});if(c.ok){let e=function(e){if(!e||"object"!=typeof e)return null;let t=e.outputEnv;if(!t||"object"!=typeof t||Array.isArray(t))return null;let r=Object.entries(t).filter(e=>"string"==typeof e[1]);return r.length>0?Object.fromEntries(r):null}(c.data);e&&t3(i,e)}return c}async function o9(e){let{control:t,baseReq:r,line:a,step:n,invoke:i,invokeReplayAction:o}=e;if(t){switch(t.kind){case"retry":return await o1({actions:t.actions,maxRetries:t.maxRetries,line:a,step:n,invokeReplayAction:o});case"maestroRunFlowWhen":return await o3({baseReq:r,control:t,line:a,step:n,invoke:i,invokeReplayAction:o})}return t}}function se(e,r){e&&t.appendFileSync(e,`${JSON.stringify(r)}
|
|
31
|
-
`)}async function st(e){let{req:a,sessionName:n,logPath:o,sessionStore:l,tracePath:u,invoke:d}=e,p=a.positionals?.[0];if(!p)return L("INVALID_ARGS","replay requires a path");let c="",f=new Set;try{var m,h,g,w,y,v,A,S,_,b,I,k,N,D,x,R,M,P,C,E;c=ep.expandHome(p,a.meta?.cwd);let e=t.readFileSync(c,"utf8"),i=e.trimStart()[0];if("{"===i||"["===i)return L("INVALID_ARGS","replay accepts .ad script files. JSON replay payloads are no longer supported.");let $=function(e,t,r={}){var a;let n=function(e){let t=e?.replayBackend;if("string"!=typeof t)return;let r=iq[t];if(!r)throw new s("INVALID_ARGS",`Unsupported replay backend "${t}".`);return r}(t);return n?{...n.parse(e,{...r,platform:t?.platform,env:(a=t,{...tK(tE(a?.replayShellEnv)),...tG(tU(a?.replayEnv))})}),updateUnsupportedMessage:"replay -u is not supported for compat flow input. Convert to .ad first, then update that replay file."}:{...tC(e),metadata:tT(e)}}(e,a.flags,{sourcePath:c}),V=$.metadata,U=V.platform||V.target?{...a,flags:(m=a.flags,h=V,{...m??{},...void 0!==h.platform&&m?.platform===void 0?{platform:h.platform}:{},...void 0!==h.target&&m?.target===void 0?{target:h.target}:{}})}:a,F=$.actions,q=$.actionLines;if(a.flags?.replayUpdate===!0&&$.updateUnsupportedMessage)return L("INVALID_ARGS",$.updateUnsupportedMessage);if(a.flags?.replayUpdate===!0&&V.env&&Object.keys(V.env).length>0)return L("INVALID_ARGS","replay -u does not yet preserve env directives. Temporarily remove the env lines, run replay -u, then restore them.");if(a.flags?.replayUpdate===!0&&function(e){for(let t of e){for(let e of t.positionals??[])if("string"==typeof e&&e.includes("${"))return!0;if(ss(t.flags)||ss(t.runtime))return!0}return!1}(F))return L("INVALID_ARGS","replay -u does not yet preserve ${VAR} substitutions. Resolve or inline the variables before running with -u.");let T=t0({builtins:function(e){let{req:t,sessionName:a,metadata:n,resolvedPath:i}=e,o=t.flags??{},s=t.meta?.cwd??process.cwd(),l={AD_SESSION:a,AD_FILENAME:r.relative(s,i)||i},u=o.platform??n.platform;u&&(l.AD_PLATFORM=u);let d=o.target??n.target;d&&(l.AD_TARGET=d);let p=o.device;"string"==typeof p&&p.length>0&&(l.AD_DEVICE=p);let c="string"==typeof o.serial?o.serial:o.udid;"string"==typeof c&&c.length>0&&(l.AD_DEVICE_ID=c),"number"==typeof o.shardIndex&&(l.AD_SHARD_INDEX=String(o.shardIndex)),"number"==typeof o.shardCount&&(l.AD_SHARD_COUNT=String(o.shardCount));let f=o.artifactsDir;return"string"==typeof f&&f.length>0&&(l.AD_ARTIFACTS=f),l}({req:U,sessionName:n,metadata:V,resolvedPath:c}),fileEnv:V.env,shellEnv:tK(tE(a.flags?.replayShellEnv)),cliEnv:tG(tU(a.flags?.replayEnv))}),G=a.flags?.replayUpdate===!0,K=u??l.get(n)?.trace?.outPath,B=[],H=0;for(let e=0;e<F.length;e+=1){let t=F[e];if(!t||"replay"===t.command)continue;!function(e,t,r){let a=O();a&&eB({type:"replay-test",...a,file:a.file||e,status:"progress",stepIndex:t+1,stepTotal:r})}(c,e,F.length);let r=sn(l,n),a=await o8({req:U,sessionName:n,action:t,scope:T,filePath:c,line:q[e]??0,step:e+1,tracePath:K,invoke:d});if(B.push(...si(l,n,r)),a.ok){sa(a).forEach(e=>f.add(e));continue}if(sa(a).forEach(e=>f.add(e)),!G){return g=a,w=t,y=e,v=c,A=[...f],S=B,sr(g,w,y,v,A,t4(S))}let i=await iG({action:t,sessionName:n,logPath:o,sessionStore:l});if(!i){return _=a,b=t,I=e,k=c,N=[...f],D=B,sr(_,b,I,k,N,t4(D))}F[e]=i;let s=sn(l,n);if(a=await o8({req:U,sessionName:n,action:i,scope:T,filePath:c,line:q[e]??0,step:e+1,tracePath:K,invoke:d}),B.push(...si(l,n,s)),!a.ok){return sa(a).forEach(e=>f.add(e)),x=a,R=i,M=e,P=c,C=[...f],E=B,sr(x,R,M,P,C,t4(E))}sa(a).forEach(e=>f.add(e)),H+=1}G&&H>0&&tQ(c,F,l.get(n));let j=t4(B);return{ok:!0,data:{replayed:F.length,healed:H,session:n,artifactPaths:[...f],...j?{snapshotDiagnostics:j}:{}}}}catch(t){let e=i(t);return L(e.code,e.message,f.size>0?{artifactPaths:[...f]}:void 0)}}function sr(e,t,r,a,n=[],i){if(e.ok)return e;let o=r+1;return{ok:!1,error:{code:e.error.code,message:`Replay failed at step ${o} (${ro(t)}): ${e.error.message}`,hint:e.error.hint,diagnosticId:e.error.diagnosticId,logPath:e.error.logPath,details:{...e.error.details??{},replayPath:a,step:o,action:t.command,positionals:t.positionals??[],artifactPaths:n,...i?{snapshotDiagnostics:i}:{}}}}}function sa(e){if(!e.ok){let t=e.error.details?.artifactPaths;return Array.isArray(t)?[...new Set(t.filter(e=>"string"==typeof e&&so(e)))]:[]}if(!e.data)return[];let t=[];if("string"==typeof e.data.path&&t.push(e.data.path),"string"==typeof e.data.outPath&&t.push(e.data.outPath),Array.isArray(e.data.artifacts))for(let r of e.data.artifacts){if(!r||"object"!=typeof r)continue;let e="string"==typeof r.localPath?r.localPath:void 0,a="string"==typeof r.path?r.path:void 0;e?t.push(e):a&&t.push(a)}return[...new Set(t.filter(e=>so(e)))]}function sn(e,t){return e.get(t)?.snapshotDiagnostics?.samples.length??0}function si(e,t,r){return e.get(t)?.snapshotDiagnostics?.samples.slice(r)??[]}function so(e){try{return t.statSync(e).isFile()}catch{return!1}}function ss(e){return"string"==typeof e?e.includes("${"):Array.isArray(e)?e.some(ss):!!e&&"object"==typeof e&&Object.values(e).some(ss)}async function sl(e){let{req:t,sessionName:a,logPath:n,sessionStore:i,artifactsDir:o,tracePath:s}=e;if(t.flags?.recordVideo!==!0)return;let l=i.get(a);if(!l||l.recording)return;let u=rh(l.device.platform),d=o?r.join(o,`recording${u}`):rg(l.device.platform);sd(s,{type:"video_recording_start",session:a,videoPath:d}),tb({phase:"replay_test_video_recording_start",data:{session:a,videoPath:d}});let p=await rm({req:{token:t.token,session:a,command:"record",positionals:["start",d],flags:{},meta:t.meta},sessionName:a,sessionStore:i,logPath:n});if(!p.ok)return sd(s,{type:"video_recording_start_failed",session:a,videoPath:d,errorCode:p.error.code}),p;let c=Date.now();return await rf(1e3),sd(s,{type:"video_preroll_done",session:a,durationMs:Date.now()-c,requestedDurationMs:1e3}),tb({phase:"replay_test_video_recording_preroll_done",durationMs:Date.now()-c,data:{session:a,requestedDurationMs:1e3}}),p}async function su(e){let{req:t,sessionName:r,logPath:a,sessionStore:n,tracePath:i,artifactPaths:o}=e;if(t.flags?.recordVideo!==!0||!n.get(r)?.recording)return;sd(i,{type:"video_tail_start",session:r,requestedDurationMs:3e3});let s=Date.now();await rf(3e3);let l=Date.now(),u=await rm({req:{token:t.token,session:r,command:"record",positionals:["stop"],flags:{},meta:t.meta},sessionName:r,sessionStore:n,logPath:a});return sa(u).forEach(e=>o.add(e)),sd(i,{type:"video_recording_stop",session:r,ok:u.ok,durationMs:Date.now()-l,tailDurationMs:l-s,errorCode:u.ok?void 0:u.error.code}),tb({phase:"replay_test_video_recording_stop",durationMs:Date.now()-l,data:{session:r,ok:u.ok,tailDurationMs:l-s}}),u}function sd(e,t){iA(e,{...t,ts:new Date().toISOString()})}async function sp(e){let{req:t,sessionName:r,logPath:a,sessionStore:n,leaseRegistry:i,invoke:o}=e;return"replay"===t.command?await st({req:t,sessionName:r,logPath:a,sessionStore:n,invoke:o}):"test"===t.command?await iL({req:t,sessionName:r,runReplay:async({filePath:e,sessionName:r,platform:i,target:s,requestId:l,artifactsDir:u,artifactPaths:d,tracePath:p,shard:c})=>{let f=function(e){let{platform:t,target:r,artifactsDir:a,shard:n}=e,i=function(e){if(e?.recordVideo!==!0)return e;let t={...e};return delete t.recordVideo,Object.keys(t).length>0?t:void 0}(e.parentFlags);if(void 0===t&&void 0===r&&void 0===a&&void 0===n)return i;var o={...i??{},...void 0!==t?{platform:t}:{},...void 0!==r?{target:r}:{},...void 0!==a?{artifactsDir:a}:{}};if(!n)return o;let s={...o??{},device:void 0,udid:void 0,serial:void 0,platform:n.device.platform,target:n.device.target,shardAll:void 0,shardSplit:void 0,shardCount:n.shardCount,shardIndex:n.shardIndex};return"android"===n.device.platform?{...s,serial:n.device.id}:{...s,udid:n.device.id}}({parentFlags:t.flags,platform:i,target:s,artifactsDir:u,shard:c}),m={req:t,sessionName:r,logPath:a,sessionStore:n,artifactsDir:u,tracePath:p},h=function(e){if(e.req.flags?.recordVideo===!0)return{beforeDispatch:async()=>await sl(e)}}(m);return await st({req:{...t,command:"replay",session:r,positionals:[e],flags:f,meta:{...t.meta??{},...l?{requestId:l}:{}},...t.internal||h?{internal:{...t.internal??{},...h?{openLifecycle:h}:{}}}:{}},sessionName:r,logPath:a,sessionStore:n,tracePath:p,invoke:async e=>{var t;let r=await sl(m);return r&&!r.ok?r:(t=await o(e),d&&sa(t).forEach(e=>d.add(e)),t)}})},finalizeAttempt:async({sessionName:e,artifactPaths:r,artifactsDir:i,tracePath:o})=>await su({req:t,sessionName:e,logPath:a,sessionStore:n,artifactsDir:i,tracePath:o,artifactPaths:r}),cleanupSession:async e=>{n.get(e)&&await ab({req:{token:t.token,session:e,command:"close",positionals:[],flags:{},meta:t.meta},sessionName:e,logPath:a,sessionStore:n,leaseRegistry:i})}}):null}async function sc(e){var t,r,a,n,i,o,s,l;let u,d,{req:p,sessionName:c,logPath:f,sessionStore:m}=e,h=p.positionals?.[0]??"";if("ios-runner"!==h)return L("INVALID_ARGS","prepare requires a subcommand: ios-runner");let g=m.get(c),w=p.flags??{},y=rN(ry.prepare,g,w);if(y)return y;let v=await rx({session:g,flags:w,ensureReady:!0});if(!ty(v.platform))return L("UNSUPPORTED_OPERATION","prepare ios-runner is only supported on Apple runner platforms");let A=Date.now(),S=await Y(v,(t=p,r=g,a=f,d=(n=t,"number"==typeof(u=n.flags?.timeoutMs)&&Number.isFinite(u)&&u>0?u:3e5),{verbose:t.flags?.verbose,logPath:a,traceLogPath:r?.trace?.outPath,cleanStaleBundles:!0,startupTimeoutMs:function(e){if("number"==typeof e&&Number.isFinite(e)&&!(e<=0))return Math.max(45e3,Math.floor(e))}(t.flags?.timeoutMs),requestId:t.meta?.requestId,buildTimeoutMs:d,healthTimeoutMs:Math.min(d,9e4),iosXctestrunFile:t.flags?.iosXctestrunFile,iosXctestDerivedDataPath:t.flags?.iosXctestDerivedDataPath,iosXctestEnvDir:t.flags?.iosXctestEnvDir}));return{ok:!0,data:(i=h,o=v,s=Math.max(0,Date.now()-A),l=S,{action:i,platform:o.platform,deviceId:o.id,deviceName:o.name,kind:o.kind,durationMs:s,...l,message:`Prepared Apple runner: ${o.name}`})}}async function sf(e){let{req:t,sessionName:r,logPath:a,sessionStore:n,command:i,positionals:o,recordPositionals:s,deriveNextSession:l}=e,u=n.get(r),d=t.flags??{},c=rN(i,u,d);if(c)return c;let f=await rx({session:u,flags:d,ensureReady:!0});if(!eV(i,f))return L("UNSUPPORTED_OPERATION",`${i} is not supported on this device`);let m=await p(f,i,o,t.flags?.out,{...eu(a,t.flags,u?.appBundleId,u?.trace?.outPath)});if(u){let e=l?await l(u,m,f):u;n.recordAction(e,{command:i,positionals:s??o,flags:t.flags??{},result:m??{}}),e!==u&&n.set(r,e)}return{ok:!0,data:m??{}}}async function sm(e){let{req:t,sessionName:r,logPath:a,sessionStore:n}=e,i=n.get(r),o=t.flags??{},s=rN(ry.clipboard,i,o);if(s)return s;let l=(t.positionals?.[0]??"").toLowerCase();if("read"!==l&&"write"!==l)return L("INVALID_ARGS","clipboard requires a subcommand: read or write");let u=await rx({session:i,flags:o,ensureReady:!0});if(!eV(ry.clipboard,u))return L("UNSUPPORTED_OPERATION","clipboard is not supported on this device");let d=await p(u,ry.clipboard,t.positionals??[],t.flags?.out,{...eu(a,t.flags,i?.appBundleId,i?.trace?.outPath)});return i&&n.recordAction(i,{command:t.command,positionals:t.positionals??[],flags:t.flags??{},result:d??{}}),{ok:!0,data:{platform:u.platform,...d??{}}}}async function sh(e){let{req:t,sessionName:r,logPath:a,sessionStore:n,leaseRegistry:i=new X,invoke:o,invokeReplayAction:s,androidAdbExecutor:l}=e;if("inventory"===g(t.command))return await aR({req:t,sessionName:r,sessionStore:n});if("runtime"===t.command)return await r4({req:t,sessionName:r,sessionStore:n});if("state"===g(t.command))return await aC({req:t,sessionName:r,sessionStore:n});if(t.command===ry.clipboard)return await sm({req:t,sessionName:r,logPath:a,sessionStore:n});if(t.command===ry.keyboard){let e=n.get(r),i=t.positionals?.[0]?.trim().toLowerCase();return e||"dismiss"!==i&&"enter"!==i&&"return"!==i||"ios"!==tA((t.flags??{}).platform)?await sf({req:t,sessionName:r,logPath:a,sessionStore:n,command:ry.keyboard,positionals:t.positionals??[]}):L("SESSION_NOT_FOUND","iOS keyboard action requires an active session so the target app stays foregrounded. Run open first.")}if("observability"===g(t.command))return await nw({req:t,sessionName:r,sessionStore:n,androidAdbExecutor:l});if(t.command===ry.prepare)return await sc({req:t,sessionName:r,logPath:a,sessionStore:n});if(t.command===ry.install||t.command===ry.reinstall)return await aD({req:t,command:t.command,sessionName:r,sessionStore:n,deployOps:t.command===ry.install?aN:ak});if(t.command===rw.installSource)return await rb({req:t,sessionName:r,sessionStore:n});if(t.command===rw.releaseMaterializedPaths)return await rI({req:t});if(t.command===ry.push){let e,i=t.positionals?.[0]?.trim(),o=t.positionals?.[1]?.trim();return i&&o?await sf({req:t,sessionName:r,logPath:a,sessionStore:n,command:ry.push,positionals:[i,"file"===(e=ev(o,{subject:"Push payload",cwd:t.meta?.cwd,expandPath:(e,t)=>ep.expandHome(e,t)})).kind?e.path:e.text],recordPositionals:[i,o]}):L("INVALID_ARGS","push requires <bundle|package> <payload.json|inline-json>")}return t.command===ry.triggerAppEvent?await sf({req:t,sessionName:r,logPath:a,sessionStore:n,command:ry.triggerAppEvent,positionals:t.positionals??[],deriveNextSession:async(e,t)=>{let r="string"==typeof t?.eventUrl?t.eventUrl:void 0,a=r?await ao(e.device,r,e.appBundleId,an)??e.appBundleId:e.appBundleId;return{...e,appBundleId:a}}}):t.command===ry.open?await aw({req:t,sessionName:r,logPath:a,sessionStore:n}):"replay"===g(t.command)?await sp({req:t,sessionName:r,logPath:a,sessionStore:n,leaseRegistry:i,invoke:s??o}):t.command===ry.batch?await ax(t,r,o):t.command===ry.close?await ab({req:t,sessionName:r,logPath:a,sessionStore:n,leaseRegistry:i}):null}export{rv as session_namespaceObject};
|
|
25
|
+
`;function iT(e){if("string"!=typeof e)throw new l("COMMAND_FAILED",`Maestro runScript json() expected a string body, received ${typeof e}.`);if(0===e.trim().length)throw new l("COMMAND_FAILED","Maestro runScript json() received an empty body. Check the preceding http response status and setup server output.");try{return JSON.parse(e,iU)}catch(t){throw new l("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 iU(e,t){return"__proto__"===e||"constructor"===e||"prototype"===e?void 0:t}let iG={launchApp:({value:e,config:t,context:r})=>[iu(e,t,r)],tapOn:({value:e,context:t})=>[function(e,t){if("string"==typeof e)return ri(i_,[iM(ru(e,t))],i$(e));if(ro(e)&&"string"==typeof e.point){rl(e,"tapOn",["point","repeat","delay","optional","label"]);let t=rp(e.point);return"percent"===t.kind?ri(iI,[String(t.x),String(t.y)],iO(e)):ri("click",[String(t.x),String(t.y)],iO(e))}ro(e)&&rl(e,"tapOn",["id","text","childOf","enabled","index","selected","repeat","delay","optional","label"]);let r=i$(e);return ri(i_,[iR(e,"tapOn",["repeat","delay","optional","label","index","childOf"],t),...function(e,t){if(!ro(e))return[];let r={};if(void 0!==e.index){if("number"!=typeof e.index||!Number.isInteger(e.index)||e.index<0)throw new l("INVALID_ARGS","tapOn.index must be a non-negative integer.");r.index=e.index}return void 0!==e.childOf&&(r.childOf=iR(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(ro(e)&&"string"==typeof e.point){rl(e,"doubleTapOn",["point","delay"]);let t=rt(e.point);return ri("click",[String(t.x),String(t.y)],iC(e))}return ro(e)&&rl(e,"doubleTapOn",["id","text","enabled","selected","delay"]),ri("click",[iR(e,"doubleTapOn",["delay"],t)],iC(e))}(e,t)],longPressOn:({value:e,context:t})=>[function(e,t){if(ro(e)&&"string"==typeof e.point){rl(e,"longPressOn",["point"]);let t=rt(e.point);return ri("longpress",[String(t.x),String(t.y),"3000"])}return ro(e)&&rl(e,"longPressOn",["id","text","enabled","selected"]),ri("click",[iR(e,"longPressOn",[],t)],{holdMs:3e3})}(e,t)],inputText:({value:e,context:t})=>[ri("type",[ru(function(e){if("string"==typeof e)return e;if(!ro(e))throw new l("INVALID_ARGS","inputText expects a string or map.");if(rl(e,"inputText",["text","label"]),"string"!=typeof e.text)throw new l("INVALID_ARGS","inputText map requires a string text field.");return e.text}(e),t)])],eraseText:({value:e})=>[ik(e)],pasteText:({value:e,context:t,name:r})=>[ri("type",[ru(rd(r,e),t)])],openLink:({value:e,config:t,context:r,name:a})=>{var n,i,o,s,l,u;let d;return[(n=e,i=t,o=r,s=a,d=ru((l=n,u=s,"string"==typeof l?l:ro(l)?(rl(l,u,["link"]),rd(`${u}.link`,l.link)):rd(u,l)),o),("ios"===o.platform||"android"===o.platform)&&i.appId?ri("open",[ru(rs(i,s),o),d],"ios"===o.platform?{maestro:{prewarmRunnerBeforeOpen:!0}}:void 0):ri("open",[d]))]},assertVisible:({value:e,context:t,name:r})=>[ri(ig,[iR(e,r,[],t),"17000"])],assertNotVisible:({value:e,context:t,name:r})=>[ri(iw,[iR(e,r,[],t)])],extendedWaitUntil:({value:e,context:t})=>(function(e,t){if(!ro(e))throw new l("INVALID_ARGS","extendedWaitUntil expects a map.");rl(e,"extendedWaitUntil",["visible","notVisible","timeout"]);let r=e.visible??e.notVisible;if(void 0===r)throw rc("Only Maestro extendedWaitUntil.visible/notVisible is supported.");let a=iR(r,"extendedWaitUntil",[],t),n=String(rf(e,17e3));return void 0!==e.notVisible?[ri(iw,[a,n])]:[ri(ig,[a,n],{maestro:{allowAlreadyPastLoading:!0}})]})(e,t),takeScreenshot:({value:e,context:t,name:r})=>[ri("screenshot",[ru(rd(r,e),t)])],scroll:({value:e})=>[function(e){if(null!=e)throw rc("Maestro scroll options are not supported yet.");return ri("scroll",["down"])}(e)],scrollUntilVisible:({value:e,context:t})=>(function(e,t){if("string"==typeof e)return[ri(iA,[iM(ru(e,t)),"5000","down"])];if(!ro(e))throw new l("INVALID_ARGS","scrollUntilVisible expects a string or map.");rl(e,"scrollUntilVisible",["element","direction","timeout"]);let r=iR(e.element,"scrollUntilVisible.element",[],t),a="string"==typeof e.direction?iD(e.direction,"scrollUntilVisible.direction"):"down";return[ri(iA,[r,String(rf(e,5e3)),a])]})(e,t),swipe:({value:e,context:t})=>[function(e,t){var r,a,n;let i;if(!ro(e))throw new l("INVALID_ARGS","swipe expects a map.");rl(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=ix("string"==typeof r.direction?r.direction:"up"),ri(iS,[iR(a,"swipe.from",[],n),i,...iP(r)])):"string"==typeof e.direction?ri(ib,["direction",ix(e.direction),...iP(e)]):function(e){let{start:t,end:r}=function(e){if("string"==typeof e.start&&"string"==typeof e.end)return{start:rp(e.start),end:rp(e.end)};throw rc("Only Maestro swipe start/end coordinates are supported.")}(e);var a=t,n=r,i=iN(e.duration);if("absolute"===a.kind&&"absolute"===n.kind)return ri("swipe",[String(a.x),String(a.y),String(n.x),String(n.y),...i?[i]:[]]);if("percent"===a.kind&&"percent"===n.kind)return ri(ib,["percent",String(a.x),String(a.y),String(n.x),String(n.y),...i?[i]:[]]);throw rc("Maestro swipe start/end must both be absolute pixels or both be percentages.")}(e)}(e,t)],hideKeyboard:()=>[ri("keyboard",["dismiss"])],pressKey:({value:e})=>[function(e){let t=rd("pressKey",e).toLowerCase();if("back"===t)return ri("back");if("enter"===t||"return"===t)return ri(iv);if("home"===t)return ri("home");throw rc(`Maestro pressKey "${t}" is not supported yet.`)}(e)],back:()=>[ri("back")],waitForAnimationToEnd:({value:e})=>[ri(iy,[String(rf(e,15e3))])],stopApp:({value:e,config:t,context:r})=>[id(e,t,r)],runScript:({value:e,context:t})=>{let a;return[ri(ih,[function(e,t){if(r.isAbsolute(e))return e;if(!t.baseDir)throw new l("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:ru(e,t),env:{}};if(!ro(e))throw new l("INVALID_ARGS","runScript expects a file path string or map.");return rl(e,"runScript",["file","env"]),{file:ru(rd("runScript.file",e.file),t),env:Object.fromEntries(Object.entries(t5(e.env,"runScript.env")).map(([e,r])=>[e,ru(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(ru(e,r),r).actions;if(!ro(e))throw new l("INVALID_ARGS","runFlow expects a file path string or map.");rl(e,"runFlow",["file","commands","env","when","label"]);let i=function(e,t){var r,a;if(null==e)return{shouldRun:!0};if(!ro(e))throw new l("INVALID_ARGS","runFlow.when expects a map.");return(rl(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 l("INVALID_ARGS","runFlow.when.true expects a boolean or expression string.");return new iE(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 s=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(s){t.push(s.token),r+=s.length;continue}throw new l("INVALID_ARGS",`Unsupported runFlow.when.true expression near "${i.slice(0,24)}".`)}return t}((r=ru(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 l("INVALID_ARGS",`${t} expects Android, iOS, or Web.`);let r=e.trim().toLowerCase();if("android"===r||"ios"===r||"web"===r)return r;throw new l("INVALID_ARGS",`${t} expects Android, iOS, or Web.`)}(e.platform,"runFlow.when.platform");if(!t.platform)throw new l("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:iR(r.visible,"runFlow.when.visible",[],a)}:{},...void 0!==r.notVisible?{notVisibleSelector:iR(r.notVisible,"runFlow.when.notVisible",[],a)}:{}})}}(e.when,r);if(!i.shouldRun)return[];let o={...r,env:{...r.env,...t5(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 rc("Maestro runFlow.when cannot combine visible and notVisible yet.");let n=r?"visible":"notVisible",i=r??a??"";return[iV("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(ru(e.file,r),r).actions;if(Array.isArray(e.commands))return n(t6(e.commands),t,r,a);throw new l("INVALID_ARGS","runFlow map requires either file or commands.")}(e,t,o,a,n),i)})(e,t,r,a,iB),repeat:({value:e,config:t,context:r,deps:a})=>(function(e,t,r,a,n){var i;if(!ro(e))throw new l("INVALID_ARGS","repeat expects a map.");if(rl(e,"repeat",["times","commands","while"]),void 0!==e.while)throw rc("Maestro repeat.while is not supported yet. Only deterministic repeat.times is supported.");let o=(i=e.times,iF(i,r,"repeat.times"));if(!Array.isArray(e.commands))throw new l("INVALID_ARGS","repeat requires a commands list.");if(o>1e3)throw new l("INVALID_ARGS","repeat.times must be <= 1000 for deterministic replay expansion.");let s=t6(e.commands);return Array.from({length:o}).flatMap(()=>n(s,t,r,a))})(e,t,r,a,iB),retry:({value:e,config:t,context:r,deps:a})=>(function(e,t,r,a,n){var i,o;if(!ro(e))throw new l("INVALID_ARGS","retry expects a map.");if(rl(e,"retry",["maxRetries","commands"]),!Array.isArray(e.commands))throw new l("INVALID_ARGS","retry requires a commands list.");let s=(i=e.maxRetries,o=r,void 0===i?1:iF(i,o,"retry.maxRetries")),u=n(t6(e.commands),t,r,a);return[iV("retry",[String(s)],{kind:"retry",maxRetries:s,actions:u})]})(e,t,r,a,iB)},iH={launchApp:(e,t)=>[iu(void 0,e,t)],scroll:()=>[ri("scroll",["down"])],hideKeyboard:()=>[ri("keyboard",["dismiss"])],eraseText:()=>[ik(void 0)],back:()=>[ri("back")],waitForAnimationToEnd:()=>[ri(iy,["15000"])],stopApp:(e,t)=>[id(void 0,e,t)]};function iK(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=iH[n])?a(i,o):t2(n)}let s=Object.entries(e);if(1!==s.length)throw new l("INVALID_ARGS","Maestro command maps must contain exactly one command.");let[u,d]=s[0],p=iG[u];return p?p({value:d,config:t,context:r,deps:a,name:u}):t2(u)}(e,t,a,n)}catch(e){if(e instanceof l&&!/\bline \d+\b/.test(e.message))throw new l(e.code,`${e.message} (line ${r})`,e.details);throw e}}function iB(e,t,r,a){return e.flatMap((e,n)=>iK(e,t,n+1,r,a))}function ij(e,t){let{config:r,commands:a}=iz(re(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=iK(r,t,a,n,{parseRunFlowFile:iW});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!==iv||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!==i_)return null;let[t,...r]=e.positionals??[];return r.length>0||"string"!=typeof t?null:t}(a);return n&&null!==o&&null!==s?{action:a,nextAction:n,pressEnterAction:i,tapSelector:s,typedAfterTap:o,line:t[r]??1}:null}(e,t,r);if(!n)return null;let{action:i,nextAction:o,pressEnterAction:s,tapSelector:l,typedAfterTap:u,line:d}=n;return(a=l,/\b(input|textfield|textarea|field|email|password|username|search|query)\b/i.test(a.replace(/([a-z])([A-Z])/g,"$1 $2")))?{actions:[{...i,command:"wait",positionals:[l,"30000"]},{...o,command:"fill",positionals:[l,u],flags:i.flags},s],actionLines:[d,d,t[r+2]??d],consumed:3}:{actions:[function(e){let t={...e.flags?.maestro??{}};return delete t.allowNonHittableCoordinateFallback,{...e,flags:{...e.flags??{},maestro:{...t}}}}(i)],actionLines:[d],consumed:1}}(e,t,n);if(o){r.push(...o.actions),a.push(...o.actionLines),n+=o.consumed-1;continue}r.push(i),a.push(t[n]??1)}return{actions:r,actionLines:a}}(s,l)}({config:r,commands:a,commandLines:function(e){let t=e.split(/\r?\n/),r=t.findIndex(e=>"---"===e.trim()),a=-1===r?0:r+1,n=[];for(let e=a;e<t.length;e+=1)/^-\s+/.test(t[e]??"")&&n.push(e+1);return n}(e),context:n});return{actions:i,actionLines:o,metadata:{env:r.env}}}function iz(e){if(0===e.length)throw new l("INVALID_ARGS","Maestro flow is empty.");if(Array.isArray(e[0]))return{config:{},commands:t6(e[0])};let t=function(e){if(!ro(e))throw new l("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}:{},...ro(e.env)?{env:t5(e.env,"env")}:{},...Array.isArray(e.onFlowStart)?{onFlowStart:t6(e.onFlowStart)}:{},...Array.isArray(e.onFlowComplete)?{onFlowComplete:t6(e.onFlowComplete)}:{}}}(e[0]),r=e[1];if(!Array.isArray(r))throw new l("INVALID_ARGS","Maestro flow must contain a command list after the YAML document separator.");return{config:t,commands:t6(r)}}function iW(e,a){let n=function(e,t){if(r.isAbsolute(e))return e;if(!t.baseDir)throw new l("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 l("INVALID_ARGS",`Maestro runFlow cycle detected at ${n}.`);let i=t.readFileSync(n,"utf8"),o=new Set(a.visitedPaths);return o.add(n),ij(i,{...a,baseDir:r.dirname(n),visitedPaths:o})}let iJ=/[*?[\]{}]/;function iY(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 iX(e,t){return"number"==typeof e?e:t}function iQ(e,t){let r="number"==typeof e?e:t;return"number"!=typeof r?0:Math.max(0,Math.min(3,r))}function iZ(e,a,n){var i,o;let s=ek.expandHome(e,a);if(t.existsSync(s)){let a=t.statSync(s);if(a.isDirectory())return{paths:[...n].map(e=>`**/*${e}`).flatMap(e=>t.globSync(e,{cwd:s}).map(e=>r.join(s,e))),source:"directory"};if(a.isFile()){if(!n.has(r.extname(s)))throw new l("INVALID_ARGS",`test does not support this file type: ${e}`);return{paths:[s],source:"file"}}return{paths:[],source:"file"}}if(i=e,!iJ.test(i)&&(o=s,!iJ.test(o)))throw new l("INVALID_ARGS",`test input not found: ${e}`);let u=r.isAbsolute(s)?s:e;return{paths:t.globSync(u,{cwd:r.isAbsolute(s)?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 i0(e,t){let r=i1(e),a=i1(t);return r!==a?r-a:e.localeCompare(t)}function i1(e){return+(".ad"===r.extname(e))}function i3(e){return[...new Set(e.map(e=>r.normalize(e)))]}function i2(e){return"maestro"===e}let i5=["failed to start daemon","runner did not accept connection","xcodebuild exited early","device is offline","device offline","device unauthorized"];function i4(e){var t,r,a,n;let i,o,s="ok"in(t=e)?t.ok?null:t.error:"failed"===t.status?t.error:null;return!!s&&(r=s.details,"timeout_cleanup_pending"===(i="string"==typeof r?.reason?r.reason:"")||!!i&&tC(i)||(a=s.code,n=s.message,o=`${a}
|
|
26
|
+
${n}`.toLowerCase(),i5.some(e=>o.includes(e))))}async function i8(e){let a,n,{filePath:i,sessionName:o,requestId:l,parentRequestId:u,timeoutMs:d,platform:p,target:c,artifactsDir:f,shard:m,progress:h,runReplay:g,cleanupSession:w,finalizeAttempt:v}=e;q(l);let y=function(e,t){if(!t||t===e)return()=>{};let r=e3(t);if(!r)return()=>{};let a=()=>{eG(e)};return r.aborted?(a(),()=>{}):(r.addEventListener("abort",a,{once:!0}),()=>{r.removeEventListener("abort",a)})}(l,u),A=new Set,b=!1,S=Date.now(),_=function(e){let{artifactsDir:a,artifactPaths:n,filePath:i,sessionName:o,requestId:s,timeoutMs:l,platform:u,target:d}=e;if(!a)return;let p=r.join(a,"replay-timing.ndjson");return t.mkdirSync(r.dirname(p),{recursive:!0}),t.writeFileSync(p,""),n.add(p),oe(p,{type:"replay_test_attempt_start",ts:new Date().toISOString(),replayPath:i,session:o,requestId:s,timeoutMs:l,platform:u,target:d}),p}({artifactsDir:f,artifactPaths:A,filePath:i,sessionName:o,requestId:l,timeoutMs:d,platform:p,target:c}),I=eT(h,async()=>await g({filePath:i,sessionName:o,platform:p,target:c,requestId:l,artifactsDir:f,artifactPaths:A,tracePath:_,shard:m})).catch(e=>({ok:!1,error:s(e)})).finally(()=>{y(),eJ(l)});try{n="number"==typeof d?await Promise.race([I,new Promise(e=>{a=setTimeout(()=>{b=!0,eG(l),e(function(e,t=[]){return{ok:!1,error:{code:"COMMAND_FAILED",message:`TIMEOUT after ${e}ms`,hint:"Replay test timeouts are cooperative; the active command may take a short grace period to stop.",details:{reason:"timeout",timeoutMs:e,timeoutMode:"cooperative",artifactPaths:t}}}}(d,[...A]))},d)})]):await I,oe(_,{type:"replay_test_attempt_stop",ts:new Date().toISOString(),session:o,ok:n.ok,timedOut:b,durationMs:Date.now()-S,errorCode:n.ok?void 0:n.error.code})}finally{var k,N,D;let e,t;a&&clearTimeout(a),b&&(await i6(I)||((k=n)&&!k.ok&&(k.error.details={...k.error.details??{},reason:"timeout_cleanup_pending",timeoutCleanupPending:!0}),tJ({level:"warn",phase:"test_timeout_cleanup_race",data:{session:o,requestId:l,graceMs:2e3}}),i7({replayPromise:I,cleanupSession:w,sessionName:o,requestId:l})));let r=await i9({finalizeAttempt:v,sessionName:o,artifactPaths:A,artifactsDir:f,tracePath:_});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{oe(_,{type:"replay_test_cleanup_start",ts:new Date().toISOString(),session:o}),await w(o),oe(_,{type:"replay_test_cleanup_stop",ts:new Date().toISOString(),session:o,ok:!0,durationMs:Date.now()-i})}catch(t){let e=s(t);oe(_,{type:"replay_test_cleanup_stop",ts:new Date().toISOString(),session:o,ok:!1,durationMs:Date.now()-i,errorCode:e.code}),tJ({level:"warn",phase:"test_cleanup_failed",data:{session:o,error:e.message}})}}return n??{ok:!1,error:{code:"COMMAND_FAILED",message:"Unknown replay test failure"}}}async function i6(e){return await Promise.race([e.then(()=>!0),n(2e3).then(()=>!1)])}async function i7(e){let{replayPromise:t,cleanupSession:r,sessionName:a,requestId:n}=e;try{await t}finally{try{await r(a)}catch(e){tJ({level:"warn",phase:"test_late_cleanup_failed",data:{session:a,requestId:n,error:s(e).message}})}}}async function i9(e){let{finalizeAttempt:t,sessionName:r,artifactPaths:a,artifactsDir:n,tracePath:i}=e;if(!t)return;let o=Date.now();oe(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 oe(i,{type:"replay_test_finalize_stop",ts:new Date().toISOString(),session:r,ok:e?.ok??!0,durationMs:Date.now()-o,errorCode:e?.ok===!1?e.error.code:void 0}),e}catch(t){let e=s(t);return oe(i,{type:"replay_test_finalize_stop",ts:new Date().toISOString(),session:r,ok:!1,durationMs:Date.now()-o,errorCode:e.code}),tJ({level:"warn",phase:"test_finalize_failed",data:{session:r,error:e.message}}),{ok:!1,error:e}}}function oe(e,r){e&&t.appendFileSync(e,`${JSON.stringify(r)}
|
|
27
|
+
`)}async function ot(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 or(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 e4({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,...oi(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),...on(u.data?.snapshotDiagnostics),...function(e){return oi(e)}(l),...r.attemptFailures.length>0?{attemptFailures:r.attemptFailures}:{}}}(t,a,n,i):function(e,t,r,a){var n,i;let{entry:o,suiteIndex:s,suiteTotal:l,shard:u}=e,d=(n=r.finalResponse)&&!n.ok?n.error:{code:"COMMAND_FAILED",message:"Unknown replay test failure"};return e4({type:"replay-test",file:o.path,title:o.title,status:"fail",index:s,total:l,attempt:r.attempts,maxAttempts:t.maxAttempts,durationMs:a,session:r.finalSessionName,artifactsDir:t.testArtifactsDir,message:d.message,hint:d.hint,...oi(u)}),{file:o.path,title:o.title,session:r.finalSessionName,status:"failed",durationMs:a,attempts:r.attempts,artifactsDir:t.testArtifactsDir,error:d,...on((i=r.finalResponse,i?.ok?i.data?.snapshotDiagnostics:i?.error.details?.snapshotDiagnostics)),...function(e){return oi(e)}(u)}}(t,a,n,i)}async function or(e,t){!function(e,t){let{entry:r,sessionName:a,suiteInvocationId:n,caseIndex:i,suiteIndex:o,suiteTotal:s,shard:l}=e;e4({type:"replay-test",file:r.path,title:r.title,status:"start",index:o,total:s,maxAttempts:t.maxAttempts,session:iY(a,n,r.path,i),artifactsDir:t.testArtifactsDir,...oi(l)})}(e,t);let r={finalSessionName:"",attempts:0,finalAttemptDurationMs:0,attemptFailures:[]};for(let p=0;p<=e.retries&&!eR(e.requestId);p+=1){var a,n,i,o,s,l,u,d;let c=await oa(e,t,p);if((a=r).finalResponse=(n=c).response,a.finalSessionName=n.sessionName,a.attempts=n.attempt,a.finalAttemptDurationMs=n.durationMs,n.response.ok||a.attemptFailures.push({attempt:n.attempt,message:n.response.error.message,durationMs:n.durationMs}),i=e,o=c.response,s=p,o.ok||eR(i.requestId)||i4(o)||s>=i.retries)break;l=e,u=t,(d=c).response.ok||e4({type:"replay-test",file:l.entry.path,title:l.entry.title,status:"fail",index:l.suiteIndex,total:l.suiteTotal,attempt:d.attempt,maxAttempts:u.maxAttempts,durationMs:d.durationMs,retrying:!0,message:d.response.error.message,hint:d.response.error.hint,session:d.sessionName,artifactsDir:u.testArtifactsDir,...oi(l.shard)})}return r}async function oa(e,a,n){var i;let{entry:o,sessionName:s,suiteInvocationId:l,caseIndex:u,suiteIndex:d,suiteTotal:p,requestId:c,timeoutMs:f,shard:m}=e,h=n+1,g=Date.now(),w=iY(s,l,o.path,u,n),v=r.join(a.testArtifactsDir,`attempt-${h}`);i=o.path,t.mkdirSync(v,{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,v);let y=function(e){let{requestId:t,suiteInvocationId:a,filePath:n,caseIndex:i,attemptIndex:o,shardIndex:s}=e,l=void 0===s?"":`:shard:${s+1}`;return eM(`${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 i8({filePath:o.path,sessionName:w,requestId:y,parentRequestId:c,timeoutMs:f,platform:o.metadata.platform,target:o.metadata.target,artifactsDir:v,shard:m,progress:{file:o.path,title:o.title,index:d,total:p,attempt:h,maxAttempts:a.maxAttempts,session:w,artifactsDir:a.testArtifactsDir,...oi(m)},runReplay:e.runReplay,cleanupSession:e.cleanupSession,finalizeAttempt:e.finalizeAttempt}),b=Date.now()-g;return!function(e){var a;let n,{response:i,filePath:o,sessionName:s,attempts:l,maxAttempts:u,attemptArtifactsDir:d}=e,p=[...Array.isArray(n=(a=i).ok?a.data?.artifactPaths:a.error.details?.artifactPaths)?[...new Set(n.filter(e=>"string"==typeof e))]:[]];i.ok||"string"!=typeof i.error.logPath||p.push(i.error.logPath);let c=function(e,a){let n=[],i=new Map;for(let o of e){if(!function(e){try{return t.statSync(e).isFile()}catch{return!1}}(o))continue;let e=function(e,t){let a=r.extname(e),n=a?e.slice(0,-a.length):e,i=t.get(e)??0;return(t.set(e,i+1),0===i)?e:`${n}-${i+1}${a}`}(r.basename(o),i),s=r.join(a,e);r.resolve(o)!==r.resolve(s)&&t.copyFileSync(o,s),n.push(s)}return n}(p,d),f=[`file: ${o}`,`session: ${s}`,`attempt: ${l}/${u}`,`status: ${i.ok?"passed":"failed"}`];if(i.ok){let e="number"==typeof i.data?.replayed?i.data.replayed:0,t="number"==typeof i.data?.healed?i.data.healed:0;f.push(`replayed: ${e}`,`healed: ${t}`)}else f.push(`code: ${i.error.code}`,`message: ${i.error.message}`),i.error.hint&&f.push(`hint: ${i.error.hint}`),i.error.diagnosticId&&f.push(`diagnosticId: ${i.error.diagnosticId}`),i.error.logPath&&f.push(`logPath: ${i.error.logPath}`),i.error.details?.reason==="timeout"&&f.push("timeoutMode: cooperative");c.length>0&&f.push(`copiedArtifacts: ${c.map(e=>r.basename(e)).join(", ")}`);let m=r.join(d,"result.txt"),h=`${f.join("\n")}
|
|
28
|
+
`;t.writeFileSync(m,h),i.ok||t.writeFileSync(r.join(d,"failure.txt"),h)}({response:A,filePath:o.path,sessionName:w,attempts:h,maxAttempts:a.maxAttempts,attemptArtifactsDir:v}),{response:A,sessionName:w,attempt:h,durationMs:b}}function on(e){let t=rA(e);return t?{snapshotDiagnostics:t}:{}}function oi(e){return e?{shardIndex:e.shardIndex,shardCount:e.shardCount,deviceId:e.device.id,deviceName:e.device.name}:{}}async function oo(e,t,r){let a=function(e){let t=os(e?.shardAll,"--shard-all"),r=os(e?.shardSplit,"--shard-split");if(void 0!==t&&void 0!==r)throw new l("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 ol(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 os(e,t){if(void 0!==e){if("number"!=typeof e||!Number.isInteger(e)||e<1)throw new l("INVALID_ARGS",`${t} requires a positive integer`);return e}}async function ol(e,t){var r,a,n,i,o,s,u,d,p;let c,f,m=(r=e,"string"!=typeof(c=r?.device)||0===c.trim().length?[]:c.split(",").map(e=>e.trim()).filter(Boolean)),h=(n=await eI((a=e,f=tF(a?.androidDeviceAllowlist),{platform:a?.platform,target:a?.target,iosSimulatorSetPath:tH({simulatorSetPath:tL(a?.iosSimulatorDeviceSet),platform:a?.platform,target:a?.target}),androidSerialAllowlist:f?Array.from(f).sort():void 0})),i=m,o=e,i.length>0?(s=n,u=i,d=o,u.map(e=>{let t=od(e),r=s.find(r=>ou(r,d)&&(r.id===e||od(r.name)===t));if(!r)throw new l("DEVICE_NOT_FOUND",`No shard device matched ${e}`);return r})):n.filter(e=>{var t;return!!ou(t=e,o)&&!!tj(t.platform)&&!1!==t.booted}).sort(op));if(h.length<t){throw new l("DEVICE_NOT_FOUND",`test sharding requires ${(p=t,`${p} device${1===p?"":"s"}`)}, but only ${h.length} matched`)}return h.slice(0,t)}function ou(e,t){return!(!tz(e.platform,t?.platform)||t?.target&&(e.target??"mobile")!==t.target)}function od(e){return e.toLowerCase().replace(/_/g," ").replace(/\s+/g," ").trim()}function op(e,t){return e.id.localeCompare(t.id)}async function oc(e){let{req:t,sessionName:r,runReplay:a,cleanupSession:n,finalizeAttempt:i}=e;if((t.positionals?.length??0)===0)return T("INVALID_ARGS","test requires at least one path or glob");try{var s,l,u,d;let e,o,p,c,f,m,h=Date.now(),g=await of(t);s=g,e4({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&&(e4({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 om({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:i})):w.push(...await ow({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:i}));let v=(l=g.total,u=w,d=Date.now()-h,e=u.filter(e=>"passed"===e.status).length,p=(o=u.filter(e=>"failed"===e.status)).length,c=u.filter(e=>"skipped"===e.status).length,f=e+p,m=rS(u.map(e=>"skipped"===e.status?void 0:e.snapshotDiagnostics)),{total:l,executed:f,passed:e,failed:p,skipped:c,notRun:Math.max(0,l-f-c),durationMs:d,failures:o,tests:u,...m?{snapshotDiagnostics:m}:{}});return{ok:!0,data:v}}catch(t){let e=o(t);return T(e.code,e.message)}}async function of(e){var a,n,i,o;let s=function(e){let{inputs:a,cwd:n,platformFilter:i,replayBackend:o}=e,s=new Set(i2(o)?[".yaml",".yml",".ad"]:[".ad"]),u=function(e,a,n,i){if(!i2(i))return[...new Set(e.flatMap(e=>iZ(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=ek.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"}:iZ(e,a,n)}(i,a,n);"file"===e.source?o.push(...e.paths):s.push("directory"===e.source?i3(e.paths):e.paths.map(e=>r.normalize(e)).sort(i0))}return i3([...o,...s.flat()])}(a,n??process.cwd(),s,o),d=[];for(let e of u){var p,c,f,m;let a=t.readFileSync(e,"utf8"),n=rr(a),s=(p=a,c=e,i2(o)&&".ad"!==r.extname(c)?function(e){let{config:t}=iz(re(e));return t.name}(p):void 0);if(!i){d.push({kind:"run",path:e,title:s,metadata:n});continue}if(!n.platform){i2(o)?d.push({kind:"run",path:e,title:s,metadata:n}):d.push({kind:"skip",path:e,reason:"skipped-by-filter",message:`missing platform metadata for --platform ${i}`});continue}f=i,m=n.platform,("apple"===f?tG(m):m===f)&&d.push({kind:"run",path:e,title:s,metadata:n})}if(0===d.filter(e=>"run"===e.kind).length){let e=i?` for --platform ${i}`:"";throw new l("INVALID_ARGS",`No replay tests matched${e}.`)}return d}({inputs:(n=e).positionals??[],cwd:n.meta?.cwd,platformFilter:n.flags?.platform,replayBackend:n.flags?.replayBackend}),u=s.flatMap((e,t)=>"run"===e.kind?[{entry:e,suiteIndex:t+1}]:[]),d=s.length-u.length,p=(a=e.meta?.requestId,(a?.trim()||`${process.pid}-${Date.now().toString(36)}`).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"suite"),c=await oo(e.flags,u,d);return{entries:s,runnable:u,shardPlan:c,suiteInvocationId:p,suiteArtifactsDir:(i=e,o=p,function(e){let{artifactsDir:t,cwd:a,suiteInvocationId:n}=e,i=ek.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??s.length}}async function om(e){return(await Promise.allSettled(e.shards.map(async t=>await oh({...e,shard:t})))).flatMap((t,r)=>{var a,n;let i;if("fulfilled"===t.status)return t.value;let o=e.shards[r];return o?[(a=o,n=e.sessionName,i=s(t.reason),{file:a.entries[0]?.entry.path??`shard-${a.shardIndex+1}`,session:og(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,deviceName:a.device.name})]:[]})}async function oh(e){let{shard:t,sessionName:r}=e;return await ov({...e,entries:t.entries,sessionName:og(r,t),shard:t})}function og(e,t){return`${e}:shard-${t.shardIndex+1}`}async function ow(e){let{discoveryEntries:t,sessionName:r,suiteInvocationId:a,cwd:n,requestId:i,flags:o,suiteArtifactsDir:s,suiteTotal:l,runReplay:u,cleanupSession:d,finalizeAttempt:p}=e,c=[],f=0;for(let[e,m]of t.entries()){if(eR(i))break;if("skip"===m.kind){e4({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 ot({entry:m,sessionName:r,suiteInvocationId:a,caseIndex:f-1,cwd:n,requestId:i,retries:iQ(o?.retries,m.metadata.retries),timeoutMs:iX(o?.timeoutMs,m.metadata.timeoutMs),suiteArtifactsDir:s,suiteIndex:e+1,suiteTotal:l,runReplay:u,cleanupSession:d,finalizeAttempt:p});if(c.push(t),oy(t,o,i))break}return c}async function ov(e){let{entries:t,sessionName:r,suiteInvocationId:a,cwd:n,requestId:i,flags:o,suiteArtifactsDir:s,suiteTotal:l,shard:u,runReplay:d,cleanupSession:p,finalizeAttempt:c}=e,f=[];for(let[e,m]of t.entries()){if(eR(i))break;let{entry:t,suiteIndex:h}=m,g=await ot({entry:t,sessionName:r,suiteInvocationId:a,caseIndex:e,cwd:n,requestId:i,retries:iQ(o?.retries,t.metadata.retries),timeoutMs:iX(o?.timeoutMs,t.metadata.timeoutMs),suiteArtifactsDir:s,suiteIndex:h,suiteTotal:l,shard:u,runReplay:d,cleanupSession:p,finalizeAttempt:c});if(f.push(g),oy(g,o,i))break}return f}function oy(e,t,r){return eR(r)||t?.failFast===!0||i4(e)}let oA={maestro:{parse:function(e,t={}){var a;let n;return ij(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:t7(a.platform),env:{},envOverrides:a.env??{},visitedPaths:n}))}}};function ob(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=rC(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 oS(e){let{action:t,sessionName:r,logPath:a,sessionStore:n}=e;if(!(r$(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),r$(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&&o_(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}=rD(e.positionals);r&&t.push(r.selectorExpression)}if("wait"===e.command){let{selectorExpression:r}=ob(e.positionals??[]);r&&t.push(r)}return Q(t).filter(e=>e.trim().length>0)})(t).map(e=>rV(e)).filter(e=>null!==e);if(0===o.length)return null;let s=r$(t.command)||"fill"===t.command,l=r$(t.command)||"fill"===t.command||"get"===t.command&&t.positionals?.[0]==="text",u=await oI(i,t,a,s,n);for(let e of o){let r=r_(u.nodes,e,{platform:i.device.platform,requireRect:s,requireUnique:!0,disambiguateAmbiguous:l});if(!r)continue;let a=rx(r.node,i.device.platform,{action:"fill"===t.command?"fill":r$(t.command)?"click":"get"}).join(" || ");if(r$(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&&o_(t)?t:void 0}(e.positionals??[]);return r?[t,r]:[t]}(t,a):[a]};if("fill"===t.command){let e=_(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}=rD(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}=ob(t.positionals??[]),r=[a];return e&&r.push(e),{...t,positionals:r}}}return null}function o_(e){return void 0!==e&&""!==e.trim()&&Number.isFinite(Number(e))}async function oI(e,t,r,a,n){let i=ey(await f(e.device,"snapshot",[],t.flags?.out,{...e_(r,{...t.flags??{},snapshotInteractiveOnly:a},e.appBundleId,e.trace?.outPath)}),{...t.flags??{},snapshotInteractiveOnly:a});return Z(e,i),n.set(e.name,e),i}let ok=.35,oN=120,oD=360,ox=8;function oR(e,t){return Math.round(Math.min(oD,Math.max(oN,"number"==typeof e?e*ok:0,1.5*t)))}let oM=new WeakMap,oP=new WeakMap,oL=new WeakMap;function oO(e,t,r){return{ok:!1,error:{code:e,message:t,...r?{details:r}:{}}}}async function o$(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=ed(oC(n.data)))&&oM.set(t,r)),n}function oC(e){return Array.isArray(e?.nodes)?e:void 0}function oE(e,t){e&&oP.set(e,{selector:t})}function oV(e){e&&oL.delete(e)}let oF=new Map([["button",0],["link",0],["textfield",0],["textview",0],["searchfield",0],["switch",0],["slider",0],["cell",1],["statictext",2]]);function oq(e,t,r,a,n,i={}){let o=oK(e,t,a);if(r.childOf){let t=oK(e,r.childOf,a);if(0===t.length)return{ok:!1,message:`Maestro childOf parent did not match: ${r.childOf}`};let n=rR(e.nodes);o=o.filter(r=>t.some(t=>rN(e.nodes,r,t,n)))}let s=oU({nodes:e.nodes,matches:o,platform:a}),l=oz(e.nodes,s.matches,r.index,oH(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 oT(e,t,r,a){let n=oK(e,t,r,{allowLeadingCompositeLabelMatch:!1}),i=oU({nodes:e.nodes,matches:n,platform:r}),o=oz(e.nodes,i.matches,void 0,oH(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 oU(e){let t=e.matches.filter(t=>rO({predicate:"visible",node:t,nodes:e.nodes,platform:e.platform}).pass),r=function(e,t,r){let a=tk(e);if(!a.detected||!a.redBox)return{matches:t,blockedByReactNativeOverlay:!1};let n=tI(a),i=n.filter(t=>rO({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 oG(e){return e?.platform==="android"?"android":"ios"}function oH(e){let t=rF(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 oK(e,t,r,a={}){for(let n of rF(t).selectors){let t=e.nodes.filter(e=>(function(e,t,r,a){return!!rM(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?rM(e,{raw:t.key,terms:[t]},r):oB((i=e,"id"===(o=t.key)?i.identifier:"label"===o?i.label:"value"===o?i.value:rI(i)),t.value,a)})(e,t,r,a))})(e,n,r,a));if(t.length>0)return t}return[]}function oB(e,t,r={}){var a;let n=e??"",i=rE(n),o=rE(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 oj(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 oz(e,t,r,a,n,i=!1,o=!1,s){var l,u,d,p,c,f,m,h,g,w,v,y,A,b,S,_,I,k,N;let D,x,R,M,P=rR(e),L=(l=e,u=t,d=P,p=a,c=r,f=n,m=i,R=(x=(D=u.map(e=>{var t;let r;return(r=oj(l,t=e,d))?{node:t,rect:r.rect,inheritedRect:r.inherited}:null}).filter(e=>!!e)).filter(e=>!e.inheritedRect)).length>0?x:D,p&&void 0===c?(h=R,g=f,w=m,M=h.filter(e=>{var t,r;let a,n;return t=e.rect,r=g,a=r?.referenceWidth??1/0,n=r?.referenceHeight??1/0,t.x<a&&t.y<n&&t.x+t.width>0&&t.y+t.height>0}),w||M.length>0?M:h):D),O=function(e,t,r,a,n,i){var o,s,l,u,d,p,c;if(void 0!==r)return t[r]??null;let f=(o=e,s=t,l=a,u=n,d=i,u&&l?function(e,t,r,a){let n=t.filter(e=>0===o2(e.node,r));if(n.length>=2){let t=oJ(e,n,r,a);if(t)return t}let i=t.filter(e=>1===o2(e.node,r));return n.length>0||i.length<2?null:oJ(e,i,r,a)}(o,s,l,d)??oW(o,s,l,d):oW(o,s,l,d));return(p=f,c=a,n&&c&&p)?function(e,t,r){var a,n,i,o,s,l,u,d,p,c,f,m,h,g,w,v,y,A;let b,S,_,I,k,N,D,x;if(a=t,n=r,!(("cell"===(b=rP(a.node.type??""))||"other"===b||"scrollview"===b||"scroll-area"===b)&&!(a.rect.width<120)&&!(a.rect.height<32)&&!(a.rect.height>80)&&1>=o2(a.node,n)))return null;let R=(i=e,o=t,s=r,l=rR(e),i.filter(e=>{var t,r,a;let n;return e.index!==o.node.index&&!!e.rect&&rN(i,e,o.node,l)&&(t=e,r=o.rect,a=s,!("button"!==(n=rP(t.type??""))&&"cell"!==n&&"other"!==n||1>=o2(t,a))&&!(t.rect.width<16)&&!(t.rect.height<16)&&!!o1(r,t.rect)&&oZ(r,t.rect)>=.5)}).sort((e,t)=>e.rect.x-t.rect.x));if(0===R.length)return null;let M=(_=Math.floor((S=[...R.map(e=>e.rect.width)].sort((e,t)=>e-t)).length/2),S[_]??0),P=function(e,t){let r=[],a=e.x,n=e.x+e.width;for(let i of t){let t=Math.max(e.x,i.x),o=Math.min(n,i.x+i.width);t>a&&r.push({x:a,width:t-a}),a=Math.max(a,o)}return n>a&&r.push({x:a,width:n-a}),r}(t.rect,R.map(e=>e.rect)),L=(u=t,d=r,p=P,c=M,N=p.filter(e=>{var t,r;return t=e.width,r=c,!(t<24)&&!(r<24)&&t>=.4*r&&t<=1.6*r}),D=(f=u,m=d,I=p.find(e=>1>Math.abs(e.x-f.rect.x)),k=Math.max(48,Math.min(220,8*m.length+24)),(h=f,g=m,w=I,v=k,w&&"scrollview"===rP(h.node.type??"")&&1>=o2(h.node,g)&&h.rect.width>=240&&h.rect.height>=32&&h.rect.height<=80&&w.width<=.55*h.rect.width&&w.width>=.6*v)?{x:f.rect.x,width:Math.min(k,I.width)}:null),x=N.some(e=>{var t;return t=u.rect,1>Math.abs(e.x-t.x)}),D&&!x?D:1===N.length?N[0]??null:D);return L?(y=t,A=L,{...y,rect:{x:A.x,y:y.rect.y,width:A.width,height:y.rect.height}}):null}(e,f,a)??f:f}(e,L,r,a,o,s);return v=e,y=O,A=P,b=o,S=n,y?b?(_=v,I=y,k=A,N=S,(o0(I.node)?null:rk(_,I.node,k,e=>{if(!o0(e))return null;let t=oj(_,e,k);return t&&function(e,t,r){var a,n;if(!o1(t,e)||(a=e,!((n=t).height<32||n.height>80||a.height<.75*n.height||.75>oZ(a,n))&&!(n.width<240)&&n.width>=3*a.width))return!1;let i=oX(t),o=oX(e);if(o>0&&i>30*o)return!1;if(r){let e=r.referenceWidth*r.referenceHeight;if(e>0&&i>.5*e)return!1}return!0}(I.rect,t.rect,N)?{node:e,rect:t.rect}:null}))??{node:y.node,rect:y.rect}):{node:y.node,rect:y.rect}:null}function oW(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===o2(e.node,r));if(l.length<2)return t;let u=rR(e),d=l.map(t=>({candidate:t,container:oY(e,t.node,u)})).filter(e=>!!e.container);if(d.length<2||d.length!==l.length)return t;let p=d.filter(e=>{var t;return t=e,d.some(e=>e!==t&&t.container.index!==e.container.index&&o3(t.container.rect,e.container.rect)>=.6)});if(p.length<2)return t;let c=(o=Math.max(...i=(n=p).map(e=>oX(e.container.rect))),(s=Math.min(...i))<=0||o<1.2*s?[]:n.filter(e=>oX(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=oY(e,r.node,a),i=n&&o1(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>o3(e.rect,r.rect)?1/0:Math.abs(e.index-r.index);if(o3(e.rect,t.rect)>=.6)return 0;let a=e.index-t.node.index;return a>=0?a:1e5+Math.abs(a)}(e.container,r,i)})),s=Math.min(...o.map(e=>e.score));return Number.isFinite(s)?o.filter(e=>e.score===s).map(e=>e.entry.candidate):[]}(e,p,a,u);if(f.length>0)return f;let m=Math.max(...p.map(e=>e.container.index)),h=p.filter(e=>e.container.index===m).map(e=>e.candidate);return h.length>0?h:t})(e,t,r,a).sort((e,t)=>(function(e,t,r){var a,n;let i=function(e,t,r){if(r){let a=o2(e.node,r)-o2(t.node,r);if(0!==a)return a}let a=oQ(e.node)-oQ(t.node);if(0!==a)return a;let n=Number(e.inheritedRect)-Number(t.inheritedRect);if(0!==n)return n;let i=r&&oQ(e.node)===oQ(t.node)?oX(t.rect)-oX(e.rect):oX(e.rect)-oX(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 oJ(e,t,r,a){let n=rR(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||!o1(i.rect,o.rect)||oX(i.rect)<2*oX(o.rect))&&rN(a,o.node,i.node,s)})});return oW(e,i,r,a)}function oY(e,t,r){return rk(e,t,r,e=>{let t;return!e.rect||"scrollview"!==(t=rP(e.type??""))&&"scroll-area"!==t&&"list"!==t||e.rect.width<240||e.rect.height<320?null:e})}function oX(e){return e.width*e.height}function oQ(e){return oF.get(rP(e.type??""))??3}function oZ(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 o0(e){let t=rP(e.type??"");return!0===e.hittable||"button"===t||"link"===t||"cell"===t||"textfield"===t||"searchfield"===t||"switch"===t||"slider"===t}function o1(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 o3(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(oX(e),oX(t)))}function o2(e,t){let r=[e.label,rI(e),e.identifier,e.value].filter(e=>!!e);return r.some(e=>e===t)?0:r.some(e=>rE(e)===rE(t))?1:r.some(e=>oB(e,t))?2:3}async function o5(e){let t=ss(e.positionals,{command:"assertVisible",defaultTimeoutMs:17e3});if(!t.ok)return t.response;let r=so(e.baseReq,t.selector);return r?await o4(e,t,r):await o6(e,t)}async function o4(e,t,r){let a=Date.now(),n=await o8(e,t,r);if(n.ok){var i;if(i=e.baseReq,i.flags?.platform==="android"){let r=await sl(e,t.selector,"assertVisible");if(!r.visible){let n=si(e.baseReq,t,r,a);return"return"===n.kind?n.response:await o6(e,t)}}return oE(e.scope,t.selector),sp({ok:!0,data:{selector:t.selector,nativeWait:!0,query:r,response:n.data}},t.selector,a)}return await o7(e,t,n,a)}async function o8(e,t,r){return await e.invoke({...e.baseReq,command:"wait",positionals:[r,String(t.timeoutMs)]})}async function o6(e,t){let r,a,n=Date.now(),i=t.timeoutMs+1e3,o=!1;for(;;){let s=Date.now(),l=await sl(e,t.selector,"assertVisible");if(l.visible)return sp(l.response,t.selector,n);r=l.response,a=l.snapshot??a;let u=si(e.baseReq,t,l,n);if("return"===u.kind)return u.response;let d=function(e){var t,r,a,n;return Date.now()-e.startedAt<e.deadlineMs?"wait":(t=e.capturedAfterDeadline,r=e.captureStartedAt,a=e.startedAt,n=e.deadlineMs,!t&&r-a<n)?"capture-again":"finish"}({captureStartedAt:s,capturedAfterDeadline:o,startedAt:n,deadlineMs:i});if("capture-again"===d){o=!0;continue}if("finish"===d)break;await rq(250)}let s=r??oO("COMMAND_FAILED",`Expected visible but did not match: ${t.selector}`,{selector:t.selector,timeoutMs:t.timeoutMs}),l=await o9(e,t,a);return l||sc(s,a,e.baseReq)}async function o7(e,t,r,a){let n=await sl(e,t.selector,"assertVisible");if(n.visible)return sp(n.response,t.selector,a);let i=si(e.baseReq,t,n,a);if("return"===i.kind)return i.response;let o=await o9(e,t,n.snapshot);return o||sc(r,n.snapshot,e.baseReq)}async function o9(e,t,r){if(e.baseReq.flags?.platform!=="android")return null;let a=function(e){if(!e)return;let t=oL.get(e);return oL.delete(e),t}(e.scope);return a?"tap"===a.kind?await se(e,t,r,a):await st(e,t,a):null}async function se(e,t,r,a){if(!r)return null;let n=function(e,t,r){var a;let n,i=oG(e.baseReq.flags),o=ed(t),s=oq(t,r.selector,r.options??{},i,o,{promoteTapTarget:!0});if(s.ok)return{ok:!0,target:{kind:"point",point:tp(s.rect)}};let l=oH(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&&(tJ({level:"info",phase:"maestro_assert_visible_retry_tap",data:{selector:t.selector,tapSelector:a.selector,originalPoint:a.point,retryTarget:n.target,timeoutMs:5e3}}),(await sa(e,n.target)).ok)?await sr(e,t,"retryTap"):null}async function st(e,t,r){return(tJ({level:"info",phase:"maestro_assert_visible_retry_swipe",data:{selector:t.selector,swipePositionals:r.positionals,timeoutMs:5e3}}),(await sn(e,r)).ok)?await sr(e,t,"retrySwipe"):null}async function sr(e,t,r){let a={...t,timeoutMs:Math.min(t.timeoutMs,5e3)},n=so(e.baseReq,a.selector);if(!n)return await o6(e,a);let i=Date.now(),o=await o8(e,a,n);return o.ok?(oE(e.scope,a.selector),sp({ok:!0,data:{selector:a.selector,nativeWait:!0,[r]:!0,query:n,response:o.data}},a.selector,i)):await o7(e,a,o,i)}async function sa(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 sn(e,t){return await e.invoke({...e.baseReq,command:"swipe",positionals:t.positionals})}function si(e,t,r,a){var n,i,o,s,l,u,d;return!(n=r.response).ok&&"COMMAND_FAILED"===n.error.code&&n.error.message.includes("React Native overlay")?{kind:"return",response:r.response}:(i=e,o=t.selector,s=r.snapshot,i.flags?.maestro?.allowAlreadyPastLoading===!0&&void 0!==s&&function(e,t){let r=su(oH(e));if(!sd(r))return!1;let a=t.nodes.flatMap(e=>[e.label,e.value,e.identifier]).filter(e=>!!e?.trim()).map(e=>su(e));return!a.some(e=>e.includes("something went wrong"))&&a.some(e=>e!==r&&!sd(e))}(o,s))?{kind:"return",response:(l=t.selector,u=t.timeoutMs,d=a,{ok:!0,data:{selector:l,alreadyPastLoading:!0,waitedMs:Date.now()-d,timeoutMs:u}})}:{kind:"continue"}}function so(e,t){return e.flags?.platform!=="ios"&&e.flags?.platform!=="android"?null:oH(t)}function ss(e,t){let[r,a=String(t.defaultTimeoutMs)]=e;if(!r)return{ok:!1,response:oO("INVALID_ARGS",`${t.command} requires a selector.`)};let n=Number(a);return!Number.isFinite(n)||n<0?{ok:!1,response:oO("INVALID_ARGS",`${t.command} timeout must be a non-negative number.`)}:{ok:!0,selector:r,timeoutMs:n}}async function sl(e,t,r){let a=await o$(e);var n=e,i=t,o=r,s=a;if(!s.ok)return{visible:!1,response:s,infrastructureFailure:!0};let l=oC(s.data);if(!l)return{visible:!1,response:oO("COMMAND_FAILED",`Unable to read snapshot data for ${o}.`),infrastructureFailure:!0};let u=oT(l,i,oG(n.baseReq.flags),ed(l));return u.ok?(oE(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:oO("COMMAND_FAILED",u.message,{selector:i}),infrastructureFailure:!1,snapshot:l}}function su(e){return e?.trim().toLowerCase().replace(/\u2026/g,"...")??""}function sd(e){return"loading"===e||"loading..."===e}function sp(e,t,r){return e.ok?{ok:!0,data:{selector:t,...e.data,waitedMs:Date.now()-r}}:e}function sc(e,a,n){var i;if(e.ok||!a)return e;let o="string"==typeof n.flags?.artifactsDir?n.flags.artifactsDir:void 0;if(!o)return e;let s=function(e,a){try{t.mkdirSync(a,{recursive:!0});let n=r.join(a,"failure-snapshot.json"),i=r.join(a,"failure-snapshot.txt");t.writeFileSync(n,`${JSON.stringify(e,null,2)}
|
|
29
|
+
`);let o=ts(e.nodes,{summarizeTextSurfaces:!0}).map(e=>e.text);return t.writeFileSync(i,`${o.join("\n")}
|
|
30
|
+
`),[n,i]}catch{return[]}}(a,o);return 0===s.length?e:{ok:!1,error:{...e.error,details:{...e.error.details??{},artifactPaths:[...new Set([...Array.isArray(i=e.error.details?.artifactPaths)?i.filter(e=>"string"==typeof e):[],...s])]}}}}async function sf(e){let t,r=ss(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 sl(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 rq(250)}return n>0?{ok:!0,data:{pass:!0,selector:r.selector,stableSamples:n,waitedMs:Date.now()-a,timeoutMs:r.timeoutMs}}:oO("COMMAND_FAILED",`Expected not visible but matched: ${r.selector}`,{selector:r.selector,timeoutMs:r.timeoutMs,lastResponse:t})}async function sm(e){let t,r,a=Number(e.positionals[0]??15e3);if(!Number.isFinite(a)||a<0)return oO("INVALID_ARGS","waitForAnimationToEnd timeout must be a number.");let n=Date.now();for(;Date.now()-n<a;){let n=await o$(e),i=function(e,t,r){let a=function(e){if(!e.ok)return null;let t=oC(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 rq(250)}return r?.ok===!1?r:{ok:!0,data:{stable:!1,timeoutMs:a}}}async function sh(e){var t,r,a;let[n,i="5000",o="down"]=e.positionals;if(!n)return oO("INVALID_ARGS","scrollUntilVisible requires a selector.");let s=Number(i);if(!Number.isFinite(s)||s<=0)return oO("INVALID_ARGS","scrollUntilVisible timeout must be a positive number.");let l=oH(n),u=Math.max(1,Math.ceil(s/500)),d=null;for(let t=0;t<u;t+=1){let r=await sN(e,n,l,Math.min(500,Math.max(1,s-500*t)));if(r.ok)return r;if(d=r,t===u-1)break;let a=await e.invoke({...e.baseReq,command:"scroll",positionals:[o]});if(!a.ok)return a}return t=d,r=n,a=s,t?{ok:!1,error:{...t.error,message:`scrollUntilVisible timed out after ${a}ms for selector: ${r}. Last wait: ${t.error.message}`}}:oO("COMMAND_FAILED",`scrollUntilVisible timed out after ${a}ms for selector: ${r}`)}async function sg(e){let[t,r]=e.positionals,a=Number(t),n=Number(r);if(!Number.isFinite(a)||!Number.isFinite(n))return oO("INVALID_ARGS","tapOn percentage point requires numeric x/y values.");let i=await o$(e);if(!i.ok)return i;let o=oC(i.data);if(!o)return oO("COMMAND_FAILED","Unable to read snapshot data for Maestro percentage point tap.");let s=ed(o);if(!s)return oO("COMMAND_FAILED","Unable to resolve screen size for Maestro percentage point tap.");let l=ta(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&&oV(e.scope),u}async function sw(e){let t=await sv(e);if(t)return t;let r=await sS(e);return r.ok?await sb(e,r,r.durationMs):r.response}async function sv(e){let[t,r,a]=e.positionals;if("direction"===t&&("left"===r||"right"===r)&&"android"!==oG(e.baseReq.flags))return await e.invoke({...e.baseReq,command:"gesture",positionals:["swipe",r,...a?[a]:[]]})}async function sy(e){var t,r,a,n;let i,[o,s]=e.positionals;if(!o)return oO("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:oO("INVALID_ARGS","tapOn runtime options must be valid JSON.")}}}(s);if(!l.ok)return l.response;let u=Date.now(),d=(t=e,t.baseReq.flags?.maestro?.optional===!0?3e3:3e4);for(;Date.now()-u<d;){let t=await sD(e,o,l.value??{});if(!t.retry)return t.response;i=t.response,await rq(250)}return r=e,a=o,n=i,r.baseReq.flags?.maestro?.optional===!0?{ok:!0,data:{skipped:!0,optional:!0,selector:a}}:n??oO("COMMAND_FAILED",`tapOn timed out for selector: ${a}`)}async function sA(e){let[t,r="up",a]=e.positionals;if(!t)return oO("INVALID_ARGS","swipe.label requires a label selector.");let n=await sP(e,t,{},"swipe.label",{promoteTapTarget:!1});if(!n.ok)return n.response;let i=function(e,t){let r=tp(e.rect),a=e.frame,n=oR(a?.referenceWidth,e.rect.width),i=oR(a?.referenceHeight,e.rect.height),o=ox,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:tb(r.y-i,o,l)}};case"down":return{ok:!0,start:r,end:{x:r.x,y:tb(r.y+i,o,l)}};case"left":return{ok:!0,start:r,end:{x:tb(r.x-n,o,s),y:r.y}};case"right":return{ok:!0,start:r,end:{x:tb(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 sb(e,i,a):oO("INVALID_ARGS",i.message)}async function sb(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&&oL.set(a,n)),o}async function sS(e){var t;let r=((t=e.scope)?oM.get(t):void 0)??await s_(e);if(!r)return{ok:!1,response:oO("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:oO("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:tf({x:(l=ti({direction:i,amount:.6,referenceWidth:o.referenceWidth,referenceHeight:o.referenceHeight})).x1,y:l.y1},o,8),end:tf({x:l.x2,y:l.y2},o,8),durationMs:s};case"left":case"right":return function(e,t,r,a){let n=sk(r,85,50,15,50),[i,o]="left"===e?[85,15]:[15,85],s=sI(r,t,i,50,o,50);return{ok:!0,start:ta(t,i,n.startY,{marginPx:s}),end:ta(t,o,n.endY,{marginPx:s}),durationMs:a}}(a,t,r,n);default:return{ok:!1,response:oO("INVALID_ARGS","Maestro swipe direction must be UP, DOWN, LEFT, or RIGHT.")}}}(n,r,oG(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:oO("INVALID_ARGS","Maestro percentage swipe requires numeric points.")};let[u,d,p,c]=l,f=sk(r,u,d,p,c),m=sI(r,t,u,d,p,c);return{ok:!0,start:ta(t,u,f.startY,{marginPx:m}),end:ta(t,p,f.endY,{marginPx:m}),durationMs:s}}(n,r,oG(e.baseReq.flags)):{ok:!1,response:oO("INVALID_ARGS","Maestro screen swipe requires direction or percent.")}}async function s_(e){let t=await o$(e);if(t.ok)return ed(oC(t.data))}function sI(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 sk(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 sN(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 sD(e,t,r){let a=oH(t),n=await sx(e,t,r);return n.response.ok?{retry:!1,response:n.response}:n.targetResolved&&a?await sM(e,a):{retry:!0,response:n.response}}async function sx(e,t,r){let a=await sP(e,t,r,"tapOn",{promoteTapTarget:!0});return a.ok?await sR(e,t,a.target,r):{response:a.response,targetResolved:!1}}async function sR(e,t,r,a){let n=tp(r.rect);tJ({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)&&oP.delete(o),s=e.scope,l={kind:"tap",selector:t,point:n,options:{...a}},s&&oL.set(s,l)}return{response:i,targetResolved:!0}}async function sM(e,t){let r=await e.invoke({...e.baseReq,command:"find",positionals:[t,"click"],flags:{...e.baseReq.flags,findFirst:!0,postGestureStabilization:!0}});return(tJ({level:r.ok?"info":"debug",phase:"maestro_fuzzy_tap_fallback",data:{query:t,ok:r.ok}}),r.ok)?(oV(e.scope),{retry:!1,response:r}):{retry:!0,response:r}}async function sP(e,t,r,a,n){let i=await o$({...e,raw:!0});return function(e,t,r,a,n,i){if(!i.ok)return{ok:!1,response:i};let o=oC(i.data);if(!o)return{ok:!1,response:oO("COMMAND_FAILED",`Unable to read snapshot data for ${a}.`)};let s=ed(o),l=oG(e.baseReq.flags),u=function(e,t,r,a){var n;let i=(n=e.scope)?oP.get(n):void 0;if(!i)return;let o=oT(t,i.selector,r,a);if(o.ok)return tJ({level:"debug",phase:"maestro_preferred_context",data:{selector:i.selector,node:{index:o.node.index,type:o.node.type,label:o.node.label,value:o.node.value,identifier:o.node.identifier},rect:o.rect}}),{node:o.node,rect:o.rect}}(e,o,l,s),d=oq(o,t,r,l,s,{...n,preferredContext:u,requireOnScreen:!0});if(!d.ok){let e=oH(t);if(e){let t=function(e,t,r,a,n={}){let i=function(e,t){let r=rE(t);if(!r)return[];let a=[],n=[];for(let t of e.nodes){let e=[t.label,rI(t),t.identifier,t.value].filter(e=>!!e).map(e=>rE(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=oU({nodes:e.nodes,matches:i,platform:r}),s=oz(e.nodes,o.matches,void 0,t,a,!0===n.requireOnScreen,n.promoteTapTarget,n.preferredContext);return s?{ok:!0,node:s.node,rect:s.rect}:{ok:!1,message:`Maestro fuzzy text did not match: ${t}`}}(o,e,l,s,{...n,preferredContext:u,requireOnScreen:!0});if(t.ok)return{ok:!0,target:{node:t.node,rect:t.rect,frame:s}}}}return d.ok?{ok:!0,target:{node:d.node,rect:d.rect,frame:s}}:{ok:!1,response:oO("ELEMENT_NOT_FOUND",d.message,{selector:t,options:r,command:a})}}(e,t,r,a,n,i)}async function sL(e){switch(e.command){case ig:return await o5(e);case iw:return await sf(e);case iv:return await sO(e);case iy:return await sm(e);case iA:return await sh(e);case ib:return await sw(e);case iS:return await sA(e);case i_:return await sy(e);case iI:return await sg(e);case ih:return function(e){let[r]=e.positionals;if(!r)return oO("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 s,u;a.runInNewContext(i,(s=n,u=o,{...s,output:u,json:iT,http:{post:(e,t)=>(function(e,t,r){let a=rv(process.execPath,["-e",iq],{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 l("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 l("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 l("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 l("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=o(t);return oO(e.code,e.message,e.details)}}(e);default:return}}async function sO(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 s$(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 sC(e){let t;for(let r=0;r<=e.maxRetries;r+=1){let a=await s$({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 sE(e){let t=await sV(e,e.control);return t.ok?t.matched?await sT(e):{ok:!0,data:{skipped:!0,condition:e.control.mode,selector:e.control.selector}}:t.response}async function sV(e,t){if("visible"===t.mode)return await sF(e,t);let r=await sq(e,t.selector);return r.ok?{ok:!0,matched:!r.matched}:{ok:!1,response:r.response}}async function sF(e,t){let r=Date.now();for(;;){let a=await sq(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 rq(250)}}async function sq(e,t){var r,a;let n,i=await o$(e);return i.ok?(r=e,a=t,(n=oC(i.data))?{ok:!0,matched:oT(n,a,oG(r.baseReq.flags),ed(n)).ok}:{ok:!1,response:oO("COMMAND_FAILED","Unable to read snapshot data for runFlow.when.")}):{ok:!1,response:i}}async function sT(e){let t=await s$({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 sU(e){let{req:t,sessionName:r,action:a,scope:n,filePath:i,line:o,step:s,tracePath:l,invoke:u}=e,d=rg(a,n,{file:i,line:o}),p=Date.now();sK(l,{type:"replay_action_start",ts:new Date(p).toISOString(),replayPath:i,line:o,step:s,command:d.command,positionals:d.positionals??[]});let c=await sG({req:t,sessionName:r,resolved:d,scope:n,line:o,step:s,invoke:u,invokeReplayAction:e=>sU({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 sK(l,{type:"replay_action_stop",ts:new Date(f).toISOString(),replayPath:i,line:o,step:s,command:d.command,ok:c.ok,durationMs:f-p,resultTiming:c.ok?function(e){if(!e||"object"!=typeof e||Array.isArray(e))return;let t=e.timing;if(!(!t||"object"!=typeof t||Array.isArray(t)))return Object.fromEntries(Object.entries(t).filter(([,e])=>{let t=typeof e;return"number"===t||"string"===t||"boolean"===t}))}(c.data):void 0,errorCode:c.ok?void 0:c.error.code}),c}async function sG(e){var t;let{req:r,sessionName:a,resolved:n,scope:i,line:o,step:s,invoke:l,invokeReplayAction:u}=e,d=(t=r.flags,tZ(t,{...n.flags??{}})),p={token:r.token,session:a,flags:d,runtime:n.runtime,meta:r.meta,internal:r.internal},c=await sH({control:n.replayControl,baseReq:p,line:o,step:s,invoke:l,invokeReplayAction:u})??await sL({command:n.command,baseReq:p,positionals:n.positionals??[],scope:i,line:o,step:s,invoke:l,invokeReplayAction:u})??await l({...p,command:n.command,positionals:n.positionals??[]});if(c.ok){let e=function(e){if(!e||"object"!=typeof e)return null;let t=e.outputEnv;if(!t||"object"!=typeof t||Array.isArray(t))return null;let r=Object.entries(t).filter(e=>"string"==typeof e[1]);return r.length>0?Object.fromEntries(r):null}(c.data);e&&rw(i,e)}return c}async function sH(e){let{control:t,baseReq:r,line:a,step:n,invoke:i,invokeReplayAction:o}=e;if(t){switch(t.kind){case"retry":return await sC({actions:t.actions,maxRetries:t.maxRetries,line:a,step:n,invokeReplayAction:o});case"maestroRunFlowWhen":return await sE({baseReq:r,control:t,line:a,step:n,invoke:i,invokeReplayAction:o})}return t}}function sK(e,r){e&&t.appendFileSync(e,`${JSON.stringify(r)}
|
|
31
|
+
`)}async function sB(e){let{req:a,sessionName:n,logPath:i,sessionStore:s,tracePath:u,invoke:d}=e,p=a.positionals?.[0];if(!p)return T("INVALID_ARGS","replay requires a path");let c="",f=new Set;try{var m,h,g,w,v,y,A,b,S,_,I,k,N,D,x,R,M,P,L,O;c=ek.expandHome(p,a.meta?.cwd);let e=t.readFileSync(c,"utf8"),o=e.trimStart()[0];if("{"===o||"["===o)return T("INVALID_ARGS","replay accepts .ad script files. JSON replay payloads are no longer supported.");let $=function(e,t,r={}){var a;let n=function(e){let t=e?.replayBackend;if("string"!=typeof t)return;let r=oA[t];if(!r)throw new l("INVALID_ARGS",`Unsupported replay backend "${t}".`);return r}(t);return n?{...n.parse(e,{...r,platform:t?.platform,env:(a=t,{...rn(t8(a?.replayShellEnv)),...ra(t9(a?.replayEnv))})}),updateUnsupportedMessage:"replay -u is not supported for compat flow input. Convert to .ad first, then update that replay file."}:{...t4(e),metadata:rr(e)}}(e,a.flags,{sourcePath:c}),C=$.metadata,E=C.platform||C.target?{...a,flags:(m=a.flags,h=C,{...m??{},...void 0!==h.platform&&m?.platform===void 0?{platform:h.platform}:{},...void 0!==h.target&&m?.target===void 0?{target:h.target}:{}})}:a,V=$.actions,F=$.actionLines;if(a.flags?.replayUpdate===!0&&$.updateUnsupportedMessage)return T("INVALID_ARGS",$.updateUnsupportedMessage);if(a.flags?.replayUpdate===!0&&C.env&&Object.keys(C.env).length>0)return T("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(sX(t.flags)||sX(t.runtime))return!0}return!1}(V))return T("INVALID_ARGS","replay -u does not yet preserve ${VAR} substitutions. Resolve or inline the variables before running with -u.");let q=rh({builtins:function(e){let{req:t,sessionName:a,metadata:n,resolvedPath:i}=e,o=t.flags??{},s=t.meta?.cwd??process.cwd(),l={AD_SESSION:a,AD_FILENAME:r.relative(s,i)||i},u=o.platform??n.platform;u&&(l.AD_PLATFORM=u);let d=o.target??n.target;d&&(l.AD_TARGET=d);let p=o.device;"string"==typeof p&&p.length>0&&(l.AD_DEVICE=p);let c="string"==typeof o.serial?o.serial:o.udid;"string"==typeof c&&c.length>0&&(l.AD_DEVICE_ID=c),"number"==typeof o.shardIndex&&(l.AD_SHARD_INDEX=String(o.shardIndex)),"number"==typeof o.shardCount&&(l.AD_SHARD_COUNT=String(o.shardCount));let f=o.artifactsDir;return"string"==typeof f&&f.length>0&&(l.AD_ARTIFACTS=f),l}({req:E,sessionName:n,metadata:C,resolvedPath:c}),fileEnv:C.env,shellEnv:rn(t8(a.flags?.replayShellEnv)),cliEnv:ra(t9(a.flags?.replayEnv))}),U=a.flags?.replayUpdate===!0,H=u??s.get(n)?.trace?.outPath,K=[],B=0;for(let e=0;e<V.length;e+=1){let t=V[e];if(!t||"replay"===t.command)continue;!function(e,t,r,a){var n;let i=G();i&&e4({type:"replay-test",...i,file:i.file||e,status:"progress",stepIndex:t+1,stepTotal:r,...(n=a,{stepCommand:function(e){if(!e.startsWith("__maestro"))return e;let t=e.slice(9);return t.length>0?t[0].toLowerCase()+t.slice(1):e}(n.command),...function(e){let t=e.positionals??[],r=function(e){if(!e)return;let t=rV(e);if(!t)return;let r=t.selectors.flatMap(e=>e.terms.flatMap(e=>("label"===e.key||"text"===e.key||"id"===e.key)&&"string"==typeof e.value?[e.value]:[]));if(0===r.length)return;let a=r[0];return a&&r.every(e=>e===a)?a:void 0}(t[0]);return r?{stepValue:r}:"__maestroTapPointPercent"===e.command&&t.length>=2?{stepValue:`${t[0]},${t[1]}%`}:0===t.length?{}:{stepValue:t.join(" ")}}(n)})})}(c,e,V.length,t);let r=sW(s,n),a=await sU({req:E,sessionName:n,action:t,scope:q,filePath:c,line:F[e]??0,step:e+1,tracePath:H,invoke:d});if(K.push(...sJ(s,n,r)),a.ok){sz(a).forEach(e=>f.add(e));continue}if(sz(a).forEach(e=>f.add(e)),!U){return g=a,w=t,v=e,y=c,A=[...f],b=K,sj(g,w,v,y,A,rb(b))}let o=await oS({action:t,sessionName:n,logPath:i,sessionStore:s});if(!o){return S=a,_=t,I=e,k=c,N=[...f],D=K,sj(S,_,I,k,N,rb(D))}V[e]=o;let l=sW(s,n);if(a=await sU({req:E,sessionName:n,action:o,scope:q,filePath:c,line:F[e]??0,step:e+1,tracePath:H,invoke:d}),K.push(...sJ(s,n,l)),!a.ok){return sz(a).forEach(e=>f.add(e)),x=a,R=o,M=e,P=c,L=[...f],O=K,sj(x,R,M,P,L,rb(O))}sz(a).forEach(e=>f.add(e)),B+=1}U&&B>0&&rm(c,V,s.get(n));let j=rb(K);return{ok:!0,data:{replayed:V.length,healed:B,session:n,artifactPaths:[...f],...j?{snapshotDiagnostics:j}:{}}}}catch(t){let e=o(t);return T(e.code,e.message,f.size>0?{artifactPaths:[...f]}:void 0)}}function sj(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} (${rL(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 sz(e){if(!e.ok){let t=e.error.details?.artifactPaths;return Array.isArray(t)?[...new Set(t.filter(e=>"string"==typeof e&&sY(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=>sY(e)))]}function sW(e,t){return e.get(t)?.snapshotDiagnostics?.samples.length??0}function sJ(e,t,r){return e.get(t)?.snapshotDiagnostics?.samples.slice(r)??[]}function sY(e){try{return t.statSync(e).isFile()}catch{return!1}}function sX(e){return"string"==typeof e?e.includes("${"):Array.isArray(e)?e.some(sX):!!e&&"object"==typeof e&&Object.values(e).some(sX)}async function sQ(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=rU(l.device.platform),d=o?r.join(o,`recording${u}`):rG(l.device.platform);s0(s,{type:"video_recording_start",session:a,videoPath:d}),tJ({phase:"replay_test_video_recording_start",data:{session:a,videoPath:d}});let p=await rT({req:{token:t.token,session:a,command:"record",positionals:["start",d],flags:{},meta:t.meta},sessionName:a,sessionStore:i,logPath:n});if(!p.ok)return s0(s,{type:"video_recording_start_failed",session:a,videoPath:d,errorCode:p.error.code}),p;let c=Date.now();return await rq(1e3),s0(s,{type:"video_preroll_done",session:a,durationMs:Date.now()-c,requestedDurationMs:1e3}),tJ({phase:"replay_test_video_recording_preroll_done",durationMs:Date.now()-c,data:{session:a,requestedDurationMs:1e3}}),p}async function sZ(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;s0(i,{type:"video_tail_start",session:r,requestedDurationMs:3e3});let s=Date.now();await rq(3e3);let l=Date.now(),u=await rT({req:{token:t.token,session:r,command:"record",positionals:["stop"],flags:{},meta:t.meta},sessionName:r,sessionStore:n,logPath:a});return sz(u).forEach(e=>o.add(e)),s0(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}),tJ({phase:"replay_test_video_recording_stop",durationMs:Date.now()-l,data:{session:r,ok:u.ok,tailDurationMs:l-s}}),u}function s0(e,t){oe(e,{...t,ts:new Date().toISOString()})}async function s1(e){let{req:t,sessionName:r,logPath:a,sessionStore:n,leaseRegistry:i,invoke:o}=e;return"replay"===t.command?await sB({req:t,sessionName:r,logPath:a,sessionStore:n,invoke:o}):"test"===t.command?await oc({req:t,sessionName:r,runReplay:async({filePath:e,sessionName:r,platform:i,target:s,requestId:l,artifactsDir:u,artifactPaths:d,tracePath:p,shard:c})=>{let f=function(e){let{platform:t,target:r,artifactsDir:a,shard:n}=e,i=function(e){if(e?.recordVideo!==!0)return e;let t={...e};return delete t.recordVideo,Object.keys(t).length>0?t:void 0}(e.parentFlags);if(void 0===t&&void 0===r&&void 0===a&&void 0===n)return i;var o={...i??{},...void 0!==t?{platform:t}:{},...void 0!==r?{target:r}:{},...void 0!==a?{artifactsDir:a}:{}};if(!n)return o;let s={...o??{},device:void 0,udid:void 0,serial:void 0,platform:n.device.platform,target:n.device.target,shardAll:void 0,shardSplit:void 0,shardCount:n.shardCount,shardIndex:n.shardIndex};return"android"===n.device.platform?{...s,serial:n.device.id}:{...s,udid:n.device.id}}({parentFlags:t.flags,platform:i,target:s,artifactsDir:u,shard:c}),m={req:t,sessionName:r,logPath:a,sessionStore:n,artifactsDir:u,tracePath:p},h=function(e){if(e.req.flags?.recordVideo===!0)return{beforeDispatch:async()=>await sQ(e)}}(m);return await sB({req:{...t,command:"replay",session:r,positionals:[e],flags:f,meta:{...t.meta??{},...l?{requestId:l}:{}},...t.internal||h?{internal:{...t.internal??{},...h?{openLifecycle:h}:{}}}:{}},sessionName:r,logPath:a,sessionStore:n,tracePath:p,invoke:async e=>{var t;let r=await sQ(m);return r&&!r.ok?r:(t=await o(e),d&&sz(t).forEach(e=>d.add(e)),t)}})},finalizeAttempt:async({sessionName:e,artifactPaths:r,artifactsDir:i,tracePath:o})=>await sZ({req:t,sessionName:e,logPath:a,sessionStore:n,artifactsDir:i,tracePath:o,artifactPaths:r}),cleanupSession:async e=>{n.get(e)&&await a8({req:{token:t.token,session:e,command:"close",positionals:[],flags:{},meta:t.meta},sessionName:e,logPath:a,sessionStore:n,leaseRegistry:i})}}):null}function s3(e,t){var r;e.push(t),e4({type:"command",status:"progress",message:[tv(r=t),...tl(r)].join("\n")})}async function s2(e,t){let{device:r,metroPort:a,shouldProbeMetro:n,androidAdbExecutor:i}=t;if("android"!==r.platform||!n)return;let o=tM(r,i);s3(e,await s5(o,r.id,a))}async function s5(e,t,r){try{let a=await e(["reverse","--list"],{allowFailure:!0,timeoutMs:2e3}),n=`tcp:${r} tcp:${r}`,i=a.stdout.includes(n);return{id:"android-reverse",status:i?"pass":"warn",summary:i?`Android adb reverse exists for Metro port ${r}.`:`Android adb reverse is missing for Metro port ${r}.`,command:i?void 0:`adb -s ${t} reverse tcp:${r} tcp:${r}`,evidence:{stdout:a.stdout.trim()}}}catch(t){let e=s(t);return{id:"android-reverse",status:"warn",summary:"Could not inspect Android adb reverse mappings.",hint:e.message,evidence:{code:e.code}}}}async function s4(e,t){let{device:r,targetApp:a,session:n}=t;if(a)try{let t=await s8(r,a);if(!t)return void s3(e,{id:"target-app",status:"info",summary:`Target app installation checks are not supported for ${r.platform}.`,evidence:{requested:a,platform:r.platform}});s3(e,{id:"target-app",status:"pass",summary:`Target app is launchable: ${t}`,evidence:{requested:a,resolved:t,sessionApp:n?.appBundleId}})}catch(a){let t=s(a);s3(e,{id:"target-app",status:"fail",summary:`Target app check failed: ${t.message}`,hint:t.hint??"Install the app or pass an exact package/bundle id or app name.",command:`agent-device apps --platform ${r.platform} --all`,evidence:{code:t.code,message:t.message}})}}async function s8(e,t){if("android"===e.platform){let{listAndroidApps:r}=await import("./3340.js"),a=s6(t,(await r(e,"all")).map(e=>({id:e.package,name:e.name})));return a?.id}if("ios"===e.platform||"macos"===e.platform){let{listIosApps:r}=await import("./apps.js"),a=s6(t,(await r(e,"all")).map(e=>({id:e.bundleId,name:e.name})));return a?.id}}function s6(e,t){let r=e.trim().toLowerCase(),a=t.find(e=>e.id.toLowerCase()===r||e.name.toLowerCase()===r);if(a)return a;let n=t.filter(e=>e.id.toLowerCase().includes(r)||e.name.toLowerCase().includes(r));if(1===n.length)return n[0];if(n.length>1)throw new l("AMBIGUOUS_MATCH",`Multiple launchable apps matched "${e}"`,{matches:n.map(e=>e.id),hint:"Pass an exact package/bundle id from agent-device apps --all."});throw new l("APP_NOT_INSTALLED",`No launchable installed app matched "${e}"`)}async function s7(e,t,r){var a,n,i,o,l,u;let d,p=(a=t,n=r,en({platform:(d=a.flags??{}).platform??n?.device.platform,target:d.target??n?.device.target,device:d.device,udid:d.udid,serial:d.serial,iosSimulatorDeviceSet:d.iosSimulatorDeviceSet,androidDeviceAllowlist:d.androidDeviceAllowlist}));try{let t=await s9(p),r=(i=t.devices,o=p,i.filter(e=>tK(e,o,{includeExplicitSelectors:!0})));return s3(e,{id:"device",status:0===r.length?"fail":"pass",summary:function(e,t,r){var a,n;if(0===e.length)return r.length>0?`No ${le(t)} devices found; ${r.slice(0,2).map(e=>`${lt(e.platform)} inventory failed: ${e.message}`).join("; ")}.`:`No ${le(t)} devices found.`;let i=e.filter(e=>!0===e.booted).length,o=`${e.length} ${le(t)} ${(a=e.length,n="device",1===a?n:`${n}s`)} available; ${i} booted`,s=function(e,t){if(t.platform||t.target)return;let r=g(e),a={android:"Android",apple:"Apple",linux:"Linux",web:"web"};return["android","apple","linux","web"].flatMap(e=>{let t=r[e];return t.available>0?[`${a[e]} ${t.available} available, ${t.booted} booted`]:[]}).join("; ")}(e,t);return s?`${o} (${s}).`:`${o}.`}(r,p,t.failures),hint:0===r.length?(l=t.failures,l.find(e=>e.hint)?.hint??"Start or create a simulator/emulator, connect a device, or adjust --platform/--target/--device selectors."):void 0,command:0===r.length?(u=p).platform?`agent-device devices --platform ${u.platform}`:"agent-device devices":void 0,evidence:function(e,t){let r=new Map;for(let t of e){let e=r.get(t.platform)??{available:0,booted:0};e.available+=1,!0===t.booted&&(e.booted+=1),r.set(t.platform,e)}return{available:e.length,booted:e.filter(e=>!0===e.booted).length,byPlatform:Object.fromEntries([...r.entries()].sort(([e],[t])=>e.localeCompare(t))),...t.length>0?{failures:t}:{}}}(r,t.failures)}),r.length>0&&function(e,t){for(let a of t){var r;s3(e,(r=a,{id:`device-${r.platform}`,status:"warn",summary:`${lt(r.platform)} device inventory could not be read: ${r.message}`,hint:r.hint??`Check the ${lt(r.platform)} toolchain, or scope with --platform to skip it.`,evidence:{platform:r.platform,code:r.code}}))}}(e,t.failures),{devices:r,platform:p.platform,target:p.target}}catch(r){let t=s(r);return s3(e,{id:"device",status:"fail",summary:t.message,hint:t.hint,command:"agent-device devices",evidence:{code:t.code,details:t.details}}),{devices:[],platform:p.platform,target:p.target}}}async function s9(e){if(e.platform)return{devices:await eI(e),failures:[]};let t=[],r=[];for(let a of p)try{t.push(...await eI({...e,platform:a}))}catch(e){r.push(function(e,t){let r=s(t);return{platform:e,message:r.message,hint:r.hint,code:r.code}}(a,e))}return{devices:t,failures:r}}function le(e){let t=e.platform?lt(e.platform):"local";return e.target?`${t} ${e.target}`:t}function lt(e){return"ios"===e?"iOS":"macos"===e?"macOS":"android"===e?"Android":"linux"===e?"Linux":"web"===e?"web":"Apple"}async function lr(e,t,r,a={}){let n=`http://${e}:${t}/status`;try{var i,o;let s=await fetch(n,{signal:AbortSignal.timeout(1500)}),l=await s.text(),u=s.ok&&l.toLowerCase().includes("packager-status:running"),d=u?await la(e,t,a):void 0;return{id:"metro",status:u?"pass":"warn",summary:u?(i=n,o=d,o?.cwd?`Metro is reachable at ${i} (cwd: ${o.cwd}).`:`Metro is reachable at ${i}.`):`Metro responded at ${n}, but did not report packager-status:running.`,hint:u?void 0:"Verify this is the Metro instance for the target app, or restart Metro.",evidence:{url:n,statusCode:s.status,body:l.slice(0,120),kind:r,...d?{process:d}:{}}}}catch(e){return{id:"metro",status:"auto"===r?"warn":"fail",summary:`Metro is not reachable at ${n}.`,hint:"Start Metro for this project. For non-default endpoints, launch with open --metro-host/--metro-port, or run metro prepare with --public-base-url/--proxy-base-url before retrying doctor.",command:`curl -fsS ${n}`,evidence:{url:n,error:e instanceof Error?e.message:String(e),kind:r}}}}async function la(e,t,r){try{return await (r.resolveProcessInfo??ln)(e,t)}catch{return}}async function ln(e,t){var r;if("127.0.0.1"!==(r=e)&&"localhost"!==r&&"::1"!==r&&"0.0.0.0"!==r)return;let a=await li(t);if(void 0!==a)return{pid:a,cwd:await lo(a)}}async function li(e){let t=await ry("lsof",["-nP",`-iTCP:${e}`,"-sTCP:LISTEN","-Fp"],{allowFailure:!0,timeoutMs:1500});if(0===t.exitCode)return t.stdout.split("\n").map(e=>e.startsWith("p")?Number.parseInt(e.slice(1),10):NaN).find(e=>Number.isInteger(e)&&e>0)}async function lo(e){let t=await ry("lsof",["-nP","-a","-p",String(e),"-d","cwd","-Fn"],{allowFailure:!0,timeoutMs:1500});if(0===t.exitCode)return t.stdout.split("\n").find(e=>e.startsWith("n")&&e.length>1)?.slice(1)}let ls=["daemonBaseUrl","tenant","runId","leaseId","leaseProvider"],ll=["provider","providerSessionId","providerApp","providerOsVersion","providerProject","providerBuild","providerSessionName","awsProjectArn","awsDeviceArn","awsAppArn","awsRegion","awsInteractionMode"];function lu(e){return"string"==typeof e&&e.trim().length>0?e.trim():void 0}async function ld(e,t){"android"===t?s3(e,await lp()):("ios"===t||"macos"===t||"apple"===t)&&s3(e,await lc())}async function lp(){var e,t,r;let a=process.env.ANDROID_HOME||process.env.ANDROID_SDK_ROOT,n=await lf(a),i=await lm("adb",["version"]);return i?{id:"toolchain",status:(t=e={license:n,sdkRoot:a,versionLine:i}).versionLine&&t.sdkRoot&&"missing"!==t.license?"pass":"info",summary:e.versionLine?`Android toolchain: ${e.versionLine}; ${e.sdkRoot?"ANDROID_HOME/ANDROID_SDK_ROOT set":"ANDROID_HOME unset"}.`:"Android toolchain: adb is present but version check failed.",hint:"missing"===e.license?"Accept Android SDK licenses before installing/building apps.":void 0,command:"missing"===e.license?"sdkmanager --licenses":void 0,evidence:{adbVersion:e.versionLine??null,androidHome:e.sdkRoot??null,license:e.license}}:(r=a,{id:"toolchain",status:"info",summary:"Android toolchain: adb not found on PATH.",hint:"Install Android platform-tools or add adb to PATH.",evidence:{androidHome:r??null,license:n}})}async function lc(){var e,t;let r=await lm("xcodebuild",["-version"]);return r?{id:"toolchain",status:(e={selectedPath:await lm("xcode-select",["-p"]),versionLine:r}).versionLine?"pass":"info",summary:(t=e).versionLine?t.selectedPath?`Apple toolchain: ${t.versionLine}; xcode-select ${t.selectedPath}.`:`Apple toolchain: ${t.versionLine}; xcode-select path unavailable.`:"Apple toolchain: xcodebuild version check failed.",evidence:{selectedPath:e.selectedPath??null,xcodeVersion:e.versionLine??null}}:{id:"toolchain",status:"info",summary:"Apple toolchain: xcodebuild version check failed.",hint:"Install/select Xcode and complete first launch/license setup if xcodebuild reports it.",command:"xcodebuild -version"}}async function lf(e){if(!e)return"unknown";try{return await i(r.join(e,"licenses","android-sdk-license")),"accepted"}catch{return"missing"}}async function lm(e,t){try{let r=await ry(e,t,{allowFailure:!0,timeoutMs:3e3});if(0!==r.exitCode)return;return r.stdout.split("\n").map(e=>e.trim()).find(Boolean)}catch{return}}async function lh(e){var t,a,n,i;let o,s,l,{req:u,sessionName:d,sessionStore:p,androidAdbExecutor:c}=e;if(u.command!==rB.doctor)return null;let f=p.get(d),m=(s=rH(u.meta?.cwd),l=lu(u.flags?.targetApp)??f?.appBundleId,{targetApp:l,metroHost:lu(u.runtime?.metroHost)??"127.0.0.1",metroPort:("number"==typeof(t=u.runtime?.metroPort)&&Number.isInteger(t)&&t>0?t:void 0)??8081,kind:s,remote:u.flags?.remote===!0,shouldProbeMetro:(a=u,"auto"!==s||"number"==typeof a.runtime?.metroPort||"string"==typeof a.runtime?.metroHost)}),h=(n=p,i=d,o=r.dirname(n.resolveSessionDir(i)),"sessions"===r.basename(o)?r.dirname(o):o),g=[];if(!function(e,...t){for(let r of t)s3(e,r)}(g,{id:"agent-device",status:"pass",summary:`agent-device ${rj()} using ${h}`,evidence:{version:rj(),stateDir:h}},...function(e,t={}){var r;let a,n=(r=e,Object.keys(a={...Object.fromEntries([...ls,...ll].flatMap(e=>"string"==typeof r.flags?.[e]?[[e,"<configured>"]]:[])),...r.flags?.sessionIsolation==="tenant"?{sessionIsolation:"tenant"}:{}}).length>0?a:void 0);return n?[{id:"remote-connection",status:t.required?"pass":"info",summary:"Remote daemon/session or provider scope is configured.",evidence:n}]:t.required?[{id:"remote-connection",status:"fail",summary:"No remote daemon/session or provider scope is configured.",hint:"Use connect, --remote-config <path>, or direct remote/provider flags for the command."}]:[]}(u,{required:m.remote}),...function(e,t,r,a={}){let n=r?e.toArray().filter(e=>e.name!==r.name&&e.device.platform===r.device.platform&&e.device.id===r.device.id).map(e=>e.name):[];return r?[{id:"session",status:n.length>0?"warn":"pass",summary:n.length>0?`Other active sessions target the same device: ${n.join(", ")}`:`Active session ${r.name} targets ${r.device.name}`,hint:n.length>0?"Close stale sessions before a QA run if they belong to old attempts.":void 0,command:n.length>0?`agent-device close --session ${n[0]} --platform ${r.device.platform}`:void 0,evidence:{session:r.name,sameDeviceSessions:n,sessionStateDir:e.resolveSessionDir(r.name)}}]:[{id:"session",status:"info",summary:a.remote?`No active session named ${t}. Remote doctor will use configured remote scope.`:`No active session named ${t}. Doctor will use device inventory only.`,hint:"This is expected before a run. Use open when app foreground state matters."}]}(p,d,f,{remote:m.remote})),m.remote)return lv(g,m);let w=await s7(g,u,f);await ld(g,f?.device.platform??w?.platform);let v=await lg({androidAdbExecutor:c,checks:g,inventory:w,options:m,session:f});return lv(g,m,{device:v,includeMetro:!0,inventory:w})}async function lg(e){let{checks:t,inventory:r,options:a,session:n,androidAdbExecutor:i}=e,o=n?.device??function(e,t,r){if(!r||!t)return;let a=t.devices.filter(e=>!0===e.booted);if(1===a.length)return a[0];s3(e,{id:"target-app-device",status:"fail",summary:0===a.length?"Target app check needs one booted device; none matched.":`Target app check needs one booted device; ${a.length} matched.`,hint:0===a.length?"Boot a device, or adjust --platform/--target/--device/--udid/--serial.":"Pass --platform/--target/--device/--udid/--serial so doctor checks the intended device.",command:t.platform?`agent-device devices --platform ${t.platform}`:"agent-device devices",evidence:{targetApp:r,booted:a.map(e=>({platform:e.platform,id:e.id,name:e.name}))}})}(t,r,a.targetApp);return o&&await lw(t,{androidAdbExecutor:i,device:o,options:a,session:n}),a.shouldProbeMetro&&s3(t,await lr(a.metroHost,a.metroPort,a.kind)),o}async function lw(e,t){let{androidAdbExecutor:r,device:a,options:n,session:i}=t;await s4(e,{device:a,session:i,targetApp:n.targetApp}),await s2(e,{androidAdbExecutor:r,device:a,metroPort:n.metroPort,shouldProbeMetro:n.shouldProbeMetro})}function lv(e,t,r={}){let a,n=e.some(e=>"fail"===e.status)?"fail":e.some(e=>"warn"===e.status)?"warn":"pass";return{ok:!0,data:{status:n,summary:"fail"===n?"Blockers found before the run.":"warn"===n?"No hard blockers found, but warnings need attention.":"No blockers found.",kind:t.kind,platform:r.device?.platform??r.inventory?.platform,target:r.device?.target??r.inventory?.target,targetApp:t.targetApp,metro:r.includeMetro&&t.shouldProbeMetro?{host:t.metroHost,port:t.metroPort}:void 0,checks:(a={fail:0,warn:1,pass:2,info:3},[...e].sort((e,t)=>a[e.status]-a[t.status]))}}}async function ly(e){var t,r,a,n,i,o,s,l,u;let d,p,{req:c,sessionName:f,logPath:m,sessionStore:h}=e,g=c.positionals?.[0]??"";if("ios-runner"!==g)return T("INVALID_ARGS","prepare requires a subcommand: ios-runner");let w=h.get(f),v=c.flags??{},y=r4(rB.prepare,w,v);if(y)return y;let A=await r6({session:w,flags:v,ensureReady:!0});if(!tG(A.platform))return T("UNSUPPORTED_OPERATION","prepare ios-runner is only supported on Apple runner platforms");let b=Date.now(),S=await ep(A,(t=c,r=w,a=m,n=b,p=(i=t,"number"==typeof(d=i.flags?.timeoutMs)&&Number.isFinite(d)&&d>0?d:24e4),{...e6({req:t,logPath:a,traceLogPath:r?.trace?.outPath}),cleanStaleBundles:!0,buildTimeoutMs:p,healthTimeoutMs:p,prepareDeadline:tE.fromTimeoutMs(p,n),startupTimeoutMs:p}));return{ok:!0,data:(o=g,s=A,l=Math.max(0,Date.now()-b),u=S,{action:o,platform:s.platform,deviceId:s.id,deviceName:s.name,kind:s.kind,durationMs:l,...u,message:`Prepared Apple runner: ${s.name}`})}}async function lA(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??{},p=r4(i,u,d);if(p)return p;let c=await r6({session:u,flags:d,ensureReady:!0}),m=X(i,c);if(m)return m;let h=await f(c,i,o,t.flags?.out,{...e_(a,t.flags,u?.appBundleId,u?.trace?.outPath)});if(u){let e=l?await l(u,h,c):u;tD(n,e,t,i,h??{},{positionals:s??o}),e!==u&&n.set(r,e)}return{ok:!0,data:h??{}}}async function lb(e){let{req:t,sessionName:r,logPath:a,sessionStore:n}=e,i=n.get(r),o=t.flags??{},s=r4(rB.clipboard,i,o);if(s)return s;let l=(t.positionals?.[0]??"").toLowerCase();if("read"!==l&&"write"!==l)return T("INVALID_ARGS","clipboard requires a subcommand: read or write");let u=await r6({session:i,flags:o,ensureReady:!0}),d=X(rB.clipboard,u);if(d)return d;let p=await f(u,rB.clipboard,t.positionals??[],t.flags?.out,{...e_(a,t.flags,i?.appBundleId,i?.trace?.outPath)});return tD(n,i,t,t.command,p??{}),{ok:!0,data:{platform:u.platform,...p??{}}}}async function lS(e){let{req:t,sessionName:r,logPath:a,sessionStore:n,leaseRegistry:i=new eC,leaseLifecycleProvider:o,invoke:s,invokeReplayAction:l,androidAdbExecutor:u}=e;if(t.command===rB.doctor)return await lh({req:t,sessionName:r,sessionStore:n,androidAdbExecutor:u});if("inventory"===S(t.command))return await nr({req:t,sessionName:r,sessionStore:n});if("runtime"===t.command)return await ax({req:t,sessionName:r,sessionStore:n});if("state"===S(t.command))return await ns({req:t,sessionName:r,logPath:a,sessionStore:n});if(t.command===rB.clipboard)return await lb({req:t,sessionName:r,logPath:a,sessionStore:n});if(t.command===rB.keyboard){let e=n.get(r),i=t.positionals?.[0]?.trim().toLowerCase();return e||"dismiss"!==i&&"enter"!==i&&"return"!==i||"ios"!==(t.flags??{}).platform?await lA({req:t,sessionName:r,logPath:a,sessionStore:n,command:rB.keyboard,positionals:t.positionals??[]}):T("SESSION_NOT_FOUND","iOS keyboard action requires an active session so the target app stays foregrounded. Run open first.")}if("observability"===S(t.command))return await n6({req:t,sessionName:r,sessionStore:n,androidAdbExecutor:u});if(t.command===rB.prepare)return await ly({req:t,sessionName:r,logPath:a,sessionStore:n});if(t.command===rB.install||t.command===rB.reinstall)return await ne({req:t,command:t.command,sessionName:r,sessionStore:n,deployOps:t.command===rB.install?a9:a7});if(t.command===rK.installSource)return await rX({req:t,sessionName:r,sessionStore:n});if(t.command===rK.releaseMaterializedPaths)return await r2({req:t});if(t.command===rB.push){let e,i=t.positionals?.[0]?.trim(),o=t.positionals?.[1]?.trim();return i&&o?await lA({req:t,sessionName:r,logPath:a,sessionStore:n,command:rB.push,positionals:[i,"file"===(e=eO(o,{subject:"Push payload",cwd:t.meta?.cwd,expandPath:(e,t)=>ek.expandHome(e,t)})).kind?e.path:e.text],recordPositionals:[i,o]}):T("INVALID_ARGS","push requires <bundle|package> <payload.json|inline-json>")}return t.command===rB.triggerAppEvent?await lA({req:t,sessionName:r,logPath:a,sessionStore:n,command:rB.triggerAppEvent,positionals:t.positionals??[],deriveNextSession:async(e,t)=>{let r="string"==typeof t?.eventUrl?t.eventUrl:void 0,a=r?await aH(e.device,r,e.appBundleId,aU)??e.appBundleId:e.appBundleId;return{...e,appBundleId:a}}}):t.command===rB.open?await a0({req:t,sessionName:r,logPath:a,sessionStore:n}):"replay"===S(t.command)?await s1({req:t,sessionName:r,logPath:a,sessionStore:n,leaseRegistry:i,invoke:l??s}):t.command===rB.batch?await nt(t,r,s):t.command===rB.close?await a8({req:t,sessionName:r,logPath:a,sessionStore:n,leaseRegistry:i,leaseLifecycleProvider:o}):null}export{rz as session_namespaceObject};
|