agent-device 0.18.0 → 0.18.2
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.2.apk} +0 -0
- package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.18.2.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.2.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.2.apk} +0 -0
- package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.18.2.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.2.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/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +2 -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/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/8184.js +1 -1
- 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 +4 -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 +34 -26
- package/dist/src/batch.js +1 -1
- package/dist/src/cli-help.js +61 -9
- package/dist/src/cli.js +34 -22
- package/dist/src/contracts.d.ts +33 -123
- 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 +474 -180
- 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 +15 -17
- 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 +15 -7
- 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/432.js +0 -4
- 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.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 I,scheduleIosRunnerIdleStop as _,startAndroidPerfettoTrace as k,stopIosRunnerSession as N,captureAndroidHeapSnapshot as D,stopAppleXctracePerfCapture as x,resolvePublicSessionName as R,writeAppleXctracePerfReport as M,registerBuiltinPlatformPlugins as P,stopSessionApplePerfCapture as L,cleanupUploadedArtifact as O,resolveSessionRequestLogPath as $,ANDROID_FRAME_SAMPLE_METHOD as C,buildAppleFrameSamplingMetadata as E,createRequestCanceledError as V,stopAppleRunnerForClose as F,isActiveProviderDevice as q,registerRequestAbort as T,errorResponse as U,runHostSystemAudioProbeCommand as G,readReplayTestActionProgress as H,configureProviderPortReverse as B,releaseSessionLease as K,removeProviderPortReverse as j,withKeyedLock as z,buildSessionRecoveryHint as W,resolveTargetDevice as J,getAppLogPathMetadata as Y,sampleAndroidMemoryPerf as X,requireCommandSupported as Q,uniqueStrings as Z,setSessionSnapshot as ee,stopSessionAudioProbe as et,ANDROID_HPROF_SNAPSHOT_DESCRIPTION as er,sampleAndroidCpuPerf as ea,ANDROID_HPROF_SNAPSHOT_METHOD as en,buildDeviceInventoryRequestFromFlags as ei,startAppleXctracePerfCapture as eo,buildAppleSamplingMetadata as es,cleanupRetainedMaterializedPathsForSession as el,clearAppLogFiles as eu,tryGetPlugin as ed,getSnapshotReferenceFrame as ep,prepareIosRunner as ec,hasExplicitDeviceSelector as ef,stopSessionAndroidNativePerfCapture as em,readSessionNetworkCapture as eh,cleanupRetainedMaterializedPaths as eg,isImplicitSessionScopeConflict as ew,resolveSessionRunnerLogPath as ev,ANDROID_CPU_SAMPLE_DESCRIPTION as ey,buildSnapshotState as eA,resolveLogBackend as eb,resolveSessionLeaseForRequest as eS,stopAndroidSimpleperfProfile as eI,context_contextFromFlags as e_,listDeviceInventory as ek,SessionStore as eN,ANDROID_CPU_SAMPLE_METHOD as eD,buildAppleMemorySnapshotSupport as ex,stopAndroidPerfettoTrace as eR,isRequestCanceled as eM,resolveRequestTrackingId as eP,retainMaterializedPaths as eL,runAppLogDoctor as eO,resolvePayloadInput as e$,prepareUploadedArtifact as eC,LeaseRegistry as eE,getRunnerSessionSnapshot as eV,listSessionSelectorConflicts as eF,stopSessionAppLog as eq,stopSessionAndroidSnapshotHelper as eT,withReplayTestActionProgress as eU,resetAndroidFramePerfStats as eG,ANDROID_FRAME_SAMPLE_DESCRIPTION as eH,markRequestCanceled as eB,stopAppLog as eK,resolveImplicitSessionScope as ej,APPLE_MEMGRAPH_SNAPSHOT_METHOD as ez,ANDROID_MEMORY_SAMPLE_DESCRIPTION as eW,writeAndroidSimpleperfReport as eJ,prewarmIosRunnerSession as eY,clearRequestCanceled as eX,buildSimctlArgsForDevice as eQ,resolveFrontmostMacOsApp as eZ,isCommandSupportedOnDevice as e0,sampleApplePerfMetrics as e1,sampleAndroidFramePerf as e3,ANDROID_MEMORY_SAMPLE_METHOD as e2,getRequestSignal as e5,markAndroidSnapshotFreshness as e4,startAppLog as e8,emitRequestProgress as e6}from"./9722.js";import{isMacOs as e7,resolveAppleSimulatorSetPathForSelector as e9,publicPlatformString as te,NETWORK_INCLUDE_MODES as tt,isMobilePlatform as tr,matchesPlatformSelector as ta,isApplePlatform as tn,matchesDeviceSelector as ti,isIosFamily as to}from"./6849.js";import{ensureDeviceReady as ts,buildAppleRunnerRequestOptions as tl,buildAppleRunnerSessionOptions as tu,createAppleRunnerCachePrewarmOnColdBoot as td,createAppleRunnerCacheColdBootPrewarmForOpen as tp}from"./8414.js";import{isPerfAction as tc,isPerfSubject as tf,pointFromPercent as tm,PERF_AREA_ERROR_MESSAGE as th,buildSwipeGesturePlan as tg,PERF_ACTION_ERROR_MESSAGE as tw,buildSnapshotDisplayLines as tv,formatDoctorCheckDetailLines as ty,isPerfKind as tA,isPerfMemoryKind as tb,pointInsideRect as tS,successText as tI,clampGesturePoint as t_,resolveDeployResultTarget as tk,PERF_MEMORY_KIND_ERROR_MESSAGE as tN,PERF_KIND_ERROR_MESSAGE as tD,isPerfArea as tx,formatDoctorCheckSummaryLine as tR,LOG_ACTION_VALUES as tM,withSuccessText as tP,clampToRange as tL,parseSessionSurface as tO,resolveInstallFromSourceResultTarget as t$,readReactNativeOverlayActionNodes as tC,detectReactNativeOverlay as tE,PERF_SUBJECT_ERROR_MESSAGE as tV}from"./2948.js";import{recordSessionAction as tF}from"./handler-utils.js";import{trimRuntimeValue as tq,resolveRuntimeTransportHints as tT}from"./8936.js";import{resolveAndroidAdbExecutor as tU,runAndroidAdb as tG,resolveIosSimulatorDeviceSetPath as tH,classifyAndroidAppTarget as tB,resolveIosDeviceDeepLinkBundleId as tK,isInfrastructureBootFailureReason as tj,Deadline as tz,isWebUrl as tW,resolveAndroidSerialAllowlist as tJ,isDeepLinkTarget as tY,formatAndroidInstalledPackageRequiredMessage as tX,listAndroidApps as tQ}from"./3340.js";import{getDiagnosticsMeta as tZ,runCmd as t0,runCmdSync as t1,emitDiagnostic as t3}from"./8875.js";import{shutdownSimulator as t2,getSimulatorState as t5}from"./simulator.js";import{runBatch as t4,mergeParentFlags as t8}from"./6918.js";import{assertResolvedAppsFilter as t6}from"./2748.js";import{listIosApps as t7}from"./apps.js";import{resolveWebProvider as t9}from"./provider.js";import{unsupportedCommand as re,readEnvMap as rt,parseReplayScriptDetailed as rr,readReplayShellEnvSource as ra,normalizeCommandList as rn,normalizePlatform as ri,readReplayCliEnvEntries as ro,parseMaestroYamlDocuments as rs,parseAbsolutePoint as rl,readReplayScriptMetadata as ru,parseReplayCliEnvEntries as rd,collectReplayShellEnv as rp,support_action as rc,isPlainRecord as rf,requireAppId as rm,assertOnlyKeys as rh,resolveMaestroString as rg,requireStringValue as rw,parseMaestroPoint as rv,unsupportedMaestroSyntax as ry,readTimeoutMs as rA,writeReplayScript as rb,buildReplayVarScope as rS,resolveReplayAction as rI,mergeReplayVarScopeValues as r_}from"./4428.js";import{readSnapshotDiagnosticsSummary as rk,summarizeSnapshotTimingSamples as rN,mergeSnapshotDiagnostics as rD}from"./5913.js";import{resolveSelectorChain as rx,extractNodeText as rR,findSnapshotAncestor as rM,isDescendantOfSnapshotNode as rP,splitIsSelectorArgs as rL,buildSelectorChainForNode as rO,buildSnapshotNodeByIndex as r$,matchesSelector as rC,normalizeType as rE}from"./893.js";import{formatScriptActionSummary as rV,evaluateIsPredicate as rF,isTouchTargetCommand as rq}from"./7871.js";import{splitSelectorFromArgs as rT,normalizeText as rU,tryParseSelectorChain as rG,parseSelectorChain as rH}from"./587.js";import{sleep as rB}from"./5560.js";import{handleRecordCommand as rK}from"./record-trace-recording.js";import{recordingExtensionForPlatform as rj,defaultRecordingPath as rz}from"./5643.js";import{detectProjectRuntimeKind as rW}from"./760.js";import{INTERNAL_COMMANDS as rJ,PUBLIC_COMMANDS as rY}from"./1986.js";import{readVersion as rX}from"./1404.js";var rQ={};async function rZ(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 ts(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 J(e.flags??{});return await ts(a),a}async function r0(e){let{prepared:t,retention:r,req:a,session:n,sessionName:i}=e;if(r.enabled)return await eL({archivePath:t.archivePath,installablePath:t.installablePath,tenantId:a.meta?.tenantId,sessionName:n?i:void 0,ttlMs:r.ttlMs})}function r1(e){return e?{...e.archivePath?{archivePath:e.archivePath}:{},installablePath:e.installablePath,materializationId:e.materializationId,materializationExpiresAt:e.expiresAt}:{}}async function r3(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:eC(i,t.meta?.tenantId)},cleanup:()=>{O(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 rZ({session:n,flags:t.flags}),d=Q("install",u,{message:"install_from_source is not supported on this device"});if(d)return d;let p=e5(t.meta?.requestId);if(to(u)){let{prepareIosInstallArtifact:e}=await import("./apps.js"),i=await e(o.source,{signal:p});return await r2({prepared:i,retention:s,req:t,resolvedSourceCleanup:()=>o.cleanup(),session:n,sessionName:r,sessionStore:a,buildResult:async e=>await r5(u,i,e)})}let{prepareAndroidInstallArtifact:c}=await import("./3340.js"),f=await c(o.source,{signal:p});return await r2({prepared:f,retention:s,req:t,resolvedSourceCleanup:()=>o.cleanup(),session:n,sessionName:r,sessionStore:a,buildResult:async e=>await r4(u,f,e)})}catch(e){return{ok:!1,error:s(e)}}}async function r2(e){let t;try{var r;t=await r0(e);let a=await e.buildResult(t),n=tP(a,(r=a,`Installed: ${t$(r)}`));return!function(e){let{session:t,sessionStore:r,req:a,data:n}=e;tF(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 eg(t.materializationId,e.req.meta?.tenantId).catch(()=>{}),r}finally{await e.prepared.cleanup(),e.resolvedSourceCleanup()}}async function r5(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,{...r1(i),bundleId:o,...r8(s),launchTarget:n?.launchTarget??o}}async function r4(e,t,r){let a=await d(e,t.installablePath,{packageNameHint:t.packageName}),n=await r6(e,t,a),{inferAndroidAppName:i}=await import("./3340.js"),o=i(n);return{...r1(r),packageName:n,...r8(a?.appName??o),launchTarget:a?.launchTarget??n}}function r8(e){return e?{appName:e}:{}}async function r6(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 r7(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 eg(e,t.meta?.tenantId),{ok:!0,data:{released:!0,materializationId:e}}}catch(e){return{ok:!1,error:s(e)}}}function r9(e){return to(e)&&"simulator"===e.kind}function ae(e,t,r){return t||ef(r)?null:U("INVALID_ARGS",`${e} requires an active session or an explicit device selector (e.g. --platform ios).`)}async function at(e,t){r9(e)&&!(t<=0)&&await new Promise(e=>setTimeout(e,t))}async function ar(e){let t=ef(e.flags)||!e.session?await J(e.flags??{},{allowStoppedAndroidAvdPlaceholders:e.allowStoppedAndroidAvdPlaceholders}):await aa(e.session.device);return!1!==e.ensureReady&&await ts(t),t}async function aa(e){if(!to(e)||"simulator"!==e.kind||"darwin"!==process.platform)return e;if(eV(e.id)?.alive)return{...e,booted:!0};let t={platform:"ios",target:e.target,udid:e.id,...e.simulatorSetPath?{iosSimulatorDeviceSet:e.simulatorSetPath}:{}};try{return await J(t)}catch(e){if(!(e instanceof l)||"DEVICE_NOT_FOUND"!==e.code)throw e}return await J({platform:"ios",target:e.target,device:e.name,...e.simulatorSetPath?{iosSimulatorDeviceSet:e.simulatorSetPath}:{}})}function an(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(rQ),e.d(rQ,{handleSessionCommands:()=>lD});let ai="shared_prefs/ReactNativeDevPrefs.xml",ao="debug_http_host",as="dev_server_https",al="RCT_jsLocation",au="RCT_packager_scheme",ad="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.",ap='<?xml version="1.0" encoding="utf-8" standalone="yes" ?>\n<map>\n</map>\n';function ac(e){return void 0!==tT(e)}async function af(e){let{device:t,appId:r,runtime:a}=e;if(q(t)||!r)return;let n=tT(a);if(n){if("android"===t.platform)return void await ah(t,r,n);to(t)&&"simulator"===t.kind&&await ay(t,r,n)}}async function am(e){let{device:t,appId:r}=e;if(r){if("android"===t.platform)return void await ag(t,r);to(t)&&"simulator"===t.kind&&await aA(t,r)}}async function ah(e,t,r){var a,n,i,o,s,l;let u,d;a_(t);let p=(a=await aw(e,t),n=ao,i=`${r.host}:${r.port}`,u=` <string name="${ak(n)}">${ak(i)}</string>`,aS(aI(a,n),u));o=p,s=as,l="https"===r.scheme,d=` <boolean name="${ak(s)}" value="${l?"true":"false"}" />`,p=aS(aI(o,s),d),await av(e,t,p)}async function ag(e,t){a_(t);let r=await aw(e,t),a=aI(r,ao),n=aI(a,as);n!==r&&await av(e,t,n)}async function aw(e,t){let r=await tG(e,["shell","run-as",t,"cat",ai],{allowFailure:!0});return 0!==r.exitCode?ap:ab(r.stdout)}async function av(e,t,r){let a=["shell","run-as",t,"id"],n=await tG(e,a,{allowFailure:!0});if(0!==n.exitCode){let e=aN(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?ad:"adb shell run-as probe failed. Check adb connectivity and that the device is reachable. Inspect stderr/details for more information."})}try{await tG(e,["shell","run-as",t,"mkdir","-p","shared_prefs"]),await tG(e,["shell","run-as",t,"tee",ai],{stdin:r.trimEnd()})}catch(a){let e=o(a);if("TOOL_MISSING"===e.code)throw e;let r=aN("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?ad:"adb run-as succeeded, but writing ReactNativeDevPrefs.xml failed. Inspect stderr/details for the failing shell command."},e)}}async function ay(e,t,r){await u(eQ(e,["spawn",e.id,"defaults","write",t,al,"-string",`${r.host}:${r.port}`])),await u(eQ(e,["spawn",e.id,"defaults","write",t,au,"-string",r.scheme]))}async function aA(e,t){await u(eQ(e,["spawn",e.id,"defaults","delete",t,al]),{allowFailure:!0}),await u(eQ(e,["spawn",e.id,"defaults","delete",t,au]),{allowFailure:!0})}function ab(e){let t=e.trim();return t.includes("<map")&&t.includes("</map>")?`${t}
|
|
2
|
+
`:ap}function aS(e,t){return ab(e).replace("</map>",`${t}
|
|
3
|
+
</map>`)}function aI(e,t){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return ab(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 a_(e){if("binary"!==tB(e))return;let t=tX(e);throw new l("INVALID_ARGS",t,{package:e,hint:t})}function ak(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function aN(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 aD=["platform","metroHost","metroPort","bundleUrl","launchUrl"];function ax(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>void 0!==e&&""!==e).length:0}function aR(e,t){if(void 0!==e){if("string"!=typeof e)throw new l("INVALID_ARGS",`Invalid open runtime ${t}: expected string.`);return tq(e)}}function aM(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 aP(e){if("ios"===e||"android"===e)return e}async function aL(e){let{replacedStoredRuntime:t,previousRuntime:r,runtime:a,session:n}=e;!t||!n?.appBundleId||!ac(r)||ac(a)||await am({device:n.device,appId:n.appBundleId})}async function aO(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 aC(n,s);if("set"!==(r=s)&&"show"!==r&&"clear"!==r)return U("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 a$(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=o?te(o.device):void 0,u=aP(a.flags?.platform??s?.platform??l);if(!u)return U("INVALID_ARGS","runtime set only supports iOS and Android sessions. Pass --platform ios|android or open an iOS/Android session first.");if(void 0!==l&&l!==u)return U("INVALID_ARGS",`runtime set targets ${u}, but session "${n}" is already bound to ${l}.`);let d={platform:(t=a.flags,r={platform:u,metroHost:tq(t?.metroHost),metroPort:aM(t?.metroPort),bundleUrl:tq(t?.bundleUrl),launchUrl:tq(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===ax(d)?U("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}})}({req:n,sessionName:i,sessionStore:o,session:l,current:u})}async function a$(e,t,r,a){ac(a)&&r?.appBundleId&&await am({device:r.device,appId:r.appBundleId});let n=t.clearRuntimeHints(e);return{ok:!0,data:{session:e,cleared:n}}}async function aC(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:U("INVALID_ARGS","runtime port-reverse requires a lease provider.")}:{ok:!1,response:U("INVALID_ARGS","runtime port-reverse requires a resolved remote lease.")});if(!s.ok)return s;let l=(r=e,i=aV(r.flags?.devicePort),o=aV(r.flags?.hostPort??r.flags?.devicePort),i&&o?{ok:!0,devicePort:i,hostPort:o}:{ok:!1,response:U("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 aE(t,r.options);return a?{ok:!0,data:{action:t,...a}}:U("UNSUPPORTED_OPERATION","No active provider device runtime supports port reverse for this lease.")}async function aE(e,t){return"port-reverse"===e?await B(t):await j(t)}function aV(e){if("number"==typeof e&&Number.isInteger(e)&&!(e<1)&&!(e>65535))return e}let aF="open-command-roundtrip",aq="Not implemented for this platform in this release.";function aT(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 aU=new Set(["app","desktop","frontmost-app"]);async function aG(e){if("app"===e||"desktop"===e||"menubar"===e)return{};let t=await eZ();return{appBundleId:t.bundleId,appName:t.appName}}async function aH(e,t,r){if(tn(e.platform)&&t)return tY(t)?e7(e)?void 0:"device"===e.kind?tK(r,t):tW(t)?void 0:r??await aB(e,t):await aK(e,t)}async function aB(e,t){try{let{resolveIosSimulatorDeepLinkBundleId:r}=await import("./apps.js");return await r(e,t)}catch{return}}async function aK(e,t){try{let{resolveIosApp:r}=await import("./apps.js");return await r(e,t)}catch{return}}async function aj(e,t){if(!("android"!==e.platform||!t||tY(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 az(e,t,r){if(r||"android"!==e.platform||!t||!tY(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 aW(e,t,r,a){return await aH(e,t,r)??await a(e,t)??("android"===e.platform&&t&&tY(t)?r:void 0)}function aJ(e){return U("INVALID_ARGS",e)}function aY(e,t,r,a){try{return function(e){let{device:t,surfaceFlag:r,openTarget:a,existingSurface:n}=e;if((e7(t)||"linux"===t.platform)&&!r)return n??"app";if("linux"===t.platform){if(!r)return"app";let e=tO(r);if(!aU.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(!e7(t)){if(r)throw new l("INVALID_ARGS","surface is only supported on macOS and Linux");return"app"}let i=r?tO(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 U(e instanceof l?e.code:"INVALID_ARGS",String(e.message))}}function aX(e){let{shouldRelaunch:t,openTarget:r,surface:a,device:n}=e;return t?r&&tY(r)?aJ("open --relaunch does not support URL targets."):"app"!==a?aJ("open --relaunch is supported only for app surfaces."):"android"===n.platform&&r&&"binary"===tB(r)?aJ(tX(r)):null:null}async function aQ(e){let{req:t,sessionName:r,sessionStore:a,device:n,surface:i,openTarget:s,existingSession:u,onIosSimulatorColdBootStart:d}=e;await ts(n,{deviceHub:t.flags?.deviceHub===!0,onIosSimulatorColdBootStart:d});let{appBundleId:p,appName:c}=await aZ({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=>!aD.includes(e));if(n)throw new l("INVALID_ARGS",`Invalid open runtime field: ${n}. Supported fields are ${aD.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:aR(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 aM(e)}}(t.metroPort),bundleUrl:aR(t.bundleUrl,"bundleUrl"),launchUrl:aR(t.launchUrl,"launchUrl")}}({runtime:t.runtime,sessionName:a,platform:aP(te(n))});return void 0===t.runtime?{runtime:function(e,t,r){let a=e.getRuntimeHints(t);if(!a)return;let n=r?te(r):void 0,i=aP(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&&ax(o)>0?o:void 0,previousRuntime:i,replacedStoredRuntime:!0}}(e)}}catch(t){let e=o(t);return U(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 aL({replacedStoredRuntime:r,previousRuntime:t,runtime:e,session:u})}return{type:"details",details:{appBundleId:p,appName:c,runtime:f.data.runtime}}}async function aZ(e){let{device:t,surface:r,openTarget:a,existingAppBundleId:n}=e,i=await aG(r);return{appBundleId:i.appBundleId??await aW(t,a,n,aj),appName:i.appName??a}}let a0=new Map;async function a1(e){let{device:t,closeTarget:r,outFlag:a,context:n}=e;tn(t.platform)&&!r9(t)&&await N(t.id),await f(t,"close",[r],a,n),await at(t,300)}async function a3(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||tY(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 a2(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(),I={},_=to(d)&&"app"===h&&c.length>0&&!!b,k=tu({req:o,logPath:u,appBundleId:b,traceLogPath:A}),N=o.flags?.maestro?.prewarmRunnerBeforeOpen===!0,D=!1,x=!1,M=(e=k)=>{D=!0,I.runnerPrewarmKind="session",I.runnerPrewarmScheduled=!0,i=eY(d,e)},P=async()=>{if(!i||x)return;x=!0;let e=Date.now();await i,I.runnerPrewarmWaited=!0,I.runnerPrewarmDurationMs=Math.max(0,Date.now()-e)};_&&r9(d)&&!N&&M();let L=y&&!!p&&1===c.length&&r9(d)&&o.flags?.clearAppState!==!0;if(y&&p&&!L){let e=b??p,t=Date.now();await a1({device:d,closeTarget:e,outFlag:o.flags?.out,context:{...e_(u,o.flags,b??v?.appBundleId,A)}}),I.relaunchCloseDurationMs=Math.max(0,Date.now()-t)}let O=Date.now();await af({device:d,appId:b,runtime:w}),I.runtimeHintsDurationMs=Math.max(0,Date.now()-O),_&&N&&(M({...k,propagateError:!0}),await P());let C=Date.now(),E=await a5({req:o,sessionName:s,sessionStore:l,device:d,surface:h,sessionAppBundleId:b,appName:m,existingSession:v});if("response"===E.type)return E.response;let F=E.session??v;await f(d,"open",c,o.flags?.out,{...e_(u,o.flags,b),...L?{terminateRunningApp:!0}:{}}),I.openDispatchDurationMs=Math.max(0,Date.now()-C);let q=Date.now();await a3({runtime:w,device:d,req:o,logPath:u,appBundleId:b,traceLogPath:A,openPositionals:c}),I.launchUrlDurationMs=Math.max(0,Date.now()-q),_&&!D&&M(),y?await P():i&&!x&&(I.runnerPrewarmWaited=!1),b=await az(d,p,b),"android"===d.platform&&b&&await eG(d,b);let T=p?(t=b,{durationMs:Math.max(0,Date.now()-C),measuredAt:new Date().toISOString(),method:aF,appTarget:p,appBundleId:t}):void 0,G=Date.now();if(await at(d,300),I.postOpenSettleDurationMs=Math.max(0,Date.now()-G),eM(o.meta?.requestId)){let e=V();return U(e.code,e.message,e.details)}v&&e4(v,"open",v.snapshot);let H=aT({existingSession:F,sessionName:v?.name??R(o),sessionScope:v?.sessionScope??ej(o),device:d,surface:h,appBundleId:b,appName:m,saveScript:!!o.flags?.saveScript});H.lease=eS({req:o,existingLease:v?.lease}),void 0!==o.runtime&&(r=l,a=s,(n=w)&&(0===ax(n)?r.clearRuntimeHints(a):r.setRuntimeHints(a,n)));let B=l.ensureSessionDir(s),K=$(B,o.meta?.requestId??tZ().requestId);I.totalDurationMs=Math.max(0,Date.now()-S),t3({level:"info",phase:"open_timing",durationMs:I.totalDurationMs,data:I});let j=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=te(d),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&&to(d)&&(f.device_udid=d.id,f.ios_simulator_device_set=d.simulatorSetPath??null),{...f,...tI(`Opened: ${i??o??t}`)}}({sessionName:H.name,sessionStateDir:B,runnerLogPath:ev(B),requestLogPath:K,appName:m,appBundleId:b,surface:h,startup:T,timing:I,device:d,runtime:w,runtimeHintCount:ax});return l.recordAction(H,{command:"open",positionals:c,flags:o.flags??{},runtime:void 0!==o.runtime?w:void 0,result:j}),l.set(s,H),{ok:!0,data:j}}async function a5(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=aT({existingSession:l,sessionName:l?.name??R(t),sessionScope:l?.sessionScope??ej(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 a4(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=aY(i.device,t.flags?.surface,s,i.surface);if("string"!=typeof l)return l;if(!s&&"app"===l)return e?aJ("open --relaunch requires an app name or an active session app."):aJ("Session already active. Close it first or pass a new --session name.");let u=aX({shouldRelaunch:e,openTarget:s,surface:l,device:i.device});if(u)return u;let d=await aa(i.device),p=await aQ({req:t,sessionName:r,sessionStore:n,device:d,surface:l,openTarget:s,existingSession:i,onIosSimulatorColdBootStart:tp({req:t,logPath:a,device:d,surface:l,openTarget:s,traceLogPath:i.trace?.outPath})});return"response"===p.type?p.response:await a2({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 aJ("open --relaunch requires an app argument.");let l=function(e){let{shouldRelaunch:t,openTarget:r,platform:a}=e;return t?r&&tY(r)?aJ("open --relaunch does not support URL targets."):"android"===a&&r&&"binary"===tB(r)?aJ(tX(r)):null:null}({shouldRelaunch:o,openTarget:s,platform:t.flags?.platform==="android"?"android":void 0});if(l)return l;let u=await J(t.flags??{}),d=aY(u,t.flags?.surface,s);if("string"!=typeof d)return d;let p=aX({shouldRelaunch:o,openTarget:s,surface:d,device:u});return p||await z(a0,u.id,async()=>{let e=n.toArray().find(e=>e.device.id===u.id);if(e)return ew(t,e)?U("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."}):U("DEVICE_IN_USE",`Device is already in use by session "${e.name}".`,{session:e.name,deviceId:u.id,deviceName:u.name,hint:W(e,"device-in-use")});let i=await aQ({req:t,sessionName:r,sessionStore:n,device:u,surface:d,openTarget:s,onIosSimulatorColdBootStart:tp({req:t,logPath:a,device:u,surface:d,openTarget:s})});return"response"===i.type?i.response:await a2({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 a8(e){if(!1===e.booted)return{success:!0,exitCode:0,stdout:"",stderr:""};try{return r9(e)?await a6(e):await a9(e)}catch(t){let e=s(t);return{success:!1,exitCode:-1,stdout:"",stderr:e.message,error:e}}}async function a6(e){let t=await t2(e);return t.success?t:"Shutdown"===await a7(e)?{...t,success:!0,exitCode:0}:t}async function a7(e){try{return await t5(e)}catch{return null}}async function a9(e){let t=await tG(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 ne(e){let{device:t,shutdownRequested:r}=e;if(r&&(r9(t)||"android"===t.platform&&"emulator"===t.kind))return await a8(t)}async function nt(e){let t,{req:r,sessionName:a,logPath:n,sessionStore:i,leaseRegistry:o,leaseLifecycleProvider:s}=e,l=i.get(a);if(!l)return await nr(r,n);try{var u,d,p;(await eq(l),await et(l,"session-close"),await L(l),await em(l),await eT(l),u=r,d=l,p=u,(p.positionals?.length??0)>0||"web"===d.device.platform)&&(tn(l.device.platform)&&!r9(l.device)&&await F(l),await f(l.device,"close",r.positionals??[],r.flags?.out,{...e_(n,r.flags,l.appBundleId,l.trace?.outPath)}),await at(l.device,300));tn(l.device.platform)&&(!r9(l.device)||r.flags?.shutdown||l.recording||l.lease||l.device.simulatorSetPath)?await F(l):tn(l.device.platform)&&(t3({level:"debug",phase:"ios_runner_retained_after_close",data:{session:l.name,deviceId:l.device.id}}),_(l.device.id));let e=i.getRuntimeHints(a);ac(e)&&l.appBundleId&&await am({device:l.device,appId:l.appBundleId}).catch(()=>{}),tF(i,l,r,"close",{session:l.name,...tI(`Closed: ${l.name}`)}),r.flags?.saveScript&&(l.recordSession=!0),i.writeSessionLog(l),await el(a).catch(()=>{})}finally{try{t=await K({session:l,leaseRegistry:o,leaseLifecycleProvider:s})}finally{i.delete(a)}}let c=await ne({device:l.device,shutdownRequested:r.flags?.shutdown});return c?{ok:!0,data:tP({session:l.name,shutdown:c,...t?{provider:t}:{}},`Closed: ${l.name}`)}:{ok:!0,data:{session:l.name,...tI(`Closed: ${l.name}`),...t?{provider:t}:{}}}}async function nr(e,t){if(!e.positionals||0===e.positionals.length)return U("SESSION_NOT_FOUND","No active session");let r=await ar({session:void 0,flags:e.flags,ensureReady:!0});return await f(r,"close",e.positionals,e.flags?.out,{...e_(t,e.flags)}),await at(r,300),{ok:!0,data:{app:e.positionals[0],...tI(`Closed: ${e.positionals[0]}`)}}}let na={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)}},nn={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 ni(e){let{req:r,command:a,sessionName:n,sessionStore:i,deployOps:o}=e,s=i.get(n),l=r.flags??{},u=ae(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:U("INVALID_ARGS","install requires: install <path-to-app-binary>")}}return r&&a?{ok:!0,app:r,appPathInput:a}:{ok:!1,response:U("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?eC(f,r.meta?.tenantId):eN.expandHome(c);if(!t.existsSync(u))return U("INVALID_ARGS",`App binary not found: ${u}`);let d=await ar({session:s,flags:l,ensureReady:!1}),b=Q(a,d);if(b)return b;let S=to(d)?(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}),I=tP(S,(A=S,`Installed: ${A.appName??tk(A)}`));return tF(i,s,r,a,I),{ok:!0,data:I}}finally{f&&O(f)}}async function no(e,t,r){return await t4(e,t,r)}async function ns(e){let{req:t,sessionName:r,sessionStore:a}=e;if("session_list"===t.command){let e=ej(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:ev(t),platform:te(e.device),...tn(e.device.platform)&&e.device.appleOs?{appleOs:e.device.appleOs}:{},target:e.device.target??"mobile",surface:e.surface??"app",device:e.device.name,id:e.device.id,device_id:e.device.id,createdAt:e.createdAt,...tn(e.device.platform)&&!e7(e.device)&&{device_udid:e.device.id,ios_simulator_device_set:e.device.simulatorSetPath??null}}})}}}if("devices"===t.command)try{let e=tJ(t.flags?.androidDeviceAllowlist),r=t.flags?.platform,a=e9({simulatorSetPath:tH(t.flags?.iosSimulatorDeviceSet),platform:r,target:t.flags?.target}),n=await ek({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,ta(t,a)}):n,o=(t.flags?.target?i.filter(e=>(e.target??"mobile")===t.flags?.target):i).map(({simulatorSetPath:e,appleOs:t,...r})=>({...r,platform:te({platform:r.platform,appleOs:t}),...tn(r.platform)&&t?{appleOs:t}:{}}));return{ok:!0,data:{devices:o}}}catch(t){let e=o(t);return U(e.code,e.message,e.details)}if("apps"===t.command){let e=a.get(r),n=t.flags??{},i=ae(t.command,e,n);if(i)return i;let o=await ar({session:e,flags:n,ensureReady:!0}),s=Q("apps",o);if(s)return s;let l=t6(t.flags?.appsFilter);return tn(o.platform)?{ok:!0,data:{apps:(await t7(o,l)).map(e=>e.name&&e.name!==e.bundleId?`${e.name} (${e.bundleId})`:e.bundleId)}}:{ok:!0,data:{apps:(await tQ(o,l)).map(e=>e.name&&e.name!==e.package?`${e.name} (${e.package})`:e.package)}}}return null}async function nl(e){let{ensureAndroidEmulatorBooted:t}=await import("./3340.js");return await t(e)}let nu='iOS appstate requires an active session on the target device. Run open first (for example: open --session sim --platform ios --device "<name>" <app>).',nd='macOS appstate requires an active session on the target device. Run open first (for example: open --session macos --platform macos "System Settings").';async function np(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 U("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=ae("appstate",n,i);if(s)return s;let l=tn(n?.device.platform)&&!!n&&0===eF(n,i).length;if("ios"===o&&!l)return U("SESSION_NOT_FOUND",nu);if("macos"===o&&!l)return U("SESSION_NOT_FOUND",nd);if(l&&n){let e=n.appName??n.appBundleId;if(!n.appName&&!n.appBundleId){if(e7(n.device)&&n.surface&&"app"!==n.surface&&"frontmost-app"!==n.surface)return{ok:!0,data:{platform:te(n.device),appName:n.surface,appBundleId:n.appBundleId,source:"session",surface:n.surface}};let e=e7(n.device)?"macOS":"iOS";return U("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:te(n.device),appName:e??"unknown",appBundleId:n.appBundleId,source:"session",surface:n.surface??"app",...to(n.device)?{device_udid:n.device.id,ios_simulator_device_set:n.device.simulatorSetPath??null}:{}}}}let u=await ar({session:n,flags:i,ensureReady:!0});if(to(u))return U("SESSION_NOT_FOUND",nu);if(e7(u))return U("SESSION_NOT_FOUND",nd);if("web"===u.platform)return U("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 nc(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=ae(t.command,i,s);if(l)return l;let u="android"===(s.platform??i?.device.platform),d=!0===s.headless;if(d&&!u)return U("INVALID_ARGS","boot --headless is supported only for Android emulators.");let p=an({flags:s,sessionDevice:i?.device}),c=u&&!!p,f=!1;try{e=await ar({session:i,flags:s,ensureReady:!1,allowStoppedAndroidAvdPlaceholders:!0})}catch(r){let t=o(r);if(u&&d&&!p&&"DEVICE_NOT_FOUND"===t.code)return U("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 nl({avdName:p,serial:s.serial,headless:d}),f=!0}if(s.target&&(e.target??"mobile")!==s.target)return U("DEVICE_NOT_FOUND",`No ${e.platform} device found matching --target ${s.target}.`);if(u&&d){if("android"!==e.platform||"emulator"!==e.kind)return U("INVALID_ARGS","boot --headless is supported only for Android emulators.");if(!f){let t=an({flags:s,sessionDevice:i?.device,resolvedDevice:e});if(!t)return U("INVALID_ARGS","boot --headless requires --device <avd-name> (or an Android emulator session target).");e=await nl({avdName:t,serial:s.serial,headless:!0})}await ts(e)}else"android"===e.platform&&"emulator"===e.kind&&!0!==e.booted?(e=await nl({avdName:e.name,serial:s.serial,headless:!1}),await ts(e)):("android"!==e.platform||!0!==e.booted)&&await ts(e,{onIosSimulatorColdBootStart:td({req:t,logPath:a,device:e,enabled:!0})});let m=Q("boot",e);return m||{ok:!0,data:{platform:te(e),target:e.target??"mobile",device:e.name,id:e.id,kind:e.kind,booted:!0,...tn(e.platform)&&e.appleOs?{appleOs:e.appleOs}:{}}}}if("shutdown"===t.command){var i;let e,a=n.get(r),o=t.flags??{},s=ae(t.command,a,o);if(s)return s;let l=await ar({ensureReady:!1,flags:o,session:a}),u=Q("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 U("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:te(l),target:l.target??"mobile",device:l.name,id:l.id,kind:l.kind});let d=await a8(l);return d.success?{ok:!0,data:{platform:te(l),target:l.target??"mobile",device:l.name,id:l.id,kind:l.kind,shutdown:d,...tn(l.platform)&&l.appleOs?{appleOs:l.appleOs}:{}}}:U(d.error?.code??"COMMAND_FAILED",(i=d,(e=i.error?.message??i.stderr.trim()).length>0?e:"Shutdown failed"),{platform:te(l),target:l.target??"mobile",device:l.name,id:l.id,kind:l.kind,shutdown:d})}return"appstate"===t.command?await np({req:t,sessionName:r,sessionStore:n}):null}async function nf(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===aF&&t.push({durationMs:Math.max(0,Math.round(e.durationMs)),measuredAt:e.measuredAt,method:aF,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:aF,sampleCount:i.length,samples:i}:{available:!1,reason:"No startup sample captured yet. Run open <app|url> in this session first.",method:aF},{session:r.name,platform:te(r.device),device:r.device.name,deviceId:r.device.id,metrics:{startup:s,...{fps:ng(),memory:{available:!1,reason:aq},cpu:{available:!1,reason:aq}}},sampling:{startup:{method:aF,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:e2,description:eW,unit:"kB"},cpu:{method:eD,description:ey,unit:"percent"},fps:{method:C,description:eH,unit:"percent",primaryField:"droppedFramePercent",window:"since previous Android gfxinfo reset or app process start",resetsAfterRead:!0,relatedActionsLimit:12}}:es(a.device)}});return nb(e)&&(e.appBundleId?"android"===e.device.platform?await nw(u,e,e.appBundleId,t):await nv(u,e,e.appBundleId):(n=u,l=nS(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 nm(e,t={}){var r,a;let n={session:(r=e).name,platform:te(r.device),device:r.device.name,deviceId:r.device.id,metrics:{fps:ng()},sampling:{fps:"android"===(a=r).device.platform?{method:C,description:eH,unit:"percent",primaryField:"droppedFramePercent",window:"since previous Android gfxinfo reset or app process start",resetsAfterRead:!0,relatedActionsLimit:12}:E(a.device)}};return nb(e)&&(e.appBundleId?await nA(n,e,e.appBundleId,t):n.metrics.fps={available:!1,reason:nS(e)}),n}async function nh(e,t){var r,a;let n={session:(r=e).name,platform:te(r.device),device:r.device.name,deviceId:r.device.id,sampling:{memory:"android"===(a=r).device.platform?{method:e2,description:eW,unit:"kB",topConsumerLimit:5}:es(a.device).memory,snapshot:"android"===r.device.platform?{method:en,description:er,defaultKind:"android-hprof",artifactOnly:!0}:{method:ez,description:c,defaultKind:"memgraph",artifactOnly:!0}}};if(!nb(e)){if("snapshot"===t.action){let r=nx(e,t.kind);return n.artifact=nR(e,r),n.support=nP(n.artifact.support)??nM(e),n}return n.metrics={memory:{available:!1,reason:aq}},n}return"sample"===t.action?n.metrics={memory:await nk(e,t)}:(n.artifact=await nD(e,t),n.support=nP(n.artifact.support)??nM(e)),n}function ng(){return{available:!1,reason:"Dropped-frame sampling is currently available only on Android app sessions and connected iOS device app sessions."}}async function nw(e,t,r,a){let n=await nI(t,r,a);ny(e,t,n)}async function nv(e,t,r){let a=await n_(t,r);ny(e,t,a)}function ny(e,t,r){e.metrics.memory=nO(r.memory),e.metrics.cpu=nO(r.cpu),e.metrics.fps=n$(nO(r.fps),t)}async function nA(e,t,r,a){let n="android"===t.device.platform?await nL(e3(t.device,r,{adb:a.androidAdb})):await nL(y(t.device,r));e.metrics.fps=n$(nO(n),t)}function nb(e){return ed(e.device.platform)?.perf?.supportsMetrics(e.device)??!1}function nS(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 nI(e,t,r){let a={adb:r.androidAdb},[n,i,o]=await Promise.allSettled([X(e.device,t,a),ea(e.device,t,a),e3(e.device,t,a)]);return{memory:n,cpu:i,fps:o}}async function n_(e,t){let r=await nL(y(e.device,t)),a=await nL(e1(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 nk(e,t){return e.appBundleId?nO("android"===e.device.platform?await nL(X(e.device,e.appBundleId,{adb:t.androidAdb})):await nL(nN(e))):{available:!1,reason:nS(e)}}async function nN(e){if(!e.appBundleId)throw new l("INVALID_ARGS",nS(e));return(await e1(e.device,e.appBundleId)).memory}async function nD(e,t){if(!e.appBundleId)throw new l("INVALID_ARGS",nS(e),{hint:"Run open <app> first so perf memory snapshot can resolve the app process."});let a=nx(e,t.kind),n=function(e,t){if(e.out)return eN.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?nR(e,a):await D(e.device,e.appBundleId,n,{adb:t.androidAdb}):"memgraph"!==a?nR(e,a):await A(e.device,e.appBundleId,n)}function nx(e,t){return t||("android"===e.device.platform?"android-hprof":"memgraph")}function nR(e,t){var r,a;let n=nM(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."}:tn(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 nM(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."}:tn(e.device.platform)?{...ex(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 nP(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:void 0}async function nL(e){try{return{status:"fulfilled",value:await e}}catch(e){return{status:"rejected",reason:e}}}function nO(e){if("fulfilled"===e.status)return{available:!0,...e.value};let t=s(e.reason);return{available:!1,reason:t.message,error:t}}function n$(e,t){var r,a;let n,i;if(!0!==e.available)return e;let o=(r=t.actions,n=nC((a=e).windowStartedAt),i=nC(a.windowEndedAt)??nC(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 nC(e){if("string"!=typeof e)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}async function nE(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=nV(i,1),m=nV(i,2),h=nV(i,3),tf(f)?"start"!==(l=m)&&"stop"!==l&&"report"!==l?U("INVALID_ARGS","perf cpu profile action must be start, stop, or report"):"simpleperf"!==h?U("INVALID_ARGS","perf cpu profile requires --kind simpleperf"):{ok:!0,area:"cpu",subject:f,action:m,kind:h,outPath:o}:U("INVALID_ARGS",tV)):(u=t,d=c,g=nV(u,1),w=nV(u,2),"start"!==(p=g)&&"stop"!==p?U("INVALID_ARGS","perf trace action must be start or stop"):tA(w)?"perfetto"!==w?U("INVALID_ARGS","perf trace requires --kind perfetto"):{ok:!0,area:"trace",action:g,kind:w,outPath:d}:U("INVALID_ARGS",tD)));if(!v.ok)return v;let{session:y}=e;if("android"!==y.device.platform)return U("UNSUPPORTED_OPERATION","Android native perf collectors are supported only on Android sessions.");if(!y.appBundleId)return U("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 nT(e,y,y.appBundleId,v):await nU(e,y,y.appBundleId,v);return{ok:!0,data:t}}catch(e){return{ok:!1,error:s(e)}}}function nV(e,t){return(e.positionals?.[t]??"").toLowerCase()}function nF(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 nq(e,t,a){var n,i,o;let s;return t?eN.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 nT(e,t,r,a){if("start"===a.action){nG(t);let n=nq(e,a.outPath,"cpu.perf.data"),i=await w(t.device,r,n,{adb:e.androidAdbExecutor});return nF(e,i)}let n=nB(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=nq(e,a.outPath,"cpu-report.json");return await eJ(t.device,n,r,{adb:e.androidAdbExecutor})}let i=nH(e,a.outPath,n),o=await eI(t.device,n,i,{adb:e.androidAdbExecutor});return nF(e,o)}async function nU(e,t,r,a){if("start"===a.action){nG(t);let n=nq(e,a.outPath,"app.perfetto-trace"),i=await k(t.device,r,n,{adb:e.androidAdbExecutor});return nF(e,i)}let n=nB(t,"trace",a.kind),i=nH(e,a.outPath,n),o=await eR(t.device,n,i,{adb:e.androidAdbExecutor});return nF(e,o)}function nG(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 nH(e,t,r){return t?nq(e,t,r.outPath):r.outPath}function nB(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 nK(e){if(!b(e))return;let{macOsScreenCaptureKitAudioProbeBackend:t}=await import("./audio-probe.js");return t}P();let nj=["probe"],nz=["start","status","stop"],nW=`audio probe requires ${nz.join(", ")}`;async function nJ(e){let t=function(e){var t;let r,a=(r=(t=e).sessionStore.get(t.sessionName))?e0("audio",r.device)?{ok:!0,session:r}:U("UNSUPPORTED_OPERATION","audio is supported for web browser sessions, macOS sessions, iOS simulators, and Android emulators on macOS hosts"):U("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(),nj.includes(t)?!"probe":!void 0)return U("INVALID_ARGS","audio requires probe");let a=(r=(e.positionals?.[1]??"status").toLowerCase(),nz.includes(r)?r:void 0);return a?{ok:!0,probeAction:a}:U("INVALID_ARGS",nW)}(e.req);if(!n.ok)return n;let i=function(e,t){if("start"!==t&&e.positionals&&e.positionals.length>2)return U("INVALID_ARGS","audio probe duration and bucket are only supported with audio probe start");let r=nX(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 U("INVALID_ARGS",r.message);let a=nX(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?U("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 nK(t.session.device);if(r)return await nY(e,t,r);let a=t9();if(!a.probeAudio)return U("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 nY(e,t,r){try{return{ok:!0,data:await G({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 nX(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 nQ(e,t){let r,a,n=(r=e.req.positionals??[],"cpu"===(a=r[0]?.toLowerCase())?function(e){if(e[1]?.toLowerCase()!=="profile")return U("INVALID_ARGS","perf cpu requires profile");let t=nZ(e[2],"perf cpu profile",!0);if(!t.ok)return t;let r=n0(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=nZ(e[1],"perf trace",!1);if(!t.ok)return t;let r=n0(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):U("INVALID_ARGS",th));if(!n.ok)return n;if("android"===t.device.platform)return U("UNSUPPORTED_OPERATION","Android native profiling belongs to the Android perf rollout; Apple xctrace perf supports iOS and macOS sessions only.");if(!tn(t.device.platform))return U("UNSUPPORTED_OPERATION",`Apple xctrace perf is not supported on ${t.device.platform}.`);if(!t.appBundleId)return U("INVALID_ARGS","Apple xctrace perf requires an active app session. Run open <app> first.");try{if("start"===n.action)return await n1(e,t,n);if("stop"===n.action)return await n3(e,t,n);return await n2(e,t,n)}catch(e){return{ok:!1,error:s(e)}}}function nZ(e,t,r){let a=e?.toLowerCase();return"start"===a||"stop"===a||r&&"report"===a?{ok:!0,value:a}:U("INVALID_ARGS",r?`${t} requires start, stop, or report`:`${t} requires start or stop`)}function n0(e){return e?.toLowerCase()==="xctrace"?{ok:!0}:U("INVALID_ARGS","perf native collection currently supports --kind xctrace")}async function n1(e,t,r){if(t.applePerf?.active)return U("INVALID_ARGS","Apple xctrace perf capture already in progress");let a=r.template??("cpu-profile"===r.mode?"Time Profiler":"Animation Hitches"),n=n4(e,r),i=await eo({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=n8("started",i);return n5(e,t,o),{ok:!0,data:o}}async function n3(e,t,r){var a,n,i,s,l,u,d;let p,c=t.applePerf?.active;if(!c)return U("INVALID_ARGS","no active Apple xctrace perf capture");let f=r.outPath?eN.expandHome(r.outPath,e.req.meta?.cwd):c.outPath;try{p=await x(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=n8("stopped",p);return n5(e,t,m),{ok:!0,data:m}}async function n2(e,t,r){var a;let n;if("cpu-profile"!==r.mode)return U("INVALID_ARGS","perf trace does not support report");if(t.applePerf?.active)return U("INVALID_ARGS","perf cpu profile report requires a stopped profile trace; stop the active capture first.");let i=n4(e,r),o=(a=t,(n=r.tracePath??a.applePerf?.lastProfileTracePath??a.applePerf?.active?.outPath)?{ok:!0,value:n}:U("INVALID_ARGS","perf cpu profile report requires a stopped profile trace or tracePath option"));if(!o.ok)return o;let s={perf:"reported",...await M({tracePath:eN.expandHome(o.value,e.req.meta?.cwd),outPath:i,mode:r.mode,template:t.applePerf?.lastProfileTemplate??r.template,appBundleId:t.appBundleId})};return n5(e,t,s),{ok:!0,data:s}}function n5(e,t,r){tF(e.sessionStore,t,e.req,"perf",r)}function n4(e,t){if(t.outPath)return eN.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 n8(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 n6=`logs requires ${tM.slice(0,-1).join(", ")}, or ${tM.at(-1)}`,n7=["dump","log"],n9=`network requires ${n7.join(" or ")}`,ie=`network include mode must be one of: ${tt.join(", ")}`,it={path:({session:e,sessionName:t,sessionStore:r})=>(function(e,t,r){let a=r.resolveAppLogPath(t),n=Y(a);return{ok:!0,data:{path:a,active:!!e.appLog,state:e.appLog?.getState()??"inactive",backend:e.appLog?.backend??eb(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})=>il(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})=>iu(e,t,r,a),start:({session:e,sessionName:t,sessionStore:r})=>id(e,t,r),stop:({session:e,sessionName:t,sessionStore:r})=>ip(e,t,r)};async function ir(e){let{req:t}=e;return"perf"===t.command?ia(e):"logs"===t.command?is(e):"network"===t.command?ic(e):"audio"===t.command?await nJ(e):null}async function ia(e){var t;let{req:r,sessionName:a,sessionStore:n,androidAdbExecutor:i}=e,o=n.get(a);if(!o)return U("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 nE({req:r,sessionName:a,sessionStore:n,session:o,androidAdbExecutor:i,area:u}):await nQ(e,o);let d=function(e){var t,r,a,n,i,o,u,d,p,c;let f,m,h=tx(f=(e.positionals?.[0]??"metrics").toString().toLowerCase())?f:void 0;if(!h)return U("INVALID_ARGS",th);if("cpu"===h||"trace"===h)return{ok:!0,native:!0};let g=tc(m=(e.positionals?.[1]??"sample").toString().toLowerCase())?m:void 0;if(!g)return U("INVALID_ARGS",tw);let w=function(e){if(void 0!==e)return"string"==typeof e&&tA(e)?e:new l("INVALID_ARGS",tD)}(e.flags?.kind);if(w instanceof l)return{ok:!1,error:s(w)};let v=(t=h,r=g,("memory"===t?io(r)?void 0:U("INVALID_ARGS","perf memory requires sample or snapshot"):"sample"!==r?U("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 U("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?U("INVALID_ARGS","--kind is only supported with perf memory snapshot"):tb(u)?void 0:U("INVALID_ARGS",tN):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 nQ(e,o);try{return{ok:!0,data:await ii(e,o,d)}}catch(e){return{ok:!1,error:s(e)}}}async function ii(e,t,r){let{sessionName:a,sessionStore:n,androidAdbExecutor:i}=e;return"memory"===r.area?await nh(t,{action:function(e){if(io(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 nm(t,{androidAdb:i}):await nf(t,{androidAdb:i})}function io(e){return"sample"===e||"snapshot"===e}async function is(e){var t;let r,a,{req:n,sessionName:i,sessionStore:o}=e,s=o.get(i);if(!s)return U("SESSION_NOT_FOUND","logs requires an active session");let l=Q("logs",s.device);if(l)return l;let u=(t=n,r=(t.positionals?.[0]??"path").toLowerCase(),a=!!t.flags?.restart,tM.includes(r)?a&&"clear"!==r?U("INVALID_ARGS","logs --restart is only supported with logs clear"):{ok:!0,action:r,restart:a}:U("INVALID_ARGS",n6));return u.ok?await it[u.action]({...e,session:s,restart:u.restart}):u}async function il(e,t,r){let a=r.resolveAppLogPath(t),n=await eO(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 iu(e,t,r,a){if(e.appLog&&!a)return U("INVALID_ARGS","logs clear requires logs to be stopped first; run logs stop");let n=r.resolveAppLogPath(t);if(!a)return{ok:!0,data:eu(n)};let i=e.appBundleId;if(!i)return U("INVALID_ARGS","logs clear --restart requires an app session; run open <app> first");e.appLog&&await eK(e.appLog);let o=eu(n),l=r.resolveAppLogPidPath(t);try{let a=await e8(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 id(e,t,r){if(e.appLog)return U("INVALID_ARGS","app log already streaming; run logs stop first");if(!e.appBundleId)return U("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 e8(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 ip(e,t,r){if(!e.appLog)return U("INVALID_ARGS","no app log stream active");let a=e.appLog.outPath;return await eK(e.appLog),r.set(t,{...e,appLog:void 0}),{ok:!0,data:{path:a,stopped:!0}}}async function ic(e){let t=function(e){let{req:t,sessionName:r,sessionStore:a}=e,n=a.get(r);if(!n)return U("SESSION_NOT_FOUND","network requires an active session");let i=Q("network",n.device);if(i)return i;let o=(t.positionals?.[0]??"dump").toLowerCase();if(!n7.includes(o))return U("INVALID_ARGS",n9);let s=t.positionals?.[1]?Number.parseInt(t.positionals[1],10):25;if(!Number.isInteger(s)||s<1||s>200)return U("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 U("INVALID_ARGS","network include mode was provided both positionally and via --include with different values");let a=(r??t??"summary").toLowerCase();return tt.includes(a)?{ok:!0,include:a}:U("INVALID_ARGS",ie)}(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 im({include:r,maxEntries:a});let i=await eh({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 im(e){let t=t9();if(!t.dumpNetwork)return U("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 ih(e,t,r){var a,n;if(null==e)return rc("open",[rg(rm(t,"launchApp"),r)]);if("string"==typeof e)return rc("open",[rg(e,r)]);if(!rf(e))throw new l("INVALID_ARGS","launchApp expects a string or map.");rh(e,"launchApp",["appId","stopApp","clearState","clearKeychain","arguments","permissions","launchArguments"]),iy(e,"permissions"),iy(e,"clearKeychain");let i=rg("string"==typeof e.appId?e.appId:rm(t,"launchApp"),r),o=(a=e,n=r,[...iw(a.arguments,"launchApp.arguments",n),...iw(a.launchArguments,"launchApp.launchArguments",n)]),s=!0===e.clearState;return rc("open",[i],{...!s&&(!0===e.stopApp||o.length>0)?{relaunch:!0}:{},...s?{clearAppState:!0}:{},...o.length>0?{launchArgs:o}:{}})}function ig(e,t,r){if(null==e)return rc("close",[rg(rm(t,"stopApp"),r)]);if("string"==typeof e)return rc("close",[rg(e,r)]);throw new l("INVALID_ARGS","stopApp expects a string appId or no value.")}function iw(e,t,r){if(null==e)return[];if("string"==typeof e)return[rg(e,r)];if(Array.isArray(e))return e.map((e,a)=>iv(e,`${t}[${a}]`,r));if(rf(e))return Object.entries(e).flatMap(([e,a])=>[rg(e,r),iv(a,`${t}.${e}`,r)]);throw new l("INVALID_ARGS",`${t} expects a string, list, or map.`)}function iv(e,t,r){if("string"==typeof e)return rg(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 iy(e,t){if(void 0!==e[t])throw ry(`Maestro launchApp field "${t}" is not supported yet.`)}let iA="__maestroRunScript",ib="__maestroAssertVisible",iS="__maestroAssertNotVisible",iI="__maestroPressEnter",i_="__maestroWaitForAnimationToEnd",ik="__maestroScrollUntilVisible",iN="__maestroSwipeScreen",iD="__maestroSwipeOn",ix="__maestroTapOn",iR="__maestroTapPointPercent";function iM(e){if(null==e)return rc("type",["\b".repeat(50)]);if("number"==typeof e&&Number.isInteger(e)&&e>0)return rc("type",["\b".repeat(e)]);if(!rf(e))throw new l("INVALID_ARGS","eraseText expects empty, a positive count, or a map.");if(rh(e,"eraseText",["charactersToErase"]),void 0===e.charactersToErase)return rc("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 rc("type",["\b".repeat(e.charactersToErase)])}function iP(e){return"number"==typeof e&&Number.isFinite(e)?String(Math.max(16,Math.floor(e))):void 0}function iL(e,t){let r=e.toLowerCase();switch(r){case"up":case"down":case"left":case"right":return r;default:throw ry(`Maestro ${t} must be UP, DOWN, LEFT, or RIGHT.`)}}function iO(e){return iL(e,"swipe direction")}function i$(e,t,r=[],a){if("string"==typeof e)return iC(rg(e,a));if(!rf(e))throw new l("INVALID_ARGS",`${t} expects a string or selector map.`);rh(e,t,["id","text","enabled","selected",...r]);let n=[],i=[];if("boolean"==typeof e.enabled&&i.push(iV("enabled",String(e.enabled))),"boolean"==typeof e.selected&&i.push(iV("selected",String(e.selected))),"string"==typeof e.id&&n.push(iV("id",rg(e.id,a)),...i),"string"==typeof e.text&&0===n.length)return iC(rg(e.text,a),i);if("string"==typeof e.label&&0===n.length&&n.push(iV("label",rg(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 iC(e,t=[]){return[[iV("label",e),...t].join(" "),[iV("text",e),...t].join(" "),[iV("id",e),...t].join(" ")].join(" || ")}function iE(e){let t=iP(e.duration);return t?[t]:[]}function iV(e,t){return`${e}=${JSON.stringify(t)}`}function iF(e){var t,r;if(!rf(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 iq(e){let t=iF(e)??{};return{...t,maestro:{...t.maestro??{},allowNonHittableCoordinateFallback:!0}}}function iT(e){let t={doubleTap:!0};return rf(e)&&"number"==typeof e.delay&&Number.isInteger(e.delay)&&(t.intervalMs=Math.max(0,e.delay)),t}class iU{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 iG(e,t,r){return{...rc(e,t),replayControl:r}}function iH(e,t,r){let a="string"==typeof e?rg(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 iB=`
|
|
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 iK(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,ij)}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 ij(e,t){return"__proto__"===e||"constructor"===e||"prototype"===e?void 0:t}let iz={launchApp:({value:e,config:t,context:r})=>[ih(e,t,r)],tapOn:({value:e,context:t})=>[function(e,t){if("string"==typeof e)return rc(ix,[iC(rg(e,t))],iq(e));if(rf(e)&&"string"==typeof e.point){rh(e,"tapOn",["point","repeat","delay","optional","label"]);let t=rv(e.point);return"percent"===t.kind?rc(iR,[String(t.x),String(t.y)],iF(e)):rc("click",[String(t.x),String(t.y)],iF(e))}rf(e)&&rh(e,"tapOn",["id","text","childOf","enabled","index","selected","repeat","delay","optional","label"]);let r=iq(e);return rc(ix,[i$(e,"tapOn",["repeat","delay","optional","label","index","childOf"],t),...function(e,t){if(!rf(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=i$(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(rf(e)&&"string"==typeof e.point){rh(e,"doubleTapOn",["point","delay"]);let t=rl(e.point);return rc("click",[String(t.x),String(t.y)],iT(e))}return rf(e)&&rh(e,"doubleTapOn",["id","text","enabled","selected","delay"]),rc("click",[i$(e,"doubleTapOn",["delay"],t)],iT(e))}(e,t)],longPressOn:({value:e,context:t})=>[function(e,t){if(rf(e)&&"string"==typeof e.point){rh(e,"longPressOn",["point"]);let t=rl(e.point);return rc("longpress",[String(t.x),String(t.y),"3000"])}return rf(e)&&rh(e,"longPressOn",["id","text","enabled","selected"]),rc("click",[i$(e,"longPressOn",[],t)],{holdMs:3e3})}(e,t)],inputText:({value:e,context:t})=>[rc("type",[rg(function(e){if("string"==typeof e)return e;if(!rf(e))throw new l("INVALID_ARGS","inputText expects a string or map.");if(rh(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})=>[iM(e)],pasteText:({value:e,context:t,name:r})=>[rc("type",[rg(rw(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=rg((l=n,u=s,"string"==typeof l?l:rf(l)?(rh(l,u,["link"]),rw(`${u}.link`,l.link)):rw(u,l)),o),("ios"===o.platform||"android"===o.platform)&&i.appId?rc("open",[rg(rm(i,s),o),d],"ios"===o.platform?{maestro:{prewarmRunnerBeforeOpen:!0}}:void 0):rc("open",[d]))]},assertVisible:({value:e,context:t,name:r})=>[rc(ib,[i$(e,r,[],t),"17000"])],assertNotVisible:({value:e,context:t,name:r})=>[rc(iS,[i$(e,r,[],t)])],extendedWaitUntil:({value:e,context:t})=>(function(e,t){if(!rf(e))throw new l("INVALID_ARGS","extendedWaitUntil expects a map.");rh(e,"extendedWaitUntil",["visible","notVisible","timeout"]);let r=e.visible??e.notVisible;if(void 0===r)throw ry("Only Maestro extendedWaitUntil.visible/notVisible is supported.");let a=i$(r,"extendedWaitUntil",[],t),n=String(rA(e,17e3));return void 0!==e.notVisible?[rc(iS,[a,n])]:[rc(ib,[a,n],{maestro:{allowAlreadyPastLoading:!0}})]})(e,t),takeScreenshot:({value:e,context:t,name:r})=>[rc("screenshot",[rg(rw(r,e),t)])],scroll:({value:e})=>[function(e){if(null!=e)throw ry("Maestro scroll options are not supported yet.");return rc("scroll",["down"])}(e)],scrollUntilVisible:({value:e,context:t})=>(function(e,t){if("string"==typeof e)return[rc(ik,[iC(rg(e,t)),"5000","down"])];if(!rf(e))throw new l("INVALID_ARGS","scrollUntilVisible expects a string or map.");rh(e,"scrollUntilVisible",["element","direction","timeout"]);let r=i$(e.element,"scrollUntilVisible.element",[],t),a="string"==typeof e.direction?iL(e.direction,"scrollUntilVisible.direction"):"down";return[rc(ik,[r,String(rA(e,5e3)),a])]})(e,t),swipe:({value:e,context:t})=>[function(e,t){var r,a,n;let i;if(!rf(e))throw new l("INVALID_ARGS","swipe expects a map.");rh(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=iO("string"==typeof r.direction?r.direction:"up"),rc(iD,[i$(a,"swipe.from",[],n),i,...iE(r)])):"string"==typeof e.direction?rc(iN,["direction",iO(e.direction),...iE(e)]):function(e){let{start:t,end:r}=function(e){if("string"==typeof e.start&&"string"==typeof e.end)return{start:rv(e.start),end:rv(e.end)};throw ry("Only Maestro swipe start/end coordinates are supported.")}(e);var a=t,n=r,i=iP(e.duration);if("absolute"===a.kind&&"absolute"===n.kind)return rc("swipe",[String(a.x),String(a.y),String(n.x),String(n.y),...i?[i]:[]]);if("percent"===a.kind&&"percent"===n.kind)return rc(iN,["percent",String(a.x),String(a.y),String(n.x),String(n.y),...i?[i]:[]]);throw ry("Maestro swipe start/end must both be absolute pixels or both be percentages.")}(e)}(e,t)],hideKeyboard:()=>[rc("keyboard",["dismiss"])],pressKey:({value:e})=>[function(e){let t=rw("pressKey",e).toLowerCase();if("back"===t)return rc("back");if("enter"===t||"return"===t)return rc(iI);if("home"===t)return rc("home");throw ry(`Maestro pressKey "${t}" is not supported yet.`)}(e)],back:()=>[rc("back")],waitForAnimationToEnd:({value:e})=>[rc(i_,[String(rA(e,15e3))])],stopApp:({value:e,config:t,context:r})=>[ig(e,t,r)],runScript:({value:e,context:t})=>{let a;return[rc(iA,[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:rg(e,t),env:{}};if(!rf(e))throw new l("INVALID_ARGS","runScript expects a file path string or map.");return rh(e,"runScript",["file","env"]),{file:rg(rw("runScript.file",e.file),t),env:Object.fromEntries(Object.entries(rt(e.env,"runScript.env")).map(([e,r])=>[e,rg(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(rg(e,r),r).actions;if(!rf(e))throw new l("INVALID_ARGS","runFlow expects a file path string or map.");rh(e,"runFlow",["file","commands","env","when","label"]);let i=function(e,t){var r,a;if(null==e)return{shouldRun:!0};if(!rf(e))throw new l("INVALID_ARGS","runFlow.when expects a map.");return(rh(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 iU(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=rg(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:i$(r.visible,"runFlow.when.visible",[],a)}:{},...void 0!==r.notVisible?{notVisibleSelector:i$(r.notVisible,"runFlow.when.notVisible",[],a)}:{}})}}(e.when,r);if(!i.shouldRun)return[];let o={...r,env:{...r.env,...rt(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 ry("Maestro runFlow.when cannot combine visible and notVisible yet.");let n=r?"visible":"notVisible",i=r??a??"";return[iG("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(rg(e.file,r),r).actions;if(Array.isArray(e.commands))return n(rn(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,iY),repeat:({value:e,config:t,context:r,deps:a})=>(function(e,t,r,a,n){var i;if(!rf(e))throw new l("INVALID_ARGS","repeat expects a map.");if(rh(e,"repeat",["times","commands","while"]),void 0!==e.while)throw ry("Maestro repeat.while is not supported yet. Only deterministic repeat.times is supported.");let o=(i=e.times,iH(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=rn(e.commands);return Array.from({length:o}).flatMap(()=>n(s,t,r,a))})(e,t,r,a,iY),retry:({value:e,config:t,context:r,deps:a})=>(function(e,t,r,a,n){var i,o;if(!rf(e))throw new l("INVALID_ARGS","retry expects a map.");if(rh(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:iH(i,o,"retry.maxRetries")),u=n(rn(e.commands),t,r,a);return[iG("retry",[String(s)],{kind:"retry",maxRetries:s,actions:u})]})(e,t,r,a,iY)},iW={launchApp:(e,t)=>[ih(void 0,e,t)],scroll:()=>[rc("scroll",["down"])],hideKeyboard:()=>[rc("keyboard",["dismiss"])],eraseText:()=>[iM(void 0)],back:()=>[rc("back")],waitForAnimationToEnd:()=>[rc(i_,["15000"])],stopApp:(e,t)=>[ig(void 0,e,t)]};function iJ(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=iW[n])?a(i,o):re(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=iz[u];return p?p({value:d,config:t,context:r,deps:a,name:u}):re(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 iY(e,t,r,a){return e.flatMap((e,n)=>iJ(e,t,n+1,r,a))}function iX(e,t){let{config:r,commands:a}=iQ(rs(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=iJ(r,t,a,n,{parseRunFlowFile:iZ});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!==iI||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!==ix)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 iQ(e){if(0===e.length)throw new l("INVALID_ARGS","Maestro flow is empty.");if(Array.isArray(e[0]))return{config:{},commands:rn(e[0])};let t=function(e){if(!rf(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}:{},...rf(e.env)?{env:rt(e.env,"env")}:{},...Array.isArray(e.onFlowStart)?{onFlowStart:rn(e.onFlowStart)}:{},...Array.isArray(e.onFlowComplete)?{onFlowComplete:rn(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:rn(r)}}function iZ(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),iX(i,{...a,baseDir:r.dirname(n),visitedPaths:o})}let i0=/[*?[\]{}]/;function i1(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 i3(e,t){return"number"==typeof e?e:t}function i2(e,t){let r="number"==typeof e?e:t;return"number"!=typeof r?0:Math.max(0,Math.min(3,r))}function i5(e,a,n){var i,o;let s=eN.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,!i0.test(i)&&(o=s,!i0.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 i4(e,t){let r=i8(e),a=i8(t);return r!==a?r-a:e.localeCompare(t)}function i8(e){return+(".ad"===r.extname(e))}function i6(e){return[...new Set(e.map(e=>r.normalize(e)))]}function i7(e){return"maestro"===e}let i9=["failed to start daemon","runner did not accept connection","xcodebuild exited early","device is offline","device offline","device unauthorized"];function oe(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&&tj(i)||(a=s.code,n=s.message,o=`${a}
|
|
26
|
+
${n}`.toLowerCase(),i9.some(e=>o.includes(e))))}async function ot(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;T(l);let y=function(e,t){if(!t||t===e)return()=>{};let r=e5(t);if(!r)return()=>{};let a=()=>{eB(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(),I=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),oi(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}),_=eU(h,async()=>await g({filePath:i,sessionName:o,platform:p,target:c,requestId:l,artifactsDir:f,artifactPaths:A,tracePath:I,shard:m})).catch(e=>({ok:!1,error:s(e)})).finally(()=>{y(),eX(l)});try{n="number"==typeof d?await Promise.race([_,new Promise(e=>{a=setTimeout(()=>{b=!0,eB(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 _,oi(I,{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 or(_)||((k=n)&&!k.ok&&(k.error.details={...k.error.details??{},reason:"timeout_cleanup_pending",timeoutCleanupPending:!0}),t3({level:"warn",phase:"test_timeout_cleanup_race",data:{session:o,requestId:l,graceMs:2e3}}),oa({replayPromise:_,cleanupSession:w,sessionName:o,requestId:l})));let r=await on({finalizeAttempt:v,sessionName:o,artifactPaths:A,artifactsDir:f,tracePath:I});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{oi(I,{type:"replay_test_cleanup_start",ts:new Date().toISOString(),session:o}),await w(o),oi(I,{type:"replay_test_cleanup_stop",ts:new Date().toISOString(),session:o,ok:!0,durationMs:Date.now()-i})}catch(t){let e=s(t);oi(I,{type:"replay_test_cleanup_stop",ts:new Date().toISOString(),session:o,ok:!1,durationMs:Date.now()-i,errorCode:e.code}),t3({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 or(e){return await Promise.race([e.then(()=>!0),n(2e3).then(()=>!1)])}async function oa(e){let{replayPromise:t,cleanupSession:r,sessionName:a,requestId:n}=e;try{await t}finally{try{await r(a)}catch(e){t3({level:"warn",phase:"test_late_cleanup_failed",data:{session:a,requestId:n,error:s(e).message}})}}}async function on(e){let{finalizeAttempt:t,sessionName:r,artifactPaths:a,artifactsDir:n,tracePath:i}=e;if(!t)return;let o=Date.now();oi(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 oi(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 oi(i,{type:"replay_test_finalize_stop",ts:new Date().toISOString(),session:r,ok:!1,durationMs:Date.now()-o,errorCode:e.code}),t3({level:"warn",phase:"test_finalize_failed",data:{session:r,error:e.message}}),{ok:!1,error:e}}}function oi(e,r){e&&t.appendFileSync(e,`${JSON.stringify(r)}
|
|
27
|
+
`)}async function oo(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 os(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 e6({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,...od(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),...ou(u.data?.snapshotDiagnostics),...function(e){return od(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 e6({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,...od(u)}),{file:o.path,title:o.title,session:r.finalSessionName,status:"failed",durationMs:a,attempts:r.attempts,artifactsDir:t.testArtifactsDir,error:d,...ou((i=r.finalResponse,i?.ok?i.data?.snapshotDiagnostics:i?.error.details?.snapshotDiagnostics)),...function(e){return od(e)}(u)}}(t,a,n,i)}async function os(e,t){!function(e,t){let{entry:r,sessionName:a,suiteInvocationId:n,caseIndex:i,suiteIndex:o,suiteTotal:s,shard:l}=e;e6({type:"replay-test",file:r.path,title:r.title,status:"start",index:o,total:s,maxAttempts:t.maxAttempts,session:i1(a,n,r.path,i),artifactsDir:t.testArtifactsDir,...od(l)})}(e,t);let r={finalSessionName:"",attempts:0,finalAttemptDurationMs:0,attemptFailures:[]};for(let p=0;p<=e.retries&&!eM(e.requestId);p+=1){var a,n,i,o,s,l,u,d;let c=await ol(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||eM(i.requestId)||oe(o)||s>=i.retries)break;l=e,u=t,(d=c).response.ok||e6({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,...od(l.shard)})}return r}async function ol(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=i1(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 eP(`${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 ot({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,...od(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 ou(e){let t=rk(e);return t?{snapshotDiagnostics:t}:{}}function od(e){return e?{shardIndex:e.shardIndex,shardCount:e.shardCount,deviceId:e.device.id,deviceName:e.device.name}:{}}async function op(e,t,r){let a=function(e){let t=oc(e?.shardAll,"--shard-all"),r=oc(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 of(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 oc(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 of(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 ek((a=e,f=tJ(a?.androidDeviceAllowlist),{platform:a?.platform,target:a?.target,iosSimulatorSetPath:e9({simulatorSetPath:tH(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=oh(e),r=s.find(r=>om(r,d)&&(r.id===e||oh(r.name)===t));if(!r)throw new l("DEVICE_NOT_FOUND",`No shard device matched ${e}`);return r})):n.filter(e=>{var t;return!!om(t=e,o)&&!!tr(t)&&!1!==t.booted}).sort(og));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 om(e,t){return!(!ta(e,t?.platform)||t?.target&&(e.target??"mobile")!==t.target)}function oh(e){return e.toLowerCase().replace(/_/g," ").replace(/\s+/g," ").trim()}function og(e,t){return e.id.localeCompare(t.id)}async function ow(e){let{req:t,sessionName:r,runReplay:a,cleanupSession:n,finalizeAttempt:i}=e;if((t.positionals?.length??0)===0)return U("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 ov(t);s=g,e6({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&&(e6({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 oy({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 oS({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=rD(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 U(e.code,e.message)}}async function ov(e){var a,n,i,o;let s=function(e){let{inputs:a,cwd:n,platformFilter:i,replayBackend:o}=e,s=new Set(i7(o)?[".yaml",".yml",".ad"]:[".ad"]),u=function(e,a,n,i){if(!i7(i))return[...new Set(e.flatMap(e=>i5(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=eN.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"}:i5(e,a,n)}(i,a,n);"file"===e.source?o.push(...e.paths):s.push("directory"===e.source?i6(e.paths):e.paths.map(e=>r.normalize(e)).sort(i4))}return i6([...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=ru(a),s=(p=a,c=e,i7(o)&&".ad"!==r.extname(c)?function(e){let{config:t}=iQ(rs(e));return t.name}(p):void 0);if(!i){d.push({kind:"run",path:e,title:s,metadata:n});continue}if(!n.platform){i7(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?tn(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 op(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=eN.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 oy(e){return(await Promise.allSettled(e.shards.map(async t=>await oA({...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:ob(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 oA(e){let{shard:t,sessionName:r}=e;return await oI({...e,entries:t.entries,sessionName:ob(r,t),shard:t})}function ob(e,t){return`${e}:shard-${t.shardIndex+1}`}async function oS(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(eM(i))break;if("skip"===m.kind){e6({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 oo({entry:m,sessionName:r,suiteInvocationId:a,caseIndex:f-1,cwd:n,requestId:i,retries:i2(o?.retries,m.metadata.retries),timeoutMs:i3(o?.timeoutMs,m.metadata.timeoutMs),suiteArtifactsDir:s,suiteIndex:e+1,suiteTotal:l,runReplay:u,cleanupSession:d,finalizeAttempt:p});if(c.push(t),o_(t,o,i))break}return c}async function oI(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(eM(i))break;let{entry:t,suiteIndex:h}=m,g=await oo({entry:t,sessionName:r,suiteInvocationId:a,caseIndex:e,cwd:n,requestId:i,retries:i2(o?.retries,t.metadata.retries),timeoutMs:i3(o?.timeoutMs,t.metadata.timeoutMs),suiteArtifactsDir:s,suiteIndex:h,suiteTotal:l,shard:u,runReplay:d,cleanupSession:p,finalizeAttempt:c});if(f.push(g),o_(g,o,i))break}return f}function o_(e,t,r){return eM(r)||t?.failFast===!0||oe(e)}let ok={maestro:{parse:function(e,t={}){var a;let n;return iX(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:ri(a.platform),env:{},envOverrides:a.env??{},visitedPaths:n}))}}};function oN(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=rT(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 oD(e){let{action:t,sessionName:r,logPath:a,sessionStore:n}=e;if(!(rq(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),rq(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&&ox(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}=rL(e.positionals);r&&t.push(r.selectorExpression)}if("wait"===e.command){let{selectorExpression:r}=oN(e.positionals??[]);r&&t.push(r)}return Z(t).filter(e=>e.trim().length>0)})(t).map(e=>rG(e)).filter(e=>null!==e);if(0===o.length)return null;let s=rq(t.command)||"fill"===t.command,l=rq(t.command)||"fill"===t.command||"get"===t.command&&t.positionals?.[0]==="text",u=await oR(i,t,a,s,n);for(let e of o){let r=rx(u.nodes,e,{platform:i.device.platform,requireRect:s,requireUnique:!0,disambiguateAmbiguous:l});if(!r)continue;let a=rO(r.node,i.device.platform,{action:"fill"===t.command?"fill":rq(t.command)?"click":"get"}).join(" || ");if(rq(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&&ox(t)?t:void 0}(e.positionals??[]);return r?[t,r]:[t]}(t,a):[a]};if("fill"===t.command){let e=I(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}=rL(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}=oN(t.positionals??[]),r=[a];return e&&r.push(e),{...t,positionals:r}}}return null}function ox(e){return void 0!==e&&""!==e.trim()&&Number.isFinite(Number(e))}async function oR(e,t,r,a,n){let i=eA(await f(e.device,"snapshot",[],t.flags?.out,{...e_(r,{...t.flags??{},snapshotInteractiveOnly:a},e.appBundleId,e.trace?.outPath)}),{...t.flags??{},snapshotInteractiveOnly:a});return ee(e,i),n.set(e.name,e),i}let oM=.35,oP=120,oL=360,oO=8;function o$(e,t){return Math.round(Math.min(oL,Math.max(oP,"number"==typeof e?e*oM:0,1.5*t)))}let oC=new WeakMap,oE=new WeakMap,oV=new WeakMap;function oF(e,t,r){return{ok:!1,error:{code:e,message:t,...r?{details:r}:{}}}}async function oq(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=ep(oT(n.data)))&&oC.set(t,r)),n}function oT(e){return Array.isArray(e?.nodes)?e:void 0}function oU(e,t){e&&oE.set(e,{selector:t})}function oG(e){e&&oV.delete(e)}let oH=new Map([["button",0],["link",0],["textfield",0],["textview",0],["searchfield",0],["switch",0],["slider",0],["cell",1],["statictext",2]]);function oB(e,t,r,a,n,i={}){let o=oJ(e,t,a);if(r.childOf){let t=oJ(e,r.childOf,a);if(0===t.length)return{ok:!1,message:`Maestro childOf parent did not match: ${r.childOf}`};let n=r$(e.nodes);o=o.filter(r=>t.some(t=>rP(e.nodes,r,t,n)))}let s=oj({nodes:e.nodes,matches:o,platform:a}),l=oQ(e.nodes,s.matches,r.index,oW(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 oK(e,t,r,a){let n=oJ(e,t,r,{allowLeadingCompositeLabelMatch:!1}),i=oj({nodes:e.nodes,matches:n,platform:r}),o=oQ(e.nodes,i.matches,void 0,oW(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 oj(e){let t=e.matches.filter(t=>rF({predicate:"visible",node:t,nodes:e.nodes,platform:e.platform}).pass),r=function(e,t,r){let a=tE(e);if(!a.detected||!a.redBox)return{matches:t,blockedByReactNativeOverlay:!1};let n=tC(a),i=n.filter(t=>rF({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 oz(e){return e?.platform==="android"?"android":"ios"}function oW(e){let t=rH(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 oJ(e,t,r,a={}){for(let n of rH(t).selectors){let t=e.nodes.filter(e=>(function(e,t,r,a){return!!rC(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?rC(e,{raw:t.key,terms:[t]},r):oY((i=e,"id"===(o=t.key)?i.identifier:"label"===o?i.label:"value"===o?i.value:rR(i)),t.value,a)})(e,t,r,a))})(e,n,r,a));if(t.length>0)return t}return[]}function oY(e,t,r={}){var a;let n=e??"",i=rU(n),o=rU(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 oX(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 oQ(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=r$(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=oX(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===o7(e.node,r));if(n.length>=2){let t=o0(e,n,r,a);if(t)return t}let i=t.filter(e=>1===o7(e.node,r));return n.length>0||i.length<2?null:o0(e,i,r,a)}(o,s,l,d)??oZ(o,s,l,d):oZ(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=rE(a.node.type??""))||"other"===b||"scrollview"===b||"scroll-area"===b)&&!(a.rect.width<120)&&!(a.rect.height<32)&&!(a.rect.height>80)&&1>=o7(a.node,n)))return null;let R=(i=e,o=t,s=r,l=r$(e),i.filter(e=>{var t,r,a;let n;return e.index!==o.node.index&&!!e.rect&&rP(i,e,o.node,l)&&(t=e,r=o.rect,a=s,!("button"!==(n=rE(t.type??""))&&"cell"!==n&&"other"!==n||1>=o7(t,a))&&!(t.rect.width<16)&&!(t.rect.height<16)&&!!o8(r,t.rect)&&o5(r,t.rect)>=.5)}).sort((e,t)=>e.rect.x-t.rect.x));if(0===R.length)return null;let M=(I=Math.floor((S=[...R.map(e=>e.rect.width)].sort((e,t)=>e-t)).length/2),S[I]??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,_=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=_,v=k,w&&"scrollview"===rE(h.node.type??"")&&1>=o7(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,_.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?(I=v,_=y,k=A,N=S,(o4(_.node)?null:rM(I,_.node,k,e=>{if(!o4(e))return null;let t=oX(I,e,k);return t&&function(e,t,r){var a,n;if(!o8(t,e)||(a=e,!((n=t).height<32||n.height>80||a.height<.75*n.height||.75>o5(a,n))&&!(n.width<240)&&n.width>=3*a.width))return!1;let i=o3(t),o=o3(e);if(o>0&&i>30*o)return!1;if(r){let e=r.referenceWidth*r.referenceHeight;if(e>0&&i>.5*e)return!1}return!0}(_.rect,t.rect,N)?{node:e,rect:t.rect}:null}))??{node:y.node,rect:y.rect}):{node:y.node,rect:y.rect}:null}function oZ(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===o7(e.node,r));if(l.length<2)return t;let u=r$(e),d=l.map(t=>({candidate:t,container:o1(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&&o6(t.container.rect,e.container.rect)>=.6)});if(p.length<2)return t;let c=(o=Math.max(...i=(n=p).map(e=>o3(e.container.rect))),(s=Math.min(...i))<=0||o<1.2*s?[]:n.filter(e=>o3(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=o1(e,r.node,a),i=n&&o8(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>o6(e.rect,r.rect)?1/0:Math.abs(e.index-r.index);if(o6(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=o7(e.node,r)-o7(t.node,r);if(0!==a)return a}let a=o2(e.node)-o2(t.node);if(0!==a)return a;let n=Number(e.inheritedRect)-Number(t.inheritedRect);if(0!==n)return n;let i=r&&o2(e.node)===o2(t.node)?o3(t.rect)-o3(e.rect):o3(e.rect)-o3(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 o0(e,t,r,a){let n=r$(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||!o8(i.rect,o.rect)||o3(i.rect)<2*o3(o.rect))&&rP(a,o.node,i.node,s)})});return oZ(e,i,r,a)}function o1(e,t,r){return rM(e,t,r,e=>{let t;return!e.rect||"scrollview"!==(t=rE(e.type??""))&&"scroll-area"!==t&&"list"!==t||e.rect.width<240||e.rect.height<320?null:e})}function o3(e){return e.width*e.height}function o2(e){return oH.get(rE(e.type??""))??3}function o5(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 o4(e){let t=rE(e.type??"");return!0===e.hittable||"button"===t||"link"===t||"cell"===t||"textfield"===t||"searchfield"===t||"switch"===t||"slider"===t}function o8(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 o6(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(o3(e),o3(t)))}function o7(e,t){let r=[e.label,rR(e),e.identifier,e.value].filter(e=>!!e);return r.some(e=>e===t)?0:r.some(e=>rU(e)===rU(t))?1:r.some(e=>oY(e,t))?2:3}async function o9(e){let t=sc(e.positionals,{command:"assertVisible",defaultTimeoutMs:17e3});if(!t.ok)return t.response;let r=sp(e.baseReq,t.selector);return r?await se(e,t,r):await sr(e,t)}async function se(e,t,r){let a=Date.now(),n=await st(e,t,r);if(n.ok){var i;if(i=e.baseReq,i.flags?.platform==="android"){let r=await sf(e,t.selector,"assertVisible");if(!r.visible){let n=sd(e.baseReq,t,r,a);return"return"===n.kind?n.response:await sr(e,t)}}return oU(e.scope,t.selector),sg({ok:!0,data:{selector:t.selector,nativeWait:!0,query:r,response:n.data}},t.selector,a)}return await sa(e,t,n,a)}async function st(e,t,r){return await e.invoke({...e.baseReq,command:"wait",positionals:[r,String(t.timeoutMs)]})}async function sr(e,t){let r,a,n=Date.now(),i=t.timeoutMs+1e3,o=!1;for(;;){let s=Date.now(),l=await sf(e,t.selector,"assertVisible");if(l.visible)return sg(l.response,t.selector,n);r=l.response,a=l.snapshot??a;let u=sd(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 rB(250)}let s=r??oF("COMMAND_FAILED",`Expected visible but did not match: ${t.selector}`,{selector:t.selector,timeoutMs:t.timeoutMs}),l=await sn(e,t,a);return l||sw(s,a,e.baseReq)}async function sa(e,t,r,a){let n=await sf(e,t.selector,"assertVisible");if(n.visible)return sg(n.response,t.selector,a);let i=sd(e.baseReq,t,n,a);if("return"===i.kind)return i.response;let o=await sn(e,t,n.snapshot);return o||sw(r,n.snapshot,e.baseReq)}async function sn(e,t,r){if(e.baseReq.flags?.platform!=="android")return null;let a=function(e){if(!e)return;let t=oV.get(e);return oV.delete(e),t}(e.scope);return a?"tap"===a.kind?await si(e,t,r,a):await so(e,t,a):null}async function si(e,t,r,a){if(!r)return null;let n=function(e,t,r){var a;let n,i=oz(e.baseReq.flags),o=ep(t),s=oB(t,r.selector,r.options??{},i,o,{promoteTapTarget:!0});if(s.ok)return{ok:!0,target:{kind:"point",point:tS(s.rect)}};let l=oW(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&&(t3({level:"info",phase:"maestro_assert_visible_retry_tap",data:{selector:t.selector,tapSelector:a.selector,originalPoint:a.point,retryTarget:n.target,timeoutMs:5e3}}),(await sl(e,n.target)).ok)?await ss(e,t,"retryTap"):null}async function so(e,t,r){return(t3({level:"info",phase:"maestro_assert_visible_retry_swipe",data:{selector:t.selector,swipePositionals:r.positionals,timeoutMs:5e3}}),(await su(e,r)).ok)?await ss(e,t,"retrySwipe"):null}async function ss(e,t,r){let a={...t,timeoutMs:Math.min(t.timeoutMs,5e3)},n=sp(e.baseReq,a.selector);if(!n)return await sr(e,a);let i=Date.now(),o=await st(e,a,n);return o.ok?(oU(e.scope,a.selector),sg({ok:!0,data:{selector:a.selector,nativeWait:!0,[r]:!0,query:n,response:o.data}},a.selector,i)):await sa(e,a,o,i)}async function sl(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 su(e,t){return await e.invoke({...e.baseReq,command:"swipe",positionals:t.positionals})}function sd(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=sm(oW(e));if(!sh(r))return!1;let a=t.nodes.flatMap(e=>[e.label,e.value,e.identifier]).filter(e=>!!e?.trim()).map(e=>sm(e));return!a.some(e=>e.includes("something went wrong"))&&a.some(e=>e!==r&&!sh(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 sp(e,t){return e.flags?.platform!=="ios"&&e.flags?.platform!=="android"?null:oW(t)}function sc(e,t){let[r,a=String(t.defaultTimeoutMs)]=e;if(!r)return{ok:!1,response:oF("INVALID_ARGS",`${t.command} requires a selector.`)};let n=Number(a);return!Number.isFinite(n)||n<0?{ok:!1,response:oF("INVALID_ARGS",`${t.command} timeout must be a non-negative number.`)}:{ok:!0,selector:r,timeoutMs:n}}async function sf(e,t,r){let a=await oq(e);var n=e,i=t,o=r,s=a;if(!s.ok)return{visible:!1,response:s,infrastructureFailure:!0};let l=oT(s.data);if(!l)return{visible:!1,response:oF("COMMAND_FAILED",`Unable to read snapshot data for ${o}.`),infrastructureFailure:!0};let u=oK(l,i,oz(n.baseReq.flags),ep(l));return u.ok?(oU(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:oF("COMMAND_FAILED",u.message,{selector:i}),infrastructureFailure:!1,snapshot:l}}function sm(e){return e?.trim().toLowerCase().replace(/\u2026/g,"...")??""}function sh(e){return"loading"===e||"loading..."===e}function sg(e,t,r){return e.ok?{ok:!0,data:{selector:t,...e.data,waitedMs:Date.now()-r}}:e}function sw(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=tv(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 sv(e){let t,r=sc(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 sf(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 rB(250)}return n>0?{ok:!0,data:{pass:!0,selector:r.selector,stableSamples:n,waitedMs:Date.now()-a,timeoutMs:r.timeoutMs}}:oF("COMMAND_FAILED",`Expected not visible but matched: ${r.selector}`,{selector:r.selector,timeoutMs:r.timeoutMs,lastResponse:t})}async function sy(e){let t,r,a=Number(e.positionals[0]??15e3);if(!Number.isFinite(a)||a<0)return oF("INVALID_ARGS","waitForAnimationToEnd timeout must be a number.");let n=Date.now();for(;Date.now()-n<a;){let n=await oq(e),i=function(e,t,r){let a=function(e){if(!e.ok)return null;let t=oT(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 rB(250)}return r?.ok===!1?r:{ok:!0,data:{stable:!1,timeoutMs:a}}}async function sA(e){var t,r,a;let[n,i="5000",o="down"]=e.positionals;if(!n)return oF("INVALID_ARGS","scrollUntilVisible requires a selector.");let s=Number(i);if(!Number.isFinite(s)||s<=0)return oF("INVALID_ARGS","scrollUntilVisible timeout must be a positive number.");let l=oW(n),u=Math.max(1,Math.ceil(s/500)),d=null;for(let t=0;t<u;t+=1){let r=await sP(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}`}}:oF("COMMAND_FAILED",`scrollUntilVisible timed out after ${a}ms for selector: ${r}`)}async function sb(e){let[t,r]=e.positionals,a=Number(t),n=Number(r);if(!Number.isFinite(a)||!Number.isFinite(n))return oF("INVALID_ARGS","tapOn percentage point requires numeric x/y values.");let i=await oq(e);if(!i.ok)return i;let o=oT(i.data);if(!o)return oF("COMMAND_FAILED","Unable to read snapshot data for Maestro percentage point tap.");let s=ep(o);if(!s)return oF("COMMAND_FAILED","Unable to resolve screen size for Maestro percentage point tap.");let l=tm(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&&oG(e.scope),u}async function sS(e){let t=await sI(e);if(t)return t;let r=await sD(e);return r.ok?await sN(e,r,r.durationMs):r.response}async function sI(e){let[t,r,a]=e.positionals;if("direction"===t&&("left"===r||"right"===r)&&"android"!==oz(e.baseReq.flags))return await e.invoke({...e.baseReq,command:"gesture",positionals:["swipe",r,...a?[a]:[]]})}async function s_(e){var t,r,a,n;let i,[o,s]=e.positionals;if(!o)return oF("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:oF("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 sL(e,o,l.value??{});if(!t.retry)return t.response;i=t.response,await rB(250)}return r=e,a=o,n=i,r.baseReq.flags?.maestro?.optional===!0?{ok:!0,data:{skipped:!0,optional:!0,selector:a}}:n??oF("COMMAND_FAILED",`tapOn timed out for selector: ${a}`)}async function sk(e){let[t,r="up",a]=e.positionals;if(!t)return oF("INVALID_ARGS","swipe.label requires a label selector.");let n=await sE(e,t,{},"swipe.label",{promoteTapTarget:!1});if(!n.ok)return n.response;let i=function(e,t){let r=tS(e.rect),a=e.frame,n=o$(a?.referenceWidth,e.rect.width),i=o$(a?.referenceHeight,e.rect.height),o=oO,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:tL(r.y-i,o,l)}};case"down":return{ok:!0,start:r,end:{x:r.x,y:tL(r.y+i,o,l)}};case"left":return{ok:!0,start:r,end:{x:tL(r.x-n,o,s),y:r.y}};case"right":return{ok:!0,start:r,end:{x:tL(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 sN(e,i,a):oF("INVALID_ARGS",i.message)}async function sN(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&&oV.set(a,n)),o}async function sD(e){var t;let r=((t=e.scope)?oC.get(t):void 0)??await sx(e);if(!r)return{ok:!1,response:oF("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:oF("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:t_({x:(l=tg({direction:i,amount:.6,referenceWidth:o.referenceWidth,referenceHeight:o.referenceHeight})).x1,y:l.y1},o,8),end:t_({x:l.x2,y:l.y2},o,8),durationMs:s};case"left":case"right":return function(e,t,r,a){let n=sM(r,85,50,15,50),[i,o]="left"===e?[85,15]:[15,85],s=sR(r,t,i,50,o,50);return{ok:!0,start:tm(t,i,n.startY,{marginPx:s}),end:tm(t,o,n.endY,{marginPx:s}),durationMs:a}}(a,t,r,n);default:return{ok:!1,response:oF("INVALID_ARGS","Maestro swipe direction must be UP, DOWN, LEFT, or RIGHT.")}}}(n,r,oz(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:oF("INVALID_ARGS","Maestro percentage swipe requires numeric points.")};let[u,d,p,c]=l,f=sM(r,u,d,p,c),m=sR(r,t,u,d,p,c);return{ok:!0,start:tm(t,u,f.startY,{marginPx:m}),end:tm(t,p,f.endY,{marginPx:m}),durationMs:s}}(n,r,oz(e.baseReq.flags)):{ok:!1,response:oF("INVALID_ARGS","Maestro screen swipe requires direction or percent.")}}async function sx(e){let t=await oq(e);if(t.ok)return ep(oT(t.data))}function sR(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 sM(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 sP(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 sL(e,t,r){let a=oW(t),n=await sO(e,t,r);return n.response.ok?{retry:!1,response:n.response}:n.targetResolved&&a?await sC(e,a):{retry:!0,response:n.response}}async function sO(e,t,r){let a=await sE(e,t,r,"tapOn",{promoteTapTarget:!0});return a.ok?await s$(e,t,a.target,r):{response:a.response,targetResolved:!1}}async function s$(e,t,r,a){let n=tS(r.rect);t3({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)&&oE.delete(o),s=e.scope,l={kind:"tap",selector:t,point:n,options:{...a}},s&&oV.set(s,l)}return{response:i,targetResolved:!0}}async function sC(e,t){let r=await e.invoke({...e.baseReq,command:"find",positionals:[t,"click"],flags:{...e.baseReq.flags,findFirst:!0,postGestureStabilization:!0}});return(t3({level:r.ok?"info":"debug",phase:"maestro_fuzzy_tap_fallback",data:{query:t,ok:r.ok}}),r.ok)?(oG(e.scope),{retry:!1,response:r}):{retry:!0,response:r}}async function sE(e,t,r,a,n){let i=await oq({...e,raw:!0});return function(e,t,r,a,n,i){if(!i.ok)return{ok:!1,response:i};let o=oT(i.data);if(!o)return{ok:!1,response:oF("COMMAND_FAILED",`Unable to read snapshot data for ${a}.`)};let s=ep(o),l=oz(e.baseReq.flags),u=function(e,t,r,a){var n;let i=(n=e.scope)?oE.get(n):void 0;if(!i)return;let o=oK(t,i.selector,r,a);if(o.ok)return t3({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=oB(o,t,r,l,s,{...n,preferredContext:u,requireOnScreen:!0});if(!d.ok){let e=oW(t);if(e){let t=function(e,t,r,a,n={}){let i=function(e,t){let r=rU(t);if(!r)return[];let a=[],n=[];for(let t of e.nodes){let e=[t.label,rR(t),t.identifier,t.value].filter(e=>!!e).map(e=>rU(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=oj({nodes:e.nodes,matches:i,platform:r}),s=oQ(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:oF("ELEMENT_NOT_FOUND",d.message,{selector:t,options:r,command:a})}}(e,t,r,a,n,i)}async function sV(e){switch(e.command){case ib:return await o9(e);case iS:return await sv(e);case iI:return await sF(e);case i_:return await sy(e);case ik:return await sA(e);case iN:return await sS(e);case iD:return await sk(e);case ix:return await s_(e);case iR:return await sb(e);case iA:return function(e){let[r]=e.positionals;if(!r)return oF("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:iK,http:{post:(e,t)=>(function(e,t,r){let a=t1(process.execPath,["-e",iB],{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 oF(e.code,e.message,e.details)}}(e);default:return}}async function sF(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 sq(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 sT(e){let t;for(let r=0;r<=e.maxRetries;r+=1){let a=await sq({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 sU(e){let t=await sG(e,e.control);return t.ok?t.matched?await sK(e):{ok:!0,data:{skipped:!0,condition:e.control.mode,selector:e.control.selector}}:t.response}async function sG(e,t){if("visible"===t.mode)return await sH(e,t);let r=await sB(e,t.selector);return r.ok?{ok:!0,matched:!r.matched}:{ok:!1,response:r.response}}async function sH(e,t){let r=Date.now();for(;;){let a=await sB(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 rB(250)}}async function sB(e,t){var r,a;let n,i=await oq(e);return i.ok?(r=e,a=t,(n=oT(i.data))?{ok:!0,matched:oK(n,a,oz(r.baseReq.flags),ep(n)).ok}:{ok:!1,response:oF("COMMAND_FAILED","Unable to read snapshot data for runFlow.when.")}):{ok:!1,response:i}}async function sK(e){let t=await sq({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 sj(e){let{req:t,sessionName:r,action:a,scope:n,filePath:i,line:o,step:s,tracePath:l,invoke:u}=e,d=rI(a,n,{file:i,line:o}),p=Date.now();sJ(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 sz({req:t,sessionName:r,resolved:d,scope:n,line:o,step:s,invoke:u,invokeReplayAction:e=>sj({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 sJ(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 sz(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,t8(t,{...n.flags??{}})),p={token:r.token,session:a,flags:d,runtime:n.runtime,meta:r.meta,internal:r.internal},c=await sW({control:n.replayControl,baseReq:p,line:o,step:s,invoke:l,invokeReplayAction:u})??await sV({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&&r_(i,e)}return c}async function sW(e){let{control:t,baseReq:r,line:a,step:n,invoke:i,invokeReplayAction:o}=e;if(t){switch(t.kind){case"retry":return await sT({actions:t.actions,maxRetries:t.maxRetries,line:a,step:n,invokeReplayAction:o});case"maestroRunFlowWhen":return await sU({baseReq:r,control:t,line:a,step:n,invoke:i,invokeReplayAction:o})}return t}}function sJ(e,r){e&&t.appendFileSync(e,`${JSON.stringify(r)}
|
|
31
|
+
`)}async function sY(e){let{req:a,sessionName:n,logPath:i,sessionStore:s,tracePath:u,invoke:d}=e,p=a.positionals?.[0];if(!p)return U("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=eN.expandHome(p,a.meta?.cwd);let e=t.readFileSync(c,"utf8"),o=e.trimStart()[0];if("{"===o||"["===o)return U("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=ok[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,{...rp(ra(a?.replayShellEnv)),...rd(ro(a?.replayEnv))})}),updateUnsupportedMessage:"replay -u is not supported for compat flow input. Convert to .ad first, then update that replay file."}:{...rr(e),metadata:ru(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 U("INVALID_ARGS",$.updateUnsupportedMessage);if(a.flags?.replayUpdate===!0&&C.env&&Object.keys(C.env).length>0)return U("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(s3(t.flags)||s3(t.runtime))return!0}return!1}(V))return U("INVALID_ARGS","replay -u does not yet preserve ${VAR} substitutions. Resolve or inline the variables before running with -u.");let q=rS({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:rp(ra(a.flags?.replayShellEnv)),cliEnv:rd(ro(a.flags?.replayEnv))}),T=a.flags?.replayUpdate===!0,G=u??s.get(n)?.trace?.outPath,B=[],K=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=H();i&&e6({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=rG(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=sZ(s,n),a=await sj({req:E,sessionName:n,action:t,scope:q,filePath:c,line:F[e]??0,step:e+1,tracePath:G,invoke:d});if(B.push(...s0(s,n,r)),a.ok){sQ(a).forEach(e=>f.add(e));continue}if(sQ(a).forEach(e=>f.add(e)),!T){return g=a,w=t,v=e,y=c,A=[...f],b=B,sX(g,w,v,y,A,rN(b))}let o=await oD({action:t,sessionName:n,logPath:i,sessionStore:s});if(!o){return S=a,I=t,_=e,k=c,N=[...f],D=B,sX(S,I,_,k,N,rN(D))}V[e]=o;let l=sZ(s,n);if(a=await sj({req:E,sessionName:n,action:o,scope:q,filePath:c,line:F[e]??0,step:e+1,tracePath:G,invoke:d}),B.push(...s0(s,n,l)),!a.ok){return sQ(a).forEach(e=>f.add(e)),x=a,R=o,M=e,P=c,L=[...f],O=B,sX(x,R,M,P,L,rN(O))}sQ(a).forEach(e=>f.add(e)),K+=1}T&&K>0&&rb(c,V,s.get(n));let j=rN(B);return{ok:!0,data:{replayed:V.length,healed:K,session:n,artifactPaths:[...f],...j?{snapshotDiagnostics:j}:{}}}}catch(t){let e=o(t);return U(e.code,e.message,f.size>0?{artifactPaths:[...f]}:void 0)}}function sX(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} (${rV(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 sQ(e){if(!e.ok){let t=e.error.details?.artifactPaths;return Array.isArray(t)?[...new Set(t.filter(e=>"string"==typeof e&&s1(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=>s1(e)))]}function sZ(e,t){return e.get(t)?.snapshotDiagnostics?.samples.length??0}function s0(e,t,r){return e.get(t)?.snapshotDiagnostics?.samples.slice(r)??[]}function s1(e){try{return t.statSync(e).isFile()}catch{return!1}}function s3(e){return"string"==typeof e?e.includes("${"):Array.isArray(e)?e.some(s3):!!e&&"object"==typeof e&&Object.values(e).some(s3)}async function s2(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=rj(l.device.platform),d=o?r.join(o,`recording${u}`):rz(l.device.platform);s4(s,{type:"video_recording_start",session:a,videoPath:d}),t3({phase:"replay_test_video_recording_start",data:{session:a,videoPath:d}});let p=await rK({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 s4(s,{type:"video_recording_start_failed",session:a,videoPath:d,errorCode:p.error.code}),p;let c=Date.now();return await rB(1e3),s4(s,{type:"video_preroll_done",session:a,durationMs:Date.now()-c,requestedDurationMs:1e3}),t3({phase:"replay_test_video_recording_preroll_done",durationMs:Date.now()-c,data:{session:a,requestedDurationMs:1e3}}),p}async function s5(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;s4(i,{type:"video_tail_start",session:r,requestedDurationMs:3e3});let s=Date.now();await rB(3e3);let l=Date.now(),u=await rK({req:{token:t.token,session:r,command:"record",positionals:["stop"],flags:{},meta:t.meta},sessionName:r,sessionStore:n,logPath:a});return sQ(u).forEach(e=>o.add(e)),s4(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}),t3({phase:"replay_test_video_recording_stop",durationMs:Date.now()-l,data:{session:r,ok:u.ok,tailDurationMs:l-s}}),u}function s4(e,t){oi(e,{...t,ts:new Date().toISOString()})}async function s8(e){let{req:t,sessionName:r,logPath:a,sessionStore:n,leaseRegistry:i,invoke:o}=e;return"replay"===t.command?await sY({req:t,sessionName:r,logPath:a,sessionStore:n,invoke:o}):"test"===t.command?await ow({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 s2(e)}}(m);return await sY({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 s2(m);return r&&!r.ok?r:(t=await o(e),d&&sQ(t).forEach(e=>d.add(e)),t)}})},finalizeAttempt:async({sessionName:e,artifactPaths:r,artifactsDir:i,tracePath:o})=>await s5({req:t,sessionName:e,logPath:a,sessionStore:n,artifactsDir:i,tracePath:o,artifactPaths:r}),cleanupSession:async e=>{n.get(e)&&await nt({req:{token:t.token,session:e,command:"close",positionals:[],flags:{},meta:t.meta},sessionName:e,logPath:a,sessionStore:n,leaseRegistry:i})}}):null}function s6(e,t){var r;e.push(t),e6({type:"command",status:"progress",message:[tR(r=t),...ty(r)].join("\n")})}async function s7(e,t){let{device:r,metroPort:a,shouldProbeMetro:n,androidAdbExecutor:i}=t;if("android"!==r.platform||!n)return;let o=tU(r,i);s6(e,await s9(o,r.id,a))}async function s9(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 le(e,t){let{device:r,targetApp:a,session:n}=t;if(a)try{let t=await lt(r,a);if(!t)return void s6(e,{id:"target-app",status:"info",summary:`Target app installation checks are not supported for ${te(r)}.`,evidence:{requested:a,platform:te(r)}});s6(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);s6(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 ${te(r)} --all`,evidence:{code:t.code,message:t.message}})}}async function lt(e,t){if("android"===e.platform){let{listAndroidApps:r}=await import("./3340.js"),a=lr(t,(await r(e,"all")).map(e=>({id:e.package,name:e.name})));return a?.id}if(to(e)||e7(e)){let{listIosApps:r}=await import("./apps.js"),a=lr(t,(await r(e,"all")).map(e=>({id:e.bundleId,name:e.name})));return a?.id}}function lr(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 la(e,t,r){var a,n,i,o,l,u;let d,p=(a=t,n=r,ei({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 ln(p),r=(i=t.devices,o=p,i.filter(e=>ti(e,o,{includeExplicitSelectors:!0})));return s6(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 ${li(t)} devices found; ${r.slice(0,2).map(e=>`${lo(e.platform)} inventory failed: ${e.message}`).join("; ")}.`:`No ${li(t)} devices found.`;let i=e.filter(e=>!0===e.booted).length,o=`${e.length} ${li(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=te(t),a=r.get(e)??{available:0,booted:0};a.available+=1,!0===t.booted&&(a.booted+=1),r.set(e,a)}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;s6(e,(r=a,{id:`device-${r.platform}`,status:"warn",summary:`${lo(r.platform)} device inventory could not be read: ${r.message}`,hint:r.hint??`Check the ${lo(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 s6(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 ln(e){if(e.platform)return{devices:await ek(e),failures:[]};let t=[],r=[];for(let a of p)try{t.push(...await ek({...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 li(e){let t=e.platform?lo(e.platform):"local";return e.target?`${t} ${e.target}`:t}function lo(e){return"ios"===e?"iOS":"macos"===e?"macOS":"android"===e?"Android":"linux"===e?"Linux":"web"===e?"web":"Apple"}async function ls(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 ll(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 ll(e,t,r){try{return await (r.resolveProcessInfo??lu)(e,t)}catch{return}}async function lu(e,t){var r;if("127.0.0.1"!==(r=e)&&"localhost"!==r&&"::1"!==r&&"0.0.0.0"!==r)return;let a=await ld(t);if(void 0!==a)return{pid:a,cwd:await lp(a)}}async function ld(e){let t=await t0("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 lp(e){let t=await t0("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 lc=["daemonBaseUrl","tenant","runId","leaseId","leaseProvider"],lf=["provider","providerSessionId","providerApp","providerOsVersion","providerProject","providerBuild","providerSessionName","awsProjectArn","awsDeviceArn","awsAppArn","awsRegion","awsInteractionMode"];function lm(e){return"string"==typeof e&&e.trim().length>0?e.trim():void 0}async function lh(e,t){"android"===t?s6(e,await lg()):("ios"===t||"macos"===t||"apple"===t)&&s6(e,await lw())}async function lg(){var e,t,r;let a=process.env.ANDROID_HOME||process.env.ANDROID_SDK_ROOT,n=await lv(a),i=await ly("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 lw(){var e,t;let r=await ly("xcodebuild",["-version"]);return r?{id:"toolchain",status:(e={selectedPath:await ly("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 lv(e){if(!e)return"unknown";try{return await i(r.join(e,"licenses","android-sdk-license")),"accepted"}catch{return"missing"}}async function ly(e,t){try{let r=await t0(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 lA(e){var t,a,n,i;let o,s,l,{req:u,sessionName:d,sessionStore:p,androidAdbExecutor:c}=e;if(u.command!==rY.doctor)return null;let f=p.get(d),m=(s=rW(u.meta?.cwd),l=lm(u.flags?.targetApp)??f?.appBundleId,{targetApp:l,metroHost:lm(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)s6(e,r)}(g,{id:"agent-device",status:"pass",summary:`agent-device ${rX()} using ${h}`,evidence:{version:rX(),stateDir:h}},...function(e,t={}){var r;let a,n=(r=e,Object.keys(a={...Object.fromEntries([...lc,...lf].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 ${te(r.device)}`: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 lI(g,m);let w=await la(g,u,f);await lh(g,f?.device.platform??w?.platform);let v=await lb({androidAdbExecutor:c,checks:g,inventory:w,options:m,session:f});return lI(g,m,{device:v,includeMetro:!0,inventory:w})}async function lb(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];s6(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:te(e),id:e.id,name:e.name}))}})}(t,r,a.targetApp);return o&&await lS(t,{androidAdbExecutor:i,device:o,options:a,session:n}),a.shouldProbeMetro&&s6(t,await ls(a.metroHost,a.metroPort,a.kind)),o}async function lS(e,t){let{androidAdbExecutor:r,device:a,options:n,session:i}=t;await le(e,{device:a,session:i,targetApp:n.targetApp}),await s7(e,{androidAdbExecutor:r,device:a,metroPort:n.metroPort,shouldProbeMetro:n.shouldProbeMetro})}function lI(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?te(r.device):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 l_(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 U("INVALID_ARGS","prepare requires a subcommand: ios-runner");let w=h.get(f),v=c.flags??{},y=ae(rY.prepare,w,v);if(y)return y;let A=await ar({session:w,flags:v,ensureReady:!0});if(!tn(A.platform))return U("UNSUPPORTED_OPERATION","prepare ios-runner is only supported on Apple runner platforms");let b=Date.now(),S=await ec(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),{...tl({req:t,logPath:a,traceLogPath:r?.trace?.outPath}),cleanStaleBundles:!0,buildTimeoutMs:p,healthTimeoutMs:p,prepareDeadline:tz.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:te(s),deviceId:s.id,deviceName:s.name,kind:s.kind,durationMs:l,...u,message:`Prepared Apple runner: ${s.name}`})}}async function lk(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=ae(i,u,d);if(p)return p;let c=await ar({session:u,flags:d,ensureReady:!0}),m=Q(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;tF(n,e,t,i,h??{},{positionals:s??o}),e!==u&&n.set(r,e)}return{ok:!0,data:h??{}}}async function lN(e){let{req:t,sessionName:r,logPath:a,sessionStore:n}=e,i=n.get(r),o=t.flags??{},s=ae(rY.clipboard,i,o);if(s)return s;let l=(t.positionals?.[0]??"").toLowerCase();if("read"!==l&&"write"!==l)return U("INVALID_ARGS","clipboard requires a subcommand: read or write");let u=await ar({session:i,flags:o,ensureReady:!0}),d=Q(rY.clipboard,u);if(d)return d;let p=await f(u,rY.clipboard,t.positionals??[],t.flags?.out,{...e_(a,t.flags,i?.appBundleId,i?.trace?.outPath)});return tF(n,i,t,t.command,p??{}),{ok:!0,data:{platform:te(u),...p??{}}}}async function lD(e){let{req:t,sessionName:r,logPath:a,sessionStore:n,leaseRegistry:i=new eE,leaseLifecycleProvider:o,invoke:s,invokeReplayAction:l,androidAdbExecutor:u}=e;if(t.command===rY.doctor)return await lA({req:t,sessionName:r,sessionStore:n,androidAdbExecutor:u});if("inventory"===S(t.command))return await ns({req:t,sessionName:r,sessionStore:n});if("runtime"===t.command)return await aO({req:t,sessionName:r,sessionStore:n});if("state"===S(t.command))return await nc({req:t,sessionName:r,logPath:a,sessionStore:n});if(t.command===rY.clipboard)return await lN({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"!==(t.flags??{}).platform?await lk({req:t,sessionName:r,logPath:a,sessionStore:n,command:rY.keyboard,positionals:t.positionals??[]}):U("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 ir({req:t,sessionName:r,sessionStore:n,androidAdbExecutor:u});if(t.command===rY.prepare)return await l_({req:t,sessionName:r,logPath:a,sessionStore:n});if(t.command===rY.install||t.command===rY.reinstall)return await ni({req:t,command:t.command,sessionName:r,sessionStore:n,deployOps:t.command===rY.install?nn:na});if(t.command===rJ.installSource)return await r3({req:t,sessionName:r,sessionStore:n});if(t.command===rJ.releaseMaterializedPaths)return await r7({req:t});if(t.command===rY.push){let e,i=t.positionals?.[0]?.trim(),o=t.positionals?.[1]?.trim();return i&&o?await lk({req:t,sessionName:r,logPath:a,sessionStore:n,command:rY.push,positionals:[i,"file"===(e=e$(o,{subject:"Push payload",cwd:t.meta?.cwd,expandPath:(e,t)=>eN.expandHome(e,t)})).kind?e.path:e.text],recordPositionals:[i,o]}):U("INVALID_ARGS","push requires <bundle|package> <payload.json|inline-json>")}return t.command===rY.triggerAppEvent?await lk({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 aW(e.device,r,e.appBundleId,aj)??e.appBundleId:e.appBundleId;return{...e,appBundleId:a}}}):t.command===rY.open?await a4({req:t,sessionName:r,logPath:a,sessionStore:n}):"replay"===S(t.command)?await s8({req:t,sessionName:r,logPath:a,sessionStore:n,leaseRegistry:i,invoke:l??s}):t.command===rY.batch?await no(t,r,s):t.command===rY.close?await nt({req:t,sessionName:r,logPath:a,sessionStore:n,leaseRegistry:i,leaseLifecycleProvider:o}):null}export{rQ as session_namespaceObject};
|