agent-device 0.21.34 → 0.21.35
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.34.apk → agent-device-android-ime-helper-0.21.35.apk} +0 -0
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.35.apk.sha256 +1 -0
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.34.manifest.json → agent-device-android-ime-helper-0.21.35.manifest.json} +4 -4
- package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.34.apk → agent-device-android-snapshot-helper-0.21.35.apk} +0 -0
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.35.apk.sha256 +1 -0
- package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.34.manifest.json → agent-device-android-snapshot-helper-0.21.35.manifest.json} +7 -7
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Keyboard.swift +27 -18
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextInputProbe.swift +26 -7
- package/dist/src/agent-browser-provider.js +1 -1
- package/dist/src/agent-device-client.js +1 -1
- package/dist/src/ai-sdk.d.ts +1 -1
- package/dist/src/alert.js +1 -1
- package/dist/src/android-adb.d.ts +1 -1
- package/dist/src/app-backend.js +1 -1
- package/dist/src/app-launch.js +1 -1
- package/dist/src/app-lifecycle.js +1 -1
- package/dist/src/app-log-reconnect.js +1 -1
- package/dist/src/app-log-runtime2.js +2 -2
- package/dist/src/app-log-session-resource.js +1 -1
- package/dist/src/app-resolution.js +2 -2
- package/dist/src/app-state-runtime.d.ts +1 -1
- package/dist/src/apple-runner-platform.js +1 -1
- package/dist/src/application-lifecycle-interaction.js +1 -1
- package/dist/src/artifact-download.js +1 -1
- package/dist/src/back-mode.js +1 -1
- package/dist/src/cli-config.js +1 -1
- package/dist/src/cli-help.js +3 -2
- package/dist/src/cli.js +2 -2
- package/dist/src/client-types.d.ts +17 -4
- package/dist/src/cloud-artifacts.d.ts +2 -2
- package/dist/src/command-metadata.js +41 -41
- package/dist/src/command-schema.js +3 -1
- package/dist/src/command-tools.js +1 -1
- package/dist/src/composed-inventory-gateways.js +1 -1
- package/dist/src/composite-resource-admission.js +1 -1
- package/dist/src/connection-runtime.js +1 -1
- package/dist/src/connection.js +5 -5
- package/dist/src/contract.d.ts +2 -1
- package/dist/src/contracts.d.ts +1 -1
- package/dist/src/daemon-client-lease-beat.js +1 -1
- package/dist/src/daemon-client.js +2 -2
- package/dist/src/daemon-command-registry.js +1 -1
- package/dist/src/daemon-composition.js +1 -1
- package/dist/src/daemon-policy-file.js +1 -1
- package/dist/src/debug-symbols-facade.js +1 -1
- package/dist/src/destination-tunnel-dialer.js +27 -0
- package/dist/src/device-claim-recovery.js +1 -1
- package/dist/src/device-claims.js +1 -1
- package/dist/src/device-input-state.d.ts +1 -1
- package/dist/src/device-readiness-runtime.js +1 -1
- package/dist/src/device-selection-resolver.js +1 -1
- package/dist/src/device.js +1 -1
- package/dist/src/discovery.js +1 -1
- package/dist/src/doctor-facade.js +1 -1
- package/dist/src/durable-resource.js +1 -1
- package/dist/src/explicit-session-resolution.js +1 -1
- package/dist/src/find.js +1 -1
- package/dist/src/generic.js +1 -1
- package/dist/src/gesture-admission.js +1 -1
- package/dist/src/gesture-plan-types.d.ts +1 -1
- package/dist/src/gesture-runtime.js +1 -1
- package/dist/src/human-control.js +1 -1
- package/dist/src/index.d.ts +1 -1
- package/dist/src/instance-client.js +1 -1
- package/dist/src/interaction.js +1 -1
- package/dist/src/interaction2.js +1 -1
- package/dist/src/interactor.js +5 -5
- package/dist/src/interactor4.js +1 -1
- package/dist/src/interactors.js +1 -1
- package/dist/src/internal/bin.js +1 -1
- package/dist/src/inventory2.js +1 -1
- package/dist/src/ios-client.js +4 -4
- package/dist/src/launch-confirmation.js +1 -1
- package/dist/src/lease-context.js +1 -1
- package/dist/src/lease-registry-scope.js +1 -1
- package/dist/src/lease.js +1 -1
- package/dist/src/leased-recording-retention.js +1 -1
- package/dist/src/legacy.js +1 -1
- package/dist/src/limrun.d.ts +6 -1
- package/dist/src/local-interactor-operation-set.js +1 -1
- package/dist/src/log-stream.js +2 -28
- package/dist/src/mechanics.js +1 -1
- package/dist/src/metro.d.ts +1 -1
- package/dist/src/network-har.js +2 -0
- package/dist/src/open-target-resolution.js +1 -1
- package/dist/src/perf-facade.js +1 -1
- package/dist/src/perf-target.js +1 -1
- package/dist/src/platform-runtime-daemon-services.js +1 -1
- package/dist/src/platform-runtime-open-target.js +1 -1
- package/dist/src/platform-runtime-operation-host.js +3 -3
- package/dist/src/platform-runtime-runtime-hints.js +1 -1
- package/dist/src/platform-runtime-unavailable.js +1 -1
- package/dist/src/platform-runtime.js +1 -1
- package/dist/src/platform-runtime2.js +1 -1
- package/dist/src/plugin-inventory.js +1 -1
- package/dist/src/provider-device-runtime.d.ts +1 -1
- package/dist/src/provider-plugin.d.ts +1 -1
- package/dist/src/proxy.js +2 -2
- package/dist/src/react-native.js +1 -1
- package/dist/src/record-runtime-response.js +1 -1
- package/dist/src/record-runtime.js +1 -1
- package/dist/src/record-trace.js +1 -1
- package/dist/src/registry.js +1 -1
- package/dist/src/replay-maestro-backend.js +3 -3
- package/dist/src/replay-script-selection.js +1 -1
- package/dist/src/replay.d.ts +1 -1
- package/dist/src/request-runtime-binding.js +1 -1
- package/dist/src/result-serialization.js +2 -1
- package/dist/src/runner-client.js +1 -1
- package/dist/src/runner-dev-tools-security.js +1 -1
- package/dist/src/runner-device-readiness.js +1 -1
- package/dist/src/runner-retention.js +1 -1
- package/dist/src/runner-selector-query.js +1 -1
- package/dist/src/runner-startup-transport.js +1 -1
- package/dist/src/runner.js +1 -1
- package/dist/src/runtime-admission.js +1 -1
- package/dist/src/runtime-deployment.js +1 -1
- package/dist/src/runtime-session.js +1 -1
- package/dist/src/runtime.js +2 -2
- package/dist/src/runtime3.js +4 -4
- package/dist/src/runtime4.js +1 -1
- package/dist/src/runtime5.js +1 -1
- package/dist/src/runtime6.js +1 -1
- package/dist/src/runtime7.js +1 -1
- package/dist/src/runtime8.js +1 -1
- package/dist/src/runtime9.js +1 -1
- package/dist/src/screen-recording-resource-recovery.js +1 -1
- package/dist/src/screen-recording-session-resource.js +1 -1
- package/dist/src/screen-recording-transport.js +1 -1
- package/dist/src/screenshot-density.js +1 -1
- package/dist/src/screenshot-runtime.js +1 -1
- package/dist/src/sdk-batch-runner.js +2 -2
- package/dist/src/sdk-batch.js +2 -2
- package/dist/src/sdk-contracts.d.ts +4 -1
- package/dist/src/sdk-device.js +1 -1
- package/dist/src/sdk-finders.d.ts +1 -1
- package/dist/src/sdk-remote-config.d.ts +8 -1
- package/dist/src/sdk-remote-config.js +1 -1
- package/dist/src/sdk-selectors.d.ts +1 -1
- package/dist/src/selector-runtime.js +1 -1
- package/dist/src/server-startup.js +1 -1
- package/dist/src/server.js +1 -1
- package/dist/src/session-artifact-paths.js +1 -1
- package/dist/src/session-device-resolution.js +1 -1
- package/dist/src/session-open.js +1 -1
- package/dist/src/session-runtime.js +1 -1
- package/dist/src/session-selector.js +1 -1
- package/dist/src/session-store.js +1 -1
- package/dist/src/session2.js +4 -4
- package/dist/src/settle-observation-capture.js +1 -1
- package/dist/src/simctl.js +1 -1
- package/dist/src/simulator-boot.js +1 -1
- package/dist/src/snapshot-diagnostics.js +1 -1
- package/dist/src/snapshot-runtime-binding.js +1 -1
- package/dist/src/snapshot-runtime-capture-input.js +1 -1
- package/dist/src/snapshot-runtime.js +1 -1
- package/dist/src/snapshot.js +1 -1
- package/dist/src/src.js +1 -1
- package/dist/src/src3.js +4 -4
- package/dist/src/src4.js +1 -1
- package/dist/src/src9.js +1 -1
- package/dist/src/store.js +1 -1
- package/dist/src/telephony-runtime.js +1 -1
- package/dist/src/touch-runtime2.js +1 -1
- package/dist/src/transport.js +2 -2
- package/dist/src/tv-remote-runtime.js +1 -1
- package/dist/src/tv-remote.js +1 -1
- package/dist/src/type-text-runtime.js +1 -1
- package/package.json +1 -1
- package/server.json +2 -2
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.34.apk.sha256 +0 -1
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.34.apk.sha256 +0 -1
- package/dist/src/session-capture-binding.js +0 -1
- package/dist/src/session-teardown.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{i as e,t}from"./rolldown-runtime.js";import{H as n,Q as r,R as i,V as a,b as o,s,tt as c}from"./sdk-contracts.js";import{ut as l}from"./tv-remote.js";import{
|
|
1
|
+
import{i as e,t}from"./rolldown-runtime.js";import{H as n,Q as r,R as i,V as a,b as o,s,tt as c}from"./sdk-contracts.js";import{ut as l}from"./tv-remote.js";import{M as u,a as d}from"./sdk-batch-runner.js";import{a as f}from"./snapshot-diagnostics.js";import{a as p,i as m}from"./snapshot-private-evidence.js";import{K as h}from"./back-mode.js";import{_t as g,bt as _,rt as v}from"./sdk-io.js";import"./diagnostics.js";import{Kr as y,On as b,Tr as x,Yr as S,di as C,gi as w,jn as T,mi as E,qr as ee,ri as te,vi as ne,xi as re}from"./sdk-batch.js";import{a as ie,i as ae,o as oe,r as se}from"./vars.js";import{t as ce}from"./interaction-error.js";import"./command.js";import{i as le}from"./rect-center.js";import"./gesture-plan.js";import{t as ue}from"./touch-reference-frame.js";import{t as de}from"./png-worker-client.js";import{a as fe}from"./ios-snapshot-engine.js";import{createHash as pe}from"node:crypto";import me,{promises as he}from"node:fs";import ge from"node:os";import D from"node:path";import{fileURLToPath as _e}from"node:url";import{setTimeout as ve}from"node:timers/promises";import ye from"node:vm";function O(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function be(e){return e.trim().toLowerCase().replaceAll(/\s+/g,` `)}function xe(e){return[e.label,e.value,e.identifier].find(e=>typeof e==`string`&&e.length>0)?.trim()??``}function Se(e){let t={version:2,platform:e.platform??null,target:e.target??null,runtimeHints:e.runtimeHints??null,initialStaticEnv:e.initialStaticEnv,steps:e.steps};return pe(`sha256`).update(x(t),`utf8`).digest(`hex`)}function Ce(e={},t={}){let n={...t},r=we(e),a=[],o,s=0,c;return{get values(){return l()},get generation(){return s},get observation(){return c?.generation===s?c:void 0},enter(e={}){let t=u(e);return a.push(t),o=void 0,()=>{if(a.pop()!==t)throw new i(`COMMAND_FAILED`,`Maestro environment scopes were left out of order.`);o=void 0}},merge(e){r={...r,...e},o=void 0},replaceOutput(e){let t={};for(let[e,n]of Object.entries(r))e===`output`||e.startsWith(`output.`)||(t[e]=n);Object.assign(t,e),r=t,o=void 0},recordObservation(e){if(e.generation!==s)throw new i(`COMMAND_FAILED`,`Maestro observation generation ${e.generation} does not match ${s}.`);c=e},invalidateObservation(){s+=1,c=void 0},resolve(e){return Te(e,l())},resolveDeferred(e){return Te(e,l(),new Set,!1)}};function l(){return o||(o={...a.reduce((e,t)=>({...e,...t}),{...r}),...n},o)}function u(e){let t=we(e),r={};for(let[e,i]of Object.entries(t))r[e]=Te(i,{...l(),...t,...r,...n},new Set,!1);return r}}function we(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,String(t)]))}function Te(e,t,n=new Set,r=!0){let a=e.replaceAll(/\$\{([A-Za-z_][A-Za-z0-9_.]*)\}/g,(e,a)=>{if(!Object.hasOwn(t,a)){if(!r)return e;throw new i(`INVALID_ARGS`,`Maestro variable "${a}" is not defined.`)}if(n.has(a)){if(!r)return e;throw new i(`INVALID_ARGS`,`Maestro variable "${a}" has a cyclic reference.`)}return Te(t[a],t,new Set([...n,a]),r)});return r&&Ee(a),a}function Ee(e){for(let t of e.matchAll(/\$\{[^{}]*\}/g))if(!De(t[0]))throw new i(`INVALID_ARGS`,`Maestro interpolation "${t[0]}" is unresolved or unsupported.`)}function De(e){return/^\$\{\s*maestro\.platform\s*(?:==|!=)\s*(['"]).*\1(?:\s*(?:&&|\|\|).*)?\s*\}$/.test(e)}var k=t((e=>{let t=Symbol.for(`yaml.alias`),n=Symbol.for(`yaml.document`),r=Symbol.for(`yaml.map`),i=Symbol.for(`yaml.pair`),a=Symbol.for(`yaml.scalar`),o=Symbol.for(`yaml.seq`),s=Symbol.for(`yaml.node.type`),c=e=>!!e&&typeof e==`object`&&e[s]===t,l=e=>!!e&&typeof e==`object`&&e[s]===n,u=e=>!!e&&typeof e==`object`&&e[s]===r,d=e=>!!e&&typeof e==`object`&&e[s]===i,f=e=>!!e&&typeof e==`object`&&e[s]===a,p=e=>!!e&&typeof e==`object`&&e[s]===o;function m(e){if(e&&typeof e==`object`)switch(e[s]){case r:case o:return!0}return!1}function h(e){if(e&&typeof e==`object`)switch(e[s]){case t:case r:case a:case o:return!0}return!1}e.ALIAS=t,e.DOC=n,e.MAP=r,e.NODE_TYPE=s,e.PAIR=i,e.SCALAR=a,e.SEQ=o,e.hasAnchor=e=>(f(e)||m(e))&&!!e.anchor,e.isAlias=c,e.isCollection=m,e.isDocument=l,e.isMap=u,e.isNode=h,e.isPair=d,e.isScalar=f,e.isSeq=p})),Oe=t((e=>{var t=k();let n=Symbol(`break visit`),r=Symbol(`skip children`),i=Symbol(`remove node`);function a(e,n){let r=l(n);t.isDocument(e)?o(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):o(null,e,r,Object.freeze([]))}a.BREAK=n,a.SKIP=r,a.REMOVE=i;function o(e,r,a,s){let c=u(e,r,a,s);if(t.isNode(c)||t.isPair(c))return d(e,s,c),o(e,c,a,s);if(typeof c!=`symbol`){if(t.isCollection(r)){s=Object.freeze(s.concat(r));for(let e=0;e<r.items.length;++e){let t=o(e,r.items[e],a,s);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){s=Object.freeze(s.concat(r));let e=o(`key`,r.key,a,s);if(e===n)return n;e===i&&(r.key=null);let t=o(`value`,r.value,a,s);if(t===n)return n;t===i&&(r.value=null)}}return c}async function s(e,n){let r=l(n);t.isDocument(e)?await c(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):await c(null,e,r,Object.freeze([]))}s.BREAK=n,s.SKIP=r,s.REMOVE=i;async function c(e,r,a,o){let s=await u(e,r,a,o);if(t.isNode(s)||t.isPair(s))return d(e,o,s),c(e,s,a,o);if(typeof s!=`symbol`){if(t.isCollection(r)){o=Object.freeze(o.concat(r));for(let e=0;e<r.items.length;++e){let t=await c(e,r.items[e],a,o);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){o=Object.freeze(o.concat(r));let e=await c(`key`,r.key,a,o);if(e===n)return n;e===i&&(r.key=null);let t=await c(`value`,r.value,a,o);if(t===n)return n;t===i&&(r.value=null)}}return s}function l(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function u(e,n,r,i){if(typeof r==`function`)return r(e,n,i);if(t.isMap(n))return r.Map?.(e,n,i);if(t.isSeq(n))return r.Seq?.(e,n,i);if(t.isPair(n))return r.Pair?.(e,n,i);if(t.isScalar(n))return r.Scalar?.(e,n,i);if(t.isAlias(n))return r.Alias?.(e,n,i)}function d(e,n,r){let i=n[n.length-1];if(t.isCollection(i))i.items[e]=r;else if(t.isPair(i))e===`key`?i.key=r:i.value=r;else if(t.isDocument(i))i.contents=r;else{let e=t.isAlias(i)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}e.visit=a,e.visitAsync=s})),ke=t((e=>{var t=k(),n=Oe();let r={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},i=e=>e.replace(/[!,[\]{}]/g,e=>r[e]);var a=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags)}return t}add(t,n){this.atNextDocument&&=(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),!1);let r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case`%TAG`:{if(r.length!==2&&(n(0,`%TAG directive should contain exactly two parts`),r.length<2))return!1;let[e,t]=r;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,r.length!==1)return n(0,`%YAML directive should contain exactly one part`),!1;let[e]=r;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return n(6,`Unsupported YAML version ${e}`,t),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let n=e.slice(2,-1);return n===`!`||n===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),n)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return n===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+i(e.substring(n.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],i=Object.entries(this.tags),a;if(e&&i.length>0&&t.isNode(e.contents)){let r={};n.visit(e.contents,(e,n)=>{t.isNode(n)&&n.tag&&(r[n.tag]=!0)}),a=Object.keys(r)}else a=[];for(let[t,n]of i)(t!==`!!`||n!==`tag:yaml.org,2002:`)&&(!e||a.some(e=>e.startsWith(n)))&&r.push(`%TAG ${t} ${n}`);return r.join(`
|
|
2
2
|
`)}};a.defaultYaml={explicit:!1,version:`1.2`},a.defaultTags={"!!":`tag:yaml.org,2002:`},e.Directives=a})),Ae=t((e=>{var t=k(),n=Oe();function r(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(t)}return!0}function i(e){let t=new Set;return n.visit(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function a(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function o(e,n){let r=[],o=new Map,s=null;return{onAnchor:t=>{r.push(t),s??=i(e);let o=a(n,s);return s.add(o),o},setAnchors:()=>{for(let e of r){let n=o.get(e);if(typeof n==`object`&&n.anchor&&(t.isScalar(n.node)||t.isCollection(n.node)))n.node.anchor=n.anchor;else{let t=Error(`Failed to resolve repeated object (this should not happen)`);throw t.source=e,t}}},sourceObjects:o}}e.anchorIsValid=r,e.anchorNames=i,e.createNodeAnchors=o,e.findNewAnchor=a})),je=t((e=>{function t(e,n,r,i){if(i&&typeof i==`object`){if(Array.isArray(i))for(let n=0,r=i.length;n<r;++n){let r=i[n],a=t(e,i,String(n),r);a===void 0?delete i[n]:a!==r&&(i[n]=a)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let r=i.get(n),a=t(e,i,n,r);a===void 0?i.delete(n):a!==r&&i.set(n,a)}else if(i instanceof Set)for(let n of Array.from(i)){let r=t(e,i,n,n);r===void 0?i.delete(n):r!==n&&(i.delete(n),i.add(r))}else for(let[n,r]of Object.entries(i)){let a=t(e,i,n,r);a===void 0?delete i[n]:a!==r&&(i[n]=a)}}return e.call(n,r,i)}e.applyReviver=t})),Me=t((e=>{var t=k();function n(e,r,i){if(Array.isArray(e))return e.map((e,t)=>n(e,String(t),i));if(e&&typeof e.toJSON==`function`){if(!i||!t.hasAnchor(e))return e.toJSON(r,i);let n={aliasCount:0,count:1,res:void 0};i.anchors.set(e,n),i.onCreate=e=>{n.res=e,delete i.onCreate};let a=e.toJSON(r,i);return i.onCreate&&i.onCreate(a),a}return typeof e==`bigint`&&!i?.keep?Number(e):e}e.toJS=n})),Ne=t((e=>{var t=je(),n=k(),r=Me();e.NodeBase=class{constructor(e){Object.defineProperty(this,n.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:i,maxAliasCount:a,onAnchor:o,reviver:s}={}){if(!n.isDocument(e))throw TypeError(`A document argument is required`);let c={anchors:new Map,doc:e,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof a==`number`?a:100},l=r.toJS(this,``,c);if(typeof o==`function`)for(let{count:e,res:t}of c.anchors.values())o(t,e);return typeof s==`function`?t.applyReviver(s,{"":l},``,l):l}}})),Pe=t((e=>{var t=Ae(),n=Oe(),r=k(),i=Ne(),a=Me(),o=class extends i.NodeBase{constructor(e){super(r.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){if(t?.maxAliasCount===0)throw ReferenceError(`Alias resolution is disabled`);let i;t?.aliasResolveCache?i=t.aliasResolveCache:(i=[],n.visit(e,{Node:(e,t)=>{(r.isAlias(t)||r.hasAnchor(t))&&i.push(t)}}),t&&(t.aliasResolveCache=i));let a;for(let e of i){if(e===this)break;e.anchor===this.source&&(a=e)}return a}toJSON(e,t){if(!t)return{source:this.source};let{anchors:n,doc:r,maxAliasCount:i}=t,o=this.resolve(r,t);if(!o){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}let c=n.get(o);if(c||=(a.toJS(o,null,t),n.get(o)),c?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(i>=0&&(c.count+=1,c.aliasCount===0&&(c.aliasCount=s(r,o,n)),c.count*c.aliasCount>i))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`);return c.res}toString(e,n,r){let i=`*${this.source}`;if(e){if(t.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${i} `}return i}};function s(e,t,n){if(r.isAlias(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(r.isCollection(t)){let r=0;for(let i of t.items){let t=s(e,i,n);t>r&&(r=t)}return r}if(r.isPair(t)){let r=s(e,t.key,n),i=s(e,t.value,n);return Math.max(r,i)}return 1}e.Alias=o})),A=t((e=>{var t=k(),n=Ne(),r=Me();let i=e=>!e||typeof e!=`function`&&typeof e!=`object`;var a=class extends n.NodeBase{constructor(e){super(t.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:r.toJS(this.value,e,t)}toString(){return String(this.value)}};a.BLOCK_FOLDED=`BLOCK_FOLDED`,a.BLOCK_LITERAL=`BLOCK_LITERAL`,a.PLAIN=`PLAIN`,a.QUOTE_DOUBLE=`QUOTE_DOUBLE`,a.QUOTE_SINGLE=`QUOTE_SINGLE`,e.Scalar=a,e.isScalarValue=i})),Fe=t((e=>{var t=Pe(),n=k(),r=A();function i(e,t,n){if(t){let e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}function a(e,a,o){if(n.isDocument(e)&&(e=e.contents),n.isNode(e))return e;if(n.isPair(e)){let t=o.schema[n.MAP].createNode?.(o.schema,null,o);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:s,onAnchor:c,onTagObj:l,schema:u,sourceObjects:d}=o,f;if(s&&e&&typeof e==`object`){if(f=d.get(e),f)return f.anchor??(f.anchor=c(e)),new t.Alias(f.anchor);f={anchor:null,node:null},d.set(e,f)}a?.startsWith(`!!`)&&(a=`tag:yaml.org,2002:`+a.slice(2));let p=i(e,a,u.tags);if(!p){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new r.Scalar(e);return f&&(f.node=t),t}p=e instanceof Map?u[n.MAP]:Symbol.iterator in Object(e)?u[n.SEQ]:u[n.MAP]}l&&(l(p),delete o.onTagObj);let m=p?.createNode?p.createNode(o.schema,e,o):typeof p?.nodeClass?.from==`function`?p.nodeClass.from(o.schema,e,o):new r.Scalar(e);return a?m.tag=a:p.default||(m.tag=p.tag),f&&(f.node=m),m}e.createNode=a})),Ie=t((e=>{var t=Fe(),n=k(),r=Ne();function i(e,n,r){let i=r;for(let e=n.length-1;e>=0;--e){let t=n[e];if(typeof t==`number`&&Number.isInteger(t)&&t>=0){let e=[];e[t]=i,i=e}else i=new Map([[t,i]])}return t.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:new Map})}let a=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done;e.Collection=class extends r.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(t=>n.isNode(t)||n.isPair(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(a(e))this.add(t);else{let[r,...a]=e,o=this.get(r,!0);if(n.isCollection(o))o.addIn(a,t);else if(o===void 0&&this.schema)this.set(r,i(this.schema,a,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${a}`)}}deleteIn(e){let[t,...r]=e;if(r.length===0)return this.delete(t);let i=this.get(t,!0);if(n.isCollection(i))return i.deleteIn(r);throw Error(`Expected YAML collection at ${t}. Remaining path: ${r}`)}getIn(e,t){let[r,...i]=e,a=this.get(r,!0);return i.length===0?!t&&n.isScalar(a)?a.value:a:n.isCollection(a)?a.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!n.isPair(t))return!1;let r=t.value;return r==null||e&&n.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[t,...r]=e;if(r.length===0)return this.has(t);let i=this.get(t,!0);return n.isCollection(i)?i.hasIn(r):!1}setIn(e,t){let[r,...a]=e;if(a.length===0)this.set(r,t);else{let e=this.get(r,!0);if(n.isCollection(e))e.setIn(a,t);else if(e===void 0&&this.schema)this.set(r,i(this.schema,a,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${a}`)}}},e.collectionFromPath=i,e.isEmptyPath=a})),Le=t((e=>{let t=e=>e.replace(/^(?!$)(?: $)?/gm,`#`);function n(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}e.indentComment=n,e.lineComment=(e,t,r)=>e.endsWith(`
|
|
3
3
|
`)?n(r,t):r.includes(`
|
|
4
4
|
`)?`
|
|
@@ -112,6 +112,6 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
|
|
|
112
112
|
`)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
|
|
113
113
|
`,e)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(this.onKeyLine=!1,t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){u(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&this.type!==`seq-item-ind`,i=[];if(r&&t.sep&&!t.value){let n=[];for(let r=0;r<t.sep.length;++r){let i=t.sep[r];switch(i.type){case`newline`:n.push(r);break;case`space`:break;case`comment`:i.indent>e.indent&&(n.length=0);break;default:n.length=0}}n.length>=2&&(i=t.sep.splice(n[1]))}switch(this.type){case`anchor`:case`tag`:r||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`explicit-key-ind`:!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):r||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case`map-value-ind`:if(t.explicitKey){if(!t.sep){if(a(t.start,`newline`))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let e=l(t.start);this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:null,sep:[this.sourceToken]}]})}}else if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(a(t.sep,`map-value-ind`))this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(s(t.key)&&!a(t.sep,`newline`)){let e=l(t.start),n=t.key,r=t.sep;r.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:n,sep:r}]})}else i.length>0?t.sep=t.sep.concat(i,this.sourceToken):t.sep.push(this.sourceToken)}else t.sep?t.value||r?e.items.push({start:i,key:null,sep:[this.sourceToken]}):a(t.sep,`map-value-ind`)?this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);r||t.value?(e.items.push({start:i,key:n,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(n):(Object.assign(t,{key:n,sep:[]}),this.onKeyLine=!0);return}default:{let r=this.startBlockValue(e);if(r){if(r.type===`block-seq`){if(!t.explicitKey&&t.sep&&!a(t.sep,`newline`)){yield*this.pop({type:`error`,offset:this.offset,message:`Unexpected block-seq-ind on same line with key`,source:this.source});return}}else n&&e.items.push({start:i});this.stack.push(r);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){u(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case`anchor`:case`tag`:if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case`seq-item-ind`:if(this.indent!==e.indent)break;t.value||a(t.start,`seq-item-ind`)?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let t=this.startBlockValue(e);if(t){this.stack.push(t);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type===`flow-error-end`){let e;do yield*this.pop(),e=this.peek(1);while(e?.type===`flow-collection`)}else if(e.end.length===0){switch(this.type){case`comma`:case`explicit-key-ind`:!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case`map-value-ind`:!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case`space`:case`comment`:case`newline`:case`anchor`:case`tag`:!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:n,sep:[]}):t.sep?this.stack.push(n):Object.assign(t,{key:n,sep:[]});return}case`flow-map-end`:case`flow-seq-end`:e.end.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let t=this.peek(2);if(t.type===`block-map`&&(this.type===`map-value-ind`&&t.indent===e.indent||this.type===`newline`&&!t.items[t.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type===`map-value-ind`&&t.type!==`flow-collection`){let n=l(c(t));d(e);let r=e.end.splice(1,e.end.length);r.push(this.sourceToken);let i={type:`block-map`,offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let e=this.source.indexOf(`
|
|
114
114
|
`)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
|
|
115
|
-
`,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=l(c(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=l(c(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}}})),Ht=t((e=>{var t=Pt(),n=_t(),r=vt(),i=He(),a=k(),o=Bt(),s=Vt();function c(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new o.LineCounter||null,prettyErrors:t}}function l(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=Array.from(l.compose(o.parse(e)));if(a&&i)for(let t of u)t.errors.forEach(r.prettifyError(e,i)),t.warnings.forEach(r.prettifyError(e,i));return u.length>0?u:Object.assign([],{empty:!0},l.streamInfo())}function u(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=null;for(let t of l.compose(o.parse(e),!0,e.length))if(!u)u=t;else if(u.options.logLevel!==`silent`){u.errors.push(new r.YAMLParseError(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return a&&i&&(u.errors.forEach(r.prettifyError(e,i)),u.warnings.forEach(r.prettifyError(e,i))),u}function d(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let a=u(e,n);if(!a)return null;if(a.warnings.forEach(e=>i.warn(a.options.logLevel,e)),a.errors.length>0){if(a.options.logLevel!==`silent`)throw a.errors[0];a.errors=[]}return a.toJS(Object.assign({reviver:r},n))}function f(e,t,r){let i=null;if(typeof t==`function`||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r==`string`&&(r=r.length),typeof r==`number`){let e=Math.round(r);r=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=r??t??{};if(!e)return}return a.isDocument(e)&&!i?e.toString(r):new n.Document(e,i,r).toString(r)}e.parse=d,e.parseAllDocuments=l,e.parseDocument=u,e.stringify=f})),j=t((e=>{var t=Pt(),n=_t(),r=ht(),i=vt(),a=Pe(),o=k(),s=Ge(),c=A(),l=qe(),u=Ye();Rt();var d=zt(),f=Bt(),p=Vt(),m=Ht(),h=Oe();e.Composer=t.Composer,e.Document=n.Document,e.Schema=r.Schema,e.YAMLError=i.YAMLError,e.YAMLParseError=i.YAMLParseError,e.YAMLWarning=i.YAMLWarning,e.Alias=a.Alias,e.isAlias=o.isAlias,e.isCollection=o.isCollection,e.isDocument=o.isDocument,e.isMap=o.isMap,e.isNode=o.isNode,e.isPair=o.isPair,e.isScalar=o.isScalar,e.isSeq=o.isSeq,e.Pair=s.Pair,e.Scalar=c.Scalar,e.YAMLMap=l.YAMLMap,e.YAMLSeq=u.YAMLSeq,e.Lexer=d.Lexer,e.LineCounter=f.LineCounter,e.Parser=p.Parser,e.parse=m.parse,e.parseAllDocuments=m.parseAllDocuments,e.parseDocument=m.parseDocument,e.stringify=m.stringify,e.visit=h.visit,e.visitAsync=h.visitAsync}))();function M(e,t){return Ut(e?.range?.[0],t)}function Ut(e,t){let n=t.lineCounter.linePos(e!==void 0&&e>=0?e:0).line;return t.sourcePath===void 0?{line:n}:{path:t.sourcePath,line:n}}function Wt(e){return`${e.path===void 0?``:`${e.path}:`}line ${e.line}`}function N(e,t,n){throw new i(`INVALID_ARGS`,`${e} (${Wt(M(t,n))})`)}function P(e,t,n){(0,j.isMap)(e)||N(`Maestro ${t} expects a map.`,e,n);let r=[];for(let i of e.items){let e=i.key;(0,j.isScalar)(e)||N(`Maestro ${t} map keys must be strings.`,void 0,n);let a=e.value;typeof a!=`string`&&typeof a!=`number`&&typeof a!=`boolean`&&N(`Maestro ${t} map keys must be strings.`,e,n),i.value!==null&&!(0,j.isNode)(i.value)&&N(`Maestro ${t} values must be YAML nodes.`,e,n),r.push({key:String(a),keyNode:e,value:i.value})}return r}function Gt(e,t,n){return(0,j.isSeq)(e)||N(`Maestro ${t} expects a list.`,e,n),e.items}function Kt(e,t,n){return Gt(e,t,n).map((e,r)=>H(e,`${t}[${r}]`,n))}function F(e,t,n,r){let i=new Set(n),a=new Set;for(let n of e)a.has(n.key)&&N(`Maestro ${t} contains duplicate field "${n.key}".`,n.keyNode,r),a.add(n.key),i.has(n.key)||N(`Maestro ${t} field "${n.key}" is not supported.`,n.keyNode,r)}function I(e,t){return e.some(e=>e.key===t)}function L(e,t){return e.find(e=>e.key===t)?.value}function R(e,t,n){return I(e,t)?n(L(e,t)):void 0}function z(e,t,n){return O({optional:R(e,`optional`,e=>Jt(e,`${t}.optional`,n))})}function B(e){return e===null||(0,j.isScalar)(e)&&e.value===null}function V(e,t,n){if(e==null)return null;(0,j.isScalar)(e)||N(`Maestro ${t} expects a scalar value.`,e,n);let r=e.value;if(r===null||typeof r==`string`||typeof r==`number`||typeof r==`boolean`)return r;N(`Maestro ${t} contains an unsupported scalar value.`,e,n)}function H(e,t,n){let r=V(e,t,n);return typeof r!=`string`&&N(`Maestro ${t} expects a string.`,e,n),r}function qt(e,t,n){let r=V(e,t,n);if(r!==null)return typeof r!=`string`&&N(`Maestro ${t} expects a string.`,e,n),r}function Jt(e,t,n){let r=V(e,t,n);if(r!==null)return typeof r!=`boolean`&&N(`Maestro ${t} expects a boolean.`,e,n),r}const Yt=/^\$\{[A-Za-z_][A-Za-z0-9_.]*\}$/,Xt=new Set([`allow`,`deny`,`unset`,`always`,`inuse`,`never`,`limited`]),Zt=/^-?\d+(\.\d+)?$/,Qt=/^-?\d+$/,$t={"tapOn.index":{integer:!0,nonNegative:!0},"tapOn.repeat":{integer:!0,positive:!0},"tapOn.delay":{integer:!0,nonNegative:!0},"doubleTapOn.delay":{integer:!0,nonNegative:!0},eraseText:{integer:!0,positive:!0},"eraseText.charactersToErase":{integer:!0,positive:!0},"extendedWaitUntil.timeout":{nonNegative:!0},"scrollUntilVisible.timeout":{nonNegative:!0},waitForAnimationToEnd:{nonNegative:!0},"waitForAnimationToEnd.timeout":{nonNegative:!0},"swipe.duration":{nonNegative:!0},"repeat.times":{integer:!0,nonNegative:!0},"retry.maxRetries":{integer:!0,nonNegative:!0}};function en(e){return e.positive&&e.integer?`a positive integer`:e.positive?`a positive number`:e.nonNegative&&e.integer?`a non-negative integer`:e.nonNegative?`a non-negative finite number`:e.integer?`an integer`:`a finite number`}function tn(e,t,n,r,i){let a=`Maestro ${t} expects ${en(i)} or a variable expression.`;Number.isFinite(e)||N(a,n,r),Math.abs(e)>2**53-1&&N(a,n,r),i.integer&&!Number.isSafeInteger(e)&&N(a,n,r),i.nonNegative&&e<0&&N(a,n,r),i.positive&&e<=0&&N(a,n,r)}function nn(e,t,n,r,i){if(typeof e==`number`)return tn(e,t,n,r,i),e;if(typeof e==`string`){if(Yt.test(e))return e;if((i.integer?Qt:Zt).test(e)){let a=Number(e);return tn(a,t,n,r,i),a}}N(`Maestro ${t} expects ${en(i)} or a variable expression.`,n,r)}function U(e,t,n,r=$t[t]??{}){let i=V(e,t,n);if(i!==null)return nn(i,t,e,n,r)}function rn(e,t,n){let r=$t[t]??{},i=V(e,t,n);return i===null&&N(`Maestro ${t} expects ${en(r)} or a variable expression.`,e,n),nn(i,t,e,n,r)}function an(e,t,n){let r=V(e,t,n);return r===null&&N(`Maestro ${t} requires a condition.`,e,n),typeof r==`string`&&r.includes("${")&&!Yt.test(r)&&N(`Maestro ${t} only supports a literal value or a bare \${VAR} lookup; JavaScript expressions are not supported — compute it in a runScript and reference \${output.x}.`,e,n),r}function on(e,t,n){let r=P(e,t,n),i={};for(let e of r){let r=V(e.value,`${t}.${e.key}`,n);r===null&&N(`Maestro ${t}.${e.key} expects a string, number, or boolean.`,e.value,n),i[e.key]=r}return i}function sn(e,t){try{return new gn(ln(cn(e)),t).parse()}catch(e){if(e instanceof i&&e.code===`INVALID_ARGS`)return;throw e}}function cn(e){let t=e.trim();return t.startsWith("${")&&t.endsWith(`}`)?t.slice(2,-1).trim():t}function ln(e){let t=[],n=0;for(;n<e.length;){let r=e.slice(n),a=/^\s+/.exec(r)?.[0].length??0;if(a>0){n+=a;continue}let o=un(r);if(!o)throw new i(`INVALID_ARGS`,`Unsupported runFlow.when.true expression near "${r.slice(0,24)}".`);t.push(o.value),n+=o.length}return t}function un(e){return dn(e)??fn(e)??pn(e)??mn(e)??hn(e)}function dn(e){return e.startsWith(`maestro.platform`)?{value:{type:`platform`},length:16}:null}function fn(e){let t=/^(==|!=|&&|\|\|)/.exec(e)?.[1];return t?{value:{type:`operator`,value:t},length:t.length}:null}function pn(e){let t=e[0];return t===`(`||t===`)`?{value:{type:`paren`,value:t},length:1}:null}function mn(e){let t=/^(['"])(.*?)\1/.exec(e);return t?{value:{type:`string`,value:t[2]??``},length:t[0].length}:null}function hn(e){let t=/^(true|false)\b/.exec(e)?.[1];return t?{value:{type:`boolean`,value:t===`true`},length:t.length}:null}var gn=class{index=0;tokens;platform;constructor(e,t){this.tokens=e,this.platform=t}parse(){let e=this.parseOr();if(this.peek())throw new i(`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 i(`INVALID_ARGS`,`Incomplete runFlow.when.true expression.`);if(e.type===`boolean`)return this.index+=1,e.value;if(e.type===`paren`&&e.value===`(`){this.index+=1;let e=this.parseOr();if(!this.consumeParen(`)`))throw new i(`INVALID_ARGS`,`Unclosed runFlow.when.true parenthesis.`);return e}return this.parsePlatformComparison()}parsePlatformComparison(){this.consumePlatformToken();let e=this.consumeComparisonOperator(),t=this.consumeStringLiteral(),n=this.platform===t.toLowerCase();return e.value===`==`?n:!n}consumePlatformToken(){if(this.peek()?.type!==`platform`)throw new i(`INVALID_ARGS`,`runFlow.when.true supports maestro.platform comparisons.`);this.index+=1}consumeComparisonOperator(){let e=this.peek();if(e?.type!==`operator`||e.value!==`==`&&e.value!==`!=`)throw new i(`INVALID_ARGS`,`runFlow.when.true comparison requires == or !=.`);return this.index+=1,e}consumeStringLiteral(){let e=this.peek();if(e?.type!==`string`)throw new i(`INVALID_ARGS`,`runFlow.when.true comparison requires a string literal.`);return this.index+=1,e.value}consumeOperator(e){let t=this.peek();return t?.type!==`operator`||t.value!==e?!1:(this.index+=1,!0)}consumeParen(e){let t=this.peek();return t?.type!==`paren`||t.value!==e?!1:(this.index+=1,!0)}peek(){return this.tokens[this.index]}};const _n=new Set([``,`false`,`0`,`null`,`undefined`]);function vn(e){return typeof e==`boolean`?e:typeof e==`number`?e!==0&&!Number.isNaN(e):!_n.has(e)}function yn(e){return typeof e==`boolean`||typeof e==`number`||typeof e==`string`?vn(e):typeof e==`bigint`?e!==0n:e!=null}function bn(e){switch(e.kind){case`runFlow`:return!(`include`in e);case`repeat`:case`retry`:return!(`commands`in e);default:return!1}}function xn(e,t){return{...Mn(e,t),source:e.source}}function W(e,t,n){if(e===void 0)return;let r=n??$t[t]??{},a=en(r),o;if(typeof e==`number`)o=e;else{let n=e.trim();if(n===``)throw new i(`INVALID_ARGS`,`Maestro ${t} must be ${a}.`);o=Number(n)}if(!Number.isFinite(o)||Math.abs(o)>2**53-1||r.integer&&!Number.isSafeInteger(o)||r.nonNegative&&o<0||r.positive&&o<=0)throw new i(`INVALID_ARGS`,`Maestro ${t} must be ${a}.`);return o}function Sn(e,t,n,r){return W(e===void 0?t:n.resolve(String(e)),r)}function G(e){if(e?.aborted)throw n()}async function Cn(e,t){if(e.include.kind===`commands`)return{kind:`program`,source:e.source,config:{},commands:e.include.commands};if(!t.loadProgram)throw new i(`INVALID_ARGS`,`Maestro file runFlow requires a program loader.`);return G(t.signal),t.signal?await t.loadProgram(e.include.path,e.source.path,t.signal):await t.loadProgram(e.include.path,e.source.path)}function wn(e,t,n){if(e.include.kind===`file`)return D.resolve(t?D.dirname(t):n,e.include.path)}function Tn(e){return e===void 0?void 0:D.resolve(e)}function En(e,t,n){let r=wn(e,e.source.path,n);if(r&&t.has(r))throw new i(`INVALID_ARGS`,`Maestro runFlow cycle detected at ${r}.`);return r}function Dn(e,t,n,r){let a=e.include.kind===`file`?Tn(t.source.path):void 0,o=new Set([n,a].filter(e=>e!==void 0)),s=[...o].find(e=>r.has(e));if(s)throw new i(`INVALID_ARGS`,`Maestro runFlow cycle detected at ${s}.`);return o.forEach(e=>r.add(e)),o}function On(e,t){if(e.trustedScripts===!1)throw new i(`UNAUTHORIZED`,`Maestro ${t} is not permitted for flows received over the remote daemon surface: node:vm is not a security sandbox, so an untrusted expression can escape to the host.`)}async function kn(e,t,n,r){if(e===void 0)return!0;if(typeof e==`boolean`)return e;let i=An(e,n);if(i!==void 0){let e=sn(i,r.platform);if(e!==void 0)return e;if(!i.includes("${"))return vn(i)}On(r,t);let{evaluateMaestroConditionScript:a}=await import(`./engine-eval-script.js`),o=await a(e,n.values,r.platform,t);return n.replaceOutput(o.outputEnv),yn(o.value)}function An(e,t){try{return t.resolve(e)}catch(e){if(e instanceof i&&e.code===`INVALID_ARGS`)return;throw e}}function jn(e,t){return[...e.visible?[{kind:`visible`,selector:Mn(e.visible,t)}]:[],...e.notVisible?[{kind:`notVisible`,selector:Mn(e.notVisible,t)}]:[]]}function Mn(e,t){return typeof e==`string`?t.resolve(e):Array.isArray(e)?e.map(e=>Mn(e,t)):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,Mn(n,t)])):e}async function Nn(e,t){G(t.signal);let n=Tn(e.source.path),r={options:t,context:Ce(t.defaults,t.env),activeIncludePaths:new Set(n===void 0?[]:[n]),staticallyExecutedControls:0,staticallySkippedControls:0};return{steps:await Pn(e,[],void 0,e.source.path,r),staticallyExecutedControls:r.staticallyExecutedControls,staticallySkippedControls:r.staticallySkippedControls}}async function Pn(e,t,n,r,i){G(i.options.signal);let a=Gn(t,e.config.env),o=e.config.appId??n,s=i.context.enter(e.config.env);try{let t=[...e.config.onFlowStart??[],...e.commands,...e.config.onFlowComplete??[]],n=[];for(let s of t)n.push(...await In(s,a,o,e.source.path??r,i));return n}finally{s()}}async function Fn(e,t,n,r,i){let a=[];for(let o of e)a.push(...await In(o,t,n,r,i));return a}async function In(e,t,n,r,i){G(i.options.signal);let a=Kn(e,r);switch(a.kind){case`runFlow`:{let e=Rn(a,i);if(e===`omit`)return i.staticallySkippedControls+=1,[];let o=await Ln(a,t,n,r,i);return e===`flatten`?(i.staticallyExecutedControls+=1,o):[Un(a,t,n,o)]}case`repeat`:return[Un(a,t,n,await Fn(a.commands,t,n,r,i))];case`retry`:return[Un(a,t,n,await Fn(a.commands,t,n,r,i))];default:return[Hn(a,t,n)]}}async function Ln(e,t,n,r,i){let a=Bn(e,i.context),o=En(a,i.activeIncludePaths,i.options.baseDir),s=await Cn(a,i.options);G(i.options.signal);let c=Dn(a,s,o,i.activeIncludePaths),l=Gn(t,e.env),u=i.context.enter(e.env);try{return await Pn(s,l,n,s.source.path??e.source.path??r,i)}finally{u(),c.forEach(e=>i.activeIncludePaths.delete(e))}}function Rn(e,t){let n=e.when;return n?n.platform!==void 0&&n.platform!==t.options.platform?`omit`:zn(n.true,t)||(n.visible||n.notVisible?`opaque`:`flatten`):`flatten`}function zn(e,t){if(e===!1)return`omit`;if(typeof e!=`string`)return;let n=t.context.resolveDeferred(e);if(Vn(n))return`opaque`;let r=sn(n,t.options.platform);return r===void 0?`opaque`:r?void 0:`omit`}function Bn(e,t){return e.include.kind===`file`?{...e,include:{...e.include,path:t.resolve(e.include.path)}}:e}function Vn(e){return/\$\{[A-Za-z_][A-Za-z0-9_.]*\}/.test(e)}function Hn(e,t,n){return O({kind:`command`,command:e,source:e.source,scopes:t,appId:n})}function Un(e,t,n,r){return O({kind:`opaque`,command:Wn(e),source:e.source,scopes:t,body:r,appId:n})}function Wn(e){switch(e.kind){case`runFlow`:return O({kind:e.kind,source:e.source,when:e.when,label:e.label,...e.include.kind===`file`?{includePath:e.include.path}:{}});case`repeat`:return O({kind:e.kind,source:e.source,times:e.times,while:e.while});case`retry`:return O({kind:e.kind,source:e.source,maxRetries:e.maxRetries})}}function Gn(e,t){return t===void 0?e:[...e,t]}function Kn(e,t){return e.source.path||!t?e:{...e,source:{...e.source,path:t}}}async function qn(e,t){let{steps:n,staticallyExecutedControls:r,staticallySkippedControls:i}=await Nn(e,t),a=Jn(t.runtimeHints),o=O({kind:`maestroReplayPlan`,platform:t.platform,target:t.target,runtimeHints:a,initialStaticEnv:structuredClone({...t.defaults??{},...e.config.env??{},...t.env??{}}),steps:structuredClone(n),total:n.length,compatibility:{staticallyExecutedControls:r,staticallySkippedControls:i}}),s=Se(o);return Yn({...o,digest:s})}function Jn(e){if(!e)return;let t=Object.entries(e).filter(e=>e[1]!==void 0);return t.length===0?void 0:Object.fromEntries(t)}function Yn(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;for(let t of Object.values(e))Yn(t);return Object.freeze(e)}function Xn(e,t={}){let{from:n,planDigest:r}=t;if(n===void 0&&r===void 0)return{allowed:!0,startIndex:0};if(n===void 0||r===void 0)return{allowed:!1,reason:`replay --from requires --plan-digest (and --plan-digest requires --from).`};if(!Number.isInteger(n)||n<1||n>e.total)return{allowed:!1,reason:`replay --from ${n} is out of range for a ${e.total}-step plan.`};if(r!==e.digest)return{allowed:!1,reason:`replay --plan-digest does not match the current plan digest.`};if(n===1)return{allowed:!0,startIndex:0};for(let t=0;t<n-1;t+=1){let n=e.steps[t];if(n.kind===`opaque`)return{allowed:!1,reason:`step ${t+1} is opaque runtime control flow (${n.command.kind}) and cannot be skipped safely.`};if(n.command.kind===`runScript`||n.command.kind===`evalScript`)return{allowed:!1,reason:`step ${t+1} (${n.command.kind}) can produce outputEnv values and cannot be skipped safely.`}}let i=e.steps[n-1];return i.kind===`opaque`?{allowed:!1,reason:`step ${n} is opaque runtime control flow (${i.command.kind}) and cannot be resumed into.`}:{allowed:!0,startIndex:n-1}}function Zn(e,t={}){let n=Xn(e,t);if(!n.allowed)throw new i(`INVALID_ARGS`,n.reason);return n.startIndex}function Qn(e,t){if(!Number.isInteger(t)||t<0||t>e.total)throw new i(`INVALID_ARGS`,`Maestro replay startIndex ${t} is out of range for a ${e.total}-step plan.`);return t}const K={control:{retryMaxRetries:3},command:{retryTapMaxAttempts:2,targetLookupTimeoutMs:17e3,optionalTargetLookupTimeoutMs:7e3,scrollUntilVisibleTimeoutMs:2e4,waitForAnimationToEndTimeoutMs:15e3,waitForAnimationToEndDifferencePercent:.005,longPressDurationMs:3e3,swipeDurationMs:400,repeatDelayMs:100,scrollUntilVisibleSpeed:40,scrollUntilVisiblePercentage:100,eraseTextMaxCharacters:50,androidInputTextCharacterDelayMs:75},observation:{pollIntervalMs:200,defaultSettleAttempts:10},targetSwipe:{nearEdgeFraction:.1,farEdgeFraction:.9},screenSwipe:{nearEdgeFraction:.1,farEdgeFraction:.9,centerFraction:.5,downStartFraction:.2,upStartFraction:{android:.5,ios:.9}},scrollUntilVisibleSwipe:{nearEdgeFraction:.1,farEdgeFraction:.9}};function $n(e){return Math.trunc(1e3*(100-e)/100)+1}const er={assertVisibleTimeoutMs:K.command.targetLookupTimeoutMs,assertNotVisibleTimeoutMs:K.command.targetLookupTimeoutMs,extendedWaitUntilTimeoutMs:K.command.targetLookupTimeoutMs,runFlowConditionTimeoutMs:K.command.optionalTargetLookupTimeoutMs},tr=K.observation.pollIntervalMs*K.observation.defaultSettleAttempts,nr=`maestro-test-failure`;function rr(e,t={}){return new i(`COMMAND_FAILED`,e,{...t,reason:nr})}function ir(e){return e instanceof i&&e.code===`COMMAND_FAILED`&&e.details?.reason===nr}async function ar(e,t){G(t.options.signal);try{return await xr(e,t.context,async()=>await or(e,t))}catch(t){throw Sr(t,e)}}async function or(e,t){if(e.kind===`command`)return await sr(e.command,e.appId,t);await pr(e,t)}async function sr(e,t,n){if(e.kind===`evalScript`)return await ur(e,n);let r=xn(e,n.context);try{return await dr(r,t,n)}catch(e){if(G(n.options.signal),lr(r)&&ir(e)){n.warnings.push(cr(r,e)),n.skipped+=1;return}throw Cr(e,r)}}function cr(e,t){let n=`${e.source.path?`${e.source.path}:`:``}line ${e.source.line}`,r=t instanceof i?t.message:String(t);return`Optional Maestro ${e.kind} skipped at ${n}: ${r}`}function lr(e){return`optional`in e&&e.optional===!0}async function ur(e,t){let{evaluateMaestroEvalScript:n}=await import(`./engine-eval-script.js`);On(t.options,`evalScript`);let r=await n(e.script,t.context.values);t.context.replaceOutput(r),t.executed+=1}async function dr(e,t,n){switch(e.kind){case`assertVisible`:await vr({kind:`visible`,selector:e.target},n.timing.assertVisibleTimeoutMs,n),n.executed+=1;return;case`assertNotVisible`:await vr({kind:`notVisible`,selector:e.target},n.timing.assertNotVisibleTimeoutMs,n),n.executed+=1;return;case`assertTrue`:if(!vn(e.condition))throw rr(`Maestro assertTrue condition was falsy: ${JSON.stringify(e.condition)}`);n.executed+=1;return;case`extendedWaitUntil`:await vr(br(e),W(e.timeout,`extendedWaitUntil.timeout`)??n.timing.extendedWaitUntilTimeoutMs,n),n.executed+=1;return;default:return await fr(e,t,n)}}async function fr(e,t,n){let r=O({command:e,env:n.context.values,appId:t===void 0?void 0:n.context.resolve(t),generation:n.context.generation,invalidateObservation:n.context.invalidateObservation,cachedObservation:n.context.observation,signal:n.options.signal}),i=await n.port.execute(r);return G(n.options.signal),i.observation&&n.context.recordObservation(i.observation),i.outputEnv&&n.context.merge(i.outputEnv),i.artifactPaths?.forEach(e=>n.artifacts.add(e)),n.executed+=1,i}async function pr(e,t){let n=e.command;switch(n.kind){case`runFlow`:if(n.when&&!await _r(n.when,`runFlow.when`,t)){t.skipped+=1;return}t.executed+=1,await mr(e.body,t);return;case`repeat`:t.executed+=1,await hr(e.body,n.times,n.while,t);return;case`retry`:{let r=Math.min(Sn(n.maxRetries,1,t.context,`retry.maxRetries`),K.control.retryMaxRetries);t.executed+=1,await gr(e.body,r,t);return}}}async function mr(e,t){for(let n of e)await ar(n,t)}async function hr(e,t,n,r){let i=t===void 0&&n?1/0:Sn(t,0,r.context,`repeat.times`);for(let t=0;t<i;t+=1){if(await new Promise(e=>setImmediate(e)),G(r.options.signal),n&&!await _r(n,`repeat.while`,r))return;await mr(e,r)}}async function gr(e,t,n){let r;for(let i=0;i<=t;i+=1){G(n.options.signal);try{await mr(e,n);return}catch(t){if(G(n.options.signal),!ir(Tr(t)))throw t;r=Sr(t,e[0])}}throw r||new i(`COMMAND_FAILED`,`Maestro retry commands failed.`)}async function _r(e,t,n){if(e.platform&&e.platform!==n.options.platform||!await kn(e.true,`${t}.true`,n.context,n.options))return!1;for(let t of jn(e,n.context))if(G(n.options.signal),!(await yr(t,n.timing.runFlowConditionTimeoutMs,n)).matched)return!1;return!0}async function vr(e,t,n){if(!(await yr(e,t,n)).matched)throw rr(`Maestro ${e.kind} condition did not match.`)}async function yr(e,t,n){let r={condition:e,timeoutMs:t,generation:n.context.generation,env:n.context.values,...n.context.observation?{cachedObservation:n.context.observation}:{},...n.options.signal?{signal:n.options.signal}:{}},i=await n.port.observe(r);return G(n.options.signal),n.context.recordObservation(i),i}function br(e){if(e.visible)return{kind:`visible`,selector:e.visible};if(e.notVisible)return{kind:`notVisible`,selector:e.notVisible};throw new i(`INVALID_ARGS`,`Maestro extendedWaitUntil requires one condition.`)}async function xr(e,t,n){let r=e.scopes.map(e=>t.enter({...e}));try{return await n()}finally{for(let e=r.length-1;e>=0;--e)r[e]()}}function Sr(e,t){if(wr(e))return e;let n=t?.source??{line:1};return{kind:`maestroPlanStepFailure`,error:Er(e,t?.command),source:n,...t?{command:t.command}:{}}}function Cr(e,t){return{kind:`maestroPlanStepFailure`,error:Er(e,t),source:t.source,command:t}}function wr(e){return!!(e&&typeof e==`object`&&e.kind===`maestroPlanStepFailure`)}function Tr(e){return wr(e)?e.error:e}function Er(e,t){if(!(e instanceof i)||!t||/\bline \d+\b/.test(e.message))return e;let n=t.source.path?`${t.source.path}:`:``;return new i(e.code,`${e.message} (${n}line ${t.source.line})`,e.details)}async function Dr(e,t,n={}){G(n.signal);let r=n.startIndex??0;if(!Number.isInteger(r)||r<0||r>e.total)throw new i(`INVALID_ARGS`,`Maestro replay startIndex ${r} is out of range for a ${e.total}-step plan.`);let a={plan:e,port:t,options:n,context:Ce(n.defaults,n.env?{...n.env}:{}),timing:er,artifacts:new Set,warnings:[],executed:e.compatibility.staticallyExecutedControls,skipped:e.compatibility.staticallySkippedControls};for(let t=r;t<e.steps.length;t+=1)try{await Or(e.steps[t],t,a)}catch(e){throw Tr(e)}return{executed:a.executed,skipped:a.skipped,generation:a.context.generation,artifactPaths:[...a.artifacts],...a.warnings.length>0?{warnings:a.warnings}:{}}}async function Or(e,t,n){G(n.options.signal);let r=n.options.now??Date.now,i=r(),a=n.port.readMetrics?.(),o=n.context.generation,s={command:e.command,source:e.source,generation:o,stepIndex:t+1,stepTotal:n.plan.total};Ar(()=>n.options.observer?.commandStarted?.(s));try{let t=await ar(e,n);G(n.options.signal),Ar(()=>n.options.observer?.commandCompleted?.({...s,durationMs:r()-i,...kr(a,n.port.readMetrics?.()),...t?.data?{data:t.data}:{}}))}catch(t){let o=Sr(t,e);throw Ar(()=>n.options.observer?.commandFailed?.({...s,...o.command?{command:o.command}:{},source:o.source,durationMs:r()-i,...kr(a,n.port.readMetrics?.()),error:o.error,artifactPaths:[...n.artifacts],warnings:[...n.warnings]})),o}}function kr(e,t){return!e||!t?{}:{runtimeMetrics:{hierarchyCaptures:t.hierarchyCaptures-e.hierarchyCaptures,screenshotCaptures:t.screenshotCaptures-e.screenshotCaptures,tapRetries:t.tapRetries-e.tapRetries,settleLatches:t.settleLatches-e.settleLatches,settleTimeouts:t.settleTimeouts-e.settleTimeouts}}}function Ar(e){try{e?.()}catch{}}async function jr(e,t,n={}){let r=Mr(e,n);return await Dr(e,t,{...n,startIndex:r})}function Mr(e,t){return t.from!==void 0||t.planDigest!==void 0?Zn(e,{from:t.from,planDigest:t.planDigest}):Qn(e,t.startIndex??0)}function q(e,t,n){return R(e,`label`,e=>qt(e,`${t}.label`,n))}const J=[`id`,`text`,`enabled`,`selected`,`index`,`childOf`,`below`,`above`,`leftOf`,`rightOf`,`containsChild`,`containsDescendants`],Nr={textKeys:[`id`,`text`],booleanKeys:[`enabled`,`selected`],textAliases:{label:`text`}},Pr={id:(e,t,n,r)=>zr(e,`id`,t,n,r),text:(e,t,n,r)=>zr(e,`text`,t,n,r),enabled:(e,t,n,r)=>Br(e,`enabled`,t,n,r),selected:(e,t,n,r)=>Br(e,`selected`,t,n,r),index:(e,t,n,r)=>{e.index=U(t.value,`${n}.index`,r,{integer:!0,nonNegative:!0})},childOf:(e,t,n,r)=>{e.childOf=Y(t.value,`${n}.childOf`,r)},below:(e,t,n,r)=>{e.below=Y(t.value,`${n}.below`,r)},above:(e,t,n,r)=>{e.above=Y(t.value,`${n}.above`,r)},leftOf:(e,t,n,r)=>{e.leftOf=Y(t.value,`${n}.leftOf`,r)},rightOf:(e,t,n,r)=>{e.rightOf=Y(t.value,`${n}.rightOf`,r)},containsChild:(e,t,n,r)=>{e.containsChild=Y(t.value,`${n}.containsChild`,r)},containsDescendants:(e,t,n,r)=>{e.containsDescendants=Gt(t.value,`${n}.containsDescendants`,r).map(e=>Y(e,`${n}.containsDescendants`,r))},optional:(e,t,n,r)=>Br(e,`optional`,t,n,r)};function Y(e,t,n,r=J){if((0,j.isScalar)(e))return{text:H(e,t,n)};let i=P(e,t,n);return F(i,t,r,n),Fr(i,t,n)}function Fr(e,t,n){e.length===0&&N(`Maestro ${t} selector is empty.`,void 0,n);let r={};for(let i of e){let e=Pr[i.key];e||N(`Maestro ${t} selector field "${i.key}" is not supported.`,i.keyNode,n),e(r,i,t,n)}return Object.keys(r).filter(e=>e!==`optional`).length===0&&N(`Maestro ${t} selector must contain a selector value.`,e[0]?.keyNode,n),r}function Ir(e,t,n,r){let i=M(t,n);if((0,j.isScalar)(e))return{source:i,entries:[],target:Hr(Y(e,r.name,n,r.selectorKeys))};let a=P(e,r.name,n),o=I(a,`point`);if(F(a,r.name,o?r.pointAllowedKeys:r.selectorAllowedKeys,n),o){let e=r.pointConflictingSelectorKeys??r.selectorKeys;return a.some(t=>Vr(t.key,e))&&N(`Maestro ${r.name}.point cannot be combined with a selector.`,t,n),{source:i,entries:a,target:r.parsePoint(L(a,`point`),`${r.name}.point`,n)}}return{source:i,entries:a,target:Hr(Fr(a.filter(e=>Vr(e.key,r.selectorKeys)),r.name,n))}}function Lr(e,t,n){let r=H(e,t,n),i=/^\s*(\d+)\s*,\s*(\d+)\s*$/.exec(r);if(i)return{space:`absolute`,x:Number(i[1]),y:Number(i[2])};let a=/^\s*(\d+)%\s*,\s*(\d+)%\s*$/.exec(r);if(a){let r=Number(a[1]),i=Number(a[2]);return(r>100||i>100)&&N(`Maestro ${t} percentage coordinates must be between 0% and 100%.`,e,n),{space:`percent`,x:r,y:i}}/^\s*\d+(?:\.\d+)?%\s*,\s*\d+(?:\.\d+)?%\s*$/.test(r)&&N(`Maestro ${t} percentage coordinates must be whole numbers.`,e,n),N(`Maestro ${t} expects absolute or percentage coordinates.`,e,n)}function Rr(e,t,n){let r=Lr(e,t,n);return r.space!==`absolute`&&N(`Maestro ${t} only supports absolute coordinates.`,e,n),r}function zr(e,t,n,r,i){let a=qt(n.value,`${r}.${t}`,i);a!==void 0&&(e[t]=a)}function Br(e,t,n,r,i){let a=Jt(n.value,`${r}.${t}`,i);a!==void 0&&(e[t]=a)}function Vr(e,t){return t.includes(e)}function Hr(e){return{space:`target`,selector:e}}function Ur(e,t,n){let r=Ir(e,t,n,{name:`tapOn`,selectorKeys:J,pointConflictingSelectorKeys:J,pointAllowedKeys:[`point`,`retryTapIfNoChange`,`repeat`,`delay`,`optional`,`label`],selectorAllowedKeys:[...J,`retryTapIfNoChange`,`repeat`,`delay`,`optional`,`label`],parsePoint:Lr});if(r.entries.length===0)return{kind:`tapOn`,source:r.source,target:r.target};if(r.target.space!==`target`)return{kind:`tapOn`,source:r.source,target:r.target,...Xr(r.entries,n)};let i=Xr(r.entries,n);return O({kind:`tapOn`,source:r.source,target:r.target,...i})}function Wr(e,t,n){let r=Ir(e,t,n,{name:`doubleTapOn`,selectorKeys:J,pointAllowedKeys:[`point`,`delay`,`optional`,`label`],selectorAllowedKeys:[...J,`delay`,`optional`,`label`],parsePoint:Rr}),i=z(r.entries,`doubleTapOn`,n),a=I(r.entries,`delay`)?U(L(r.entries,`delay`),`doubleTapOn.delay`,n):void 0,o=q(r.entries,`doubleTapOn`,n);return O({kind:`doubleTapOn`,source:r.source,target:r.target,...i,delay:a,label:o})}function Gr(e,t,n){let r=Ir(e,t,n,{name:`longPressOn`,selectorKeys:J,pointAllowedKeys:[`point`,`optional`,`label`],selectorAllowedKeys:[...J,`optional`,`label`],parsePoint:Rr});return O({kind:`longPressOn`,source:r.source,target:r.target,...z(r.entries,`longPressOn`,n),label:q(r.entries,`longPressOn`,n)})}function Kr(e,t,n){let r=M(t,n),i=P(e,`swipe`,n);F(i,`swipe`,[`start`,`end`,`direction`,`duration`,`from`,`label`,`optional`],n);let a=z(i,`swipe`,n),o=q(i,`swipe`,n),s=I(i,`duration`)?U(L(i,`duration`),`swipe.duration`,n):void 0;if(I(i,`start`)||I(i,`end`))return{...qr(i,r,s,t,n),...a,label:o};let c=I(i,`direction`)?Zr(L(i,`direction`),`swipe.direction`,n):void 0;return I(i,`from`)?{...Jr(i,r,c,s,t,n),...a,label:o}:{...Yr(r,c,s,t,n),...a,label:o}}function qr(e,t,n,r,i){I(e,`direction`)&&N(`Maestro swipe cannot combine direction with start/end coordinates.`,r,i),(!I(e,`start`)||!I(e,`end`))&&N(`Maestro swipe requires both start and end coordinates.`,r,i);let a=Lr(L(e,`start`),`swipe.start`,i),o=Lr(L(e,`end`),`swipe.end`,i);return a.space!==o.space&&N(`Maestro swipe start/end must use the same coordinate space.`,r,i),{kind:`swipe`,source:t,gesture:O({kind:`coordinates`,start:a,end:o,duration:n})}}function Jr(e,t,n,r,i,a){return n===void 0&&N(`Maestro target swipe requires direction.`,i,a),{kind:`swipe`,source:t,gesture:O({kind:`target`,from:Y(L(e,`from`),`swipe.from`,a),direction:n,duration:r})}}function Yr(e,t,n,r,i){return t===void 0&&N(`Maestro swipe requires direction, target, or start/end coordinates.`,r,i),{kind:`swipe`,source:e,gesture:O({kind:`screen`,direction:t,duration:n})}}function Xr(e,t){let n=R(e,`retryTapIfNoChange`,e=>Jt(e,`tapOn.retryTapIfNoChange`,t)),r=R(e,`repeat`,e=>rn(e,`tapOn.repeat`,t)),i=R(e,`delay`,e=>U(e,`tapOn.delay`,t)),a=z(e,`tapOn`,t).optional;return O({retryTapIfNoChange:n,repeat:r,delay:i,optional:a,label:q(e,`tapOn`,t)})}function Zr(e,t,n){let r=H(e,t,n).toLowerCase();if(r===`up`||r===`down`||r===`left`||r===`right`)return r;N(`Maestro ${t} must be UP, DOWN, LEFT, or RIGHT.`,e,n)}function Qr(e,t,n,r){let i=M(n,r);if((0,j.isScalar)(t))return{kind:e,source:i,target:Y(t,e,r)};let a=P(t,e,r);F(a,e,[...J,`optional`,`label`],r);let o=z(a,e,r),s=q(a,e,r);return O({kind:e,source:i,target:Fr(a.filter(e=>e.key!==`optional`&&e.key!==`label`),e,r),...o,label:s})}const $r=[...J,`optional`];function ei(e,t,n,r){if(!I(e,t))return;let{optional:i,...a}=Y(L(e,t),n,r,$r);return{selector:a,optional:i}}function ti(e,t,n){let r=ei(e,`visible`,`extendedWaitUntil.visible`,n),i=ei(e,`notVisible`,`extendedWaitUntil.notVisible`,n);return r&&i&&N(`Maestro extendedWaitUntil cannot specify both visible and notVisible.`,t,n),!r&&!i&&N(`Maestro extendedWaitUntil requires visible or notVisible.`,t,n),r?{key:`visible`,selector:r.selector,optional:r.optional}:{key:`notVisible`,selector:i.selector,optional:i.optional}}function ni(e,t,n){let r=M(t,n);if((0,j.isScalar)(e))return{kind:`runScript`,source:r,file:H(e,`runScript`,n)};let i=P(e,`runScript`,n);return F(i,`runScript`,[`file`,`env`],n),I(i,`file`)||N(`Maestro runScript requires a file.`,t,n),O({kind:`runScript`,source:r,file:H(L(i,`file`),`runScript.file`,n),env:I(i,`env`)?on(L(i,`env`),`runScript.env`,n):void 0})}function ri(e,t,n,r){let i=M(t,n);if((0,j.isScalar)(e))return{kind:`runFlow`,source:i,include:{kind:`file`,path:H(e,`runFlow`,n)}};let a=P(e,`runFlow`,n);F(a,`runFlow`,[`file`,`commands`,`env`,`when`,`label`],n);let o=I(a,`file`);return o===I(a,`commands`)&&N(`Maestro runFlow requires exactly one of file or commands.`,t,n),O({kind:`runFlow`,source:i,include:o?{kind:`file`,path:H(L(a,`file`),`runFlow.file`,n)}:{kind:`commands`,commands:r(L(a,`commands`),`runFlow.commands`,n)},env:I(a,`env`)?on(L(a,`env`),`runFlow.env`,n):void 0,when:I(a,`when`)?oi(L(a,`when`),`runFlow.when`,n):void 0,label:q(a,`runFlow`,n)})}function ii(e,t,n,r){let i=M(t,n),a=P(e,`repeat`,n);F(a,`repeat`,[`times`,`commands`,`while`],n);let o=I(a,`while`)?oi(L(a,`while`),`repeat.while`,n):void 0;return!I(a,`times`)&&!o&&N(`Maestro repeat requires times or while.`,t,n),I(a,`commands`)||N(`Maestro repeat requires commands.`,t,n),O({kind:`repeat`,source:i,times:I(a,`times`)?rn(L(a,`times`),`repeat.times`,n):void 0,while:o,commands:r(L(a,`commands`),`repeat.commands`,n)})}function ai(e,t,n,r){let i=M(t,n),a=P(e,`retry`,n);F(a,`retry`,[`maxRetries`,`commands`],n),I(a,`commands`)||N(`Maestro retry requires commands.`,t,n);let o=I(a,`maxRetries`)?rn(L(a,`maxRetries`),`retry.maxRetries`,n):void 0;return O({kind:`retry`,source:i,commands:r(L(a,`commands`),`retry.commands`,n),maxRetries:o})}function oi(e,t,n){let r=P(e,t,n);return F(r,t,[`platform`,`visible`,`notVisible`,`true`],n),r.length===0&&N(`Maestro ${t} cannot be empty.`,e,n),O({platform:R(r,`platform`,e=>ci(e,n,`${t}.platform`)),visible:R(r,`visible`,e=>Y(e,`${t}.visible`,n)),notVisible:R(r,`notVisible`,e=>Y(e,`${t}.notVisible`,n)),true:R(r,`true`,e=>si(e,n,`${t}.true`))})}function si(e,t,n){let r=V(e,n,t);if(typeof r==`boolean`||typeof r==`string`)return r;N(`Maestro ${n} expects a boolean or expression string.`,e,t)}function ci(e,t,n){let r=H(e,n,t).toLowerCase();if(r===`android`||r===`ios`||r===`web`)return r;N(`Maestro ${n} expects Android, iOS, or Web.`,e,t)}function li(e,t,n){return Gt(e,t,n).map(e=>ui(e,n))}function ui(e,t){if((0,j.isScalar)(e))return typeof e.value!=`string`&&N(`Maestro command names must be strings.`,e,t),di(e.value,e,t);(0,j.isMap)(e)||N(`Maestro commands must be a scalar or one-key map.`,e,t);let n=P(e,`command`,t);n.length!==1&&N(`Maestro command maps must contain exactly one command.`,e,t);let r=n[0];return pi(r.key,r.value,e,t)}function di(e,t,n){return pi(e,null,t,n)}const fi={launchApp:mi,tapOn:Ur,doubleTapOn:Wr,longPressOn:Gr,inputText:hi,eraseText:gi,openLink:_i,assertVisible:(e,t,n)=>Qr(`assertVisible`,e,t,n),assertNotVisible:(e,t,n)=>Qr(`assertNotVisible`,e,t,n),assertTrue:vi,extendedWaitUntil:yi,takeScreenshot:bi,scroll:xi,scrollUntilVisible:Si,swipe:Kr,hideKeyboard:Ci,pressKey:wi,back:Ti,waitForAnimationToEnd:Ei,stopApp:Di,killApp:Oi,setPermissions:ki,clearState:Mi,runScript:ni,evalScript:Ni,runFlow:(e,t,n)=>ri(e,t,n,li),repeat:(e,t,n)=>ii(e,t,n,li),retry:(e,t,n)=>ai(e,t,n,li)};Object.keys(fi);function pi(e,t,n,r){let i=fi[e];return i||N(`Maestro command "${e}" is not supported.`,n,r),i(t,n,r)}function mi(e,t,n){let r=M(t,n);if(B(e))return{kind:`launchApp`,source:r};if((0,j.isScalar)(e))return{kind:`launchApp`,source:r,appId:H(e,`launchApp`,n)};let i=P(e,`launchApp`,n);return F(i,`launchApp`,[`appId`,`stopApp`,`clearState`,`permissions`,`arguments`,`launchArguments`],n),O({kind:`launchApp`,source:r,appId:R(i,`appId`,e=>qt(e,`launchApp.appId`,n)),stopApp:R(i,`stopApp`,e=>Jt(e,`launchApp.stopApp`,n)),clearState:R(i,`clearState`,e=>Jt(e,`launchApp.clearState`,n)),permissions:R(i,`permissions`,e=>Ai(e,n,`launchApp`)),arguments:R(i,`arguments`,e=>Pi(e,`launchApp.arguments`,n)),launchArguments:R(i,`launchArguments`,e=>Pi(e,`launchApp.launchArguments`,n))})}function hi(e,t,n){let r=M(t,n);if((0,j.isScalar)(e))return{kind:`inputText`,source:r,text:H(e,`inputText`,n)};let i=P(e,`inputText`,n);return F(i,`inputText`,[`text`,`label`],n),I(i,`text`)||N(`Maestro inputText requires text.`,t,n),O({kind:`inputText`,source:r,text:H(L(i,`text`),`inputText.text`,n),label:q(i,`inputText`,n)})}function gi(e,t,n){let r=M(t,n);if(B(e))return{kind:`eraseText`,source:r};if((0,j.isScalar)(e))return{kind:`eraseText`,source:r,charactersToErase:rn(e,`eraseText`,n)};let i=P(e,`eraseText`,n);return F(i,`eraseText`,[`charactersToErase`],n),O({kind:`eraseText`,source:r,charactersToErase:I(i,`charactersToErase`)?U(L(i,`charactersToErase`),`eraseText.charactersToErase`,n):void 0})}function _i(e,t,n){let r=M(t,n);if((0,j.isScalar)(e))return{kind:`openLink`,source:r,link:H(e,`openLink`,n)};let i=P(e,`openLink`,n);return F(i,`openLink`,[`link`],n),{kind:`openLink`,source:r,link:H(L(i,`link`),`openLink.link`,n)}}function vi(e,t,n){let r=M(t,n);if(B(e)&&N(`Maestro assertTrue requires condition.`,t,n),(0,j.isScalar)(e))return{kind:`assertTrue`,source:r,condition:an(e,`assertTrue`,n)};let i=P(e,`assertTrue`,n);F(i,`assertTrue`,[`condition`,`optional`,`label`],n),I(i,`condition`)||N(`Maestro assertTrue requires condition.`,t,n);let a=an(L(i,`condition`),`assertTrue.condition`,n),o=z(i,`assertTrue`,n),s=q(i,`assertTrue`,n);return O({kind:`assertTrue`,source:r,condition:a,...o,label:s})}function yi(e,t,n){let r=P(e,`extendedWaitUntil`,n);F(r,`extendedWaitUntil`,[`visible`,`notVisible`,`timeout`,`optional`,`label`],n);let i=z(r,`extendedWaitUntil`,n),a=q(r,`extendedWaitUntil`,n),o=ti(r,t,n),s=I(r,`timeout`)?U(L(r,`timeout`),`extendedWaitUntil.timeout`,n):void 0,c=i.optional===!0||o.optional===!0||void 0,l={kind:`extendedWaitUntil`,source:M(t,n),timeout:s,optional:c,label:a};return l[o.key]=o.selector,O(l)}function bi(e,t,n){return{kind:`takeScreenshot`,source:M(t,n),path:H(e,`takeScreenshot`,n)}}function xi(e,t,n){return B(e)||N(`Maestro scroll does not accept options yet.`,t,n),{kind:`scroll`,source:M(t,n)}}function Si(e,t,n){let r=M(t,n);if((0,j.isScalar)(e))return{kind:`scrollUntilVisible`,source:r,element:Y(e,`scrollUntilVisible.element`,n)};let i=P(e,`scrollUntilVisible`,n);F(i,`scrollUntilVisible`,[`element`,`direction`,`timeout`,`optional`,`label`],n);let a=z(i,`scrollUntilVisible`,n),o=q(i,`scrollUntilVisible`,n),s=ei(i,`element`,`scrollUntilVisible.element`,n);s||N(`Maestro scrollUntilVisible requires element.`,t,n);let c=I(i,`direction`)?Zr(L(i,`direction`),`scrollUntilVisible.direction`,n):void 0,l=I(i,`timeout`)?U(L(i,`timeout`),`scrollUntilVisible.timeout`,n):void 0,u=a.optional===!0||s.optional===!0||void 0;return O({kind:`scrollUntilVisible`,source:r,element:s.selector,direction:c,timeout:l,optional:u,label:o})}function Ci(e,t,n){return B(e)||N(`Maestro hideKeyboard does not accept options.`,t,n),{kind:`hideKeyboard`,source:M(t,n)}}function wi(e,t,n){let r=H(e,`pressKey`,n).toLowerCase();return r!==`back`&&r!==`enter`&&r!==`return`&&r!==`home`&&N(`Maestro pressKey "${r}" is not supported.`,e,n),{kind:`pressKey`,source:M(t,n),key:r}}function Ti(e,t,n){return B(e)||N(`Maestro back does not accept options.`,t,n),{kind:`back`,source:M(t,n)}}function Ei(e,t,n){let r=M(t,n);if(B(e))return{kind:`waitForAnimationToEnd`,source:r};if((0,j.isScalar)(e))return O({kind:`waitForAnimationToEnd`,source:r,timeout:U(e,`waitForAnimationToEnd`,n)});let i=P(e,`waitForAnimationToEnd`,n);return F(i,`waitForAnimationToEnd`,[`timeout`],n),O({kind:`waitForAnimationToEnd`,source:r,timeout:I(i,`timeout`)?U(L(i,`timeout`),`waitForAnimationToEnd.timeout`,n):void 0})}function Di(e,t,n){let r=M(t,n);return B(e)?{kind:`stopApp`,source:r}:{kind:`stopApp`,source:r,appId:H(e,`stopApp`,n)}}function Oi(e,t,n){let r=M(t,n);return B(e)?{kind:`killApp`,source:r}:{kind:`killApp`,source:r,appId:H(e,`killApp`,n)}}function ki(e,t,n){let r=M(t,n),i=P(e,`setPermissions`,n);F(i,`setPermissions`,[`appId`,`permissions`,`optional`,`label`],n),I(i,`permissions`)||N(`Maestro setPermissions requires permissions.`,t,n);let a=R(i,`appId`,e=>qt(e,`setPermissions.appId`,n)),o=Ai(L(i,`permissions`),n),s=z(i,`setPermissions`,n),c=q(i,`setPermissions`,n);return O({kind:`setPermissions`,source:r,appId:a,permissions:o,...s,label:c})}function Ai(e,t,n=`setPermissions`){let r=P(e,`${n}.permissions`,t);r.length===0&&N(`Maestro ${n}.permissions requires at least one permission.`,e,t);let i={};for(let e of r)i[e.key]=ji(e,t,n);return i}function ji(e,t,n=`setPermissions`){let r=`${n}.permissions.${e.key}`,i=V(e.value,r,t);typeof i!=`string`&&N(`Maestro ${r} expects a string.`,e.value,t);let a=i.toLowerCase();if(Xt.has(a))return a;if(Yt.test(i))return i;i.includes("${")&&N(`Maestro ${r} only supports allow|deny|unset (plus always|inuse|never|limited for location/photos) or a bare \${VAR} lookup; JavaScript expressions are not supported.`,e.value,t),N(`Maestro ${r} expects allow|deny|unset (plus always|inuse|never|limited for location/photos) or a bare \${VAR} lookup.`,e.value,t)}function Mi(e,t,n){let r=M(t,n);return B(e)?{kind:`clearState`,source:r}:{kind:`clearState`,source:r,appId:H(e,`clearState`,n)}}function Ni(e,t,n){return{kind:`evalScript`,source:M(t,n),script:H(e,`evalScript`,n)}}function Pi(e,t,n){if((0,j.isSeq)(e))return{kind:`list`,values:Gt(e,t,n).map((e,r)=>{let i=V(e,`${t}[${r}]`,n);return i===null&&N(`${t}[${r}] expects a scalar value.`,e,n),i})};if((0,j.isMap)(e))return{kind:`map`,values:on(e,t,n)};let r=V(e,t,n);return r===null&&N(`${t} expects a scalar, list, or map.`,e,n),{kind:`scalar`,value:r}}function Fi(e,t={}){let n=new j.LineCounter,r=O({lineCounter:n,sourcePath:t.sourcePath}),a=(0,j.parseAllDocuments)(e,{lineCounter:n});for(let e of a)if(e.errors.length>0){let t=e.errors[0],n=t?.message??`Invalid Maestro YAML flow.`,a=Ut(t?.pos[0],r);throw new i(`INVALID_ARGS`,`Invalid Maestro YAML flow: ${n} (${Wt(a)})`)}let o=a.map(e=>e.contents).filter(e=>e!==null);o.length===0&&N(`Maestro flow is empty.`,void 0,r);let s,c;o.length===1&&(0,j.isSeq)(o[0])?c=o[0]:o.length===2&&(0,j.isMap)(o[0])&&(0,j.isSeq)(o[1])?(s=o[0],c=o[1]):N(`Maestro flow must contain a command list, optionally preceded by one config document.`,o[0],r);let l=s?Ii(s,r):{};return{kind:`program`,source:M(s??c,r),config:l,commands:li(c,`commands`,r)}}function Ii(e,t){let n=P(e,`flow config`,t);return F(n,`flow config`,[`name`,`appId`,`tags`,`env`,`onFlowStart`,`onFlowComplete`],t),O({name:R(n,`name`,e=>qt(e,`name`,t)),appId:R(n,`appId`,e=>qt(e,`appId`,t)),tags:R(n,`tags`,e=>Kt(e,`tags`,t)),env:R(n,`env`,e=>on(e,`env`,t)),onFlowStart:R(n,`onFlowStart`,e=>li(e,`onFlowStart`,t)),onFlowComplete:R(n,`onFlowComplete`,e=>li(e,`onFlowComplete`,t))})}function Li(e,t){let r=new Map;return async(i,a,o)=>{if(o?.aborted)throw n();let s=Ri(i,a,e),c=r.get(s);if(c)return c;let l=Fi(t(s),{sourcePath:s});return r.set(s,l),l}}function Ri(e,t,n){let r=t?D.dirname(t):n;return D.resolve(r,e)}function zi(e){return bn(e)?{command:e.kind,...e.kind===`runFlow`?X(e.label??e.includePath):{}}:{command:e.kind,...Bi(e)}}function Bi(e){return`label`in e&&e.label?X(e.label):Vi(e)?X(Ji(e.target)):Hi(e)?Ui(e):e.kind===`inputText`?X(`<text>`):Wi(e)}function Vi(e){return e.kind===`tapOn`||e.kind===`doubleTapOn`||e.kind===`longPressOn`}function Hi(e){return e.kind===`assertVisible`||e.kind===`assertNotVisible`||e.kind===`extendedWaitUntil`||e.kind===`scrollUntilVisible`}function Ui(e){switch(e.kind){case`assertVisible`:case`assertNotVisible`:return X(Yi(e.target));case`extendedWaitUntil`:return X(Yi(e.visible??e.notVisible));case`scrollUntilVisible`:return X(Yi(e.element))}}function Wi(e){return Gi(e)?Ki(e):e.kind===`swipe`?qi(e):e.kind===`runFlow`?X(e.label??(e.include.kind===`file`?e.include.path:``)):e.kind===`assertTrue`?X(String(e.condition)):{}}function Gi(e){return e.kind===`openLink`||e.kind===`takeScreenshot`||e.kind===`runScript`||e.kind===`pressKey`}function Ki(e){switch(e.kind){case`openLink`:return X(e.link);case`takeScreenshot`:return X(e.path);case`runScript`:return X(e.file);case`pressKey`:return X(e.key)}}function qi(e){return X(e.gesture.kind===`coordinates`?`${Xi(e.gesture.start)} to ${Xi(e.gesture.end)}`:e.gesture.direction)}function Ji(e){return e.space===`target`?Yi(e.selector):`${e.x},${e.y}${e.space===`percent`?`%`:``}`}function Yi(e){return e?.id??e?.text}function Xi(e){return`${e.x},${e.y}${e.space===`percent`?`%`:``}`}function X(e){return e?{value:e}:{}}const Zi=new Set(String.raw`^$\.*+?()[]{}|`);function Qi(e,t){try{return RegExp(`^(?:${t})$`,`ims`).test(e)}catch{return e.toLocaleLowerCase()===t.toLocaleLowerCase()}}function $i(e){try{new RegExp(e)}catch{return e}let t=``;for(let n=0;n<e.length;n+=1){let r=e[n];if(r!==`\\`){if(Zi.has(r))return;t+=r;continue}let i=e[n+1];if(i===void 0||!Zi.has(i))return;t+=i,n+=1}return t}function ea(e,t,n){if(n===`android`&&e.visibleToUser===!1)return!1;if(w(e.rect))return t.isVisibleInEffectiveViewport(e);if(e.rect)return!1;if(n!==`android`&&e.hittable===!0)return!0;let r=t.findAncestor(e,e=>S(e,n)?e:null);return r?w(r.rect)?t.isVisibleInEffectiveViewport(r):n!==`android`&&r.hittable===!0:!1}function ta(e,t,n){return!!n.findAncestor(e,e=>e.index===t.index?e:null)}function na(e,t){let n=[t.id===void 0?void 0:ia(e.identifier,t.id),t.text===void 0?void 0:aa(e,t.text)].filter(e=>e!==void 0);return!(n.length===0&&t.enabled===void 0&&t.selected===void 0||n.some(e=>!e)||t.enabled!==void 0&&e.enabled!==!1!==t.enabled||t.selected!==void 0&&e.selected===!0!==t.selected)}function ra(e){return e.matches.filter(t=>ea(t,e.visibility,e.platform))}function ia(e,t){let n=e??``;return be(n)===be(t)||Qi(n,t)}function aa(e,t){return[e.label,xe(e),e.identifier].filter(e=>!!e).some(e=>ia(e,t))}function oa(e){return e.index!==void 0||e.childOf!==void 0||e.below!==void 0||e.above!==void 0||e.leftOf!==void 0||e.rightOf!==void 0||e.containsChild!==void 0||e.containsDescendants!==void 0}function sa(e){return e.text!==void 0||e.id!==void 0||e.enabled!==void 0||e.selected!==void 0}function ca(e,t,n){let r=[],i=0;for(let a of e)for(let e of n){let n=ua(a.rect,e.rect);n===void 0||!la(t,a.rect,e.rect)||r.push({node:a,distance:n,order:i++})}return r.sort((e,t)=>e.distance-t.distance||e.order-t.order),r.map(({node:e})=>e)}function la(e,t,n){switch(e){case`below`:return t.y>n.y;case`above`:return t.y<n.y;case`leftOf`:return t.x<n.x;case`rightOf`:return t.x>n.x}}function ua(e,t){if(!(!da(e)||!da(t)))return Math.fround(Math.hypot(fa(e.x,e.width)-fa(t.x,t.width),fa(e.y,e.height)-fa(t.y,t.height)))}function da(e){return!!(e&&[e.x,e.y,e.width,e.height].every(Number.isFinite))}function fa(e,t){return e+Math.trunc(t/2)}function pa(e,t={},n={}){let r=y(e.nodes,t);t.onVisibilityContextCreated?.();let a=new WeakMap,o=new WeakSet,s=new WeakMap,c=new Map,l=t=>t.parentIndex===void 0?void 0:r.nodeByIndex.get(t.parentIndex)??e.nodes[t.parentIndex],u=e=>{let t=s.get(e);if(t)return t;let n=new Set,r=new Set,i=l(e);for(;i&&!r.has(i.index);)r.add(i.index),n.add(i.index),i=l(i);return s.set(e,n),n},d=(n,r)=>{let i=c.get(n);i||(i=new WeakMap,c.set(n,i));let a=i.get(r);if(a)return a;t.onPositionComputed?.(n,r);let o=ca(e.nodes,n,m(r).indexed),s={ordered:o,candidateIndexes:new Set(o.map(e=>e.index))};return i.set(r,s),s},f=(e,t)=>d(e,t).ordered,p=(e,t)=>d(e,t).candidateIndexes,m=r=>{let s=a.get(r);if(s)return s;if(o.has(r))throw new i(`INVALID_ARGS`,`Maestro selector relations cannot contain cycles.`);o.add(r),t.onSelectorComputed?.(r);try{let t=ma(e,r,l,u,m,p),i={matches:t,indexed:va(t,r.index,n.orderUnindexed)};return a.set(r,i),i}finally{o.delete(r)}};return{visibility:r,resolve:m,resolvePosition:f}}function ma(e,t,n,r,i,a){let{index:o,childOf:s,below:c,above:l,leftOf:u,rightOf:d,containsChild:f,containsDescendants:p,...m}=t,h=sa(m)?e.nodes.filter(e=>na(e,m)):[...e.nodes];if(s){let e=new Set(i(s).indexed.map(e=>e.index));h=h.filter(t=>ga(r(t),e))}if(f){let e=new Set(i(f).indexed.map(n).filter(e=>e!==void 0).map(e=>e.index));h=h.filter(t=>e.has(t.index))}if(p){let e=p.map(e=>ha(i(e).indexed,r));h=h.filter(t=>e.every(e=>e.has(t.index)))}for(let[e,n]of _a(t)){let t=a(e,n);h=h.filter(e=>t.has(e.index))}return h}function ha(e,t){let n=new Set;for(let r of e)for(let e of t(r))n.add(e);return n}function ga(e,t){for(let n of e)if(t.has(n))return!0;return!1}function _a(e){return[[`below`,e.below],[`above`,e.above],[`leftOf`,e.leftOf],[`rightOf`,e.rightOf]].filter(e=>e[1]!==void 0)}function va(e,t,n){if(t===void 0)return n?n(e):[...e];let r=ba(e)[Sa(t)];return r?[r]:[]}function ya(e,t){return t===void 0?e[0]:ba(e)[Sa(t)]}function ba(e){return[...e].sort((e,t)=>{let n=xa(e.rect?.y),r=xa(t.rect?.y);return n===r?xa(e.rect?.x)-xa(t.rect?.x):n-r})}function xa(e){return e!==void 0&&Number.isFinite(e)?e:2**53-1}function Sa(e){let t=typeof e==`number`?e:Number(e.trim());if(!Number.isSafeInteger(t)||t<0)throw new i(`INVALID_ARGS`,`Maestro selector.index must be a non-negative integer.`);return t}const Ca={android:{kind:`exact`,provider:`android-helper`},ios:{kind:`divergence`,provider:`apple-xctest`,reason:`maestro-clickable-not-exposed-by-provider`}};function wa(e,t){let n=Ca[t];if(n.kind===`divergence`)return n;let r=p(e);return r?r.kind!==`exact`||r.provider!==n.provider?{kind:`divergence`,provider:n.provider,reason:`unregistered-provider-evidence`}:r:{kind:`divergence`,provider:n.provider,reason:`exact-evidence-not-retained`}}function Ta(e,t){return t.kind===`exact`?e.map((e,n)=>({node:e,order:n,rank:Ea(t.clickableByNodeIndex.get(e.index))})).sort((e,t)=>t.rank-e.rank||e.order-t.order).map(({node:e})=>e):[...e]}function Ea(e){return e===!0?2:+(e===!1)}function Da(e,t,n,r={}){let i=wa(e,n),a=ka(e,i,r),o=Oa(t,a),s=ra({visibility:a.visibility,matches:o.matches,platform:n});return{...o,visible:s,clickability:i,ranked:Aa(s,t,n,a.visibility,i)}}function Oa(e,t){return{matches:t.resolve(e).matches,parentMatched:e.childOf===void 0||t.resolve(e.childOf).indexed.length>0}}function ka(e,t,n={}){return pa(e,n,t?{orderUnindexed:e=>Ta(e,t)}:{})}function Aa(e,t,n,r,i){let a=n!==`ios`||!Fa(t)?e:e.filter(n=>{if(za(n))return!0;let i=e.filter(e=>e!==n&&Ia(n,e,t));return!i.some(e=>za(e)&&ta(n,e,r))&&!i.some(e=>ta(e,n,r))});return t.index===void 0&&i?Ta(a,i):a}function ja(e,t){let n=t===void 0?e.find(Pa):Ma(e,t);return!n||!Pa(n)?null:{node:n,rect:n.rect}}function Ma(e,t){return ya(e,t)}function Na(e){return Pa(e)?e.rect:void 0}function Pa(e){return w(e.rect)}function Fa(e){return e.id!==void 0||e.text!==void 0}function Ia(e,t,n){if(n.id!==void 0&&Ra(e.identifier)!==Ra(t.identifier))return!1;if(n.text!==void 0){let n=La(e),r=new Set(La(t));if(!n.some(e=>r.has(e)))return!1}return!0}function La(e){return[e.label,e.value,e.identifier].map(Ra).filter(e=>e!==void 0)}function Ra(e){if(e)return be(e)||void 0}function za(e){let t=te(e.type??``);return t===`button`||t===`link`||t===`switch`||t===`searchfield`||t===`textfield`||t===`securetextfield`||t===`textview`}const Ba=Symbol(`maestroFlowProgram`),Va=Symbol(`maestroFailureCommand`),Ha=Symbol(`maestroFailurePlan`);function Ua(e,t){let n=Fi(e,{sourcePath:t});return{sourcePath:t,name:n.config.name,appTarget:Ja(n),[Ba]:n}}async function Wa(e,t,n){let r;try{let i=D.dirname(e.sourcePath),a=Li(i,n.readSource),o=await qn(e[Ba],{baseDir:i,defaults:n.defaults,env:n.env,platform:n.platform,target:n.target,runtimeHints:n.runtimeHints,loadProgram:a,signal:n.signal}),s=Zn(o,{from:n.from,planDigest:n.planDigest}),c=await jr(o,t,{defaults:n.defaults,env:n.env,platform:n.platform,target:n.target,loadProgram:a,signal:n.signal,startIndex:s,trustedScripts:n.trustedScripts,observer:Ka(o,n.observer,e=>{r=e})});return{ok:!0,replayed:o.total-s,planDigest:o.digest,startIndex:s,artifactPaths:c.artifactPaths,...c.warnings?{warnings:c.warnings}:{}}}catch(e){return{ok:!1,error:r?.error??e,...r?{failure:r}:{}}}}function Ga(e,t){let n=Xa(e[Va]),r=e[Ha].platform;return!n||r!==`android`&&r!==`ios`?[]:Da(t,n.selector,r).ranked.map(e=>({node:e,basis:Za(n.selector,e)}))}function Ka(e,t,n){return{commandStarted:e=>t?.actionStarted?.(qa(e)),commandCompleted:e=>t?.actionCompleted?.({...qa(e),durationMs:e.durationMs,runtimeMetrics:e.runtimeMetrics,data:e.data}),commandFailed:r=>{let i=Xn(e,{from:r.stepIndex,planDigest:e.digest}),a={...qa(r),durationMs:r.durationMs,error:r.error,artifactPaths:r.artifactPaths,warnings:[...r.warnings],isControl:bn(r.command),redactions:r.command.kind===`inputText`&&r.command.text.length>0?[{name:`inputText.text`,value:r.command.text}]:[],resume:i.allowed?{allowed:!0,from:r.stepIndex,planDigest:e.digest}:{allowed:!1,from:r.stepIndex,planDigest:e.digest,reason:i.reason},[Va]:r.command,[Ha]:e};n(a),t?.actionFailed?.(a)}}}function qa(e){let t=zi(e.command);return{action:t.command,...t.value?{value:t.value}:{},source:e.source,generation:e.generation,stepIndex:e.stepIndex,stepTotal:e.stepTotal}}function Ja(e){return[e.config.appId,...[...e.config.onFlowStart??[],...e.commands].filter(e=>e.kind===`launchApp`).map(e=>e.kind===`launchApp`?e.appId:void 0)].find(Ya)}function Ya(e){return!!(e?.trim()&&!e.includes(`$`)&&!u(e))}function Xa(e){switch(e.kind){case`tapOn`:return e.target.space===`target`?{selector:e.target.selector}:void 0;case`doubleTapOn`:case`longPressOn`:return e.target.space===`target`?{selector:e.target.selector}:void 0;case`assertVisible`:case`assertNotVisible`:return{selector:e.target};case`extendedWaitUntil`:return e.visible?{selector:e.visible}:e.notVisible?{selector:e.notVisible}:void 0;case`scrollUntilVisible`:return{selector:e.element};case`swipe`:return e.gesture.kind===`target`?{selector:e.gesture.from}:void 0;default:return}}function Za(e,t){return e.id!==void 0||e.text!==void 0&&na({...t,label:void 0,value:void 0},{text:e.text})?`id`:e.text===void 0?`other`:`label`}function Qa(e){let t={[e.entryPath]:e.entrySource},n=$a(e.entrySource,e.entryPath);return n&&eo({program:n,sourcePath:e.entryPath,context:Ce({},{...e.env}),files:t,readSource:e.readSource}),t}function $a(e,t){try{return Fi(e,{sourcePath:t})}catch{return}}function eo(e){let t=e.context.enter(e.program.config.env??{});try{to([...e.program.config.onFlowStart??[],...e.program.commands,...e.program.config.onFlowComplete??[]],e)}finally{t()}}function to(e,t){for(let n of e){if(n.kind===`repeat`||n.kind===`retry`){to(n.commands,t);continue}if(n.kind!==`runFlow`)continue;let e=t.context.enter(n.env??{});try{if(n.include.kind===`commands`){to(n.include.commands,t);continue}no(n.include.path,t)}finally{e()}}}function no(e,t){let n=t.context.resolveDeferred(e);if(n.includes("${"))return;let r=Ri(n,t.sourcePath,t.sourcePath);if(t.files[r]!==void 0)return;let i=t.readSource(r);if(i===void 0)return;t.files[r]=i;let a=$a(i,r);a&&eo({...t,program:a,sourcePath:r})}function ro(e,t){return`${e},${t}`}const io={open:ao,back:()=>({kind:`commands`,commands:[`back`]}),home:()=>({kind:`commands`,commands:[{pressKey:`Home`}]}),keyboard:co};function ao(e){let[t,n]=e.positionals;if(!t)return{kind:`unsupported`,message:`open requires an app id or URL`};if(u(t))return{kind:`commands`,commands:[{openLink:t}]};let r=oo(e,t);return n&&u(n)?{kind:`config`,appId:t,commands:[r,{openLink:n}]}:n?{kind:`unsupported`,message:`open with a non-URL second argument is unsupported`}:{kind:`config`,appId:t,commands:[r]}}function oo(e,t){return{launchApp:{appId:t,...so(e)}}}function so(e){let t=e.flags?.launchArgs,n={};return e.flags?.relaunch===!0&&(n.stopApp=!0),e.flags?.clearAppState===!0&&(n.clearState=!0),Array.isArray(t)&&t.length>0&&(n.launchArguments=t),n}function co(e){let[t]=e.positionals;return t===`dismiss`?{kind:`commands`,commands:[`hideKeyboard`]}:t===`enter`||t===`return`?{kind:`commands`,commands:[{pressKey:`Enter`}]}:{kind:`unsupported`,message:`keyboard ${t??``}`.trim()}}function lo(e){return`${e.map(e=>(0,j.stringify)(e).trimEnd()).join(`
|
|
115
|
+
`,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=l(c(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=l(c(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}}})),Ht=t((e=>{var t=Pt(),n=_t(),r=vt(),i=He(),a=k(),o=Bt(),s=Vt();function c(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new o.LineCounter||null,prettyErrors:t}}function l(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=Array.from(l.compose(o.parse(e)));if(a&&i)for(let t of u)t.errors.forEach(r.prettifyError(e,i)),t.warnings.forEach(r.prettifyError(e,i));return u.length>0?u:Object.assign([],{empty:!0},l.streamInfo())}function u(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=null;for(let t of l.compose(o.parse(e),!0,e.length))if(!u)u=t;else if(u.options.logLevel!==`silent`){u.errors.push(new r.YAMLParseError(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return a&&i&&(u.errors.forEach(r.prettifyError(e,i)),u.warnings.forEach(r.prettifyError(e,i))),u}function d(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let a=u(e,n);if(!a)return null;if(a.warnings.forEach(e=>i.warn(a.options.logLevel,e)),a.errors.length>0){if(a.options.logLevel!==`silent`)throw a.errors[0];a.errors=[]}return a.toJS(Object.assign({reviver:r},n))}function f(e,t,r){let i=null;if(typeof t==`function`||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r==`string`&&(r=r.length),typeof r==`number`){let e=Math.round(r);r=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=r??t??{};if(!e)return}return a.isDocument(e)&&!i?e.toString(r):new n.Document(e,i,r).toString(r)}e.parse=d,e.parseAllDocuments=l,e.parseDocument=u,e.stringify=f})),j=t((e=>{var t=Pt(),n=_t(),r=ht(),i=vt(),a=Pe(),o=k(),s=Ge(),c=A(),l=qe(),u=Ye();Rt();var d=zt(),f=Bt(),p=Vt(),m=Ht(),h=Oe();e.Composer=t.Composer,e.Document=n.Document,e.Schema=r.Schema,e.YAMLError=i.YAMLError,e.YAMLParseError=i.YAMLParseError,e.YAMLWarning=i.YAMLWarning,e.Alias=a.Alias,e.isAlias=o.isAlias,e.isCollection=o.isCollection,e.isDocument=o.isDocument,e.isMap=o.isMap,e.isNode=o.isNode,e.isPair=o.isPair,e.isScalar=o.isScalar,e.isSeq=o.isSeq,e.Pair=s.Pair,e.Scalar=c.Scalar,e.YAMLMap=l.YAMLMap,e.YAMLSeq=u.YAMLSeq,e.Lexer=d.Lexer,e.LineCounter=f.LineCounter,e.Parser=p.Parser,e.parse=m.parse,e.parseAllDocuments=m.parseAllDocuments,e.parseDocument=m.parseDocument,e.stringify=m.stringify,e.visit=h.visit,e.visitAsync=h.visitAsync}))();function M(e,t){return Ut(e?.range?.[0],t)}function Ut(e,t){let n=t.lineCounter.linePos(e!==void 0&&e>=0?e:0).line;return t.sourcePath===void 0?{line:n}:{path:t.sourcePath,line:n}}function Wt(e){return`${e.path===void 0?``:`${e.path}:`}line ${e.line}`}function N(e,t,n){throw new i(`INVALID_ARGS`,`${e} (${Wt(M(t,n))})`)}function P(e,t,n){(0,j.isMap)(e)||N(`Maestro ${t} expects a map.`,e,n);let r=[];for(let i of e.items){let e=i.key;(0,j.isScalar)(e)||N(`Maestro ${t} map keys must be strings.`,void 0,n);let a=e.value;typeof a!=`string`&&typeof a!=`number`&&typeof a!=`boolean`&&N(`Maestro ${t} map keys must be strings.`,e,n),i.value!==null&&!(0,j.isNode)(i.value)&&N(`Maestro ${t} values must be YAML nodes.`,e,n),r.push({key:String(a),keyNode:e,value:i.value})}return r}function Gt(e,t,n){return(0,j.isSeq)(e)||N(`Maestro ${t} expects a list.`,e,n),e.items}function Kt(e,t,n){return Gt(e,t,n).map((e,r)=>V(e,`${t}[${r}]`,n))}function F(e,t,n,r){let i=new Set(n),a=new Set;for(let n of e)a.has(n.key)&&N(`Maestro ${t} contains duplicate field "${n.key}".`,n.keyNode,r),a.add(n.key),i.has(n.key)||N(`Maestro ${t} field "${n.key}" is not supported.`,n.keyNode,r)}function I(e,t){return e.some(e=>e.key===t)}function L(e,t){return e.find(e=>e.key===t)?.value}function R(e,t,n){return I(e,t)?n(L(e,t)):void 0}function qt(e,t,n){return O({optional:R(e,`optional`,e=>Yt(e,`${t}.optional`,n))})}function z(e){return e===null||(0,j.isScalar)(e)&&e.value===null}function B(e,t,n){if(e==null)return null;(0,j.isScalar)(e)||N(`Maestro ${t} expects a scalar value.`,e,n);let r=e.value;if(r===null||typeof r==`string`||typeof r==`number`||typeof r==`boolean`)return r;N(`Maestro ${t} contains an unsupported scalar value.`,e,n)}function V(e,t,n){let r=B(e,t,n);return typeof r!=`string`&&N(`Maestro ${t} expects a string.`,e,n),r}function Jt(e,t,n){let r=B(e,t,n);if(r!==null)return typeof r!=`string`&&N(`Maestro ${t} expects a string.`,e,n),r}function Yt(e,t,n){let r=B(e,t,n);if(r!==null)return typeof r!=`boolean`&&N(`Maestro ${t} expects a boolean.`,e,n),r}const Xt=/^\$\{[A-Za-z_][A-Za-z0-9_.]*\}$/,Zt=new Set([`allow`,`deny`,`unset`,`always`,`inuse`,`never`,`limited`]),Qt=/^-?\d+(\.\d+)?$/,$t=/^-?\d+$/,en={"tapOn.index":{integer:!0,nonNegative:!0},"tapOn.repeat":{integer:!0,positive:!0},"tapOn.delay":{integer:!0,nonNegative:!0},"doubleTapOn.delay":{integer:!0,nonNegative:!0},eraseText:{integer:!0,positive:!0},"eraseText.charactersToErase":{integer:!0,positive:!0},"extendedWaitUntil.timeout":{nonNegative:!0},"scrollUntilVisible.timeout":{nonNegative:!0},waitForAnimationToEnd:{nonNegative:!0},"waitForAnimationToEnd.timeout":{nonNegative:!0},"swipe.duration":{nonNegative:!0},"repeat.times":{integer:!0,nonNegative:!0},"retry.maxRetries":{integer:!0,nonNegative:!0}};function tn(e){return e.positive&&e.integer?`a positive integer`:e.positive?`a positive number`:e.nonNegative&&e.integer?`a non-negative integer`:e.nonNegative?`a non-negative finite number`:e.integer?`an integer`:`a finite number`}function nn(e,t,n,r,i){let a=`Maestro ${t} expects ${tn(i)} or a variable expression.`;Number.isFinite(e)||N(a,n,r),Math.abs(e)>2**53-1&&N(a,n,r),i.integer&&!Number.isSafeInteger(e)&&N(a,n,r),i.nonNegative&&e<0&&N(a,n,r),i.positive&&e<=0&&N(a,n,r)}function rn(e,t,n,r,i){if(typeof e==`number`)return nn(e,t,n,r,i),e;if(typeof e==`string`){if(Xt.test(e))return e;if((i.integer?$t:Qt).test(e)){let a=Number(e);return nn(a,t,n,r,i),a}}N(`Maestro ${t} expects ${tn(i)} or a variable expression.`,n,r)}function H(e,t,n,r=en[t]??{}){let i=B(e,t,n);if(i!==null)return rn(i,t,e,n,r)}function an(e,t,n){let r=en[t]??{},i=B(e,t,n);return i===null&&N(`Maestro ${t} expects ${tn(r)} or a variable expression.`,e,n),rn(i,t,e,n,r)}function on(e,t,n){let r=B(e,t,n);return r===null&&N(`Maestro ${t} requires a condition.`,e,n),typeof r==`string`&&r.includes("${")&&!Xt.test(r)&&N(`Maestro ${t} only supports a literal value or a bare \${VAR} lookup; JavaScript expressions are not supported — compute it in a runScript and reference \${output.x}.`,e,n),r}function sn(e,t,n){let r=P(e,t,n),i={};for(let e of r){let r=B(e.value,`${t}.${e.key}`,n);r===null&&N(`Maestro ${t}.${e.key} expects a string, number, or boolean.`,e.value,n),i[e.key]=r}return i}function cn(e,t){try{return new _n(un(ln(e)),t).parse()}catch(e){if(e instanceof i&&e.code===`INVALID_ARGS`)return;throw e}}function ln(e){let t=e.trim();return t.startsWith("${")&&t.endsWith(`}`)?t.slice(2,-1).trim():t}function un(e){let t=[],n=0;for(;n<e.length;){let r=e.slice(n),a=/^\s+/.exec(r)?.[0].length??0;if(a>0){n+=a;continue}let o=dn(r);if(!o)throw new i(`INVALID_ARGS`,`Unsupported runFlow.when.true expression near "${r.slice(0,24)}".`);t.push(o.value),n+=o.length}return t}function dn(e){return fn(e)??pn(e)??mn(e)??hn(e)??gn(e)}function fn(e){return e.startsWith(`maestro.platform`)?{value:{type:`platform`},length:16}:null}function pn(e){let t=/^(==|!=|&&|\|\|)/.exec(e)?.[1];return t?{value:{type:`operator`,value:t},length:t.length}:null}function mn(e){let t=e[0];return t===`(`||t===`)`?{value:{type:`paren`,value:t},length:1}:null}function hn(e){let t=/^(['"])(.*?)\1/.exec(e);return t?{value:{type:`string`,value:t[2]??``},length:t[0].length}:null}function gn(e){let t=/^(true|false)\b/.exec(e)?.[1];return t?{value:{type:`boolean`,value:t===`true`},length:t.length}:null}var _n=class{index=0;tokens;platform;constructor(e,t){this.tokens=e,this.platform=t}parse(){let e=this.parseOr();if(this.peek())throw new i(`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 i(`INVALID_ARGS`,`Incomplete runFlow.when.true expression.`);if(e.type===`boolean`)return this.index+=1,e.value;if(e.type===`paren`&&e.value===`(`){this.index+=1;let e=this.parseOr();if(!this.consumeParen(`)`))throw new i(`INVALID_ARGS`,`Unclosed runFlow.when.true parenthesis.`);return e}return this.parsePlatformComparison()}parsePlatformComparison(){this.consumePlatformToken();let e=this.consumeComparisonOperator(),t=this.consumeStringLiteral(),n=this.platform===t.toLowerCase();return e.value===`==`?n:!n}consumePlatformToken(){if(this.peek()?.type!==`platform`)throw new i(`INVALID_ARGS`,`runFlow.when.true supports maestro.platform comparisons.`);this.index+=1}consumeComparisonOperator(){let e=this.peek();if(e?.type!==`operator`||e.value!==`==`&&e.value!==`!=`)throw new i(`INVALID_ARGS`,`runFlow.when.true comparison requires == or !=.`);return this.index+=1,e}consumeStringLiteral(){let e=this.peek();if(e?.type!==`string`)throw new i(`INVALID_ARGS`,`runFlow.when.true comparison requires a string literal.`);return this.index+=1,e.value}consumeOperator(e){let t=this.peek();return t?.type!==`operator`||t.value!==e?!1:(this.index+=1,!0)}consumeParen(e){let t=this.peek();return t?.type!==`paren`||t.value!==e?!1:(this.index+=1,!0)}peek(){return this.tokens[this.index]}};const vn=new Set([``,`false`,`0`,`null`,`undefined`]);function yn(e){return typeof e==`boolean`?e:typeof e==`number`?e!==0&&!Number.isNaN(e):!vn.has(e)}function bn(e){return typeof e==`boolean`||typeof e==`number`||typeof e==`string`?yn(e):typeof e==`bigint`?e!==0n:e!=null}function xn(e){switch(e.kind){case`runFlow`:return!(`include`in e);case`repeat`:case`retry`:return!(`commands`in e);default:return!1}}function Sn(e,t){return{...Nn(e,t),source:e.source}}function U(e,t,n){if(e===void 0)return;let r=n??en[t]??{},a=tn(r),o;if(typeof e==`number`)o=e;else{let n=e.trim();if(n===``)throw new i(`INVALID_ARGS`,`Maestro ${t} must be ${a}.`);o=Number(n)}if(!Number.isFinite(o)||Math.abs(o)>2**53-1||r.integer&&!Number.isSafeInteger(o)||r.nonNegative&&o<0||r.positive&&o<=0)throw new i(`INVALID_ARGS`,`Maestro ${t} must be ${a}.`);return o}function Cn(e,t,n,r){return U(e===void 0?t:n.resolve(String(e)),r)}function W(e){if(e?.aborted)throw n()}async function wn(e,t){if(e.include.kind===`commands`)return{kind:`program`,source:e.source,config:{},commands:e.include.commands};if(!t.loadProgram)throw new i(`INVALID_ARGS`,`Maestro file runFlow requires a program loader.`);return W(t.signal),t.signal?await t.loadProgram(e.include.path,e.source.path,t.signal):await t.loadProgram(e.include.path,e.source.path)}function Tn(e,t,n){if(e.include.kind===`file`)return D.resolve(t?D.dirname(t):n,e.include.path)}function En(e){return e===void 0?void 0:D.resolve(e)}function Dn(e,t,n){let r=Tn(e,e.source.path,n);if(r&&t.has(r))throw new i(`INVALID_ARGS`,`Maestro runFlow cycle detected at ${r}.`);return r}function On(e,t,n,r){let a=e.include.kind===`file`?En(t.source.path):void 0,o=new Set([n,a].filter(e=>e!==void 0)),s=[...o].find(e=>r.has(e));if(s)throw new i(`INVALID_ARGS`,`Maestro runFlow cycle detected at ${s}.`);return o.forEach(e=>r.add(e)),o}function kn(e,t){if(e.trustedScripts===!1)throw new i(`UNAUTHORIZED`,`Maestro ${t} is not permitted for flows received over the remote daemon surface: node:vm is not a security sandbox, so an untrusted expression can escape to the host.`)}async function An(e,t,n,r){if(e===void 0)return!0;if(typeof e==`boolean`)return e;let i=jn(e,n);if(i!==void 0){let e=cn(i,r.platform);if(e!==void 0)return e;if(!i.includes("${"))return yn(i)}kn(r,t);let{evaluateMaestroConditionScript:a}=await import(`./engine-eval-script.js`),o=await a(e,n.values,r.platform,t);return n.replaceOutput(o.outputEnv),bn(o.value)}function jn(e,t){try{return t.resolve(e)}catch(e){if(e instanceof i&&e.code===`INVALID_ARGS`)return;throw e}}function Mn(e,t){return[...e.visible?[{kind:`visible`,selector:Nn(e.visible,t)}]:[],...e.notVisible?[{kind:`notVisible`,selector:Nn(e.notVisible,t)}]:[]]}function Nn(e,t){return typeof e==`string`?t.resolve(e):Array.isArray(e)?e.map(e=>Nn(e,t)):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,Nn(n,t)])):e}async function Pn(e,t){W(t.signal);let n=En(e.source.path),r={options:t,context:Ce(t.defaults,t.env),activeIncludePaths:new Set(n===void 0?[]:[n]),staticallyExecutedControls:0,staticallySkippedControls:0};return{steps:await Fn(e,[],void 0,e.source.path,r),staticallyExecutedControls:r.staticallyExecutedControls,staticallySkippedControls:r.staticallySkippedControls}}async function Fn(e,t,n,r,i){W(i.options.signal);let a=Kn(t,e.config.env),o=e.config.appId??n,s=i.context.enter(e.config.env);try{let t=[...e.config.onFlowStart??[],...e.commands,...e.config.onFlowComplete??[]],n=[];for(let s of t)n.push(...await Ln(s,a,o,e.source.path??r,i));return n}finally{s()}}async function In(e,t,n,r,i){let a=[];for(let o of e)a.push(...await Ln(o,t,n,r,i));return a}async function Ln(e,t,n,r,i){W(i.options.signal);let a=qn(e,r);switch(a.kind){case`runFlow`:{let e=zn(a,i);if(e===`omit`)return i.staticallySkippedControls+=1,[];let o=await Rn(a,t,n,r,i);return e===`flatten`?(i.staticallyExecutedControls+=1,o):[Wn(a,t,n,o)]}case`repeat`:return[Wn(a,t,n,await In(a.commands,t,n,r,i))];case`retry`:return[Wn(a,t,n,await In(a.commands,t,n,r,i))];default:return[Un(a,t,n)]}}async function Rn(e,t,n,r,i){let a=Vn(e,i.context),o=Dn(a,i.activeIncludePaths,i.options.baseDir),s=await wn(a,i.options);W(i.options.signal);let c=On(a,s,o,i.activeIncludePaths),l=Kn(t,e.env),u=i.context.enter(e.env);try{return await Fn(s,l,n,s.source.path??e.source.path??r,i)}finally{u(),c.forEach(e=>i.activeIncludePaths.delete(e))}}function zn(e,t){let n=e.when;return n?n.platform!==void 0&&n.platform!==t.options.platform?`omit`:Bn(n.true,t)||(n.visible||n.notVisible?`opaque`:`flatten`):`flatten`}function Bn(e,t){if(e===!1)return`omit`;if(typeof e!=`string`)return;let n=t.context.resolveDeferred(e);if(Hn(n))return`opaque`;let r=cn(n,t.options.platform);return r===void 0?`opaque`:r?void 0:`omit`}function Vn(e,t){return e.include.kind===`file`?{...e,include:{...e.include,path:t.resolve(e.include.path)}}:e}function Hn(e){return/\$\{[A-Za-z_][A-Za-z0-9_.]*\}/.test(e)}function Un(e,t,n){return O({kind:`command`,command:e,source:e.source,scopes:t,appId:n})}function Wn(e,t,n,r){return O({kind:`opaque`,command:Gn(e),source:e.source,scopes:t,body:r,appId:n})}function Gn(e){switch(e.kind){case`runFlow`:return O({kind:e.kind,source:e.source,when:e.when,label:e.label,...e.include.kind===`file`?{includePath:e.include.path}:{}});case`repeat`:return O({kind:e.kind,source:e.source,times:e.times,while:e.while});case`retry`:return O({kind:e.kind,source:e.source,maxRetries:e.maxRetries})}}function Kn(e,t){return t===void 0?e:[...e,t]}function qn(e,t){return e.source.path||!t?e:{...e,source:{...e.source,path:t}}}async function Jn(e,t){let{steps:n,staticallyExecutedControls:r,staticallySkippedControls:i}=await Pn(e,t),a=Yn(t.runtimeHints),o=O({kind:`maestroReplayPlan`,platform:t.platform,target:t.target,runtimeHints:a,initialStaticEnv:structuredClone({...t.defaults??{},...e.config.env??{},...t.env??{}}),steps:structuredClone(n),total:n.length,compatibility:{staticallyExecutedControls:r,staticallySkippedControls:i}}),s=Se(o);return Xn({...o,digest:s})}function Yn(e){if(!e)return;let t=Object.entries(e).filter(e=>e[1]!==void 0);return t.length===0?void 0:Object.fromEntries(t)}function Xn(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;for(let t of Object.values(e))Xn(t);return Object.freeze(e)}function Zn(e,t={}){let{from:n,planDigest:r}=t;if(n===void 0&&r===void 0)return{allowed:!0,startIndex:0};if(n===void 0||r===void 0)return{allowed:!1,reason:`replay --from requires --plan-digest (and --plan-digest requires --from).`};if(!Number.isInteger(n)||n<1||n>e.total)return{allowed:!1,reason:`replay --from ${n} is out of range for a ${e.total}-step plan.`};if(r!==e.digest)return{allowed:!1,reason:`replay --plan-digest does not match the current plan digest.`};if(n===1)return{allowed:!0,startIndex:0};for(let t=0;t<n-1;t+=1){let n=e.steps[t];if(n.kind===`opaque`)return{allowed:!1,reason:`step ${t+1} is opaque runtime control flow (${n.command.kind}) and cannot be skipped safely.`};if(n.command.kind===`runScript`||n.command.kind===`evalScript`)return{allowed:!1,reason:`step ${t+1} (${n.command.kind}) can produce outputEnv values and cannot be skipped safely.`}}let i=e.steps[n-1];return i.kind===`opaque`?{allowed:!1,reason:`step ${n} is opaque runtime control flow (${i.command.kind}) and cannot be resumed into.`}:{allowed:!0,startIndex:n-1}}function Qn(e,t={}){let n=Zn(e,t);if(!n.allowed)throw new i(`INVALID_ARGS`,n.reason);return n.startIndex}function $n(e,t){if(!Number.isInteger(t)||t<0||t>e.total)throw new i(`INVALID_ARGS`,`Maestro replay startIndex ${t} is out of range for a ${e.total}-step plan.`);return t}const G={control:{retryMaxRetries:3},command:{retryTapMaxAttempts:2,targetLookupTimeoutMs:17e3,optionalTargetLookupTimeoutMs:7e3,scrollUntilVisibleTimeoutMs:2e4,waitForAnimationToEndTimeoutMs:15e3,waitForAnimationToEndDifferencePercent:.005,longPressDurationMs:3e3,swipeDurationMs:400,repeatDelayMs:100,scrollUntilVisibleSpeed:40,scrollUntilVisiblePercentage:100,eraseTextMaxCharacters:50,androidInputTextCharacterDelayMs:75},observation:{pollIntervalMs:200,defaultSettleAttempts:10},targetSwipe:{nearEdgeFraction:.1,farEdgeFraction:.9},screenSwipe:{nearEdgeFraction:.1,farEdgeFraction:.9,centerFraction:.5,downStartFraction:.2,upStartFraction:{android:.5,ios:.9}},scrollUntilVisibleSwipe:{nearEdgeFraction:.1,farEdgeFraction:.9}};function er(e){return Math.trunc(1e3*(100-e)/100)+1}const tr={assertVisibleTimeoutMs:G.command.targetLookupTimeoutMs,assertNotVisibleTimeoutMs:G.command.targetLookupTimeoutMs,extendedWaitUntilTimeoutMs:G.command.targetLookupTimeoutMs,runFlowConditionTimeoutMs:G.command.optionalTargetLookupTimeoutMs},nr=G.observation.pollIntervalMs*G.observation.defaultSettleAttempts,rr=`maestro-test-failure`;function ir(e,t={}){return new i(`COMMAND_FAILED`,e,{...t,reason:rr})}function ar(e){return e instanceof i&&e.code===`COMMAND_FAILED`&&e.details?.reason===rr}async function or(e,t){W(t.options.signal);try{return await Sr(e,t.context,async()=>await sr(e,t))}catch(t){throw Cr(t,e)}}async function sr(e,t){if(e.kind===`command`)return await cr(e.command,e.appId,t);await mr(e,t)}async function cr(e,t,n){if(e.kind===`evalScript`)return await dr(e,n);e.kind===`runScript`&&kn(n.options,`runScript`);let r=Sn(e,n.context);try{return await fr(r,t,n)}catch(e){if(W(n.options.signal),ur(r)&&ar(e)){n.warnings.push(lr(r,e)),n.skipped+=1;return}throw wr(e,r)}}function lr(e,t){let n=`${e.source.path?`${e.source.path}:`:``}line ${e.source.line}`,r=t instanceof i?t.message:String(t);return`Optional Maestro ${e.kind} skipped at ${n}: ${r}`}function ur(e){return`optional`in e&&e.optional===!0}async function dr(e,t){let{evaluateMaestroEvalScript:n}=await import(`./engine-eval-script.js`);kn(t.options,`evalScript`);let r=await n(e.script,t.context.values);t.context.replaceOutput(r),t.executed+=1}async function fr(e,t,n){switch(e.kind){case`assertVisible`:await yr({kind:`visible`,selector:e.target},n.timing.assertVisibleTimeoutMs,n),n.executed+=1;return;case`assertNotVisible`:await yr({kind:`notVisible`,selector:e.target},n.timing.assertNotVisibleTimeoutMs,n),n.executed+=1;return;case`assertTrue`:if(!yn(e.condition))throw ir(`Maestro assertTrue condition was falsy: ${JSON.stringify(e.condition)}`);n.executed+=1;return;case`extendedWaitUntil`:await yr(xr(e),U(e.timeout,`extendedWaitUntil.timeout`)??n.timing.extendedWaitUntilTimeoutMs,n),n.executed+=1;return;default:return await pr(e,t,n)}}async function pr(e,t,n){let r=O({command:e,env:n.context.values,appId:t===void 0?void 0:n.context.resolve(t),generation:n.context.generation,invalidateObservation:n.context.invalidateObservation,cachedObservation:n.context.observation,signal:n.options.signal}),i=await n.port.execute(r);return W(n.options.signal),i.observation&&n.context.recordObservation(i.observation),i.outputEnv&&n.context.merge(i.outputEnv),i.artifactPaths?.forEach(e=>n.artifacts.add(e)),n.executed+=1,i}async function mr(e,t){let n=e.command;switch(n.kind){case`runFlow`:if(n.when&&!await vr(n.when,`runFlow.when`,t)){t.skipped+=1;return}t.executed+=1,await hr(e.body,t);return;case`repeat`:t.executed+=1,await gr(e.body,n.times,n.while,t);return;case`retry`:{let r=Math.min(Cn(n.maxRetries,1,t.context,`retry.maxRetries`),G.control.retryMaxRetries);t.executed+=1,await _r(e.body,r,t);return}}}async function hr(e,t){for(let n of e)await or(n,t)}async function gr(e,t,n,r){let i=t===void 0&&n?1/0:Cn(t,0,r.context,`repeat.times`);for(let t=0;t<i;t+=1){if(await new Promise(e=>setImmediate(e)),W(r.options.signal),n&&!await vr(n,`repeat.while`,r))return;await hr(e,r)}}async function _r(e,t,n){let r;for(let i=0;i<=t;i+=1){W(n.options.signal);try{await hr(e,n);return}catch(t){if(W(n.options.signal),!ar(Er(t)))throw t;r=Cr(t,e[0])}}throw r||new i(`COMMAND_FAILED`,`Maestro retry commands failed.`)}async function vr(e,t,n){if(e.platform&&e.platform!==n.options.platform||!await An(e.true,`${t}.true`,n.context,n.options))return!1;for(let t of Mn(e,n.context))if(W(n.options.signal),!(await br(t,n.timing.runFlowConditionTimeoutMs,n)).matched)return!1;return!0}async function yr(e,t,n){if(!(await br(e,t,n)).matched)throw ir(`Maestro ${e.kind} condition did not match.`)}async function br(e,t,n){let r={condition:e,timeoutMs:t,generation:n.context.generation,env:n.context.values,...n.context.observation?{cachedObservation:n.context.observation}:{},...n.options.signal?{signal:n.options.signal}:{}},i=await n.port.observe(r);return W(n.options.signal),n.context.recordObservation(i),i}function xr(e){if(e.visible)return{kind:`visible`,selector:e.visible};if(e.notVisible)return{kind:`notVisible`,selector:e.notVisible};throw new i(`INVALID_ARGS`,`Maestro extendedWaitUntil requires one condition.`)}async function Sr(e,t,n){let r=e.scopes.map(e=>t.enter({...e}));try{return await n()}finally{for(let e=r.length-1;e>=0;--e)r[e]()}}function Cr(e,t){if(Tr(e))return e;let n=t?.source??{line:1};return{kind:`maestroPlanStepFailure`,error:Dr(e,t?.command),source:n,...t?{command:t.command}:{}}}function wr(e,t){return{kind:`maestroPlanStepFailure`,error:Dr(e,t),source:t.source,command:t}}function Tr(e){return!!(e&&typeof e==`object`&&e.kind===`maestroPlanStepFailure`)}function Er(e){return Tr(e)?e.error:e}function Dr(e,t){if(!(e instanceof i)||!t||/\bline \d+\b/.test(e.message))return e;let n=t.source.path?`${t.source.path}:`:``;return new i(e.code,`${e.message} (${n}line ${t.source.line})`,e.details)}async function Or(e,t,n={}){W(n.signal);let r=n.startIndex??0;if(!Number.isInteger(r)||r<0||r>e.total)throw new i(`INVALID_ARGS`,`Maestro replay startIndex ${r} is out of range for a ${e.total}-step plan.`);let a={plan:e,port:t,options:n,context:Ce(n.defaults,n.env?{...n.env}:{}),timing:tr,artifacts:new Set,warnings:[],executed:e.compatibility.staticallyExecutedControls,skipped:e.compatibility.staticallySkippedControls};for(let t=r;t<e.steps.length;t+=1)try{await kr(e.steps[t],t,a)}catch(e){throw Er(e)}return{executed:a.executed,skipped:a.skipped,generation:a.context.generation,artifactPaths:[...a.artifacts],...a.warnings.length>0?{warnings:a.warnings}:{}}}async function kr(e,t,n){W(n.options.signal);let r=n.options.now??Date.now,i=r(),a=n.port.readMetrics?.(),o=n.context.generation,s={command:e.command,source:e.source,generation:o,stepIndex:t+1,stepTotal:n.plan.total};jr(()=>n.options.observer?.commandStarted?.(s));try{let t=await or(e,n);W(n.options.signal),jr(()=>n.options.observer?.commandCompleted?.({...s,durationMs:r()-i,...Ar(a,n.port.readMetrics?.()),...t?.data?{data:t.data}:{}}))}catch(t){let o=Cr(t,e);throw jr(()=>n.options.observer?.commandFailed?.({...s,...o.command?{command:o.command}:{},source:o.source,durationMs:r()-i,...Ar(a,n.port.readMetrics?.()),error:o.error,artifactPaths:[...n.artifacts],warnings:[...n.warnings]})),o}}function Ar(e,t){return!e||!t?{}:{runtimeMetrics:{hierarchyCaptures:t.hierarchyCaptures-e.hierarchyCaptures,screenshotCaptures:t.screenshotCaptures-e.screenshotCaptures,tapRetries:t.tapRetries-e.tapRetries,settleLatches:t.settleLatches-e.settleLatches,settleTimeouts:t.settleTimeouts-e.settleTimeouts}}}function jr(e){try{e?.()}catch{}}async function Mr(e,t,n={}){let r=Nr(e,n);return await Or(e,t,{...n,startIndex:r})}function Nr(e,t){return t.from!==void 0||t.planDigest!==void 0?Qn(e,{from:t.from,planDigest:t.planDigest}):$n(e,t.startIndex??0)}function K(e,t,n){return R(e,`label`,e=>Jt(e,`${t}.label`,n))}const q=[`id`,`text`,`enabled`,`selected`,`index`,`childOf`,`below`,`above`,`leftOf`,`rightOf`,`containsChild`,`containsDescendants`],Pr={textKeys:[`id`,`text`],booleanKeys:[`enabled`,`selected`],textAliases:{label:`text`}},Fr={id:(e,t,n,r)=>Br(e,`id`,t,n,r),text:(e,t,n,r)=>Br(e,`text`,t,n,r),enabled:(e,t,n,r)=>Vr(e,`enabled`,t,n,r),selected:(e,t,n,r)=>Vr(e,`selected`,t,n,r),index:(e,t,n,r)=>{e.index=H(t.value,`${n}.index`,r,{integer:!0,nonNegative:!0})},childOf:(e,t,n,r)=>{e.childOf=J(t.value,`${n}.childOf`,r)},below:(e,t,n,r)=>{e.below=J(t.value,`${n}.below`,r)},above:(e,t,n,r)=>{e.above=J(t.value,`${n}.above`,r)},leftOf:(e,t,n,r)=>{e.leftOf=J(t.value,`${n}.leftOf`,r)},rightOf:(e,t,n,r)=>{e.rightOf=J(t.value,`${n}.rightOf`,r)},containsChild:(e,t,n,r)=>{e.containsChild=J(t.value,`${n}.containsChild`,r)},containsDescendants:(e,t,n,r)=>{e.containsDescendants=Gt(t.value,`${n}.containsDescendants`,r).map(e=>J(e,`${n}.containsDescendants`,r))},optional:(e,t,n,r)=>Vr(e,`optional`,t,n,r)};function J(e,t,n,r=q){if((0,j.isScalar)(e))return{text:V(e,t,n)};let i=P(e,t,n);return F(i,t,r,n),Ir(i,t,n)}function Ir(e,t,n){e.length===0&&N(`Maestro ${t} selector is empty.`,void 0,n);let r={};for(let i of e){let e=Fr[i.key];e||N(`Maestro ${t} selector field "${i.key}" is not supported.`,i.keyNode,n),e(r,i,t,n)}return Object.keys(r).filter(e=>e!==`optional`).length===0&&N(`Maestro ${t} selector must contain a selector value.`,e[0]?.keyNode,n),r}function Lr(e,t,n,r){let i=M(t,n);if((0,j.isScalar)(e))return{source:i,entries:[],target:Ur(J(e,r.name,n,r.selectorKeys))};let a=P(e,r.name,n),o=I(a,`point`);if(F(a,r.name,o?r.pointAllowedKeys:r.selectorAllowedKeys,n),o){let e=r.pointConflictingSelectorKeys??r.selectorKeys;return a.some(t=>Hr(t.key,e))&&N(`Maestro ${r.name}.point cannot be combined with a selector.`,t,n),{source:i,entries:a,target:r.parsePoint(L(a,`point`),`${r.name}.point`,n)}}return{source:i,entries:a,target:Ur(Ir(a.filter(e=>Hr(e.key,r.selectorKeys)),r.name,n))}}function Rr(e,t,n){let r=V(e,t,n),i=/^\s*(\d+)\s*,\s*(\d+)\s*$/.exec(r);if(i)return{space:`absolute`,x:Number(i[1]),y:Number(i[2])};let a=/^\s*(\d+)%\s*,\s*(\d+)%\s*$/.exec(r);if(a){let r=Number(a[1]),i=Number(a[2]);return(r>100||i>100)&&N(`Maestro ${t} percentage coordinates must be between 0% and 100%.`,e,n),{space:`percent`,x:r,y:i}}/^\s*\d+(?:\.\d+)?%\s*,\s*\d+(?:\.\d+)?%\s*$/.test(r)&&N(`Maestro ${t} percentage coordinates must be whole numbers.`,e,n),N(`Maestro ${t} expects absolute or percentage coordinates.`,e,n)}function zr(e,t,n){let r=Rr(e,t,n);return r.space!==`absolute`&&N(`Maestro ${t} only supports absolute coordinates.`,e,n),r}function Br(e,t,n,r,i){let a=Jt(n.value,`${r}.${t}`,i);a!==void 0&&(e[t]=a)}function Vr(e,t,n,r,i){let a=Yt(n.value,`${r}.${t}`,i);a!==void 0&&(e[t]=a)}function Hr(e,t){return t.includes(e)}function Ur(e){return{space:`target`,selector:e}}function Wr(e,t,n){let r=Lr(e,t,n,{name:`tapOn`,selectorKeys:q,pointConflictingSelectorKeys:q,pointAllowedKeys:[`point`,`retryTapIfNoChange`,`repeat`,`delay`,`optional`,`label`],selectorAllowedKeys:[...q,`retryTapIfNoChange`,`repeat`,`delay`,`optional`,`label`],parsePoint:Rr});if(r.entries.length===0)return{kind:`tapOn`,source:r.source,target:r.target};if(r.target.space!==`target`)return{kind:`tapOn`,source:r.source,target:r.target,...Zr(r.entries,n)};let i=Zr(r.entries,n);return O({kind:`tapOn`,source:r.source,target:r.target,...i})}function Gr(e,t,n){let r=Lr(e,t,n,{name:`doubleTapOn`,selectorKeys:q,pointAllowedKeys:[`point`,`delay`,`optional`,`label`],selectorAllowedKeys:[...q,`delay`,`optional`,`label`],parsePoint:zr}),i=qt(r.entries,`doubleTapOn`,n),a=I(r.entries,`delay`)?H(L(r.entries,`delay`),`doubleTapOn.delay`,n):void 0,o=K(r.entries,`doubleTapOn`,n);return O({kind:`doubleTapOn`,source:r.source,target:r.target,...i,delay:a,label:o})}function Kr(e,t,n){let r=Lr(e,t,n,{name:`longPressOn`,selectorKeys:q,pointAllowedKeys:[`point`,`optional`,`label`],selectorAllowedKeys:[...q,`optional`,`label`],parsePoint:zr});return O({kind:`longPressOn`,source:r.source,target:r.target,...qt(r.entries,`longPressOn`,n),label:K(r.entries,`longPressOn`,n)})}function qr(e,t,n){let r=M(t,n),i=P(e,`swipe`,n);F(i,`swipe`,[`start`,`end`,`direction`,`duration`,`from`,`label`,`optional`],n);let a=qt(i,`swipe`,n),o=K(i,`swipe`,n),s=I(i,`duration`)?H(L(i,`duration`),`swipe.duration`,n):void 0;if(I(i,`start`)||I(i,`end`))return{...Jr(i,r,s,t,n),...a,label:o};let c=I(i,`direction`)?Qr(L(i,`direction`),`swipe.direction`,n):void 0;return I(i,`from`)?{...Yr(i,r,c,s,t,n),...a,label:o}:{...Xr(r,c,s,t,n),...a,label:o}}function Jr(e,t,n,r,i){I(e,`direction`)&&N(`Maestro swipe cannot combine direction with start/end coordinates.`,r,i),(!I(e,`start`)||!I(e,`end`))&&N(`Maestro swipe requires both start and end coordinates.`,r,i);let a=Rr(L(e,`start`),`swipe.start`,i),o=Rr(L(e,`end`),`swipe.end`,i);return a.space!==o.space&&N(`Maestro swipe start/end must use the same coordinate space.`,r,i),{kind:`swipe`,source:t,gesture:O({kind:`coordinates`,start:a,end:o,duration:n})}}function Yr(e,t,n,r,i,a){return n===void 0&&N(`Maestro target swipe requires direction.`,i,a),{kind:`swipe`,source:t,gesture:O({kind:`target`,from:J(L(e,`from`),`swipe.from`,a),direction:n,duration:r})}}function Xr(e,t,n,r,i){return t===void 0&&N(`Maestro swipe requires direction, target, or start/end coordinates.`,r,i),{kind:`swipe`,source:e,gesture:O({kind:`screen`,direction:t,duration:n})}}function Zr(e,t){let n=R(e,`retryTapIfNoChange`,e=>Yt(e,`tapOn.retryTapIfNoChange`,t)),r=R(e,`repeat`,e=>an(e,`tapOn.repeat`,t)),i=R(e,`delay`,e=>H(e,`tapOn.delay`,t)),a=qt(e,`tapOn`,t).optional;return O({retryTapIfNoChange:n,repeat:r,delay:i,optional:a,label:K(e,`tapOn`,t)})}function Qr(e,t,n){let r=V(e,t,n).toLowerCase();if(r===`up`||r===`down`||r===`left`||r===`right`)return r;N(`Maestro ${t} must be UP, DOWN, LEFT, or RIGHT.`,e,n)}function $r(e,t,n,r){let i=M(n,r);if((0,j.isScalar)(t))return{kind:e,source:i,target:J(t,e,r)};let a=P(t,e,r);F(a,e,[...q,`optional`,`label`],r);let o=qt(a,e,r),s=K(a,e,r);return O({kind:e,source:i,target:Ir(a.filter(e=>e.key!==`optional`&&e.key!==`label`),e,r),...o,label:s})}const ei=[...q,`optional`];function ti(e,t,n,r){if(!I(e,t))return;let{optional:i,...a}=J(L(e,t),n,r,ei);return{selector:a,optional:i}}function ni(e,t,n){let r=ti(e,`visible`,`extendedWaitUntil.visible`,n),i=ti(e,`notVisible`,`extendedWaitUntil.notVisible`,n);return r&&i&&N(`Maestro extendedWaitUntil cannot specify both visible and notVisible.`,t,n),!r&&!i&&N(`Maestro extendedWaitUntil requires visible or notVisible.`,t,n),r?{key:`visible`,selector:r.selector,optional:r.optional}:{key:`notVisible`,selector:i.selector,optional:i.optional}}function ri(e,t,n){let r=M(t,n);if((0,j.isScalar)(e))return{kind:`runScript`,source:r,file:V(e,`runScript`,n)};let i=P(e,`runScript`,n);return F(i,`runScript`,[`file`,`env`],n),I(i,`file`)||N(`Maestro runScript requires a file.`,t,n),O({kind:`runScript`,source:r,file:V(L(i,`file`),`runScript.file`,n),env:I(i,`env`)?sn(L(i,`env`),`runScript.env`,n):void 0})}function ii(e,t,n,r){let i=M(t,n);if((0,j.isScalar)(e))return{kind:`runFlow`,source:i,include:{kind:`file`,path:V(e,`runFlow`,n)}};let a=P(e,`runFlow`,n);F(a,`runFlow`,[`file`,`commands`,`env`,`when`,`label`],n);let o=I(a,`file`);return o===I(a,`commands`)&&N(`Maestro runFlow requires exactly one of file or commands.`,t,n),O({kind:`runFlow`,source:i,include:o?{kind:`file`,path:V(L(a,`file`),`runFlow.file`,n)}:{kind:`commands`,commands:r(L(a,`commands`),`runFlow.commands`,n)},env:I(a,`env`)?sn(L(a,`env`),`runFlow.env`,n):void 0,when:I(a,`when`)?si(L(a,`when`),`runFlow.when`,n):void 0,label:K(a,`runFlow`,n)})}function ai(e,t,n,r){let i=M(t,n),a=P(e,`repeat`,n);F(a,`repeat`,[`times`,`commands`,`while`],n);let o=I(a,`while`)?si(L(a,`while`),`repeat.while`,n):void 0;return!I(a,`times`)&&!o&&N(`Maestro repeat requires times or while.`,t,n),I(a,`commands`)||N(`Maestro repeat requires commands.`,t,n),O({kind:`repeat`,source:i,times:I(a,`times`)?an(L(a,`times`),`repeat.times`,n):void 0,while:o,commands:r(L(a,`commands`),`repeat.commands`,n)})}function oi(e,t,n,r){let i=M(t,n),a=P(e,`retry`,n);F(a,`retry`,[`maxRetries`,`commands`],n),I(a,`commands`)||N(`Maestro retry requires commands.`,t,n);let o=I(a,`maxRetries`)?an(L(a,`maxRetries`),`retry.maxRetries`,n):void 0;return O({kind:`retry`,source:i,commands:r(L(a,`commands`),`retry.commands`,n),maxRetries:o})}function si(e,t,n){let r=P(e,t,n);return F(r,t,[`platform`,`visible`,`notVisible`,`true`],n),r.length===0&&N(`Maestro ${t} cannot be empty.`,e,n),O({platform:R(r,`platform`,e=>li(e,n,`${t}.platform`)),visible:R(r,`visible`,e=>J(e,`${t}.visible`,n)),notVisible:R(r,`notVisible`,e=>J(e,`${t}.notVisible`,n)),true:R(r,`true`,e=>ci(e,n,`${t}.true`))})}function ci(e,t,n){let r=B(e,n,t);if(typeof r==`boolean`||typeof r==`string`)return r;N(`Maestro ${n} expects a boolean or expression string.`,e,t)}function li(e,t,n){let r=V(e,n,t).toLowerCase();if(r===`android`||r===`ios`||r===`web`)return r;N(`Maestro ${n} expects Android, iOS, or Web.`,e,t)}function ui(e,t,n){return Gt(e,t,n).map(e=>di(e,n))}function di(e,t){if((0,j.isScalar)(e))return typeof e.value!=`string`&&N(`Maestro command names must be strings.`,e,t),fi(e.value,e,t);(0,j.isMap)(e)||N(`Maestro commands must be a scalar or one-key map.`,e,t);let n=P(e,`command`,t);n.length!==1&&N(`Maestro command maps must contain exactly one command.`,e,t);let r=n[0];return mi(r.key,r.value,e,t)}function fi(e,t,n){return mi(e,null,t,n)}const pi={launchApp:hi,tapOn:Wr,doubleTapOn:Gr,longPressOn:Kr,inputText:gi,eraseText:_i,openLink:vi,assertVisible:(e,t,n)=>$r(`assertVisible`,e,t,n),assertNotVisible:(e,t,n)=>$r(`assertNotVisible`,e,t,n),assertTrue:yi,extendedWaitUntil:bi,takeScreenshot:xi,scroll:Si,scrollUntilVisible:Ci,swipe:qr,hideKeyboard:wi,pressKey:Ti,back:Ei,waitForAnimationToEnd:Di,stopApp:Oi,killApp:ki,setPermissions:Ai,clearState:Ni,runScript:ri,evalScript:Pi,runFlow:(e,t,n)=>ii(e,t,n,ui),repeat:(e,t,n)=>ai(e,t,n,ui),retry:(e,t,n)=>oi(e,t,n,ui)};Object.keys(pi);function mi(e,t,n,r){let i=pi[e];return i||N(`Maestro command "${e}" is not supported.`,n,r),i(t,n,r)}function hi(e,t,n){let r=M(t,n);if(z(e))return{kind:`launchApp`,source:r};if((0,j.isScalar)(e))return{kind:`launchApp`,source:r,appId:V(e,`launchApp`,n)};let i=P(e,`launchApp`,n);return F(i,`launchApp`,[`appId`,`stopApp`,`clearState`,`permissions`,`arguments`,`launchArguments`],n),O({kind:`launchApp`,source:r,appId:R(i,`appId`,e=>Jt(e,`launchApp.appId`,n)),stopApp:R(i,`stopApp`,e=>Yt(e,`launchApp.stopApp`,n)),clearState:R(i,`clearState`,e=>Yt(e,`launchApp.clearState`,n)),permissions:R(i,`permissions`,e=>ji(e,n,`launchApp`)),arguments:R(i,`arguments`,e=>Fi(e,`launchApp.arguments`,n)),launchArguments:R(i,`launchArguments`,e=>Fi(e,`launchApp.launchArguments`,n))})}function gi(e,t,n){let r=M(t,n);if((0,j.isScalar)(e))return{kind:`inputText`,source:r,text:V(e,`inputText`,n)};let i=P(e,`inputText`,n);return F(i,`inputText`,[`text`,`label`],n),I(i,`text`)||N(`Maestro inputText requires text.`,t,n),O({kind:`inputText`,source:r,text:V(L(i,`text`),`inputText.text`,n),label:K(i,`inputText`,n)})}function _i(e,t,n){let r=M(t,n);if(z(e))return{kind:`eraseText`,source:r};if((0,j.isScalar)(e))return{kind:`eraseText`,source:r,charactersToErase:an(e,`eraseText`,n)};let i=P(e,`eraseText`,n);return F(i,`eraseText`,[`charactersToErase`],n),O({kind:`eraseText`,source:r,charactersToErase:I(i,`charactersToErase`)?H(L(i,`charactersToErase`),`eraseText.charactersToErase`,n):void 0})}function vi(e,t,n){let r=M(t,n);if((0,j.isScalar)(e))return{kind:`openLink`,source:r,link:V(e,`openLink`,n)};let i=P(e,`openLink`,n);return F(i,`openLink`,[`link`],n),{kind:`openLink`,source:r,link:V(L(i,`link`),`openLink.link`,n)}}function yi(e,t,n){let r=M(t,n);if(z(e)&&N(`Maestro assertTrue requires condition.`,t,n),(0,j.isScalar)(e))return{kind:`assertTrue`,source:r,condition:on(e,`assertTrue`,n)};let i=P(e,`assertTrue`,n);F(i,`assertTrue`,[`condition`,`optional`,`label`],n),I(i,`condition`)||N(`Maestro assertTrue requires condition.`,t,n);let a=on(L(i,`condition`),`assertTrue.condition`,n),o=qt(i,`assertTrue`,n),s=K(i,`assertTrue`,n);return O({kind:`assertTrue`,source:r,condition:a,...o,label:s})}function bi(e,t,n){let r=P(e,`extendedWaitUntil`,n);F(r,`extendedWaitUntil`,[`visible`,`notVisible`,`timeout`,`optional`,`label`],n);let i=qt(r,`extendedWaitUntil`,n),a=K(r,`extendedWaitUntil`,n),o=ni(r,t,n),s=I(r,`timeout`)?H(L(r,`timeout`),`extendedWaitUntil.timeout`,n):void 0,c=i.optional===!0||o.optional===!0||void 0,l={kind:`extendedWaitUntil`,source:M(t,n),timeout:s,optional:c,label:a};return l[o.key]=o.selector,O(l)}function xi(e,t,n){return{kind:`takeScreenshot`,source:M(t,n),path:V(e,`takeScreenshot`,n)}}function Si(e,t,n){return z(e)||N(`Maestro scroll does not accept options yet.`,t,n),{kind:`scroll`,source:M(t,n)}}function Ci(e,t,n){let r=M(t,n);if((0,j.isScalar)(e))return{kind:`scrollUntilVisible`,source:r,element:J(e,`scrollUntilVisible.element`,n)};let i=P(e,`scrollUntilVisible`,n);F(i,`scrollUntilVisible`,[`element`,`direction`,`timeout`,`optional`,`label`],n);let a=qt(i,`scrollUntilVisible`,n),o=K(i,`scrollUntilVisible`,n),s=ti(i,`element`,`scrollUntilVisible.element`,n);s||N(`Maestro scrollUntilVisible requires element.`,t,n);let c=I(i,`direction`)?Qr(L(i,`direction`),`scrollUntilVisible.direction`,n):void 0,l=I(i,`timeout`)?H(L(i,`timeout`),`scrollUntilVisible.timeout`,n):void 0,u=a.optional===!0||s.optional===!0||void 0;return O({kind:`scrollUntilVisible`,source:r,element:s.selector,direction:c,timeout:l,optional:u,label:o})}function wi(e,t,n){return z(e)||N(`Maestro hideKeyboard does not accept options.`,t,n),{kind:`hideKeyboard`,source:M(t,n)}}function Ti(e,t,n){let r=V(e,`pressKey`,n).toLowerCase();return r!==`back`&&r!==`enter`&&r!==`return`&&r!==`home`&&N(`Maestro pressKey "${r}" is not supported.`,e,n),{kind:`pressKey`,source:M(t,n),key:r}}function Ei(e,t,n){return z(e)||N(`Maestro back does not accept options.`,t,n),{kind:`back`,source:M(t,n)}}function Di(e,t,n){let r=M(t,n);if(z(e))return{kind:`waitForAnimationToEnd`,source:r};if((0,j.isScalar)(e))return O({kind:`waitForAnimationToEnd`,source:r,timeout:H(e,`waitForAnimationToEnd`,n)});let i=P(e,`waitForAnimationToEnd`,n);return F(i,`waitForAnimationToEnd`,[`timeout`],n),O({kind:`waitForAnimationToEnd`,source:r,timeout:I(i,`timeout`)?H(L(i,`timeout`),`waitForAnimationToEnd.timeout`,n):void 0})}function Oi(e,t,n){let r=M(t,n);return z(e)?{kind:`stopApp`,source:r}:{kind:`stopApp`,source:r,appId:V(e,`stopApp`,n)}}function ki(e,t,n){let r=M(t,n);return z(e)?{kind:`killApp`,source:r}:{kind:`killApp`,source:r,appId:V(e,`killApp`,n)}}function Ai(e,t,n){let r=M(t,n),i=P(e,`setPermissions`,n);F(i,`setPermissions`,[`appId`,`permissions`,`optional`,`label`],n),I(i,`permissions`)||N(`Maestro setPermissions requires permissions.`,t,n);let a=R(i,`appId`,e=>Jt(e,`setPermissions.appId`,n)),o=ji(L(i,`permissions`),n),s=qt(i,`setPermissions`,n),c=K(i,`setPermissions`,n);return O({kind:`setPermissions`,source:r,appId:a,permissions:o,...s,label:c})}function ji(e,t,n=`setPermissions`){let r=P(e,`${n}.permissions`,t);r.length===0&&N(`Maestro ${n}.permissions requires at least one permission.`,e,t);let i={};for(let e of r)i[e.key]=Mi(e,t,n);return i}function Mi(e,t,n=`setPermissions`){let r=`${n}.permissions.${e.key}`,i=B(e.value,r,t);typeof i!=`string`&&N(`Maestro ${r} expects a string.`,e.value,t);let a=i.toLowerCase();if(Zt.has(a))return a;if(Xt.test(i))return i;i.includes("${")&&N(`Maestro ${r} only supports allow|deny|unset (plus always|inuse|never|limited for location/photos) or a bare \${VAR} lookup; JavaScript expressions are not supported.`,e.value,t),N(`Maestro ${r} expects allow|deny|unset (plus always|inuse|never|limited for location/photos) or a bare \${VAR} lookup.`,e.value,t)}function Ni(e,t,n){let r=M(t,n);return z(e)?{kind:`clearState`,source:r}:{kind:`clearState`,source:r,appId:V(e,`clearState`,n)}}function Pi(e,t,n){return{kind:`evalScript`,source:M(t,n),script:V(e,`evalScript`,n)}}function Fi(e,t,n){if((0,j.isSeq)(e))return{kind:`list`,values:Gt(e,t,n).map((e,r)=>{let i=B(e,`${t}[${r}]`,n);return i===null&&N(`${t}[${r}] expects a scalar value.`,e,n),i})};if((0,j.isMap)(e))return{kind:`map`,values:sn(e,t,n)};let r=B(e,t,n);return r===null&&N(`${t} expects a scalar, list, or map.`,e,n),{kind:`scalar`,value:r}}function Ii(e,t={}){let n=new j.LineCounter,r=O({lineCounter:n,sourcePath:t.sourcePath}),a=(0,j.parseAllDocuments)(e,{lineCounter:n});for(let e of a)if(e.errors.length>0){let t=e.errors[0],n=t?.message??`Invalid Maestro YAML flow.`,a=Ut(t?.pos[0],r);throw new i(`INVALID_ARGS`,`Invalid Maestro YAML flow: ${n} (${Wt(a)})`)}let o=a.map(e=>e.contents).filter(e=>e!==null);o.length===0&&N(`Maestro flow is empty.`,void 0,r);let s,c;o.length===1&&(0,j.isSeq)(o[0])?c=o[0]:o.length===2&&(0,j.isMap)(o[0])&&(0,j.isSeq)(o[1])?(s=o[0],c=o[1]):N(`Maestro flow must contain a command list, optionally preceded by one config document.`,o[0],r);let l=s?Li(s,r):{};return{kind:`program`,source:M(s??c,r),config:l,commands:ui(c,`commands`,r)}}function Li(e,t){let n=P(e,`flow config`,t);return F(n,`flow config`,[`name`,`appId`,`tags`,`env`,`onFlowStart`,`onFlowComplete`],t),O({name:R(n,`name`,e=>Jt(e,`name`,t)),appId:R(n,`appId`,e=>Jt(e,`appId`,t)),tags:R(n,`tags`,e=>Kt(e,`tags`,t)),env:R(n,`env`,e=>sn(e,`env`,t)),onFlowStart:R(n,`onFlowStart`,e=>ui(e,`onFlowStart`,t)),onFlowComplete:R(n,`onFlowComplete`,e=>ui(e,`onFlowComplete`,t))})}function Ri(e,t){let r=new Map;return async(i,a,o)=>{if(o?.aborted)throw n();let s=zi(i,a,e),c=r.get(s);if(c)return c;let l=Ii(t(s),{sourcePath:s});return r.set(s,l),l}}function zi(e,t,n){let r=t?D.dirname(t):n;return D.resolve(r,e)}function Bi(e){return xn(e)?{command:e.kind,...e.kind===`runFlow`?Y(e.label??e.includePath):{}}:{command:e.kind,...Vi(e)}}function Vi(e){return`label`in e&&e.label?Y(e.label):Hi(e)?Y(Yi(e.target)):Ui(e)?Wi(e):e.kind===`inputText`?Y(`<text>`):Gi(e)}function Hi(e){return e.kind===`tapOn`||e.kind===`doubleTapOn`||e.kind===`longPressOn`}function Ui(e){return e.kind===`assertVisible`||e.kind===`assertNotVisible`||e.kind===`extendedWaitUntil`||e.kind===`scrollUntilVisible`}function Wi(e){switch(e.kind){case`assertVisible`:case`assertNotVisible`:return Y(Xi(e.target));case`extendedWaitUntil`:return Y(Xi(e.visible??e.notVisible));case`scrollUntilVisible`:return Y(Xi(e.element))}}function Gi(e){return Ki(e)?qi(e):e.kind===`swipe`?Ji(e):e.kind===`runFlow`?Y(e.label??(e.include.kind===`file`?e.include.path:``)):e.kind===`assertTrue`?Y(String(e.condition)):{}}function Ki(e){return e.kind===`openLink`||e.kind===`takeScreenshot`||e.kind===`runScript`||e.kind===`pressKey`}function qi(e){switch(e.kind){case`openLink`:return Y(e.link);case`takeScreenshot`:return Y(e.path);case`runScript`:return Y(e.file);case`pressKey`:return Y(e.key)}}function Ji(e){return Y(e.gesture.kind===`coordinates`?`${Zi(e.gesture.start)} to ${Zi(e.gesture.end)}`:e.gesture.direction)}function Yi(e){return e.space===`target`?Xi(e.selector):`${e.x},${e.y}${e.space===`percent`?`%`:``}`}function Xi(e){return e?.id??e?.text}function Zi(e){return`${e.x},${e.y}${e.space===`percent`?`%`:``}`}function Y(e){return e?{value:e}:{}}const Qi=new Set(String.raw`^$\.*+?()[]{}|`);function $i(e,t){try{return RegExp(`^(?:${t})$`,`ims`).test(e)}catch{return e.toLocaleLowerCase()===t.toLocaleLowerCase()}}function ea(e){try{new RegExp(e)}catch{return e}let t=``;for(let n=0;n<e.length;n+=1){let r=e[n];if(r!==`\\`){if(Qi.has(r))return;t+=r;continue}let i=e[n+1];if(i===void 0||!Qi.has(i))return;t+=i,n+=1}return t}function ta(e,t,n){if(n===`android`&&e.visibleToUser===!1)return!1;if(w(e.rect))return t.isVisibleInEffectiveViewport(e);if(e.rect)return!1;if(n!==`android`&&e.hittable===!0)return!0;let r=t.findAncestor(e,e=>S(e,n)?e:null);return r?w(r.rect)?t.isVisibleInEffectiveViewport(r):n!==`android`&&r.hittable===!0:!1}function na(e,t,n){return!!n.findAncestor(e,e=>e.index===t.index?e:null)}function ra(e,t){let n=[t.id===void 0?void 0:aa(e.identifier,t.id),t.text===void 0?void 0:oa(e,t.text)].filter(e=>e!==void 0);return!(n.length===0&&t.enabled===void 0&&t.selected===void 0||n.some(e=>!e)||t.enabled!==void 0&&e.enabled!==!1!==t.enabled||t.selected!==void 0&&e.selected===!0!==t.selected)}function ia(e){return e.matches.filter(t=>ta(t,e.visibility,e.platform))}function aa(e,t){let n=e??``;return be(n)===be(t)||$i(n,t)}function oa(e,t){return[e.label,xe(e),e.identifier].filter(e=>!!e).some(e=>aa(e,t))}function sa(e){return e.index!==void 0||e.childOf!==void 0||e.below!==void 0||e.above!==void 0||e.leftOf!==void 0||e.rightOf!==void 0||e.containsChild!==void 0||e.containsDescendants!==void 0}function ca(e){return e.text!==void 0||e.id!==void 0||e.enabled!==void 0||e.selected!==void 0}function la(e,t,n){let r=[],i=0;for(let a of e)for(let e of n){let n=da(a.rect,e.rect);n===void 0||!ua(t,a.rect,e.rect)||r.push({node:a,distance:n,order:i++})}return r.sort((e,t)=>e.distance-t.distance||e.order-t.order),r.map(({node:e})=>e)}function ua(e,t,n){switch(e){case`below`:return t.y>n.y;case`above`:return t.y<n.y;case`leftOf`:return t.x<n.x;case`rightOf`:return t.x>n.x}}function da(e,t){if(!(!fa(e)||!fa(t)))return Math.fround(Math.hypot(pa(e.x,e.width)-pa(t.x,t.width),pa(e.y,e.height)-pa(t.y,t.height)))}function fa(e){return!!(e&&[e.x,e.y,e.width,e.height].every(Number.isFinite))}function pa(e,t){return e+Math.trunc(t/2)}function ma(e,t={},n={}){let r=y(e.nodes,t);t.onVisibilityContextCreated?.();let a=new WeakMap,o=new WeakSet,s=new WeakMap,c=new Map,l=t=>t.parentIndex===void 0?void 0:r.nodeByIndex.get(t.parentIndex)??e.nodes[t.parentIndex],u=e=>{let t=s.get(e);if(t)return t;let n=new Set,r=new Set,i=l(e);for(;i&&!r.has(i.index);)r.add(i.index),n.add(i.index),i=l(i);return s.set(e,n),n},d=(n,r)=>{let i=c.get(n);i||(i=new WeakMap,c.set(n,i));let a=i.get(r);if(a)return a;t.onPositionComputed?.(n,r);let o=la(e.nodes,n,m(r).indexed),s={ordered:o,candidateIndexes:new Set(o.map(e=>e.index))};return i.set(r,s),s},f=(e,t)=>d(e,t).ordered,p=(e,t)=>d(e,t).candidateIndexes,m=r=>{let s=a.get(r);if(s)return s;if(o.has(r))throw new i(`INVALID_ARGS`,`Maestro selector relations cannot contain cycles.`);o.add(r),t.onSelectorComputed?.(r);try{let t=ha(e,r,l,u,m,p),i={matches:t,indexed:ya(t,r.index,n.orderUnindexed)};return a.set(r,i),i}finally{o.delete(r)}};return{visibility:r,resolve:m,resolvePosition:f}}function ha(e,t,n,r,i,a){let{index:o,childOf:s,below:c,above:l,leftOf:u,rightOf:d,containsChild:f,containsDescendants:p,...m}=t,h=ca(m)?e.nodes.filter(e=>ra(e,m)):[...e.nodes];if(s){let e=new Set(i(s).indexed.map(e=>e.index));h=h.filter(t=>_a(r(t),e))}if(f){let e=new Set(i(f).indexed.map(n).filter(e=>e!==void 0).map(e=>e.index));h=h.filter(t=>e.has(t.index))}if(p){let e=p.map(e=>ga(i(e).indexed,r));h=h.filter(t=>e.every(e=>e.has(t.index)))}for(let[e,n]of va(t)){let t=a(e,n);h=h.filter(e=>t.has(e.index))}return h}function ga(e,t){let n=new Set;for(let r of e)for(let e of t(r))n.add(e);return n}function _a(e,t){for(let n of e)if(t.has(n))return!0;return!1}function va(e){return[[`below`,e.below],[`above`,e.above],[`leftOf`,e.leftOf],[`rightOf`,e.rightOf]].filter(e=>e[1]!==void 0)}function ya(e,t,n){if(t===void 0)return n?n(e):[...e];let r=xa(e)[Ca(t)];return r?[r]:[]}function ba(e,t){return t===void 0?e[0]:xa(e)[Ca(t)]}function xa(e){return[...e].sort((e,t)=>{let n=Sa(e.rect?.y),r=Sa(t.rect?.y);return n===r?Sa(e.rect?.x)-Sa(t.rect?.x):n-r})}function Sa(e){return e!==void 0&&Number.isFinite(e)?e:2**53-1}function Ca(e){let t=typeof e==`number`?e:Number(e.trim());if(!Number.isSafeInteger(t)||t<0)throw new i(`INVALID_ARGS`,`Maestro selector.index must be a non-negative integer.`);return t}const wa={android:{kind:`exact`,provider:`android-helper`},ios:{kind:`divergence`,provider:`apple-xctest`,reason:`maestro-clickable-not-exposed-by-provider`}};function Ta(e,t){let n=wa[t];if(n.kind===`divergence`)return n;let r=p(e);return r?r.kind!==`exact`||r.provider!==n.provider?{kind:`divergence`,provider:n.provider,reason:`unregistered-provider-evidence`}:r:{kind:`divergence`,provider:n.provider,reason:`exact-evidence-not-retained`}}function Ea(e,t){return t.kind===`exact`?e.map((e,n)=>({node:e,order:n,rank:Da(t.clickableByNodeIndex.get(e.index))})).sort((e,t)=>t.rank-e.rank||e.order-t.order).map(({node:e})=>e):[...e]}function Da(e){return e===!0?2:+(e===!1)}function Oa(e,t,n,r={}){let i=Ta(e,n),a=Aa(e,i,r),o=ka(t,a),s=ia({visibility:a.visibility,matches:o.matches,platform:n});return{...o,visible:s,clickability:i,ranked:ja(s,t,n,a.visibility,i)}}function ka(e,t){return{matches:t.resolve(e).matches,parentMatched:e.childOf===void 0||t.resolve(e.childOf).indexed.length>0}}function Aa(e,t,n={}){return ma(e,n,t?{orderUnindexed:e=>Ea(e,t)}:{})}function ja(e,t,n,r,i){let a=n!==`ios`||!Ia(t)?e:e.filter(n=>{if(Ba(n))return!0;let i=e.filter(e=>e!==n&&La(n,e,t));return!i.some(e=>Ba(e)&&na(n,e,r))&&!i.some(e=>na(e,n,r))});return t.index===void 0&&i?Ea(a,i):a}function Ma(e,t){let n=t===void 0?e.find(Fa):Na(e,t);return!n||!Fa(n)?null:{node:n,rect:n.rect}}function Na(e,t){return ba(e,t)}function Pa(e){return Fa(e)?e.rect:void 0}function Fa(e){return w(e.rect)}function Ia(e){return e.id!==void 0||e.text!==void 0}function La(e,t,n){if(n.id!==void 0&&za(e.identifier)!==za(t.identifier))return!1;if(n.text!==void 0){let n=Ra(e),r=new Set(Ra(t));if(!n.some(e=>r.has(e)))return!1}return!0}function Ra(e){return[e.label,e.value,e.identifier].map(za).filter(e=>e!==void 0)}function za(e){if(e)return be(e)||void 0}function Ba(e){let t=te(e.type??``);return t===`button`||t===`link`||t===`switch`||t===`searchfield`||t===`textfield`||t===`securetextfield`||t===`textview`}const Va=Symbol(`maestroFlowProgram`),Ha=Symbol(`maestroFailureCommand`),Ua=Symbol(`maestroFailurePlan`);function Wa(e,t){let n=Ii(e,{sourcePath:t});return{sourcePath:t,name:n.config.name,appTarget:Ya(n),[Va]:n}}async function Ga(e,t,n){let r;try{let i=D.dirname(e.sourcePath),a=Ri(i,n.readSource),o=await Jn(e[Va],{baseDir:i,defaults:n.defaults,env:n.env,platform:n.platform,target:n.target,runtimeHints:n.runtimeHints,loadProgram:a,signal:n.signal}),s=Qn(o,{from:n.from,planDigest:n.planDigest}),c=await Mr(o,t,{defaults:n.defaults,env:n.env,platform:n.platform,target:n.target,loadProgram:a,signal:n.signal,startIndex:s,trustedScripts:n.trustedScripts,observer:qa(o,n.observer,e=>{r=e})});return{ok:!0,replayed:o.total-s,planDigest:o.digest,startIndex:s,artifactPaths:c.artifactPaths,...c.warnings?{warnings:c.warnings}:{}}}catch(e){return{ok:!1,error:r?.error??e,...r?{failure:r}:{}}}}function Ka(e,t){let n=Za(e[Ha]),r=e[Ua].platform;return!n||r!==`android`&&r!==`ios`?[]:Oa(t,n.selector,r).ranked.map(e=>({node:e,basis:Qa(n.selector,e)}))}function qa(e,t,n){return{commandStarted:e=>t?.actionStarted?.(Ja(e)),commandCompleted:e=>t?.actionCompleted?.({...Ja(e),durationMs:e.durationMs,runtimeMetrics:e.runtimeMetrics,data:e.data}),commandFailed:r=>{let i=Zn(e,{from:r.stepIndex,planDigest:e.digest}),a={...Ja(r),durationMs:r.durationMs,error:r.error,artifactPaths:r.artifactPaths,warnings:[...r.warnings],isControl:xn(r.command),redactions:r.command.kind===`inputText`&&r.command.text.length>0?[{name:`inputText.text`,value:r.command.text}]:[],resume:i.allowed?{allowed:!0,from:r.stepIndex,planDigest:e.digest}:{allowed:!1,from:r.stepIndex,planDigest:e.digest,reason:i.reason},[Ha]:r.command,[Ua]:e};n(a),t?.actionFailed?.(a)}}}function Ja(e){let t=Bi(e.command);return{action:t.command,...t.value?{value:t.value}:{},source:e.source,generation:e.generation,stepIndex:e.stepIndex,stepTotal:e.stepTotal}}function Ya(e){return[e.config.appId,...[...e.config.onFlowStart??[],...e.commands].filter(e=>e.kind===`launchApp`).map(e=>e.kind===`launchApp`?e.appId:void 0)].find(Xa)}function Xa(e){return!!(e?.trim()&&!e.includes(`$`)&&!d(e))}function Za(e){switch(e.kind){case`tapOn`:return e.target.space===`target`?{selector:e.target.selector}:void 0;case`doubleTapOn`:case`longPressOn`:return e.target.space===`target`?{selector:e.target.selector}:void 0;case`assertVisible`:case`assertNotVisible`:return{selector:e.target};case`extendedWaitUntil`:return e.visible?{selector:e.visible}:e.notVisible?{selector:e.notVisible}:void 0;case`scrollUntilVisible`:return{selector:e.element};case`swipe`:return e.gesture.kind===`target`?{selector:e.gesture.from}:void 0;default:return}}function Qa(e,t){return e.id!==void 0||e.text!==void 0&&ra({...t,label:void 0,value:void 0},{text:e.text})?`id`:e.text===void 0?`other`:`label`}function $a(e){let t={[e.entryPath]:e.entrySource},n=eo(e.entrySource,e.entryPath);return n&&to({program:n,sourcePath:e.entryPath,context:Ce({},{...e.env}),files:t,readSource:e.readSource}),t}function eo(e,t){try{return Ii(e,{sourcePath:t})}catch{return}}function to(e){let t=e.context.enter(e.program.config.env??{});try{no([...e.program.config.onFlowStart??[],...e.program.commands,...e.program.config.onFlowComplete??[]],e)}finally{t()}}function no(e,t){for(let n of e){if(n.kind===`repeat`||n.kind===`retry`){no(n.commands,t);continue}if(n.kind!==`runFlow`)continue;let e=t.context.enter(n.env??{});try{if(n.include.kind===`commands`){no(n.include.commands,t);continue}ro(n.include.path,t)}finally{e()}}}function ro(e,t){let n=t.context.resolveDeferred(e);if(n.includes("${"))return;let r=zi(n,t.sourcePath,t.sourcePath);if(t.files[r]!==void 0)return;let i=t.readSource(r);if(i===void 0)return;t.files[r]=i;let a=eo(i,r);a&&to({...t,program:a,sourcePath:r})}function io(e,t){return`${e},${t}`}const ao={open:oo,back:()=>({kind:`commands`,commands:[`back`]}),home:()=>({kind:`commands`,commands:[{pressKey:`Home`}]}),keyboard:lo};function oo(e){let[t,n]=e.positionals;if(!t)return{kind:`unsupported`,message:`open requires an app id or URL`};if(d(t))return{kind:`commands`,commands:[{openLink:t}]};let r=so(e,t);return n&&d(n)?{kind:`config`,appId:t,commands:[r,{openLink:n}]}:n?{kind:`unsupported`,message:`open with a non-URL second argument is unsupported`}:{kind:`config`,appId:t,commands:[r]}}function so(e,t){return{launchApp:{appId:t,...co(e)}}}function co(e){let t=e.flags?.launchArgs,n={};return e.flags?.relaunch===!0&&(n.stopApp=!0),e.flags?.clearAppState===!0&&(n.clearState=!0),Array.isArray(t)&&t.length>0&&(n.launchArguments=t),n}function lo(e){let[t]=e.positionals;return t===`dismiss`?{kind:`commands`,commands:[`hideKeyboard`]}:t===`enter`||t===`return`?{kind:`commands`,commands:[{pressKey:`Enter`}]}:{kind:`unsupported`,message:`keyboard ${t??``}`.trim()}}function uo(e){return`${e.map(e=>(0,j.stringify)(e).trimEnd()).join(`
|
|
116
116
|
---
|
|
117
|
-
`)}\n`}function uo(e,t){let n={config:fo(t.metadata),warnings:[],unsupported:[]},r=[];for(let[i,a]of e.entries()){let e=t.actionLines?.[i]??i+1,o=mo(a,t.resolveSelector);switch(o.kind){case`commands`:r.push(...o.commands),Lo(n,o.warnings,a,e);break;case`config`:n.config.appId??=o.appId,r.push(...o.commands),Lo(n,o.warnings,a,e);break;case`unsupported`:n.unsupported.push({line:e,action:Vo(a),message:o.message})}}if(n.unsupported.length>0)throw new i(`INVALID_ARGS`,`Cannot export replay to Maestro YAML: unsupported .ad action ${Bo(n.unsupported)}.`,{unsupported:n.unsupported});return{yaml:zo(n.config,r),warnings:n.warnings}}function fo(e){return e?.env&&Object.keys(e.env).length>0?{env:e.env}:{}}const po={...io,click:ho,press:ho,longpress:go,fill:bo,type:xo,wait:So,find:wo,screenshot:To,scroll:Eo,swipe:Do};function mo(e,t){return po[e.command]?.(e,t)??{kind:`unsupported`,message:`${e.command} has no Maestro equivalent`}}function ho(e,t){let[n,r]=e.positionals;if(!n)return{kind:`unsupported`,message:`${e.command} requires a target`};let i=jo(n,r,t);if(!i)return{kind:`unsupported`,message:`tap target is not Maestro-compatible`};let a=Mo(e);return a.ok?e.flags?.doubleTap===!0?{kind:`commands`,commands:[{doubleTapOn:i}],warnings:[...Co(n),...yo(e,`doubleTapOn`)]}:typeof e.flags?.holdMs==`number`?{kind:`commands`,commands:[{longPressOn:i}],warnings:[...Co(n),vo(e.flags.holdMs),...yo(e,`longPressOn`)]}:{kind:`commands`,commands:[Fo(i,a.options)],warnings:Co(n)}:{kind:`unsupported`,message:a.message}}function go(e,t){let[n,r]=e.positionals;if(!n)return{kind:`unsupported`,message:`longpress requires a target`};let i=jo(n,r,t);return i?{kind:`commands`,commands:[{longPressOn:i}],warnings:[...Co(n),..._o(e).map(vo)]}:{kind:`unsupported`,message:`longpress target is not Maestro-compatible`}}function _o(e){let[t,n,r]=e.positionals,i=Z(t)&&Z(n)?r:n;return i&&Z(i)?[Number(i)]:[]}function vo(e){return`long-press duration exports as Maestro longPressOn; Maestro uses its default long-press duration instead of ${e}ms`}function yo(e,t){let n=[];return typeof e.flags?.count==`number`&&e.flags.count>1&&n.push(`tap --count ${e.flags.count} is not represented by Maestro ${t}`),typeof e.flags?.intervalMs==`number`&&e.flags.intervalMs>0&&n.push(`tap --interval-ms ${e.flags.intervalMs} is not represented by Maestro ${t}`),n}function bo(e,t){let[n,r]=e.positionals;if(!n||r===void 0)return{kind:`unsupported`,message:`fill requires a target and text`};let i=jo(n,void 0,t);return i?r.length===0?{kind:`commands`,commands:[{tapOn:i},`eraseText`],warnings:[...Co(n),`fill "" exports as tapOn + eraseText; Maestro erases at most its 50-character default`]}:{kind:`commands`,commands:[{tapOn:i},{inputText:r}],warnings:[...Co(n),`fill exports as tapOn + inputText; Maestro may append text instead of replacing existing field contents`]}:{kind:`unsupported`,message:`fill target is not Maestro-compatible`}}function xo(e){let[t]=e.positionals;if(t===void 0)return{kind:`unsupported`,message:`type requires text`};let n=Io(t);return n===null?{kind:`commands`,commands:[{inputText:t}]}:{kind:`commands`,commands:[{eraseText:n}]}}function So(e,t){let[n,r]=e.positionals;if(!n)return{kind:`unsupported`,message:`wait requires a target or duration`};if(Z(n))return{kind:`commands`,commands:[{waitForAnimationToEnd:{timeout:Number(n)}}],warnings:[`wait <ms> exports as waitForAnimationToEnd and may return before the full duration`]};if(n===`absent`)return{kind:`unsupported`,message:`strict wait absent requires zero selector matches and is unsupported by Maestro`};if(n===`text`&&r)return{kind:`commands`,commands:[{extendedWaitUntil:{visible:r,timeout:Ro(e,er.extendedWaitUntilTimeoutMs)}}]};let i=t(n);return i?{kind:`commands`,commands:[{extendedWaitUntil:{visible:i,timeout:Ro(e,er.extendedWaitUntilTimeoutMs)}}],warnings:Co(n)}:{kind:`unsupported`,message:`wait selector is not Maestro-compatible`}}function Co(e){return T(e,`label`)?[`label= selectors export as Maestro text; Maestro text matching is broader than agent-device label-only matching`]:[]}function wo(e){let[t,n,r]=e.positionals;return t!==`text`||!n||!r?{kind:`unsupported`,message:`only find text <query> exists|missing exports to Maestro`}:r===`exists`?{kind:`commands`,commands:[{assertVisible:n}]}:r===`missing`||r===`not-exists`?{kind:`commands`,commands:[{assertNotVisible:n}]}:{kind:`unsupported`,message:`find text assertion "${r}" is unsupported`}}function To(e){let[t]=e.positionals;return t?{kind:`commands`,commands:[{takeScreenshot:t}]}:{kind:`unsupported`,message:`screenshot requires an output path`}}function Eo(e){let[t]=e.positionals;if(t&&t!==`down`)return{kind:`unsupported`,message:`scroll ${t} is not exported yet`};let n=typeof e.flags?.until==`string`?e.flags.until:void 0;return{kind:`commands`,commands:[`scroll`],warnings:n===void 0?[]:[`scroll --until ${n} is not represented by Maestro scroll`]}}function Do(e){let t=Oo(e);if(!t)return{kind:`unsupported`,message:`only coordinate swipe exports to Maestro`};let n=ko(e);if(n===null)return{kind:`unsupported`,message:`swipe count must be a positive integer`};let r=Ao(e);return r?{kind:`unsupported`,message:r}:{kind:`commands`,commands:Array.from({length:n},()=>({swipe:t}))}}function Oo(e){let[t,n,r,i]=e.positionals;if(!(!Z(t)||!Z(n)||!Z(r)||!Z(i)))return{start:ro(t,n),end:ro(r,i),duration:100}}function ko(e){let t=e.flags?.count??1;return Number.isInteger(t)&&t>=1?t:null}function Ao(e){if(e.flags?.pauseMs!==void 0)return`swipe --pause-ms has no Maestro equivalent`;if(e.flags?.pattern&&e.flags.pattern!==`one-way`)return`swipe ping-pong pattern has no Maestro equivalent`}function jo(e,t,n){return Z(e)&&Z(t)?{point:ro(e,t)}:e.startsWith(`@`)?null:n(e)}function Mo(e){let t=Po(e);return t?{ok:!1,message:t}:{ok:!0,options:No(e)}}function No(e){let t={};return typeof e.flags?.count==`number`&&e.flags.count>1&&(t.repeat=e.flags.count),typeof e.flags?.intervalMs==`number`&&e.flags.intervalMs>0&&(t.delay=e.flags.intervalMs),t}function Po(e){if(e.flags?.jitterPx!==void 0)return`tap --jitter-px has no Maestro equivalent`;if(e.flags?.clickButton&&e.flags.clickButton!==`primary`)return`tap --button ${e.flags.clickButton} has no Maestro equivalent`}function Fo(e,t){return Object.keys(t).length===0?{tapOn:e}:typeof e==`string`?{tapOn:{text:e,...t}}:e&&typeof e==`object`&&!Array.isArray(e)?{tapOn:{...e,...t}}:{tapOn:e}}function Io(e){return e.length===0||![...e].every(e=>e===`\b`)?null:e.length}function Lo(e,t,n,r){for(let i of t??[])e.warnings.push({line:r,action:Vo(n),message:i})}function Ro(e,t){let n=e.positionals.at(-1);return n&&Z(n)?Number(n):t}function zo(e,t){return lo(Object.keys(e).length>0?[e,t]:[t])}function Bo(e){return e.map(e=>`line ${e.line} (${e.action}): ${e.message}`).join(`; `)}function Vo(e){return[e.command,...e.positionals??[]].join(` `).trim()}function Z(e){return e!==void 0&&Number.isFinite(Number(e))}function Ho(e,t){return O({appId:e.appId,env:e.env,generation:e.generation,invalidateObservation:e.invalidateObservation,source:t?.source,cachedObservation:e.cachedObservation,signal:e.signal})}function Uo(e){return O({env:e.env,generation:e.generation,cachedObservation:e.cachedObservation,signal:e.signal})}async function Wo(e,t){let n=Zo(await t.observe({condition:e.condition,timeoutMs:e.timeoutMs},Uo(e)),e.generation),r={kind:`selector`,selector:e.condition.selector,visible:n.visible,candidateCount:n.candidateCount,...n.ref?{ref:n.ref}:{}};return{generation:e.generation,matched:Go(e.condition,n),candidateCount:n.candidateCount,evidence:r}}function Go(e,t){let n=t.matched&&t.visible&&t.failureReason===void 0;return e.kind===`visible`?n:!n}async function Ko(e,t,n,r){let i=Zo(await r.resolveTarget({selector:e,...t},Ho(n,n.command)),n.generation);if(!i.matched||!i.visible||!i.rect)throw rr(Jo(e,i),{selector:e,candidateCount:i.candidateCount,...i.failureReason?{targetFailureReason:i.failureReason}:{}});return{kind:`selector`,selector:e,query:{selector:e,...t},...i,rect:i.rect}}function qo(e){let t={kind:`selector`,selector:e.selector,visible:e.visible,candidateCount:e.candidateCount,...e.ref?{ref:e.ref}:{}};return{generation:e.generation,matched:e.matched&&e.visible,candidateCount:e.candidateCount,evidence:t}}function Jo(e,t){let n=Yo(e);switch(t.failureReason){case`selector-did-not-match`:return`Maestro target ${n} did not match any element.`;case`no-visible-match`:return`Maestro target ${n} matched ${t.candidateCount} element(s), but none were visible.`;case`index-out-of-range`:return`Maestro target ${n} matched ${t.candidateCount} element(s); its index is out of range.`;case`no-usable-geometry`:return`Maestro target ${n} did not provide usable geometry.`;default:return`Maestro target did not resolve to a visible element.`}}function Yo(e){let t=Object.entries(e).filter(([,e])=>e!==void 0);return t.length===0?`selector`:t.map(([e,t])=>`"${e}":${JSON.stringify(t)}`).join(`, `)}function Xo(e){if(!e||typeof e!=`object`)return!1;let t=e;return[`x`,`y`,`width`,`height`].every(e=>typeof t[e]==`number`&&Number.isFinite(t[e]))}function Zo(e,t){return Qo(e,t),$o(e),es(e),ts(e),e}function Qo(e,t){if(e.generation!==t)throw new i(`COMMAND_FAILED`,`Maestro target evidence generation ${e.generation} does not match ${t}.`)}function $o(e){if(!Number.isInteger(e.candidateCount)||e.candidateCount<0)throw new i(`COMMAND_FAILED`,`Maestro target evidence has an invalid candidate count.`)}function es(e){if(e.rect!==void 0&&!Xo(e.rect)||e.viewport!==void 0&&!Xo(e.viewport))throw new i(`COMMAND_FAILED`,`Maestro target evidence has invalid geometry.`)}function ts(e){if(e.surfaceSignature!==void 0&&typeof e.surfaceSignature!=`string`)throw new i(`COMMAND_FAILED`,`Maestro target evidence has an invalid surface signature.`)}function ns(e,t,n,r,i,a={}){let o=rs(e,t,n,i,a);if(!o)return;let{start:s,end:c}=ss(o,n);return{gesture:{from:s,to:c,durationMs:r},viewport:o}}function rs(e,t,n,r,i){let a=n===`up`||n===`down`,o=ka(e,wa(e,r),i),s=o.visibility,c=ra({visibility:s,matches:e.nodes.filter(e=>C(e)),platform:r}),l=ne(s.viewportRects)??as(c);if(!l||!w(l))return;let u=c.flatMap(e=>{if(!w(e.rect))return[];let t=E(e.rect,l);return!t||(a?t.height<=t.width:t.width<t.height)?[]:[{node:e,viewport:t}]}),d=new Map(u.map(e=>[e.node.index,e]));for(let e of o.resolve(t).indexed){let t=is(e,s.nodeByIndex),n=t?d.get(t.index):void 0;if(n)return n.viewport}return u.sort(os)[0]?.viewport}function is(e,t){return C(e)?e:ee(e,t)}function as(e){let t;for(let n of e)w(n.rect)&&(!t||n.rect.width*n.rect.height>t.width*t.height)&&(t=n.rect);return t}function os(e,t){return t.viewport.width*t.viewport.height-e.viewport.width*e.viewport.height}function ss(e,t){let n=fs(e,.5,.5),r=K.scrollUntilVisibleSwipe.nearEdgeFraction,i=K.scrollUntilVisibleSwipe.farEdgeFraction;switch(t){case`up`:return{start:n,end:fs(e,.5,i)};case`down`:return{start:n,end:fs(e,.5,r)};case`left`:return{start:n,end:fs(e,i,.5)};case`right`:return{start:n,end:fs(e,r,.5)}}}async function cs(e,t,n){let r=W(e.duration,`swipe.duration`);if(e.kind===`coordinates`){if(e.start.space!==e.end.space)throw new i(`INVALID_ARGS`,`Maestro swipe endpoints must use the same coordinate space.`);let a=e.start.space===`percent`?await n.resolveGestureViewport(Ho(t,t.command)):void 0;return{authored:e,gesture:us(await ls(e.start,t,n,a),await ls(e.end,t,n,a),r),...a?{viewport:a}:{}}}if(e.kind===`screen`){let i=await n.resolveGestureViewport(Ho(t,t.command)),{start:a,end:o}=ds(i,e.direction,n.platform);return{authored:e,gesture:us(a,o,r),viewport:i}}let a=await Ko(e.from,{purpose:`swipe`,timeoutMs:`optional`in t.command&&t.command.optional===!0?K.command.optionalTargetLookupTimeoutMs:K.command.targetLookupTimeoutMs},t,n),o=a.viewport??await n.resolveGestureViewport(Ho(t,t.command)),{start:s,end:c}=ps(a,e.direction,o);return{authored:e,gesture:us(s,c,r),target:a,viewport:o}}async function ls(e,t,n,r){if(e.space===`absolute`)return{x:e.x,y:e.y};let i=r??await n.resolveGestureViewport(Ho(t,t.command));return{x:i.x+Math.trunc(i.width*e.x/100),y:i.y+Math.trunc(i.height*e.y/100)}}function us(e,t,n){return{from:e,to:t,durationMs:n??K.command.swipeDurationMs}}function ds(e,t,n){if(t===`left`||t===`right`){let n=l(t,{referenceWidth:e.width,referenceHeight:e.height});return{start:{x:e.x+n.x1,y:e.y+n.y1},end:{x:e.x+n.x2,y:e.y+n.y2}}}let r=K.screenSwipe,i=fs(e,r.centerFraction,r.nearEdgeFraction),a=fs(e,r.centerFraction,r.farEdgeFraction),o=fs(e,r.centerFraction,r.downStartFraction),s=fs(e,r.centerFraction,r.upStartFraction[n]);return t===`up`?{start:s,end:i}:{start:o,end:a}}function fs(e,t,n){return{x:e.x+Math.trunc(e.width*t),y:e.y+Math.trunc(e.height*n)}}function ps(e,t,n){let r=le(e.rect),i=n.x+Math.trunc(n.width*K.targetSwipe.nearEdgeFraction),a=n.y+Math.trunc(n.height*K.targetSwipe.nearEdgeFraction),o=n.x+Math.trunc(n.width*K.targetSwipe.farEdgeFraction),s=n.y+Math.trunc(n.height*K.targetSwipe.farEdgeFraction);switch(t){case`up`:return{start:r,end:{x:r.x,y:a}};case`down`:return{start:r,end:{x:r.x,y:s}};case`left`:return{start:r,end:{x:i,y:r.y}};case`right`:return{start:r,end:{x:o,y:r.y}}}}const ms={launchApp:ys,stopApp:ys,killApp:ys,setPermissions:ys,clearState:ys,openLink:ys,tapOn:Ss,doubleTapOn:Ss,longPressOn:Ss,swipe:Ds,inputText:Os,eraseText:Os,scroll:ks,scrollUntilVisible:ks,hideKeyboard:ks,pressKey:ks,back:ks,waitForAnimationToEnd:ks,takeScreenshot:Ms,runScript:Ms,evalScript:Ps,assertVisible:Ns,assertNotVisible:Ns,assertTrue:Ns,extendedWaitUntil:Ns},hs={launchApp:!0,stopApp:!0,killApp:!0,setPermissions:!0,clearState:!0,openLink:!0,tapOn:!0,doubleTapOn:!0,longPressOn:!0,swipe:!0,inputText:!0,eraseText:!0,scroll:!0,scrollUntilVisible:!0,hideKeyboard:!0,pressKey:!0,back:!0,waitForAnimationToEnd:!0,takeScreenshot:!1,runScript:!1,evalScript:!1,assertVisible:!1,assertNotVisible:!1,assertTrue:!1,extendedWaitUntil:!1};function gs(e){return hs[e.kind]}async function _s(e,t){let n=e.command;return await vs(n,e,t,Ho(e,n))}function vs(e,t,n,r){let i=ms[e.kind];return i(e,t,n,r)}async function ys(e,t,n,r){switch(e.kind){case`launchApp`:return await Q(n.launchApp,bs(e,t),r,`invalidate`);case`stopApp`:return await Q(n.stopApp,{appId:e.appId??t.appId},r,`invalidate`);case`killApp`:return await Q(n.killApp,{appId:e.appId??t.appId},r,`invalidate`);case`setPermissions`:return await Q(n.setPermissions,{appId:e.appId??t.appId,permissions:xs(e.permissions)},r,`invalidate`);case`clearState`:return await Q(n.clearState,{appId:e.appId??t.appId},r,`invalidate`);case`openLink`:return await Q(n.openLink,{link:e.link},r,`invalidate`)}}function bs(e,t){return O({appId:e.appId??t.appId,stopApp:e.stopApp,clearState:e.clearState,permissions:e.permissions?xs(e.permissions):void 0,arguments:e.arguments,launchArguments:e.launchArguments})}function xs(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.toLowerCase()]))}async function Ss(e,t,n,r){switch(e.kind){case`tapOn`:return await Cs(e,t,n,r);case`doubleTapOn`:{let i=await Hs(e.target,{purpose:`doubleTap`,timeoutMs:Ts(e)},t,n),a=W(e.delay,`doubleTapOn.delay`)??K.command.repeatDelayMs;return await Q(n.doubleTapOn,{target:i,delay:a},r,`invalidate`,i.resolution?qo(i.resolution):void 0)}case`longPressOn`:{let i=await Hs(e.target,{purpose:`longPress`,timeoutMs:Ts(e)},t,n);return await Q(n.longPressOn,{target:i},r,`invalidate`,i.resolution?qo(i.resolution):void 0)}}}async function Cs(e,t,n,r){let i=await ws(e,t,n);return await Q(n.tapOn,Es(e,i),r,`invalidate`,i.resolution?qo(i.resolution):void 0)}async function ws(e,t,n){let r={purpose:`tap`,timeoutMs:Ts(e),allowAtomicSelectorDispatch:e.repeat===void 0&&e.delay===void 0,...e.retryTapIfNoChange===!0?{includeSurfaceSignature:!0}:{}};return await Hs(e.target,r,t,n)}function Ts(e){return e.optional===!0?K.command.optionalTargetLookupTimeoutMs:K.command.targetLookupTimeoutMs}function Es(e,t){let n=W(e.repeat,`tapOn.repeat`),r=W(e.delay,`tapOn.delay`),i=n===void 0?r:r??K.command.repeatDelayMs;return O({target:t,retryTapIfNoChange:e.retryTapIfNoChange,repeat:n,delay:i})}async function Ds(e,t,n,r){let i=await cs(e.gesture,t,n);return await Q(n.gesture,i.gesture,{...r,...i.viewport?{gestureViewport:i.viewport}:{}},`invalidate`,i.target?qo(i.target):void 0)}async function Os(e,t,n,r){switch(e.kind){case`inputText`:return await Q(n.inputText,O({text:e.text,label:e.label}),r,`invalidate`);case`eraseText`:return await Q(n.eraseText,O({charactersToErase:W(e.charactersToErase,`eraseText.charactersToErase`)}),r,`invalidate`)}}async function ks(e,t,n,r){switch(e.kind){case`scroll`:return await Q(n.scroll,{direction:`down`},r,`invalidate`);case`scrollUntilVisible`:return await Q(n.scrollUntilVisible,As(e),r,`invalidate`);case`hideKeyboard`:return await Q(n.hideKeyboard,{},r,`invalidate`);case`pressKey`:return await Q(n.pressKey,{key:e.key},r,`invalidate`);case`back`:return await Q(n.back,{},r,`invalidate`);case`waitForAnimationToEnd`:return await Q(n.waitForAnimationToEnd,js(e),r,`preserve`)}}function As(e){return{selector:e.element,direction:e.direction??`down`,timeoutMs:W(e.timeout,`scrollUntilVisible.timeout`)??K.command.scrollUntilVisibleTimeoutMs,durationMs:$n(K.command.scrollUntilVisibleSpeed)}}function js(e){return O({timeoutMs:W(e.timeout,`waitForAnimationToEnd.timeout`)})}async function Ms(e,t,n,r){switch(e.kind){case`takeScreenshot`:return Is(await n.takeScreenshot({path:e.path},r),[],void 0,r.generation);case`runScript`:return await Q(n.runScript,O({file:e.file,env:e.env}),r,`preserve`)}}async function Ns(e){throw new i(`COMMAND_FAILED`,`Maestro ${e.kind} must be executed by the observation engine.`)}function Ps(e){throw new i(`COMMAND_FAILED`,`Maestro evalScript must be executed by the compute engine at ${e.source.path??``}line ${e.source.line}.`)}async function Q(e,t,n,r,i){let a=Fs(n,r);return Is(await e(t,a),[],r===`preserve`?i:void 0,a.generation)}function Fs(e,t){return t===`preserve`?e:(e.invalidateObservation(),{...e,generation:e.generation+1})}function Is(e,t,n,r){let i=e?.observation;return Ls(i,r),{...Rs(n??i),...zs(e?.outputEnv),...Bs(t,e?.artifactPaths),...Vs(e?.data),...e?.visualStabilityReached===void 0?{}:{visualStabilityReached:e.visualStabilityReached}}}function Ls(e,t){if(!(!e||t===void 0||e.generation===t))throw new i(`COMMAND_FAILED`,`Maestro operation evidence generation ${e.generation} does not match ${t}.`)}function Rs(e){return e?{observation:e}:{}}function zs(e){return e?{outputEnv:{...e}}:{}}function Bs(e,t){let n=[...new Set([...e,...t??[]])];return n.length>0?{artifactPaths:n}:{}}function Vs(e){return e&&Object.keys(e).length>0?{data:{...e}}:{}}async function Hs(e,t,n,r){if(e.space===`target`){let i=await Ko(e.selector,t,n,r);return{authored:e,point:le(i.rect),resolution:i}}return{authored:e,point:await ls(e,n,r)}}function Us(e,t,n,r={}){let i=n===`ios`&&r.presentation?Gs(r.presentation):void 0,a=i?Ks(e,t,i):Da(e,t.selector,n);if(!a.parentMatched)return{ok:!1,message:`Maestro childOf parent did not match.`,failureReason:`selector-did-not-match`,evidence:Xs(t,a.matches,[],void 0)};let{matches:o,ranked:s}=a,c=i?Ma(s,t.selector.index):ja(s,t.selector.index)?.node,l=Xs(t,o,s,c);if(!c)return qs(t,o,s,l);let u=i?ja(i.visibleForSource(c),void 0):null,d=Na(c),f=r.interactiveBounds?u?.rect??d:d??u?.rect;return f?{ok:!0,node:c,rect:f,matches:s.length,dispatchCandidates:n===`ios`&&t.allowAtomicSelectorDispatch&&!Ws(t.selector)&&i?Js(d,s,u):0,evidence:l}:{ok:!1,message:`Maestro target did not provide usable geometry.`,failureReason:`no-usable-geometry`,evidence:l}}const Ws=oa;function Gs(e){let t=y(e.snapshot.nodes),n=t.nodeByIndex,r=new Map,i=t=>(e.presentedIndexesBySourceIndex.get(t.index)??[]).flatMap(e=>{let t=n.get(e);return t?[t]:[]}),a=e=>{let n=r.get(e.index);if(n)return n;let a=i(e).filter(e=>ea(e,t,`ios`));return r.set(e.index,a),a};return{visibleForSource:a,isVisible:e=>a(e).length>0}}function Ks(e,t,n){let r=wa(e,`ios`),i=pa(e,{},{orderUnindexed:e=>Ta(e,r)}),a=Oa(t.selector,i),o=a.matches.filter(n.isVisible);return{...a,visible:o,clickability:r,ranked:Aa(o,t.selector,`ios`,i.visibility,r)}}function qs(e,t,n,r){if(t.length>0&&n.length===0)return{ok:!1,message:`Maestro selector matched ${t.length} element(s), but none were visible.`,failureReason:`no-visible-match`,evidence:r};let i=e.selector.index;return n.length>0?i!==void 0&&Ma(n,i)===void 0?{ok:!1,message:`Maestro selector matched ${n.length} visible element(s); index ${i} is out of range.`,failureReason:`index-out-of-range`,evidence:r}:{ok:!1,message:`Maestro target did not provide usable geometry.`,failureReason:`no-usable-geometry`,evidence:r}:{ok:!1,message:`Maestro selector did not match.`,failureReason:`selector-did-not-match`,evidence:r}}function Js(e,t,n){return t.length===1?e&&n&&n.node.hittable!==!1&&Ys(n.rect,e)?1:0:t.length}function Ys(e,t){let n=le(e),r=le(t);return n.x===r.x&&n.y===r.y}function Xs(e,t,n,r){return O({selector:e.selector,matched:t.length>0,visible:n.length>0,candidateCount:t.length,ref:r?.ref})}const $={settleTimeoutMs:tr,retryTapMaxAttempts:K.command.retryTapMaxAttempts,longPressDurationMs:K.command.longPressDurationMs,eraseTextMaxCharacters:K.command.eraseTextMaxCharacters,androidInputTextCharacterDelayMs:K.command.androidInputTextCharacterDelayMs,scrollUntilVisiblePercentage:K.command.scrollUntilVisiblePercentage,animationWaitTimeoutMs:K.command.waitForAnimationToEndTimeoutMs,animationDifferencePercent:K.command.waitForAnimationToEndDifferencePercent,observationPollMs:K.observation.pollIntervalMs};function Zs(e,t={}){return{execute:async n=>{let r=Ho(n,n.command),i=n.command.kind===`waitForAnimationToEnd`;await t.beforeExecute?.({context:r,requiresSettledPredecessor:gs(n.command)&&!i,visualStabilityBarrier:i});let a=await _s(n,e);return t.afterExecute?.({context:r,visualStabilityReached:i&&a.visualStabilityReached===!0}),delete a.visualStabilityReached,a},observe:async n=>{let r=await Wo(n,e);return t.bindObservation?.(r)??r},...t.readMetrics?{readMetrics:t.readMetrics}:{}}}const Qs=3e4,$s=1e3;function ec(e){let{scriptPath:t,env:n,publicNetworkOnly:r}=e,a=me.readFileSync(t,`utf8`),o=Object.create(null);try{ye.runInNewContext(a,tc(n,o,r),{filename:t,timeout:Qs})}catch(e){let n=c(e);throw new i(n.code,`Maestro runScript failed: ${n.message}`,d({...n.details??{},hint:n.hint,diagnosticId:n.diagnosticId,logPath:n.logPath,retriable:n.retriable,supportedOn:n.supportedOn,scriptPath:t}),e instanceof Error?e:void 0)}return cc(o,t),Object.fromEntries(Object.entries(o).map(([e,t])=>[`output.${e}`,lc(t)]))}function tc(e,t,n){return{...e,output:t,json:nc,http:{post:(e,t)=>ic(`POST`,e,n,t)}}}function nc(e){if(typeof e!=`string`)throw new i(`COMMAND_FAILED`,`Maestro runScript json() expected a string body, received ${typeof e}.`);if(e.trim().length===0)throw new i(`COMMAND_FAILED`,`Maestro runScript json() received an empty body.`,{hint:`Check the preceding HTTP response status and setup server output.`});try{return JSON.parse(e,rc)}catch(t){throw new i(`COMMAND_FAILED`,`Maestro runScript json() could not parse response body: ${t instanceof Error?t.message:String(t)}`,{bodyPreview:e.slice(0,$s)},t instanceof Error?t:void 0)}}function rc(e,t){return e===`__proto__`||e===`constructor`||e===`prototype`?void 0:t}function ic(e,t,n,r){let a=v(process.execPath,ac(),{stdin:JSON.stringify(sc(e,t,r,n)),timeoutMs:Qs,allowFailure:!0});if(a.exitCode!==0)throw new i(`COMMAND_FAILED`,`Maestro runScript http.${e.toLowerCase()} failed for ${t}: ${uc(a.stderr)}`,{exitCode:a.exitCode,stderr:a.stderr});try{return JSON.parse(a.stdout)}catch(n){throw new i(`COMMAND_FAILED`,`Maestro runScript http.${e.toLowerCase()} returned invalid JSON for ${t}`,{stdout:a.stdout.slice(0,$s),stderr:a.stderr.slice(0,$s)},n instanceof Error?n:void 0)}}function ac(){let e=oc(import.meta.url);if(!e)throw new i(`COMMAND_FAILED`,`Maestro runScript http helper entrypoint is unavailable; rebuild the package`);return e.endsWith(`.ts`)?[`--experimental-strip-types`,e]:[e]}function oc(e){try{let t=_e(e),n=D.extname(t)||`.js`;return[D.join(D.dirname(t),`run-script-http-child`+n),D.join(D.dirname(t),`internal`,`run-script-http-child`+n)].find(e=>me.existsSync(e))??null}catch{return null}}function sc(e,t,n,r){return{method:e,url:t,headers:n?.headers??{},body:n?.body??``,publicNetworkOnly:r}}function cc(e,t){for(let n of Object.keys(e))if(n.includes(`.`))throw new i(`INVALID_ARGS`,`Maestro runScript output key cannot contain ".": ${n}`,{scriptPath:t,key:n})}function lc(e){return typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`?String(e):JSON.stringify(e)}function uc(e){let t=e.trim();return t.length>0?t.slice(0,$s):`request process exited without stderr`}async function dc(e){return await fc(`tap`,async t=>{let n=D.join(t,`before.png`),r=D.join(t,`after.png`),i=await mc(e,n);return await e.run({matchesCurrent:async()=>{if(!(!i||!await mc(e,r)))return await pc(n,r,e.signal,`tap`)}})})}async function fc(e,t){let n=await he.mkdtemp(D.join(ge.tmpdir(),`agent-device-maestro-${e}-`));try{return await t(n)}finally{try{await he.rm(n,{recursive:!0,force:!0})}catch{}}}async function pc(e,t,n,r){try{let[i,a]=await Promise.all([he.readFile(e),he.readFile(t)]);vc(n);let o=await de(i,a,`Maestro screenshot`);return vc(n),hc(o,r)}catch(e){_c(e,n),g({level:`debug`,phase:`maestro_screenshot_compare`,data:{purpose:r,result:`error`,error:e instanceof Error?e.message:String(e)}});return}}async function mc(e,t){try{return await he.rm(t,{force:!0}),vc(e.signal),await e.capture(t),vc(e.signal),!0}catch(t){return _c(t,e.signal),!1}}function hc(e,t){if(e.status!==`compared`)return gc(t,e.status,e),!1;let n=e.differencePercent<=$.animationDifferencePercent;return gc(t,n?`stable`:`changed`,e),n}function gc(e,t,n){g({level:`debug`,phase:`maestro_screenshot_compare`,data:{purpose:e,result:t,first:n.first,second:n.second,...`differencePercent`in n?{differencePercent:n.differencePercent}:{}}})}function _c(e,t){if(t?.aborted||r(e))throw n()}function vc(e){if(e?.aborted)throw n()}async function yc(e){xc(e.timeoutMs),vc(e.signal);let t=e.now()+e.timeoutMs;return await fc(`animation`,async n=>{let r=D.join(n,`first.png`),i=D.join(n,`second.png`);for(;;){if(vc(e.signal),await bc(e,r,i))return!0;if(e.now()>=t)return!1}})}async function bc(e,t,n){let r=[await mc(e,t),await mc(e,n)];return!r[0]||!r[1]?!1:await pc(t,n,e.signal,`animation`)===!0}function xc(e){if(!Number.isFinite(e)||e<0)throw new i(`INVALID_ARGS`,`waitForAnimationToEnd timeout must be a non-negative number.`)}const Sc=$.observationPollMs;async function Cc(e,t){for(;;){Rc(e.context.signal);try{return await e.snapshot(e.context)}catch(n){if(!Bc(n)||(Rc(e.context.signal),!await Lc(e.dependencies,t,Sc,e.context.signal)))throw n}}}function wc(e){return Tc({...e,mode:e.query.purpose===`swipe`?`swipe`:`tap`})}function Tc(e){let t=ue(e.snapshot),n=e.platform===`ios`?fe(e.snapshot.nodes):void 0,r=n?{...e.snapshot,nodes:o(n.nodes)}:e.snapshot;return Ac(Us(e.snapshot,e.query,e.platform,{interactiveBounds:e.mode===`tap`,presentation:n?{snapshot:r,presentedIndexesBySourceIndex:n.presentedIndexesBySourceIndex}:void 0}),e.snapshot,e.context.generation,t,e.query,e.platform,e.mode)}async function Ec(e){zc(e.timeoutMs,`observation`);let t,n=e.dependencies.now()+e.timeoutMs;for(;;){Rc(e.context.signal);let r=await Cc(e,n),i=Tc({query:{selector:e.condition.selector},context:e.context,snapshot:r,platform:e.platform,mode:`observe`});if(t=i,Go(e.condition,i))return i;if(e.dependencies.now()>=n)break;await Lc(e.dependencies,n,Sc,e.context.signal)}return Rc(e.context.signal),Uc(t)}async function Dc(e){zc(e.timeoutMs,`scrollUntilVisible`);let t=e.dependencies.now()+e.timeoutMs,n,r;for(;;){Rc(e.context.signal);let i=r??await Cc(e,t);if(r=void 0,n=Tc({query:{selector:e.selector},context:e.context,snapshot:i,platform:e.platform,mode:`observe`}),n.visiblePercentage===$.scrollUntilVisiblePercentage)return n;if(e.dependencies.now()>=t)break;let a=t-e.dependencies.now();a>0&&(r=await e.scroll(a,i))}return Rc(e.context.signal),Uc(n)}async function Oc(e){zc(e.timeoutMs,`waitForAnimationToEnd`);let t=e.dependencies.now()+e.timeoutMs,n=e.initialSnapshot??await Cc(e,t),r=Vc(n);for(;;){Rc(e.context.signal),await Lc(e.dependencies,t,Sc,e.context.signal);let i=await Cc(e,t),a=Vc(i);if(a===r)return{snapshot:i,signature:a,settled:!0};if(n=i,r=a,e.dependencies.now()>=t)return{snapshot:n,signature:r,settled:!1}}}function kc(e){return e?{x:0,y:0,width:e.referenceWidth,height:e.referenceHeight}:void 0}function Ac(e,t,n,r,i,a,o){if(!e.ok){let t=kc(r);return{generation:n,matched:e.evidence.matched,visible:e.evidence.visible,candidateCount:e.evidence.candidateCount,failureReason:e.failureReason,...e.evidence.ref?{ref:e.evidence.ref}:{},...t?{viewport:t}:{}}}let s=Mc({query:i,platform:a,mode:o,dispatchCandidates:e.dispatchCandidates}),c=kc(r);return{generation:n,matched:!0,visible:!0,...c?{visiblePercentage:jc(e.rect,c)}:{},candidateCount:e.evidence.candidateCount,rect:e.rect,...e.evidence.ref?{ref:e.evidence.ref}:{},...c?{viewport:c}:{},...s?{dispatchSelector:s}:{},...i.includeSurfaceSignature?{surfaceSignature:Vc(t)}:{}}}function jc(e,t){return!w(e)||!w(t)?0:re(t,e)?100:Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x))*Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y))*100/(e.width*e.height)}function Mc(e){let{query:t,platform:n,mode:r,dispatchCandidates:i}=e;if(!(!Nc(t,n,r)||i!==1))return Pc(t.selector)}function Nc(e,t,n){return t===`ios`&&n===`tap`&&e.allowAtomicSelectorDispatch===!0&&!Ws(e.selector)}function Pc(e){let t=Object.entries(e).filter(([,e])=>e!==void 0);if(t.length!==1)return;let[n,r]=t[0];if(!Fc(n)||typeof r!=`string`)return;let i=$i(r)?.trim();return i?{key:n,value:i}:void 0}function Fc(e){return e===`id`||e===`label`||e===`text`}async function Ic(e,t,r){try{await e.sleep(t,r)}catch(e){throw r?.aborted?n():e}Rc(r)}async function Lc(e,t,n,r){let i=t-e.now();return i<=0?!1:(await Ic(e,Math.min(n,i),r),!0)}function Rc(e){if(e?.aborted)throw n()}function zc(e,t){if(!Number.isFinite(e)||e<0)throw new i(`INVALID_ARGS`,`${t} timeout must be a non-negative number.`)}function Bc(e){return e instanceof i&&e.details?.retriable===!0}function Vc(e){return pe(`sha256`).update(JSON.stringify([...e.nodes].sort((e,t)=>e.index-t.index).map(e=>({index:e.index,parentIndex:e.parentIndex,identifier:e.identifier??``,label:e.label??``,value:e.value??``,enabled:e.enabled??!1,selected:e.selected??!1,focused:e.focused??!1,checked:e.checked??!1,bounds:Hc(e.rect)})))).digest(`hex`)}function Hc(e){if(e)return{left:Math.trunc(e.x),top:Math.trunc(e.y),right:Math.trunc(e.x+e.width),bottom:Math.trunc(e.y+e.height)}}function Uc(e){if(e)return e;throw new i(`COMMAND_FAILED`,`Maestro observation completed without a snapshot result.`)}function Wc(e){return e.kind===`clearState`?Xc(e):Gc(e)?Kc(e):dl(e)?fl(e):e.kind===`settingsPermission`?il(e):al(e)}function Gc(e){return e.kind===`launchApp`||e.kind===`stopApp`||e.kind===`killApp`||e.kind===`openLink`}function Kc(e){switch(e.kind){case`launchApp`:return qc(e);case`stopApp`:return Jc(e);case`killApp`:return Yc(e);case`openLink`:return Zc(e)}}function qc(e){return{command:`open`,positionals:e.appId?[e.appId]:[],flags:{...e.relaunch?{relaunch:!0}:{},...e.clearState?{clearAppState:!0}:{},...e.launchArgs.length>0?{launchArgs:e.launchArgs}:{}}}}function Jc(e){return{command:`close`,positionals:e.appId?[e.appId]:[],dispatch:{closeAppOnly:!0}}}function Yc(e){return{command:`close`,positionals:e.appId?[e.appId]:[],dispatch:{closeAppOnly:!0,killApp:!0}}}function Xc(e){return{command:`settings`,positionals:e.appId?[`clear-app-state`,e.appId]:[`clear-app-state`]}}function Zc(e){return{command:`open`,positionals:e.appId?[e.appId,e.link]:[e.link],...e.prewarmRunner?{flags:{maestro:{prewarmRunnerBeforeOpen:!0}}}:{}}}const Qc={camera:`camera`,microphone:`microphone`,photos:`photos`,contacts:`contacts`,notifications:`notifications`,calendar:`calendar`,location:`location`,medialibrary:`media-library`,"media-library":`media-library`,motion:`motion`,reminders:`reminders`,siri:`siri`},$c={allow:`grant`,deny:`deny`,unset:`reset`},el={location:{always:{state:`grant`,permission:`location-always`},inuse:{state:`grant`,permission:`location`},never:{state:`deny`,permission:`location`}},photos:{limited:{state:`grant`,permission:`photos`,mode:`limited`}}};function tl(e){let t=Object.entries(e).map(([e,t])=>[e.toLowerCase(),t]);if(t.length===0)throw new i(`INVALID_ARGS`,`Maestro setPermissions requires at least one permission.`);return[...t.filter(([e])=>e===`all`),...t.filter(([e])=>e!==`all`)].map(([e,t])=>nl(e,t))}function nl(e,t){let n=e===`all`?`all`:rl(Qc,e);if(n===void 0)throw new i(`UNSUPPORTED_OPERATION`,`Maestro permission "${e}" is not supported.`,{hint:`Supported: all, ${Object.keys(Qc).join(`, `)}.`});let r=el[e],a=r?rl(r,t):void 0;if(a)return a;let o=rl($c,t);if(o)return{state:o,permission:n};throw new i(`INVALID_ARGS`,`Maestro permission "${e}" does not accept "${t}".`,{hint:`Use ${[`allow`,`deny`,`unset`,...Object.keys(r??{})].join(`|`)}.`})}function rl(e,t){return Object.hasOwn(e,t)?e[t]:void 0}function il(e){return{command:`settings`,positionals:[`permission`,e.state,e.permission,...e.mode?[e.mode]:[]],...e.appId?{dispatch:{settingsAppBundleId:e.appId}}:{}}}function al(e){switch(e.kind){case`gestureViewport`:return{command:`runtime`,positionals:[`gesture-viewport`]};case`typeText`:return{command:`type`,positionals:[e.text],...e.delayMs===void 0?{}:{flags:{delayMs:e.delayMs}}};case`clickSelector`:return ol(e);case`clickPoint`:return sl(e);case`swipe`:return cl(e);case`scroll`:return ll(e);case`pressKey`:return ul(e)}}function ol(e){return{command:`click`,positionals:[`${e.selector.key}=${JSON.stringify(e.selector.value)}`],flags:{...e.options,maestro:{allowNonHittableCoordinateFallback:!0,expectedTapPoint:e.expectedPoint}}}}function sl(e){return{command:`click`,positionals:[String(e.point.x),String(e.point.y)],flags:{...e.options}}}function cl(e){let{from:t,to:n,durationMs:r}=e.gesture;return{command:`gesture`,positionals:[],input:{kind:`pan`,origin:t,delta:{x:n.x-t.x,y:n.y-t.y},durationMs:r},flags:{postGestureStabilization:!1},dispatch:{gestureExecutionProfile:`endpoint-hold`,...e.viewport?{gestureViewport:e.viewport}:{}}}}function ll(e){return{command:`scroll`,positionals:[e.direction],...e.durationMs===void 0?{}:{input:{direction:e.direction,durationMs:e.durationMs}},flags:{postGestureStabilization:!1}}}function ul(e){return e.key===`back`||e.key===`home`?{command:e.key,positionals:[]}:{command:`keyboard`,positionals:[e.key]}}function dl(e){return e.kind===`screenshot`||e.kind===`snapshot`}function fl(e){switch(e.kind){case`screenshot`:return{command:`screenshot`,positionals:[e.path],...e.stabilize===!1||e.captureBackend===`runner`?{flags:{...e.stabilize===!1?{screenshotNoStabilize:!0}:{},...e.captureBackend===`runner`?{maestro:{screenshotCaptureBackend:`runner`}}:{}}}:{}};case`snapshot`:return{command:`snapshot`,positionals:[],flags:{noRecord:!0},dispatch:{observationOnly:!0}}}}async function pl(e,t){let n=Wc(t),r=await e.invoke(d({...n,flags:ml(e.flags,n.flags??{})}));if(!r.ok)throw bl(r);if(t.kind===`gestureViewport`){let e=r.data?.viewport;if(typeof e!=`object`||!e||![`x`,`y`,`width`,`height`].every(t=>typeof e[t]==`number`))throw new i(`COMMAND_FAILED`,`runtime gesture-viewport returned no valid viewport.`);return e}return r.data}function ml(e,t){let n=e?.maestro===void 0&&t.maestro===void 0?void 0:{...e?.maestro,...t.maestro},r=d({...e,...t,maestro:n});return Object.keys(r).length>0?r:void 0}function hl(e){return e?e.kind===`scalar`?[String(e.value)]:e.kind===`list`?e.values.map(String):Object.entries(e.values).flatMap(([e,t])=>[e,String(t)]):[]}function gl(e,t){return{generation:t.generation,matched:t.matched&&t.visible,candidateCount:t.candidateCount,evidence:{kind:`selector`,selector:e,visible:t.visible,candidateCount:t.candidateCount,...t.ref?{ref:t.ref}:{}}}}function _l(e){if(!e)return[];let t=[];if(typeof e.path==`string`&&t.push(e.path),Array.isArray(e.artifactPaths)&&t.push(...e.artifactPaths.filter(e=>typeof e==`string`)),Array.isArray(e.artifacts))for(let n of e.artifacts)typeof n.localPath==`string`?t.push(n.localPath):typeof n.path==`string`&&t.push(n.path);return[...new Set(t)]}function vl(e,t,n){if(D.isAbsolute(e))return e;let r=t.source?.path??n;if(!r)throw new i(`INVALID_ARGS`,`Maestro runScript file paths require a source path.`);return D.resolve(D.dirname(r),e)}function yl(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,String(t)]))}function bl(e){let t=e.error,n=d({...t.details??{},hint:t.hint??xl(t.details,`hint`),diagnosticId:t.diagnosticId??xl(t.details,`diagnosticId`),logPath:t.logPath??xl(t.details,`logPath`),retriable:t.retriable??Sl(t.details,`retriable`),supportedOn:t.supportedOn??xl(t.details,`supportedOn`)});return new i(t.code,t.message,Object.keys(n).length?n:void 0)}function xl(e,t){let n=e?.[t];return typeof n==`string`?n:void 0}function Sl(e,t){let n=e?.[t];return typeof n==`boolean`?n:void 0}function Cl(e){let t,n,r,a,o,s=0,c=0,l=async n=>{c+=1;let r=await pl(e,{kind:`snapshot`});if(!r||!Array.isArray(r.nodes))throw new i(`COMMAND_FAILED`,`Maestro snapshot did not return node data.`);let a=m(r,r);return t={generation:n.generation,snapshot:a},a};return{capture:async e=>{if(n?.generation===e.generation){let r=n.snapshot;return n=void 0,t={generation:e.generation,snapshot:r},r}return n=void 0,await l(e)},bindObservation:e=>{if(t?.generation!==e.generation)return e;let n=`maestro-observation-${++s}`;return t.observationIdentity=n,{...e,identity:n}},reuseObservation:e=>{if(e.cachedObservation?.generation===e.generation&&e.cachedObservation.identity!==void 0&&t?.generation===e.generation&&e.cachedObservation.identity===t.observationIdentity)return t.snapshot},readMetrics:()=>({hierarchyCaptures:c}),invalidate:e=>{r=t?.generation===e-1?{generation:e,snapshot:t.snapshot}:void 0,t=void 0,n=void 0},requireStability:e=>{o=e,a=r?.generation===e?r:void 0,r=void 0,n=void 0},consumeStabilityFromVisualWait:e=>{if(o!==void 0){if(o!==e.generation)throw new i(`COMMAND_FAILED`,`Maestro stability generation ${o} does not match ${e.generation}.`);o=void 0,a=void 0,r=void 0,n=void 0}},prime:(e,t)=>{n={generation:e,snapshot:t}},settlePending:async r=>{if(o===void 0)return;if(o!==r.generation)throw new i(`COMMAND_FAILED`,`Maestro stability generation ${o} does not match ${r.generation}.`);let s=t?.generation===r.generation?t.snapshot:a?.snapshot,c=await Oc({timeoutMs:$.settleTimeoutMs,context:r,snapshot:l,dependencies:e.dependencies,...s?{initialSnapshot:s}:{}});return o=void 0,a=void 0,n={generation:r.generation,snapshot:c.snapshot},c}}}async function wl(e){let{input:t,context:n,snapshots:r,options:i}=e,a=i.dependencies.now()+t.timeoutMs,o=e.allowObservationReuse===!1?void 0:r.reuseObservation(n);for(;;){let e=i.dependencies.now(),s=o!==void 0;o??=await Cc({context:n,snapshot:r.capture,dependencies:i.dependencies},a);let c=wc({query:t,context:n,snapshot:o,platform:i.platform});if(Al(c,s))return c;if(o=void 0,!s){if(e>=a)return c;await Lc(i.dependencies,a,Sc,n.signal)}}}async function Tl(e,t,n,r,i,a){let o=async()=>await Ol(e,t,r,i,a.click);if(!a.retryIfNoChange){try{await o()}finally{t.requireStability(i.generation)}return}if(e.platform===`ios`){await dc({signal:i.signal,capture:async t=>{n.screenshotCaptures+=1,await pl(e,{kind:`screenshot`,path:t,stabilize:!1,captureBackend:`runner`})},run:async o=>await El(e,t,n,r,i,a.click,o)});return}await El(e,t,n,r,i,a.click)}async function El(e,t,n,r,i,a,o){let s=async()=>await Ol(e,t,r,i,a),c=r.resolution?.surfaceSignature??(o?void 0:Vc(await t.capture(i))),l=async()=>{let r=await Oc({timeoutMs:$.settleTimeoutMs,context:i,snapshot:t.capture,dependencies:e.dependencies});return r.settled?n.settleLatches+=1:n.settleTimeouts+=1,r};try{let e=await Dl({baselineSignature:c,screenshotBaseline:o,dispatch:s,settle:l,onRetry:()=>{n.tapRetries+=1}});t.prime(i.generation,e.snapshot)}catch(e){throw t.requireStability(i.generation),e}}async function Dl(e){await e.dispatch();let t=await e.settle(),n=1;for(;(e.baselineSignature===void 0||t.signature===e.baselineSignature)&&n<$.retryTapMaxAttempts&&!(e.screenshotBaseline&&await e.screenshotBaseline.matchesCurrent()!==!0);)e.onRetry(),await e.dispatch(),n+=1,t=await e.settle();return t}async function Ol(e,t,n,r,i){let a=n.resolution,o=a?.dispatchSelector;if(o&&n.point){t.invalidate(r.generation);try{await jl(e,o,n.point,i);return}catch(n){if(!Ml(n))throw n;let o=await wl({input:a.query,context:r,snapshots:t,options:e,allowObservationReuse:!1});if(!kl(o))throw n;t.invalidate(r.generation),await Nl(e,le(o.rect),i);return}}t.invalidate(r.generation),await Nl(e,n.point,i)}function kl(e){return e.matched&&e.visible&&e.rect!==void 0}function Al(e,t){return kl(e)?!t||e.dispatchSelector!==void 0:!1}async function jl(e,t,n,r){g({level:`debug`,phase:`maestro_tap_dispatch`,data:{kind:`selector`,selectorKey:t.key,expectedPoint:n}}),await pl(e,{kind:`clickSelector`,selector:t,expectedPoint:n,options:r})}function Ml(e){let t=a(e);return t.code===`AMBIGUOUS_MATCH`||t.code===`ELEMENT_NOT_FOUND`||t.code===`ELEMENT_OFFSCREEN`||t.details?.reason===ce.selectorNotFound}async function Nl(e,t,n){if(!t)throw new i(`COMMAND_FAILED`,`Maestro target did not resolve to a point.`);g({level:`debug`,phase:`maestro_tap_dispatch`,data:{kind:`point`,point:t}}),await pl(e,{kind:`clickPoint`,point:t,options:n})}function Pl(e){return`${e.state} ${e.permission}${e.mode?` ${e.mode}`:``}`}function Fl(e){let t=Cl(e),n={screenshotCaptures:0,tapRetries:0,settleLatches:0,settleTimeouts:0},r=e=>{e.settled?n.settleLatches+=1:n.settleTimeouts+=1},a=e.platform,o=t=>(t.kind===`screenshot`&&(n.screenshotCaptures+=1),pl(e,t)),s=async(e,n,r=`none`)=>{t.invalidate(n.generation);try{return await e()}finally{r===`deferred`&&t.requireStability(n.generation)}},c=async(e,t,n=`none`)=>await s(()=>o(e),t,n),l=async(e,t,n)=>{let r=[];for(let a of t){try{await c({kind:`settingsPermission`,...e?{appId:e}:{},state:a.state,permission:a.permission,...a.mode?{mode:a.mode}:{}},n)}catch(e){throw e instanceof i?new i(e.code,e.message,{...e.details,appliedPermissionMutations:r,failedPermissionMutation:Pl(a)}):e}r.push(Pl(a))}},u=a===`android`?$.androidInputTextCharacterDelayMs:void 0,f=async(n,i,a)=>{_(n),await c({kind:`typeText`,text:n,...a===void 0?{}:{delayMs:a}},i);let o=await Oc({timeoutMs:$.settleTimeoutMs,context:i,snapshot:t.capture,dependencies:e.dependencies});r(o),t.prime(i.generation,o.snapshot)};return{operations:{platform:a,resolveTarget:async(n,r)=>await wl({input:n,context:r,snapshots:t,options:e}),observe:async(n,r)=>await Ec({condition:n.condition,timeoutMs:n.timeoutMs,context:r,snapshot:t.capture,dependencies:e.dependencies,platform:a}),resolveGestureViewport:async()=>await o({kind:`gestureViewport`}),launchApp:async(e,t)=>{let n=e.appId??t.appId,r=[...hl(e.arguments),...hl(e.launchArguments)],i=e.clearState===!0,a=!i&&e.stopApp!==!1;if(e.permissions){let r=tl(e.permissions);i&&await c({kind:`clearState`,...n?{appId:n}:{}},t),await l(n,r,t)}await c({kind:`launchApp`,...n?{appId:n}:{},relaunch:a,clearState:i&&!e.permissions,launchArgs:r},t,`deferred`)},stopApp:async(e,t)=>{let n=e.appId??t.appId;await c({kind:`stopApp`,...n?{appId:n}:{}},t)},killApp:async(e,t)=>{let n=e.appId??t.appId;await c({kind:`killApp`,...n?{appId:n}:{}},t)},setPermissions:async(e,t)=>{await l(e.appId??t.appId,tl(e.permissions),t)},clearState:async(e,t)=>{let n=e.appId??t.appId;await c({kind:`clearState`,...n?{appId:n}:{}},t)},openLink:async(e,t)=>{await c({kind:`openLink`,...t.appId?{appId:t.appId}:{},link:e.link,prewarmRunner:a===`ios`},t,`deferred`)},tapOn:async(r,i)=>await Tl(e,t,n,r.target,i,{click:{count:r.repeat,intervalMs:r.delay},retryIfNoChange:r.retryTapIfNoChange===!0}),doubleTapOn:async(t,n)=>{await s(()=>Nl(e,t.target.point,d({doubleTap:!0,intervalMs:t.delay})),n,`deferred`)},longPressOn:async(t,n)=>{await s(()=>Nl(e,t.target.point,{holdMs:$.longPressDurationMs}),n,`deferred`)},gesture:async(e,t)=>{let n=await c({kind:`swipe`,gesture:e,...t.gestureViewport?{viewport:t.gestureViewport}:{}},t,`deferred`);return n?{data:n}:void 0},inputText:async(e,t)=>await f(e.text,t,u),eraseText:async(e,t)=>await f(`\b`.repeat(e.charactersToErase??$.eraseTextMaxCharacters),t),scroll:async(e,t)=>{await c({kind:`scroll`,direction:e.direction},t,`deferred`)},scrollUntilVisible:async(n,r)=>{let i=await Dc({selector:n.selector,direction:n.direction,timeoutMs:n.timeoutMs,context:r,snapshot:t.capture,dependencies:e.dependencies,platform:a,scroll:async(i,o)=>{let s=ns(o,n.selector,n.direction,n.durationMs,a);return await c(s?{kind:`swipe`,...s}:{kind:`scroll`,direction:n.direction,durationMs:n.durationMs},r),(await Oc({timeoutMs:Math.min($.settleTimeoutMs,i),context:r,snapshot:t.capture,dependencies:e.dependencies})).snapshot}});if(i.visiblePercentage!==$.scrollUntilVisiblePercentage)throw rr(`Maestro scrollUntilVisible target did not become visible.`,{selector:n.selector,timeoutMs:n.timeoutMs});return{observation:t.bindObservation(gl(n.selector,i))}},pressKey:async(e,t)=>{await c({kind:`pressKey`,key:e.key},t,`deferred`)},back:async(e,t)=>{await c({kind:`pressKey`,key:`back`},t,`deferred`)},hideKeyboard:async(e,t)=>{await c({kind:`pressKey`,key:`dismiss`},t,`deferred`)},waitForAnimationToEnd:async(t,n)=>({visualStabilityReached:await yc({timeoutMs:t.timeoutMs??$.animationWaitTimeoutMs,now:e.dependencies.now,signal:n.signal,capture:async t=>{await o({kind:`screenshot`,path:t,stabilize:!1,...e.platform===`ios`?{captureBackend:`runner`}:{}})}})}),takeScreenshot:async e=>({artifactPaths:_l(await o({kind:`screenshot`,path:e.path}))}),runScript:async(t,n)=>({outputEnv:ec({scriptPath:vl(t.file,n,e.sourcePath),publicNetworkOnly:e.publicNetworkOnly,env:{...n.env,...t.env?yl(t.env):{}}})})},snapshots:t,readMetrics:()=>({...t.readMetrics(),...n}),recordSettle:r}}function Il(e){let{operations:t,snapshots:n,readMetrics:r,recordSettle:i}=Fl(e);return Zs(t,{beforeExecute:async({context:e,requiresSettledPredecessor:t})=>{if(t){let t=await n.settlePending(e);t&&i(t)}},afterExecute:({context:e,visualStabilityReached:t})=>{t&&n.consumeStabilityFromVisualWait(e)},bindObservation:n.bindObservation,readMetrics:r})}function Ll(e){let{appendTraceEvent:t,filePath:n,tracePath:r,onStep:i}=e,a=new Map;return{actionStarted:e=>{a.set(e.stepIndex,e),Rl(()=>Vl(i,e)),Rl(()=>Hl(t,r,n,e))},actionCompleted:e=>{let i=zl(a,e.stepIndex);Rl(()=>Ul(t,r,n,Bl(i,e),!0))},actionFailed:e=>{let i=zl(a,e.stepIndex);Rl(()=>Ul(t,r,n,Bl(i,e),!1))}}}function Rl(e){try{e()}catch{}}function zl(e,t){let n=e.get(t);return e.delete(t),n}function Bl(e,t){return d({...e??t,durationMs:t.durationMs,runtimeMetrics:t.runtimeMetrics,data:`data`in t?t.data:void 0,error:`error`in t?t.error:void 0})}function Vl(e,t){e?.({index:t.stepIndex,total:t.stepTotal,command:t.action,...t.value?{value:t.value}:{}})}function Hl(e,t,n,r){e(t,{type:`replay_action_start`,ts:new Date().toISOString(),replayPath:n,...r.source.path&&r.source.path!==n?{sourcePath:r.source.path}:{},line:r.source.line,step:r.stepIndex,command:r.action,positionals:r.value?[r.value]:[]})}function Ul(e,t,n,r,a){let o=Wl(r);e(t,{type:`replay_action_stop`,ts:new Date().toISOString(),replayPath:n,...r.source.path&&r.source.path!==n?{sourcePath:r.source.path}:{},line:r.source.line,step:r.stepIndex,command:r.action,ok:a,durationMs:r.durationMs,...Object.keys(o).length>0?{resultTiming:o}:{},...!a&&`error`in r&&r.error instanceof i?{errorCode:r.error.code}:{}})}function Wl(e){let t=`data`in e?e.data:void 0,n=Gl(t?.timing)?t.timing:void 0;return d({...e.runtimeMetrics??{},...typeof n?.executionProfile==`string`?{executionProfile:n.executionProfile}:{},...typeof n?.gestureDurationMs==`number`?{gestureDurationMs:n.gestureDurationMs}:{}})}function Gl(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Kl(e,t){let n=d({...e.dispatch,...ql(t.dispatch)});return d({...e,command:t.command,positionals:t.positionals,input:t.input,flags:t.flags,dispatch:Object.keys(n).length>0?n:void 0})}function ql(e){return d({closeAppOnly:e?.closeAppOnly,killApp:e?.killApp,observationOnly:e?.observationOnly,gestureViewport:e?.gestureViewport,gestureExecutionProfile:e?.gestureExecutionProfile,settingsAppBundleId:e?.settingsAppBundleId})}function Jl(e,t){let n={command:e.action,...e.value?{value:e.value}:{}};return{command:{kind:e.action},source:e.source,progress:n,action:{command:Zl(e.action),positionals:Ql(e.action,e.value),flags:t.flags??{}}}}async function Yl(e,t){let{failure:n,req:r}=t,i=Jl(n,r);return await e.buildActionFailureResponse({error:t.error,req:r,sessionStore:t.sessionStore,observationStore:t.observationStore,logPath:t.logPath,replayPath:t.replayPath,stepIndex:n.stepIndex,source:n.source,action:n.action,actionLabel:[n.action,Xl(n.value)].filter(Boolean).join(` `),captureAction:i.action,isControl:n.isControl,redactions:n.redactions,resume:n.resume,artifactPaths:n.artifactPaths,warnings:n.warnings,snapshotDiagnostics:t.snapshotDiagnostics,suggestNodes:e=>Ga(n,e)})}function Xl(e){return!e||e===`<text>`?e??``:h(e)}function Zl(e){return e===`tapOn`||e===`doubleTapOn`?`click`:e===`longPressOn`?`longpress`:e===`assertVisible`||e===`assertNotVisible`||e===`extendedWaitUntil`||e===`scrollUntilVisible`?`wait`:e}function Ql(e,t){return!t||e===`inputText`?[]:[t]}function $l(e){let{command:t,outcome:n,startedAt:r,snapshotStart:i}=e,{session:{name:a,store:o}}=t,s=tu(o,i),c=n.replayed;return{ok:!0,data:{replayed:c,healed:0,session:a,sessionActive:o.get()!==void 0,artifactPaths:n.artifactPaths,...n.warnings?{warnings:n.warnings}:{},...s?{snapshotDiagnostics:s}:{},message:nu(c,Date.now()-r)}}}async function eu(e,t){let{command:n,replayPath:r,state:i,outcome:a}=t,{request:o,session:{store:s,observationStore:l,logPath:u}}=n,{failure:d}=a,f=c(a.error);return d?await Yl(e,{error:f,failure:d,replayPath:r,req:o,sessionStore:s,observationStore:l,logPath:u,snapshotDiagnostics:tu(s,i.snapshotStart)}):{ok:!1,error:f}}function tu(e,t){let n=e.get()?.snapshotDiagnostics?.samples.slice(t)??[];return f(n)}function nu(e,t){return`Replayed ${e} ${e===1?`step`:`steps`} in ${(t/1e3).toFixed(1)}s`}async function ru(e,t){let{request:n}=t,r=n.flags?.replayScriptSource;if(!r)return s(`INVALID_ARGS`,e.scriptSourceRequiredMessage);if(n.flags?.saveScript!==void 0)return s(`INVALID_ARGS`,`Maestro YAML does not support --save-script; ADR 0012 repair recording applies only to .ad scripts.`);let i=Date.now(),a={snapshotStart:0};try{return await iu({host:e,command:t,bundle:r,startedAt:i,state:a})}catch(n){return await eu(e,{command:t,replayPath:r.entry,state:a,outcome:{ok:!1,error:n}})}}async function iu(e){let{host:t,command:n,bundle:r,startedAt:i,state:a}=e,{request:o,session:{store:s},tracePath:c,onStep:l}=n,u=await au({host:t,command:n,bundle:r}),d=n.publicNetworkOnly===!0,f=fu({command:n,device:u.device,platform:u.platform,runtimeHints:u.runtimeHints,sourcePath:u.filePath,publicNetworkOnly:d});a.snapshotStart=s.get()?.snapshotDiagnostics?.samples.length??0;let p=await Wa(u.flow,f,{defaults:u.defaults,env:u.env,platform:u.platform,target:u.target,runtimeHints:u.runtimeHints,signal:u.signal,from:o.flags?.replayFrom,planDigest:o.flags?.replayPlanDigest,trustedScripts:!d,readSource:e=>t.readScriptSourceFile(r,e),observer:Ll({appendTraceEvent:t.appendTraceEvent,filePath:u.filePath,tracePath:c,onStep:l})});return p.ok?$l({outcome:p,command:n,startedAt:i,snapshotStart:a.snapshotStart}):await eu(t,{command:n,replayPath:r.entry,state:a,outcome:p})}async function au(e){let{host:t,command:n,bundle:r}=e,{request:i,session:{name:a,store:o}}=n,s=r.entry,c=Ua(t.readScriptSourceFile(r,s),s),l=o.lookup(),u=l?.session;l&&o.assertSelectorMatches(i.flags);let d=await ou({host:t,req:i,env:n.host.env,sessionStore:o,sessionName:a,session:u,flow:c});return{filePath:s,flow:c,...d,defaults:uu({host:t,req:i,sessionName:a,filePath:s,hostCwd:n.host.cwd,platform:d.platform,target:d.target}),env:du(i,n.host.env),signal:t.requestSignal(i.meta?.requestId)}}async function ou(e){let{host:t,req:n,env:r,sessionStore:i,sessionName:a,session:o,flow:s}=e,c=n.flags?.platform,l=o?.device??(c===`android`||c===`ios`?void 0:await t.resolveTargetDevice(n.flags??{},{appTarget:s.appTarget,platform:c},r)),u=_u(n,l),d=cu({req:n,sessionStore:i,sessionName:a,device:l,platform:u});return await su({host:t,req:n,env:r,sessionStore:i,sessionName:a,device:l,platform:u,target:vu(n,l),runtimeHints:d,flow:s})}async function su(e){if(e.device||!lu(e.runtimeHints))return e;let t=await e.host.resolveTargetDevice(e.req.flags??{},{appTarget:e.flow.appTarget,platform:e.platform},e.env);return{device:t,platform:e.platform,target:vu(e.req,t),runtimeHints:cu({req:e.req,sessionStore:e.sessionStore,sessionName:e.sessionName,device:t,platform:e.platform})}}function cu(e){return e.sessionStore.resolveOpenRuntimeHints({request:e.req,device:e.device,platform:e.platform})}function lu(e){return e?.metroPort!==void 0&&e.metroHost===void 0&&e.bundleUrl===void 0}function uu(e){return{...e.host.buildBuiltinVars({req:e.req,sessionName:e.sessionName,resolvedPath:e.filePath,hostCwd:e.hostCwd}),AD_PLATFORM:e.platform,AD_TARGET:e.target}}function du(e,t){return{...se(oe(e.flags?.replayShellEnv,t)),...ae(ie(e.flags?.replayEnv))}}function fu(e){let{command:t,device:n,platform:r,runtimeHints:i,sourcePath:a,publicNetworkOnly:o}=e,{request:s,invoke:c}=t,l={...s,runtime:i,...t.dispatch?{dispatch:t.dispatch}:{}};return Il({invoke:e=>c(Kl(l,e)),flags:pu(n,r,s.flags),publicNetworkOnly:o,platform:r,sourcePath:a,dependencies:{now:Date.now,sleep:async(e,t)=>{await ve(e,void 0,{signal:t})}}})}function pu(e,t,n){if(!e)return mu(t,n);let r={platform:t,target:e.target,noRecord:!0,...n?.testIme===void 0?{}:{testIme:n.testIme}};return t===`android`?{...r,serial:e.id}:{...r,udid:e.id,...e.simulatorSetPath?{iosSimulatorDeviceSet:e.simulatorSetPath}:{}}}function mu(e,t){let n={platform:e,target:t?.target??`mobile`,noRecord:!0,...t?.testIme===void 0?{}:{testIme:t.testIme}};return t?.device&&(n.device=t.device),e===`android`?hu(n,t):gu(n,t)}function hu(e,t){return t?.serial&&(e.serial=t.serial),t?.androidDeviceAllowlist&&(e.androidDeviceAllowlist=t.androidDeviceAllowlist),e}function gu(e,t){return t?.udid&&(e.udid=t.udid),t?.iosSimulatorDeviceSet&&(e.iosSimulatorDeviceSet=t.iosSimulatorDeviceSet),e}function _u(e,t){let n=e.flags?.platform;if(n===`android`||n===`ios`)return n;if(t?.platform===`android`)return`android`;if(t?.platform===`apple`&&t.appleOs===`ios`)return`ios`;throw new i(`INVALID_ARGS`,`Maestro replay requires --platform android|ios or an active mobile session.`)}function vu(e,t){return typeof e.flags?.target==`string`?e.flags.target:t?.target??`mobile`}function yu(e){return{id:`maestro`,collectSourceFiles(e){return Qa(e)},inspectSource(e,t){let n=Ua(e,t);return{title:n.name,appTarget:n.appTarget}},async runReplay(t){return await ru(e,t)},exportReplayScript(e,t){return uo(e,{...t,resolveSelector:e=>b(e,Nr)})}}}const bu={create:yu};export{bu as maestroReplayBackendPlugin};
|
|
117
|
+
`)}\n`}function fo(e,t){let n={config:po(t.metadata),warnings:[],unsupported:[]},r=[];for(let[i,a]of e.entries()){let e=t.actionLines?.[i]??i+1,o=ho(a,t.resolveSelector);switch(o.kind){case`commands`:r.push(...o.commands),Ro(n,o.warnings,a,e);break;case`config`:n.config.appId??=o.appId,r.push(...o.commands),Ro(n,o.warnings,a,e);break;case`unsupported`:n.unsupported.push({line:e,action:Ho(a),message:o.message})}}if(n.unsupported.length>0)throw new i(`INVALID_ARGS`,`Cannot export replay to Maestro YAML: unsupported .ad action ${Vo(n.unsupported)}.`,{unsupported:n.unsupported});return{yaml:Bo(n.config,r),warnings:n.warnings}}function po(e){return e?.env&&Object.keys(e.env).length>0?{env:e.env}:{}}const mo={...ao,click:go,press:go,longpress:_o,fill:xo,type:So,wait:Co,find:To,screenshot:Eo,scroll:Do,swipe:Oo};function ho(e,t){return mo[e.command]?.(e,t)??{kind:`unsupported`,message:`${e.command} has no Maestro equivalent`}}function go(e,t){let[n,r]=e.positionals;if(!n)return{kind:`unsupported`,message:`${e.command} requires a target`};let i=Mo(n,r,t);if(!i)return{kind:`unsupported`,message:`tap target is not Maestro-compatible`};let a=No(e);return a.ok?e.flags?.doubleTap===!0?{kind:`commands`,commands:[{doubleTapOn:i}],warnings:[...wo(n),...bo(e,`doubleTapOn`)]}:typeof e.flags?.holdMs==`number`?{kind:`commands`,commands:[{longPressOn:i}],warnings:[...wo(n),yo(e.flags.holdMs),...bo(e,`longPressOn`)]}:{kind:`commands`,commands:[Io(i,a.options)],warnings:wo(n)}:{kind:`unsupported`,message:a.message}}function _o(e,t){let[n,r]=e.positionals;if(!n)return{kind:`unsupported`,message:`longpress requires a target`};let i=Mo(n,r,t);return i?{kind:`commands`,commands:[{longPressOn:i}],warnings:[...wo(n),...vo(e).map(yo)]}:{kind:`unsupported`,message:`longpress target is not Maestro-compatible`}}function vo(e){let[t,n,r]=e.positionals,i=X(t)&&X(n)?r:n;return i&&X(i)?[Number(i)]:[]}function yo(e){return`long-press duration exports as Maestro longPressOn; Maestro uses its default long-press duration instead of ${e}ms`}function bo(e,t){let n=[];return typeof e.flags?.count==`number`&&e.flags.count>1&&n.push(`tap --count ${e.flags.count} is not represented by Maestro ${t}`),typeof e.flags?.intervalMs==`number`&&e.flags.intervalMs>0&&n.push(`tap --interval-ms ${e.flags.intervalMs} is not represented by Maestro ${t}`),n}function xo(e,t){let[n,r]=e.positionals;if(!n||r===void 0)return{kind:`unsupported`,message:`fill requires a target and text`};let i=Mo(n,void 0,t);return i?r.length===0?{kind:`commands`,commands:[{tapOn:i},`eraseText`],warnings:[...wo(n),`fill "" exports as tapOn + eraseText; Maestro erases at most its 50-character default`]}:{kind:`commands`,commands:[{tapOn:i},{inputText:r}],warnings:[...wo(n),`fill exports as tapOn + inputText; Maestro may append text instead of replacing existing field contents`]}:{kind:`unsupported`,message:`fill target is not Maestro-compatible`}}function So(e){let[t]=e.positionals;if(t===void 0)return{kind:`unsupported`,message:`type requires text`};let n=Lo(t);return n===null?{kind:`commands`,commands:[{inputText:t}]}:{kind:`commands`,commands:[{eraseText:n}]}}function Co(e,t){let[n,r]=e.positionals;if(!n)return{kind:`unsupported`,message:`wait requires a target or duration`};if(X(n))return{kind:`commands`,commands:[{waitForAnimationToEnd:{timeout:Number(n)}}],warnings:[`wait <ms> exports as waitForAnimationToEnd and may return before the full duration`]};if(n===`absent`)return{kind:`unsupported`,message:`strict wait absent requires zero selector matches and is unsupported by Maestro`};if(n===`text`&&r)return{kind:`commands`,commands:[{extendedWaitUntil:{visible:r,timeout:zo(e,tr.extendedWaitUntilTimeoutMs)}}]};let i=t(n);return i?{kind:`commands`,commands:[{extendedWaitUntil:{visible:i,timeout:zo(e,tr.extendedWaitUntilTimeoutMs)}}],warnings:wo(n)}:{kind:`unsupported`,message:`wait selector is not Maestro-compatible`}}function wo(e){return T(e,`label`)?[`label= selectors export as Maestro text; Maestro text matching is broader than agent-device label-only matching`]:[]}function To(e){let[t,n,r]=e.positionals;return t!==`text`||!n||!r?{kind:`unsupported`,message:`only find text <query> exists|missing exports to Maestro`}:r===`exists`?{kind:`commands`,commands:[{assertVisible:n}]}:r===`missing`||r===`not-exists`?{kind:`commands`,commands:[{assertNotVisible:n}]}:{kind:`unsupported`,message:`find text assertion "${r}" is unsupported`}}function Eo(e){let[t]=e.positionals;return t?{kind:`commands`,commands:[{takeScreenshot:t}]}:{kind:`unsupported`,message:`screenshot requires an output path`}}function Do(e){let[t]=e.positionals;if(t&&t!==`down`)return{kind:`unsupported`,message:`scroll ${t} is not exported yet`};let n=typeof e.flags?.until==`string`?e.flags.until:void 0;return{kind:`commands`,commands:[`scroll`],warnings:n===void 0?[]:[`scroll --until ${n} is not represented by Maestro scroll`]}}function Oo(e){let t=ko(e);if(!t)return{kind:`unsupported`,message:`only coordinate swipe exports to Maestro`};let n=Ao(e);if(n===null)return{kind:`unsupported`,message:`swipe count must be a positive integer`};let r=jo(e);return r?{kind:`unsupported`,message:r}:{kind:`commands`,commands:Array.from({length:n},()=>({swipe:t}))}}function ko(e){let[t,n,r,i]=e.positionals;if(!(!X(t)||!X(n)||!X(r)||!X(i)))return{start:io(t,n),end:io(r,i),duration:100}}function Ao(e){let t=e.flags?.count??1;return Number.isInteger(t)&&t>=1?t:null}function jo(e){if(e.flags?.pauseMs!==void 0)return`swipe --pause-ms has no Maestro equivalent`;if(e.flags?.pattern&&e.flags.pattern!==`one-way`)return`swipe ping-pong pattern has no Maestro equivalent`}function Mo(e,t,n){return X(e)&&X(t)?{point:io(e,t)}:e.startsWith(`@`)?null:n(e)}function No(e){let t=Fo(e);return t?{ok:!1,message:t}:{ok:!0,options:Po(e)}}function Po(e){let t={};return typeof e.flags?.count==`number`&&e.flags.count>1&&(t.repeat=e.flags.count),typeof e.flags?.intervalMs==`number`&&e.flags.intervalMs>0&&(t.delay=e.flags.intervalMs),t}function Fo(e){if(e.flags?.jitterPx!==void 0)return`tap --jitter-px has no Maestro equivalent`;if(e.flags?.clickButton&&e.flags.clickButton!==`primary`)return`tap --button ${e.flags.clickButton} has no Maestro equivalent`}function Io(e,t){return Object.keys(t).length===0?{tapOn:e}:typeof e==`string`?{tapOn:{text:e,...t}}:e&&typeof e==`object`&&!Array.isArray(e)?{tapOn:{...e,...t}}:{tapOn:e}}function Lo(e){return e.length===0||![...e].every(e=>e===`\b`)?null:e.length}function Ro(e,t,n,r){for(let i of t??[])e.warnings.push({line:r,action:Ho(n),message:i})}function zo(e,t){let n=e.positionals.at(-1);return n&&X(n)?Number(n):t}function Bo(e,t){return uo(Object.keys(e).length>0?[e,t]:[t])}function Vo(e){return e.map(e=>`line ${e.line} (${e.action}): ${e.message}`).join(`; `)}function Ho(e){return[e.command,...e.positionals??[]].join(` `).trim()}function X(e){return e!==void 0&&Number.isFinite(Number(e))}function Uo(e,t){return O({appId:e.appId,env:e.env,generation:e.generation,invalidateObservation:e.invalidateObservation,source:t?.source,cachedObservation:e.cachedObservation,signal:e.signal})}function Wo(e){return O({env:e.env,generation:e.generation,cachedObservation:e.cachedObservation,signal:e.signal})}async function Go(e,t){let n=Qo(await t.observe({condition:e.condition,timeoutMs:e.timeoutMs},Wo(e)),e.generation),r={kind:`selector`,selector:e.condition.selector,visible:n.visible,candidateCount:n.candidateCount,...n.ref?{ref:n.ref}:{}};return{generation:e.generation,matched:Ko(e.condition,n),candidateCount:n.candidateCount,evidence:r}}function Ko(e,t){let n=t.matched&&t.visible&&t.failureReason===void 0;return e.kind===`visible`?n:!n}async function qo(e,t,n,r){let i=Qo(await r.resolveTarget({selector:e,...t},Uo(n,n.command)),n.generation);if(!i.matched||!i.visible||!i.rect)throw ir(Yo(e,i),{selector:e,candidateCount:i.candidateCount,...i.failureReason?{targetFailureReason:i.failureReason}:{}});return{kind:`selector`,selector:e,query:{selector:e,...t},...i,rect:i.rect}}function Jo(e){let t={kind:`selector`,selector:e.selector,visible:e.visible,candidateCount:e.candidateCount,...e.ref?{ref:e.ref}:{}};return{generation:e.generation,matched:e.matched&&e.visible,candidateCount:e.candidateCount,evidence:t}}function Yo(e,t){let n=Xo(e);switch(t.failureReason){case`selector-did-not-match`:return`Maestro target ${n} did not match any element.`;case`no-visible-match`:return`Maestro target ${n} matched ${t.candidateCount} element(s), but none were visible.`;case`index-out-of-range`:return`Maestro target ${n} matched ${t.candidateCount} element(s); its index is out of range.`;case`no-usable-geometry`:return`Maestro target ${n} did not provide usable geometry.`;default:return`Maestro target did not resolve to a visible element.`}}function Xo(e){let t=Object.entries(e).filter(([,e])=>e!==void 0);return t.length===0?`selector`:t.map(([e,t])=>`"${e}":${JSON.stringify(t)}`).join(`, `)}function Zo(e){if(!e||typeof e!=`object`)return!1;let t=e;return[`x`,`y`,`width`,`height`].every(e=>typeof t[e]==`number`&&Number.isFinite(t[e]))}function Qo(e,t){return $o(e,t),es(e),ts(e),ns(e),e}function $o(e,t){if(e.generation!==t)throw new i(`COMMAND_FAILED`,`Maestro target evidence generation ${e.generation} does not match ${t}.`)}function es(e){if(!Number.isInteger(e.candidateCount)||e.candidateCount<0)throw new i(`COMMAND_FAILED`,`Maestro target evidence has an invalid candidate count.`)}function ts(e){if(e.rect!==void 0&&!Zo(e.rect)||e.viewport!==void 0&&!Zo(e.viewport))throw new i(`COMMAND_FAILED`,`Maestro target evidence has invalid geometry.`)}function ns(e){if(e.surfaceSignature!==void 0&&typeof e.surfaceSignature!=`string`)throw new i(`COMMAND_FAILED`,`Maestro target evidence has an invalid surface signature.`)}function rs(e,t,n,r,i,a={}){let o=is(e,t,n,i,a);if(!o)return;let{start:s,end:c}=cs(o,n);return{gesture:{from:s,to:c,durationMs:r},viewport:o}}function is(e,t,n,r,i){let a=n===`up`||n===`down`,o=Aa(e,Ta(e,r),i),s=o.visibility,c=ia({visibility:s,matches:e.nodes.filter(e=>C(e)),platform:r}),l=ne(s.viewportRects)??os(c);if(!l||!w(l))return;let u=c.flatMap(e=>{if(!w(e.rect))return[];let t=E(e.rect,l);return!t||(a?t.height<=t.width:t.width<t.height)?[]:[{node:e,viewport:t}]}),d=new Map(u.map(e=>[e.node.index,e]));for(let e of o.resolve(t).indexed){let t=as(e,s.nodeByIndex),n=t?d.get(t.index):void 0;if(n)return n.viewport}return u.sort(ss)[0]?.viewport}function as(e,t){return C(e)?e:ee(e,t)}function os(e){let t;for(let n of e)w(n.rect)&&(!t||n.rect.width*n.rect.height>t.width*t.height)&&(t=n.rect);return t}function ss(e,t){return t.viewport.width*t.viewport.height-e.viewport.width*e.viewport.height}function cs(e,t){let n=Z(e,.5,.5),r=G.scrollUntilVisibleSwipe.nearEdgeFraction,i=G.scrollUntilVisibleSwipe.farEdgeFraction;switch(t){case`up`:return{start:n,end:Z(e,.5,i)};case`down`:return{start:n,end:Z(e,.5,r)};case`left`:return{start:n,end:Z(e,i,.5)};case`right`:return{start:n,end:Z(e,r,.5)}}}async function ls(e,t,n){let r=U(e.duration,`swipe.duration`);if(e.kind===`coordinates`){if(e.start.space!==e.end.space)throw new i(`INVALID_ARGS`,`Maestro swipe endpoints must use the same coordinate space.`);let a=e.start.space===`percent`?await n.resolveGestureViewport(Uo(t,t.command)):void 0;return{authored:e,gesture:ds(await us(e.start,t,n,a),await us(e.end,t,n,a),r),...a?{viewport:a}:{}}}if(e.kind===`screen`){let i=await n.resolveGestureViewport(Uo(t,t.command)),{start:a,end:o}=fs(i,e.direction,n.platform);return{authored:e,gesture:ds(a,o,r),viewport:i}}let a=await qo(e.from,{purpose:`swipe`,timeoutMs:`optional`in t.command&&t.command.optional===!0?G.command.optionalTargetLookupTimeoutMs:G.command.targetLookupTimeoutMs},t,n),o=a.viewport??await n.resolveGestureViewport(Uo(t,t.command)),{start:s,end:c}=ps(a,e.direction,o);return{authored:e,gesture:ds(s,c,r),target:a,viewport:o}}async function us(e,t,n,r){if(e.space===`absolute`)return{x:e.x,y:e.y};let i=r??await n.resolveGestureViewport(Uo(t,t.command));return{x:i.x+Math.trunc(i.width*e.x/100),y:i.y+Math.trunc(i.height*e.y/100)}}function ds(e,t,n){return{from:e,to:t,durationMs:n??G.command.swipeDurationMs}}function fs(e,t,n){if(t===`left`||t===`right`){let n=l(t,{referenceWidth:e.width,referenceHeight:e.height});return{start:{x:e.x+n.x1,y:e.y+n.y1},end:{x:e.x+n.x2,y:e.y+n.y2}}}let r=G.screenSwipe,i=Z(e,r.centerFraction,r.nearEdgeFraction),a=Z(e,r.centerFraction,r.farEdgeFraction),o=Z(e,r.centerFraction,r.downStartFraction),s=Z(e,r.centerFraction,r.upStartFraction[n]);return t===`up`?{start:s,end:i}:{start:o,end:a}}function Z(e,t,n){return{x:e.x+Math.trunc(e.width*t),y:e.y+Math.trunc(e.height*n)}}function ps(e,t,n){let r=le(e.rect),i=n.x+Math.trunc(n.width*G.targetSwipe.nearEdgeFraction),a=n.y+Math.trunc(n.height*G.targetSwipe.nearEdgeFraction),o=n.x+Math.trunc(n.width*G.targetSwipe.farEdgeFraction),s=n.y+Math.trunc(n.height*G.targetSwipe.farEdgeFraction);switch(t){case`up`:return{start:r,end:{x:r.x,y:a}};case`down`:return{start:r,end:{x:r.x,y:s}};case`left`:return{start:r,end:{x:i,y:r.y}};case`right`:return{start:r,end:{x:o,y:r.y}}}}const ms={launchApp:ys,stopApp:ys,killApp:ys,setPermissions:ys,clearState:ys,openLink:ys,tapOn:Ss,doubleTapOn:Ss,longPressOn:Ss,swipe:Ds,inputText:Os,eraseText:Os,scroll:ks,scrollUntilVisible:ks,hideKeyboard:ks,pressKey:ks,back:ks,waitForAnimationToEnd:ks,takeScreenshot:Ms,runScript:Ms,evalScript:Ps,assertVisible:Ns,assertNotVisible:Ns,assertTrue:Ns,extendedWaitUntil:Ns},hs={launchApp:!0,stopApp:!0,killApp:!0,setPermissions:!0,clearState:!0,openLink:!0,tapOn:!0,doubleTapOn:!0,longPressOn:!0,swipe:!0,inputText:!0,eraseText:!0,scroll:!0,scrollUntilVisible:!0,hideKeyboard:!0,pressKey:!0,back:!0,waitForAnimationToEnd:!0,takeScreenshot:!1,runScript:!1,evalScript:!1,assertVisible:!1,assertNotVisible:!1,assertTrue:!1,extendedWaitUntil:!1};function gs(e){return hs[e.kind]}async function _s(e,t){let n=e.command;return await vs(n,e,t,Uo(e,n))}function vs(e,t,n,r){let i=ms[e.kind];return i(e,t,n,r)}async function ys(e,t,n,r){switch(e.kind){case`launchApp`:return await Q(n.launchApp,bs(e,t),r,`invalidate`);case`stopApp`:return await Q(n.stopApp,{appId:e.appId??t.appId},r,`invalidate`);case`killApp`:return await Q(n.killApp,{appId:e.appId??t.appId},r,`invalidate`);case`setPermissions`:return await Q(n.setPermissions,{appId:e.appId??t.appId,permissions:xs(e.permissions)},r,`invalidate`);case`clearState`:return await Q(n.clearState,{appId:e.appId??t.appId},r,`invalidate`);case`openLink`:return await Q(n.openLink,{link:e.link},r,`invalidate`)}}function bs(e,t){return O({appId:e.appId??t.appId,stopApp:e.stopApp,clearState:e.clearState,permissions:e.permissions?xs(e.permissions):void 0,arguments:e.arguments,launchArguments:e.launchArguments})}function xs(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.toLowerCase()]))}async function Ss(e,t,n,r){switch(e.kind){case`tapOn`:return await Cs(e,t,n,r);case`doubleTapOn`:{let i=await Hs(e.target,{purpose:`doubleTap`,timeoutMs:Ts(e)},t,n),a=U(e.delay,`doubleTapOn.delay`)??G.command.repeatDelayMs;return await Q(n.doubleTapOn,{target:i,delay:a},r,`invalidate`,i.resolution?Jo(i.resolution):void 0)}case`longPressOn`:{let i=await Hs(e.target,{purpose:`longPress`,timeoutMs:Ts(e)},t,n);return await Q(n.longPressOn,{target:i},r,`invalidate`,i.resolution?Jo(i.resolution):void 0)}}}async function Cs(e,t,n,r){let i=await ws(e,t,n);return await Q(n.tapOn,Es(e,i),r,`invalidate`,i.resolution?Jo(i.resolution):void 0)}async function ws(e,t,n){let r={purpose:`tap`,timeoutMs:Ts(e),allowAtomicSelectorDispatch:e.repeat===void 0&&e.delay===void 0,...e.retryTapIfNoChange===!0?{includeSurfaceSignature:!0}:{}};return await Hs(e.target,r,t,n)}function Ts(e){return e.optional===!0?G.command.optionalTargetLookupTimeoutMs:G.command.targetLookupTimeoutMs}function Es(e,t){let n=U(e.repeat,`tapOn.repeat`),r=U(e.delay,`tapOn.delay`),i=n===void 0?r:r??G.command.repeatDelayMs;return O({target:t,retryTapIfNoChange:e.retryTapIfNoChange,repeat:n,delay:i})}async function Ds(e,t,n,r){let i=await ls(e.gesture,t,n);return await Q(n.gesture,i.gesture,{...r,...i.viewport?{gestureViewport:i.viewport}:{}},`invalidate`,i.target?Jo(i.target):void 0)}async function Os(e,t,n,r){switch(e.kind){case`inputText`:return await Q(n.inputText,O({text:e.text,label:e.label}),r,`invalidate`);case`eraseText`:return await Q(n.eraseText,O({charactersToErase:U(e.charactersToErase,`eraseText.charactersToErase`)}),r,`invalidate`)}}async function ks(e,t,n,r){switch(e.kind){case`scroll`:return await Q(n.scroll,{direction:`down`},r,`invalidate`);case`scrollUntilVisible`:return await Q(n.scrollUntilVisible,As(e),r,`invalidate`);case`hideKeyboard`:return await Q(n.hideKeyboard,{},r,`invalidate`);case`pressKey`:return await Q(n.pressKey,{key:e.key},r,`invalidate`);case`back`:return await Q(n.back,{},r,`invalidate`);case`waitForAnimationToEnd`:return await Q(n.waitForAnimationToEnd,js(e),r,`preserve`)}}function As(e){return{selector:e.element,direction:e.direction??`down`,timeoutMs:U(e.timeout,`scrollUntilVisible.timeout`)??G.command.scrollUntilVisibleTimeoutMs,durationMs:er(G.command.scrollUntilVisibleSpeed)}}function js(e){return O({timeoutMs:U(e.timeout,`waitForAnimationToEnd.timeout`)})}async function Ms(e,t,n,r){switch(e.kind){case`takeScreenshot`:return Is(await n.takeScreenshot({path:e.path},r),[],void 0,r.generation);case`runScript`:return await Q(n.runScript,O({file:e.file,env:e.env}),r,`preserve`)}}async function Ns(e){throw new i(`COMMAND_FAILED`,`Maestro ${e.kind} must be executed by the observation engine.`)}function Ps(e){throw new i(`COMMAND_FAILED`,`Maestro evalScript must be executed by the compute engine at ${e.source.path??``}line ${e.source.line}.`)}async function Q(e,t,n,r,i){let a=Fs(n,r);return Is(await e(t,a),[],r===`preserve`?i:void 0,a.generation)}function Fs(e,t){return t===`preserve`?e:(e.invalidateObservation(),{...e,generation:e.generation+1})}function Is(e,t,n,r){let i=e?.observation;return Ls(i,r),{...Rs(n??i),...zs(e?.outputEnv),...Bs(t,e?.artifactPaths),...Vs(e?.data),...e?.visualStabilityReached===void 0?{}:{visualStabilityReached:e.visualStabilityReached}}}function Ls(e,t){if(!(!e||t===void 0||e.generation===t))throw new i(`COMMAND_FAILED`,`Maestro operation evidence generation ${e.generation} does not match ${t}.`)}function Rs(e){return e?{observation:e}:{}}function zs(e){return e?{outputEnv:{...e}}:{}}function Bs(e,t){let n=[...new Set([...e,...t??[]])];return n.length>0?{artifactPaths:n}:{}}function Vs(e){return e&&Object.keys(e).length>0?{data:{...e}}:{}}async function Hs(e,t,n,r){if(e.space===`target`){let i=await qo(e.selector,t,n,r);return{authored:e,point:le(i.rect),resolution:i}}return{authored:e,point:await us(e,n,r)}}function Us(e,t,n,r={}){let i=n===`ios`&&r.presentation?Gs(r.presentation):void 0,a=i?Ks(e,t,i):Oa(e,t.selector,n);if(!a.parentMatched)return{ok:!1,message:`Maestro childOf parent did not match.`,failureReason:`selector-did-not-match`,evidence:Xs(t,a.matches,[],void 0)};let{matches:o,ranked:s}=a,c=i?Na(s,t.selector.index):Ma(s,t.selector.index)?.node,l=Xs(t,o,s,c);if(!c)return qs(t,o,s,l);let u=i?Ma(i.visibleForSource(c),void 0):null,d=Pa(c),f=r.interactiveBounds?u?.rect??d:d??u?.rect;return f?{ok:!0,node:c,rect:f,matches:s.length,dispatchCandidates:n===`ios`&&t.allowAtomicSelectorDispatch&&!Ws(t.selector)&&i?Js(d,s,u):0,evidence:l}:{ok:!1,message:`Maestro target did not provide usable geometry.`,failureReason:`no-usable-geometry`,evidence:l}}const Ws=sa;function Gs(e){let t=y(e.snapshot.nodes),n=t.nodeByIndex,r=new Map,i=t=>(e.presentedIndexesBySourceIndex.get(t.index)??[]).flatMap(e=>{let t=n.get(e);return t?[t]:[]}),a=e=>{let n=r.get(e.index);if(n)return n;let a=i(e).filter(e=>ta(e,t,`ios`));return r.set(e.index,a),a};return{visibleForSource:a,isVisible:e=>a(e).length>0}}function Ks(e,t,n){let r=Ta(e,`ios`),i=ma(e,{},{orderUnindexed:e=>Ea(e,r)}),a=ka(t.selector,i),o=a.matches.filter(n.isVisible);return{...a,visible:o,clickability:r,ranked:ja(o,t.selector,`ios`,i.visibility,r)}}function qs(e,t,n,r){if(t.length>0&&n.length===0)return{ok:!1,message:`Maestro selector matched ${t.length} element(s), but none were visible.`,failureReason:`no-visible-match`,evidence:r};let i=e.selector.index;return n.length>0?i!==void 0&&Na(n,i)===void 0?{ok:!1,message:`Maestro selector matched ${n.length} visible element(s); index ${i} is out of range.`,failureReason:`index-out-of-range`,evidence:r}:{ok:!1,message:`Maestro target did not provide usable geometry.`,failureReason:`no-usable-geometry`,evidence:r}:{ok:!1,message:`Maestro selector did not match.`,failureReason:`selector-did-not-match`,evidence:r}}function Js(e,t,n){return t.length===1?e&&n&&n.node.hittable!==!1&&Ys(n.rect,e)?1:0:t.length}function Ys(e,t){let n=le(e),r=le(t);return n.x===r.x&&n.y===r.y}function Xs(e,t,n,r){return O({selector:e.selector,matched:t.length>0,visible:n.length>0,candidateCount:t.length,ref:r?.ref})}const $={settleTimeoutMs:nr,retryTapMaxAttempts:G.command.retryTapMaxAttempts,longPressDurationMs:G.command.longPressDurationMs,eraseTextMaxCharacters:G.command.eraseTextMaxCharacters,androidInputTextCharacterDelayMs:G.command.androidInputTextCharacterDelayMs,scrollUntilVisiblePercentage:G.command.scrollUntilVisiblePercentage,animationWaitTimeoutMs:G.command.waitForAnimationToEndTimeoutMs,animationDifferencePercent:G.command.waitForAnimationToEndDifferencePercent,observationPollMs:G.observation.pollIntervalMs};function Zs(e,t={}){return{execute:async n=>{let r=Uo(n,n.command),i=n.command.kind===`waitForAnimationToEnd`;await t.beforeExecute?.({context:r,requiresSettledPredecessor:gs(n.command)&&!i,visualStabilityBarrier:i});let a=await _s(n,e);return t.afterExecute?.({context:r,visualStabilityReached:i&&a.visualStabilityReached===!0}),delete a.visualStabilityReached,a},observe:async n=>{let r=await Go(n,e);return t.bindObservation?.(r)??r},...t.readMetrics?{readMetrics:t.readMetrics}:{}}}const Qs=3e4,$s=1e3;function ec(e){let{scriptPath:t,env:n,publicNetworkOnly:r}=e;kn({trustedScripts:!r},`runScript`);let a=me.readFileSync(t,`utf8`),o=Object.create(null);try{ye.runInNewContext(a,tc(n,o,r),{filename:t,timeout:Qs})}catch(e){let n=c(e);throw new i(n.code,`Maestro runScript failed: ${n.message}`,u({...n.details??{},hint:n.hint,diagnosticId:n.diagnosticId,logPath:n.logPath,retriable:n.retriable,supportedOn:n.supportedOn,scriptPath:t}),e instanceof Error?e:void 0)}return cc(o,t),Object.fromEntries(Object.entries(o).map(([e,t])=>[`output.${e}`,lc(t)]))}function tc(e,t,n){return{...e,output:t,json:nc,http:{post:(e,t)=>ic(`POST`,e,n,t)}}}function nc(e){if(typeof e!=`string`)throw new i(`COMMAND_FAILED`,`Maestro runScript json() expected a string body, received ${typeof e}.`);if(e.trim().length===0)throw new i(`COMMAND_FAILED`,`Maestro runScript json() received an empty body.`,{hint:`Check the preceding HTTP response status and setup server output.`});try{return JSON.parse(e,rc)}catch(t){throw new i(`COMMAND_FAILED`,`Maestro runScript json() could not parse response body: ${t instanceof Error?t.message:String(t)}`,{bodyPreview:e.slice(0,$s)},t instanceof Error?t:void 0)}}function rc(e,t){return e===`__proto__`||e===`constructor`||e===`prototype`?void 0:t}function ic(e,t,n,r){let a=v(process.execPath,ac(),{stdin:JSON.stringify(sc(e,t,r,n)),timeoutMs:Qs,allowFailure:!0});if(a.exitCode!==0)throw new i(`COMMAND_FAILED`,`Maestro runScript http.${e.toLowerCase()} failed for ${t}: ${uc(a.stderr)}`,{exitCode:a.exitCode,stderr:a.stderr});try{return JSON.parse(a.stdout)}catch(n){throw new i(`COMMAND_FAILED`,`Maestro runScript http.${e.toLowerCase()} returned invalid JSON for ${t}`,{stdout:a.stdout.slice(0,$s),stderr:a.stderr.slice(0,$s)},n instanceof Error?n:void 0)}}function ac(){let e=oc(import.meta.url);if(!e)throw new i(`COMMAND_FAILED`,`Maestro runScript http helper entrypoint is unavailable; rebuild the package`);return e.endsWith(`.ts`)?[`--experimental-strip-types`,e]:[e]}function oc(e){try{let t=_e(e),n=D.extname(t)||`.js`;return[D.join(D.dirname(t),`run-script-http-child`+n),D.join(D.dirname(t),`internal`,`run-script-http-child`+n)].find(e=>me.existsSync(e))??null}catch{return null}}function sc(e,t,n,r){return{method:e,url:t,headers:n?.headers??{},body:n?.body??``,publicNetworkOnly:r}}function cc(e,t){for(let n of Object.keys(e))if(n.includes(`.`))throw new i(`INVALID_ARGS`,`Maestro runScript output key cannot contain ".": ${n}`,{scriptPath:t,key:n})}function lc(e){return typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`?String(e):JSON.stringify(e)}function uc(e){let t=e.trim();return t.length>0?t.slice(0,$s):`request process exited without stderr`}function dc(e){return e.kind===`clearState`?_c(e):fc(e)?pc(e):Mc(e)?Nc(e):e.kind===`settingsPermission`?Tc(e):Ec(e)}function fc(e){return e.kind===`launchApp`||e.kind===`stopApp`||e.kind===`killApp`||e.kind===`openLink`}function pc(e){switch(e.kind){case`launchApp`:return mc(e);case`stopApp`:return hc(e);case`killApp`:return gc(e);case`openLink`:return vc(e)}}function mc(e){return{command:`open`,positionals:e.appId?[e.appId]:[],flags:{...e.relaunch?{relaunch:!0}:{},...e.clearState?{clearAppState:!0}:{},...e.launchArgs.length>0?{launchArgs:e.launchArgs}:{}}}}function hc(e){return{command:`close`,positionals:e.appId?[e.appId]:[],dispatch:{closeAppOnly:!0}}}function gc(e){return{command:`close`,positionals:e.appId?[e.appId]:[],dispatch:{closeAppOnly:!0,killApp:!0}}}function _c(e){return{command:`settings`,positionals:e.appId?[`clear-app-state`,e.appId]:[`clear-app-state`]}}function vc(e){return{command:`open`,positionals:e.appId?[e.appId,e.link]:[e.link],...e.prewarmRunner?{flags:{maestro:{prewarmRunnerBeforeOpen:!0}}}:{}}}const yc={camera:`camera`,microphone:`microphone`,photos:`photos`,contacts:`contacts`,notifications:`notifications`,calendar:`calendar`,location:`location`,medialibrary:`media-library`,"media-library":`media-library`,motion:`motion`,reminders:`reminders`,siri:`siri`},bc={allow:`grant`,deny:`deny`,unset:`reset`},xc={location:{always:{state:`grant`,permission:`location-always`},inuse:{state:`grant`,permission:`location`},never:{state:`deny`,permission:`location`}},photos:{limited:{state:`grant`,permission:`photos`,mode:`limited`}}};function Sc(e){let t=Object.entries(e).map(([e,t])=>[e.toLowerCase(),t]);if(t.length===0)throw new i(`INVALID_ARGS`,`Maestro setPermissions requires at least one permission.`);return[...t.filter(([e])=>e===`all`),...t.filter(([e])=>e!==`all`)].map(([e,t])=>Cc(e,t))}function Cc(e,t){let n=e===`all`?`all`:wc(yc,e);if(n===void 0)throw new i(`UNSUPPORTED_OPERATION`,`Maestro permission "${e}" is not supported.`,{hint:`Supported: all, ${Object.keys(yc).join(`, `)}.`});let r=xc[e],a=r?wc(r,t):void 0;if(a)return a;let o=wc(bc,t);if(o)return{state:o,permission:n};throw new i(`INVALID_ARGS`,`Maestro permission "${e}" does not accept "${t}".`,{hint:`Use ${[`allow`,`deny`,`unset`,...Object.keys(r??{})].join(`|`)}.`})}function wc(e,t){return Object.hasOwn(e,t)?e[t]:void 0}function Tc(e){return{command:`settings`,positionals:[`permission`,e.state,e.permission,...e.mode?[e.mode]:[]],...e.appId?{dispatch:{settingsAppBundleId:e.appId}}:{}}}function Ec(e){switch(e.kind){case`gestureViewport`:return{command:`runtime`,positionals:[`gesture-viewport`]};case`typeText`:return{command:`type`,positionals:[e.text],...e.delayMs===void 0?{}:{flags:{delayMs:e.delayMs}}};case`clickSelector`:return Dc(e);case`clickPoint`:return Oc(e);case`swipe`:return kc(e);case`scroll`:return Ac(e);case`pressKey`:return jc(e)}}function Dc(e){return{command:`click`,positionals:[`${e.selector.key}=${JSON.stringify(e.selector.value)}`],flags:{...e.options,maestro:{allowNonHittableCoordinateFallback:!0,expectedTapPoint:e.expectedPoint}}}}function Oc(e){return{command:`click`,positionals:[String(e.point.x),String(e.point.y)],flags:{...e.options}}}function kc(e){let{from:t,to:n,durationMs:r}=e.gesture;return{command:`gesture`,positionals:[],input:{kind:`pan`,origin:t,delta:{x:n.x-t.x,y:n.y-t.y},durationMs:r},flags:{postGestureStabilization:!1},dispatch:{gestureExecutionProfile:`endpoint-hold`,...e.viewport?{gestureViewport:e.viewport}:{}}}}function Ac(e){return{command:`scroll`,positionals:[e.direction],...e.durationMs===void 0?{}:{input:{direction:e.direction,durationMs:e.durationMs}},flags:{postGestureStabilization:!1}}}function jc(e){return e.key===`back`||e.key===`home`?{command:e.key,positionals:[]}:{command:`keyboard`,positionals:[e.key]}}function Mc(e){return e.kind===`screenshot`||e.kind===`snapshot`}function Nc(e){switch(e.kind){case`screenshot`:return{command:`screenshot`,positionals:e.path===void 0?[]:[e.path],...e.stabilize===!1||e.captureBackend===`runner`?{flags:{...e.stabilize===!1?{screenshotNoStabilize:!0}:{},...e.captureBackend===`runner`?{maestro:{screenshotCaptureBackend:`runner`}}:{}}}:{}};case`snapshot`:return{command:`snapshot`,positionals:[],flags:{noRecord:!0},dispatch:{observationOnly:!0}}}}async function Pc(e,t){let n=dc(t.kind===`screenshot`&&e.publicNetworkOnly?{...t,path:void 0}:t),r=await e.invoke(u({...n,flags:Fc(e.flags,n.flags??{})}));if(!r.ok)throw Vc(r);if(t.kind===`gestureViewport`){let e=r.data?.viewport;if(typeof e!=`object`||!e||![`x`,`y`,`width`,`height`].every(t=>typeof e[t]==`number`))throw new i(`COMMAND_FAILED`,`runtime gesture-viewport returned no valid viewport.`);return e}return r.data}function Fc(e,t){let n=e?.maestro===void 0&&t.maestro===void 0?void 0:{...e?.maestro,...t.maestro},r=u({...e,...t,maestro:n});return Object.keys(r).length>0?r:void 0}function Ic(e){return e?e.kind===`scalar`?[String(e.value)]:e.kind===`list`?e.values.map(String):Object.entries(e.values).flatMap(([e,t])=>[e,String(t)]):[]}function Lc(e,t){return{generation:t.generation,matched:t.matched&&t.visible,candidateCount:t.candidateCount,evidence:{kind:`selector`,selector:e,visible:t.visible,candidateCount:t.candidateCount,...t.ref?{ref:t.ref}:{}}}}function Rc(e){if(!e)return[];let t=[];if(typeof e.path==`string`&&t.push(e.path),Array.isArray(e.artifactPaths)&&t.push(...e.artifactPaths.filter(e=>typeof e==`string`)),Array.isArray(e.artifacts))for(let n of e.artifacts)typeof n.localPath==`string`?t.push(n.localPath):typeof n.path==`string`&&t.push(n.path);return[...new Set(t)]}function zc(e,t,n){if(D.isAbsolute(e))return e;let r=t.source?.path??n;if(!r)throw new i(`INVALID_ARGS`,`Maestro runScript file paths require a source path.`);return D.resolve(D.dirname(r),e)}function Bc(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,String(t)]))}function Vc(e){let t=e.error,n=u({...t.details??{},hint:t.hint??Hc(t.details,`hint`),diagnosticId:t.diagnosticId??Hc(t.details,`diagnosticId`),logPath:t.logPath??Hc(t.details,`logPath`),retriable:t.retriable??Uc(t.details,`retriable`),supportedOn:t.supportedOn??Hc(t.details,`supportedOn`)});return new i(t.code,t.message,Object.keys(n).length?n:void 0)}function Hc(e,t){let n=e?.[t];return typeof n==`string`?n:void 0}function Uc(e,t){let n=e?.[t];return typeof n==`boolean`?n:void 0}async function Wc(e,t){let n=await Pc(e,{kind:`screenshot`,path:t,stabilize:!1,...e.platform===`ios`?{captureBackend:`runner`}:{}});if(e.publicNetworkOnly){if(typeof n?.path!=`string`||n.path.length===0)throw new i(`COMMAND_FAILED`,`Maestro screenshot returned no capture path.`);try{await he.copyFile(n.path,t)}finally{await he.rm(n.path,{force:!0});try{await he.rmdir(D.dirname(n.path))}catch{}}}}async function Gc(e){return await Kc(`tap`,async t=>{let n=D.join(t,`before.png`),r=D.join(t,`after.png`),i=await Jc(e,n);return await e.run({matchesCurrent:async()=>{if(!(!i||!await Jc(e,r)))return await qc(n,r,e.signal,`tap`)}})})}async function Kc(e,t){let n=await he.mkdtemp(D.join(ge.tmpdir(),`agent-device-maestro-${e}-`));try{return await t(n)}finally{try{await he.rm(n,{recursive:!0,force:!0})}catch{}}}async function qc(e,t,n,r){try{let[i,a]=await Promise.all([he.readFile(e),he.readFile(t)]);Qc(n);let o=await de(i,a,`Maestro screenshot`);return Qc(n),Yc(o,r)}catch(e){Zc(e,n),g({level:`debug`,phase:`maestro_screenshot_compare`,data:{purpose:r,result:`error`,error:e instanceof Error?e.message:String(e)}});return}}async function Jc(e,t){try{return await he.rm(t,{force:!0}),Qc(e.signal),await e.capture(t),Qc(e.signal),!0}catch(t){return Zc(t,e.signal),!1}}function Yc(e,t){if(e.status!==`compared`)return Xc(t,e.status,e),!1;let n=e.differencePercent<=$.animationDifferencePercent;return Xc(t,n?`stable`:`changed`,e),n}function Xc(e,t,n){g({level:`debug`,phase:`maestro_screenshot_compare`,data:{purpose:e,result:t,first:n.first,second:n.second,...`differencePercent`in n?{differencePercent:n.differencePercent}:{}}})}function Zc(e,t){if(t?.aborted||r(e))throw n()}function Qc(e){if(e?.aborted)throw n()}async function $c(e){tl(e.timeoutMs),Qc(e.signal);let t=e.now()+e.timeoutMs;return await Kc(`animation`,async n=>{let r=D.join(n,`first.png`),i=D.join(n,`second.png`);for(;;){if(Qc(e.signal),await el(e,r,i))return!0;if(e.now()>=t)return!1}})}async function el(e,t,n){let r=[await Jc(e,t),await Jc(e,n)];return!r[0]||!r[1]?!1:await qc(t,n,e.signal,`animation`)===!0}function tl(e){if(!Number.isFinite(e)||e<0)throw new i(`INVALID_ARGS`,`waitForAnimationToEnd timeout must be a non-negative number.`)}const nl=$.observationPollMs;async function rl(e,t){for(;;){vl(e.context.signal);try{return await e.snapshot(e.context)}catch(n){if(!bl(n)||(vl(e.context.signal),!await _l(e.dependencies,t,nl,e.context.signal)))throw n}}}function il(e){return al({...e,mode:e.query.purpose===`swipe`?`swipe`:`tap`})}function al(e){let t=ue(e.snapshot),n=e.platform===`ios`?fe(e.snapshot.nodes):void 0,r=n?{...e.snapshot,nodes:o(n.nodes)}:e.snapshot;return ul(Us(e.snapshot,e.query,e.platform,{interactiveBounds:e.mode===`tap`,presentation:n?{snapshot:r,presentedIndexesBySourceIndex:n.presentedIndexesBySourceIndex}:void 0}),e.snapshot,e.context.generation,t,e.query,e.platform,e.mode)}async function ol(e){yl(e.timeoutMs,`observation`);let t,n=e.dependencies.now()+e.timeoutMs;for(;;){vl(e.context.signal);let r=await rl(e,n),i=al({query:{selector:e.condition.selector},context:e.context,snapshot:r,platform:e.platform,mode:`observe`});if(t=i,Ko(e.condition,i))return i;if(e.dependencies.now()>=n)break;await _l(e.dependencies,n,nl,e.context.signal)}return vl(e.context.signal),Cl(t)}async function sl(e){yl(e.timeoutMs,`scrollUntilVisible`);let t=e.dependencies.now()+e.timeoutMs,n,r;for(;;){vl(e.context.signal);let i=r??await rl(e,t);if(r=void 0,n=al({query:{selector:e.selector},context:e.context,snapshot:i,platform:e.platform,mode:`observe`}),n.visiblePercentage===$.scrollUntilVisiblePercentage)return n;if(e.dependencies.now()>=t)break;let a=t-e.dependencies.now();a>0&&(r=await e.scroll(a,i))}return vl(e.context.signal),Cl(n)}async function cl(e){yl(e.timeoutMs,`waitForAnimationToEnd`);let t=e.dependencies.now()+e.timeoutMs,n=e.initialSnapshot??await rl(e,t),r=xl(n);for(;;){vl(e.context.signal),await _l(e.dependencies,t,nl,e.context.signal);let i=await rl(e,t),a=xl(i);if(a===r)return{snapshot:i,signature:a,settled:!0};if(n=i,r=a,e.dependencies.now()>=t)return{snapshot:n,signature:r,settled:!1}}}function ll(e){return e?{x:0,y:0,width:e.referenceWidth,height:e.referenceHeight}:void 0}function ul(e,t,n,r,i,a,o){if(!e.ok){let t=ll(r);return{generation:n,matched:e.evidence.matched,visible:e.evidence.visible,candidateCount:e.evidence.candidateCount,failureReason:e.failureReason,...e.evidence.ref?{ref:e.evidence.ref}:{},...t?{viewport:t}:{}}}let s=fl({query:i,platform:a,mode:o,dispatchCandidates:e.dispatchCandidates}),c=ll(r);return{generation:n,matched:!0,visible:!0,...c?{visiblePercentage:dl(e.rect,c)}:{},candidateCount:e.evidence.candidateCount,rect:e.rect,...e.evidence.ref?{ref:e.evidence.ref}:{},...c?{viewport:c}:{},...s?{dispatchSelector:s}:{},...i.includeSurfaceSignature?{surfaceSignature:xl(t)}:{}}}function dl(e,t){return!w(e)||!w(t)?0:re(t,e)?100:Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x))*Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y))*100/(e.width*e.height)}function fl(e){let{query:t,platform:n,mode:r,dispatchCandidates:i}=e;if(!(!pl(t,n,r)||i!==1))return ml(t.selector)}function pl(e,t,n){return t===`ios`&&n===`tap`&&e.allowAtomicSelectorDispatch===!0&&!Ws(e.selector)}function ml(e){let t=Object.entries(e).filter(([,e])=>e!==void 0);if(t.length!==1)return;let[n,r]=t[0];if(!hl(n)||typeof r!=`string`)return;let i=ea(r)?.trim();return i?{key:n,value:i}:void 0}function hl(e){return e===`id`||e===`label`||e===`text`}async function gl(e,t,r){try{await e.sleep(t,r)}catch(e){throw r?.aborted?n():e}vl(r)}async function _l(e,t,n,r){let i=t-e.now();return i<=0?!1:(await gl(e,Math.min(n,i),r),!0)}function vl(e){if(e?.aborted)throw n()}function yl(e,t){if(!Number.isFinite(e)||e<0)throw new i(`INVALID_ARGS`,`${t} timeout must be a non-negative number.`)}function bl(e){return e instanceof i&&e.details?.retriable===!0}function xl(e){return pe(`sha256`).update(JSON.stringify([...e.nodes].sort((e,t)=>e.index-t.index).map(e=>({index:e.index,parentIndex:e.parentIndex,identifier:e.identifier??``,label:e.label??``,value:e.value??``,enabled:e.enabled??!1,selected:e.selected??!1,focused:e.focused??!1,checked:e.checked??!1,bounds:Sl(e.rect)})))).digest(`hex`)}function Sl(e){if(e)return{left:Math.trunc(e.x),top:Math.trunc(e.y),right:Math.trunc(e.x+e.width),bottom:Math.trunc(e.y+e.height)}}function Cl(e){if(e)return e;throw new i(`COMMAND_FAILED`,`Maestro observation completed without a snapshot result.`)}function wl(e){let t,n,r,a,o,s=0,c=0,l=async n=>{c+=1;let r=await Pc(e,{kind:`snapshot`});if(!r||!Array.isArray(r.nodes))throw new i(`COMMAND_FAILED`,`Maestro snapshot did not return node data.`);let a=m(r,r);return t={generation:n.generation,snapshot:a},a};return{capture:async e=>{if(n?.generation===e.generation){let r=n.snapshot;return n=void 0,t={generation:e.generation,snapshot:r},r}return n=void 0,await l(e)},bindObservation:e=>{if(t?.generation!==e.generation)return e;let n=`maestro-observation-${++s}`;return t.observationIdentity=n,{...e,identity:n}},reuseObservation:e=>{if(e.cachedObservation?.generation===e.generation&&e.cachedObservation.identity!==void 0&&t?.generation===e.generation&&e.cachedObservation.identity===t.observationIdentity)return t.snapshot},readMetrics:()=>({hierarchyCaptures:c}),invalidate:e=>{r=t?.generation===e-1?{generation:e,snapshot:t.snapshot}:void 0,t=void 0,n=void 0},requireStability:e=>{o=e,a=r?.generation===e?r:void 0,r=void 0,n=void 0},consumeStabilityFromVisualWait:e=>{if(o!==void 0){if(o!==e.generation)throw new i(`COMMAND_FAILED`,`Maestro stability generation ${o} does not match ${e.generation}.`);o=void 0,a=void 0,r=void 0,n=void 0}},prime:(e,t)=>{n={generation:e,snapshot:t}},settlePending:async r=>{if(o===void 0)return;if(o!==r.generation)throw new i(`COMMAND_FAILED`,`Maestro stability generation ${o} does not match ${r.generation}.`);let s=t?.generation===r.generation?t.snapshot:a?.snapshot,c=await cl({timeoutMs:$.settleTimeoutMs,context:r,snapshot:l,dependencies:e.dependencies,...s?{initialSnapshot:s}:{}});return o=void 0,a=void 0,n={generation:r.generation,snapshot:c.snapshot},c}}}async function Tl(e){let{input:t,context:n,snapshots:r,options:i}=e,a=i.dependencies.now()+t.timeoutMs,o=e.allowObservationReuse===!1?void 0:r.reuseObservation(n);for(;;){let e=i.dependencies.now(),s=o!==void 0;o??=await rl({context:n,snapshot:r.capture,dependencies:i.dependencies},a);let c=il({query:t,context:n,snapshot:o,platform:i.platform});if(jl(c,s))return c;if(o=void 0,!s){if(e>=a)return c;await _l(i.dependencies,a,nl,n.signal)}}}async function El(e,t,n,r,i,a){let o=async()=>await kl(e,t,r,i,a.click);if(!a.retryIfNoChange){try{await o()}finally{t.requireStability(i.generation)}return}if(e.platform===`ios`){await Gc({signal:i.signal,capture:async t=>{n.screenshotCaptures+=1,await Wc(e,t)},run:async o=>await Dl(e,t,n,r,i,a.click,o)});return}await Dl(e,t,n,r,i,a.click)}async function Dl(e,t,n,r,i,a,o){let s=async()=>await kl(e,t,r,i,a),c=r.resolution?.surfaceSignature??(o?void 0:xl(await t.capture(i))),l=async()=>{let r=await cl({timeoutMs:$.settleTimeoutMs,context:i,snapshot:t.capture,dependencies:e.dependencies});return r.settled?n.settleLatches+=1:n.settleTimeouts+=1,r};try{let e=await Ol({baselineSignature:c,screenshotBaseline:o,dispatch:s,settle:l,onRetry:()=>{n.tapRetries+=1}});t.prime(i.generation,e.snapshot)}catch(e){throw t.requireStability(i.generation),e}}async function Ol(e){await e.dispatch();let t=await e.settle(),n=1;for(;(e.baselineSignature===void 0||t.signature===e.baselineSignature)&&n<$.retryTapMaxAttempts&&!(e.screenshotBaseline&&await e.screenshotBaseline.matchesCurrent()!==!0);)e.onRetry(),await e.dispatch(),n+=1,t=await e.settle();return t}async function kl(e,t,n,r,i){let a=n.resolution,o=a?.dispatchSelector;if(o&&n.point){t.invalidate(r.generation);try{await Ml(e,o,n.point,i);return}catch(n){if(!Nl(n))throw n;let o=await Tl({input:a.query,context:r,snapshots:t,options:e,allowObservationReuse:!1});if(!Al(o))throw n;t.invalidate(r.generation),await Pl(e,le(o.rect),i);return}}t.invalidate(r.generation),await Pl(e,n.point,i)}function Al(e){return e.matched&&e.visible&&e.rect!==void 0}function jl(e,t){return Al(e)?!t||e.dispatchSelector!==void 0:!1}async function Ml(e,t,n,r){g({level:`debug`,phase:`maestro_tap_dispatch`,data:{kind:`selector`,selectorKey:t.key,expectedPoint:n}}),await Pc(e,{kind:`clickSelector`,selector:t,expectedPoint:n,options:r})}function Nl(e){let t=a(e);return t.code===`AMBIGUOUS_MATCH`||t.code===`ELEMENT_NOT_FOUND`||t.code===`ELEMENT_OFFSCREEN`||t.details?.reason===ce.selectorNotFound}async function Pl(e,t,n){if(!t)throw new i(`COMMAND_FAILED`,`Maestro target did not resolve to a point.`);g({level:`debug`,phase:`maestro_tap_dispatch`,data:{kind:`point`,point:t}}),await Pc(e,{kind:`clickPoint`,point:t,options:n})}function Fl(e){return`${e.state} ${e.permission}${e.mode?` ${e.mode}`:``}`}function Il(e){let t=wl(e),n={screenshotCaptures:0,tapRetries:0,settleLatches:0,settleTimeouts:0},r=e=>{e.settled?n.settleLatches+=1:n.settleTimeouts+=1},a=e.platform,o=t=>(t.kind===`screenshot`&&(n.screenshotCaptures+=1),Pc(e,t)),s=async(e,n,r=`none`)=>{t.invalidate(n.generation);try{return await e()}finally{r===`deferred`&&t.requireStability(n.generation)}},c=async(e,t,n=`none`)=>await s(()=>o(e),t,n),l=async(e,t,n)=>{let r=[];for(let a of t){try{await c({kind:`settingsPermission`,...e?{appId:e}:{},state:a.state,permission:a.permission,...a.mode?{mode:a.mode}:{}},n)}catch(e){throw e instanceof i?new i(e.code,e.message,{...e.details,appliedPermissionMutations:r,failedPermissionMutation:Fl(a)}):e}r.push(Fl(a))}},d=a===`android`?$.androidInputTextCharacterDelayMs:void 0,f=async(n,i,a)=>{_(n),await c({kind:`typeText`,text:n,...a===void 0?{}:{delayMs:a}},i);let o=await cl({timeoutMs:$.settleTimeoutMs,context:i,snapshot:t.capture,dependencies:e.dependencies});r(o),t.prime(i.generation,o.snapshot)};return{operations:{platform:a,resolveTarget:async(n,r)=>await Tl({input:n,context:r,snapshots:t,options:e}),observe:async(n,r)=>await ol({condition:n.condition,timeoutMs:n.timeoutMs,context:r,snapshot:t.capture,dependencies:e.dependencies,platform:a}),resolveGestureViewport:async()=>await o({kind:`gestureViewport`}),launchApp:async(e,t)=>{let n=e.appId??t.appId,r=[...Ic(e.arguments),...Ic(e.launchArguments)],i=e.clearState===!0,a=!i&&e.stopApp!==!1;if(e.permissions){let r=Sc(e.permissions);i&&await c({kind:`clearState`,...n?{appId:n}:{}},t),await l(n,r,t)}await c({kind:`launchApp`,...n?{appId:n}:{},relaunch:a,clearState:i&&!e.permissions,launchArgs:r},t,`deferred`)},stopApp:async(e,t)=>{let n=e.appId??t.appId;await c({kind:`stopApp`,...n?{appId:n}:{}},t)},killApp:async(e,t)=>{let n=e.appId??t.appId;await c({kind:`killApp`,...n?{appId:n}:{}},t)},setPermissions:async(e,t)=>{await l(e.appId??t.appId,Sc(e.permissions),t)},clearState:async(e,t)=>{let n=e.appId??t.appId;await c({kind:`clearState`,...n?{appId:n}:{}},t)},openLink:async(e,t)=>{await c({kind:`openLink`,...t.appId?{appId:t.appId}:{},link:e.link,prewarmRunner:a===`ios`},t,`deferred`)},tapOn:async(r,i)=>await El(e,t,n,r.target,i,{click:{count:r.repeat,intervalMs:r.delay},retryIfNoChange:r.retryTapIfNoChange===!0}),doubleTapOn:async(t,n)=>{await s(()=>Pl(e,t.target.point,u({doubleTap:!0,intervalMs:t.delay})),n,`deferred`)},longPressOn:async(t,n)=>{await s(()=>Pl(e,t.target.point,{holdMs:$.longPressDurationMs}),n,`deferred`)},gesture:async(e,t)=>{let n=await c({kind:`swipe`,gesture:e,...t.gestureViewport?{viewport:t.gestureViewport}:{}},t,`deferred`);return n?{data:n}:void 0},inputText:async(e,t)=>await f(e.text,t,d),eraseText:async(e,t)=>await f(`\b`.repeat(e.charactersToErase??$.eraseTextMaxCharacters),t),scroll:async(e,t)=>{await c({kind:`scroll`,direction:e.direction},t,`deferred`)},scrollUntilVisible:async(n,r)=>{let i=await sl({selector:n.selector,direction:n.direction,timeoutMs:n.timeoutMs,context:r,snapshot:t.capture,dependencies:e.dependencies,platform:a,scroll:async(i,o)=>{let s=rs(o,n.selector,n.direction,n.durationMs,a);return await c(s?{kind:`swipe`,...s}:{kind:`scroll`,direction:n.direction,durationMs:n.durationMs},r),(await cl({timeoutMs:Math.min($.settleTimeoutMs,i),context:r,snapshot:t.capture,dependencies:e.dependencies})).snapshot}});if(i.visiblePercentage!==$.scrollUntilVisiblePercentage)throw ir(`Maestro scrollUntilVisible target did not become visible.`,{selector:n.selector,timeoutMs:n.timeoutMs});return{observation:t.bindObservation(Lc(n.selector,i))}},pressKey:async(e,t)=>{await c({kind:`pressKey`,key:e.key},t,`deferred`)},back:async(e,t)=>{await c({kind:`pressKey`,key:`back`},t,`deferred`)},hideKeyboard:async(e,t)=>{await c({kind:`pressKey`,key:`dismiss`},t,`deferred`)},waitForAnimationToEnd:async(t,r)=>({visualStabilityReached:await $c({timeoutMs:t.timeoutMs??$.animationWaitTimeoutMs,now:e.dependencies.now,signal:r.signal,capture:async t=>{n.screenshotCaptures+=1,await Wc(e,t)}})}),takeScreenshot:async e=>({artifactPaths:Rc(await o({kind:`screenshot`,path:e.path}))}),runScript:async(t,n)=>({outputEnv:ec({scriptPath:zc(t.file,n,e.sourcePath),publicNetworkOnly:e.publicNetworkOnly,env:{...n.env,...t.env?Bc(t.env):{}}})})},snapshots:t,readMetrics:()=>({...t.readMetrics(),...n}),recordSettle:r}}function Ll(e){let{operations:t,snapshots:n,readMetrics:r,recordSettle:i}=Il(e);return Zs(t,{beforeExecute:async({context:e,requiresSettledPredecessor:t})=>{if(t){let t=await n.settlePending(e);t&&i(t)}},afterExecute:({context:e,visualStabilityReached:t})=>{t&&n.consumeStabilityFromVisualWait(e)},bindObservation:n.bindObservation,readMetrics:r})}function Rl(e){let{appendTraceEvent:t,filePath:n,tracePath:r,onStep:i}=e,a=new Map;return{actionStarted:e=>{a.set(e.stepIndex,e),zl(()=>Hl(i,e)),zl(()=>Ul(t,r,n,e))},actionCompleted:e=>{let i=Bl(a,e.stepIndex);zl(()=>Wl(t,r,n,Vl(i,e),!0))},actionFailed:e=>{let i=Bl(a,e.stepIndex);zl(()=>Wl(t,r,n,Vl(i,e),!1))}}}function zl(e){try{e()}catch{}}function Bl(e,t){let n=e.get(t);return e.delete(t),n}function Vl(e,t){return u({...e??t,durationMs:t.durationMs,runtimeMetrics:t.runtimeMetrics,data:`data`in t?t.data:void 0,error:`error`in t?t.error:void 0})}function Hl(e,t){e?.({index:t.stepIndex,total:t.stepTotal,command:t.action,...t.value?{value:t.value}:{}})}function Ul(e,t,n,r){e(t,{type:`replay_action_start`,ts:new Date().toISOString(),replayPath:n,...r.source.path&&r.source.path!==n?{sourcePath:r.source.path}:{},line:r.source.line,step:r.stepIndex,command:r.action,positionals:r.value?[r.value]:[]})}function Wl(e,t,n,r,a){let o=Gl(r);e(t,{type:`replay_action_stop`,ts:new Date().toISOString(),replayPath:n,...r.source.path&&r.source.path!==n?{sourcePath:r.source.path}:{},line:r.source.line,step:r.stepIndex,command:r.action,ok:a,durationMs:r.durationMs,...Object.keys(o).length>0?{resultTiming:o}:{},...!a&&`error`in r&&r.error instanceof i?{errorCode:r.error.code}:{}})}function Gl(e){let t=`data`in e?e.data:void 0,n=Kl(t?.timing)?t.timing:void 0;return u({...e.runtimeMetrics??{},...typeof n?.executionProfile==`string`?{executionProfile:n.executionProfile}:{},...typeof n?.gestureDurationMs==`number`?{gestureDurationMs:n.gestureDurationMs}:{}})}function Kl(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function ql(e,t){let n=u({...e.dispatch,...Jl(t.dispatch)});return u({...e,command:t.command,positionals:t.positionals,input:t.input,flags:t.flags,dispatch:Object.keys(n).length>0?n:void 0})}function Jl(e){return u({closeAppOnly:e?.closeAppOnly,killApp:e?.killApp,observationOnly:e?.observationOnly,gestureViewport:e?.gestureViewport,gestureExecutionProfile:e?.gestureExecutionProfile,settingsAppBundleId:e?.settingsAppBundleId})}function Yl(e,t){let n={command:e.action,...e.value?{value:e.value}:{}};return{command:{kind:e.action},source:e.source,progress:n,action:{command:Ql(e.action),positionals:$l(e.action,e.value),flags:t.flags??{}}}}async function Xl(e,t){let{failure:n,req:r}=t,i=Yl(n,r);return await e.buildActionFailureResponse({error:t.error,req:r,sessionStore:t.sessionStore,observationStore:t.observationStore,logPath:t.logPath,replayPath:t.replayPath,stepIndex:n.stepIndex,source:n.source,action:n.action,actionLabel:[n.action,Zl(n.value)].filter(Boolean).join(` `),captureAction:i.action,isControl:n.isControl,redactions:n.redactions,resume:n.resume,artifactPaths:n.artifactPaths,warnings:n.warnings,snapshotDiagnostics:t.snapshotDiagnostics,suggestNodes:e=>Ka(n,e)})}function Zl(e){return!e||e===`<text>`?e??``:h(e)}function Ql(e){return e===`tapOn`||e===`doubleTapOn`?`click`:e===`longPressOn`?`longpress`:e===`assertVisible`||e===`assertNotVisible`||e===`extendedWaitUntil`||e===`scrollUntilVisible`?`wait`:e}function $l(e,t){return!t||e===`inputText`?[]:[t]}function eu(e){let{command:t,outcome:n,startedAt:r,snapshotStart:i}=e,{session:{name:a,store:o}}=t,s=nu(o,i),c=n.replayed;return{ok:!0,data:{replayed:c,healed:0,session:a,sessionActive:o.get()!==void 0,artifactPaths:n.artifactPaths,...n.warnings?{warnings:n.warnings}:{},...s?{snapshotDiagnostics:s}:{},message:ru(c,Date.now()-r)}}}async function tu(e,t){let{command:n,replayPath:r,state:i,outcome:a}=t,{request:o,session:{store:s,observationStore:l,logPath:u}}=n,{failure:d}=a,f=c(a.error);return d?await Xl(e,{error:f,failure:d,replayPath:r,req:o,sessionStore:s,observationStore:l,logPath:u,snapshotDiagnostics:nu(s,i.snapshotStart)}):{ok:!1,error:f}}function nu(e,t){let n=e.get()?.snapshotDiagnostics?.samples.slice(t)??[];return f(n)}function ru(e,t){return`Replayed ${e} ${e===1?`step`:`steps`} in ${(t/1e3).toFixed(1)}s`}async function iu(e,t){let{request:n}=t,r=n.flags?.replayScriptSource;if(!r)return s(`INVALID_ARGS`,e.scriptSourceRequiredMessage);if(n.flags?.saveScript!==void 0)return s(`INVALID_ARGS`,`Maestro YAML does not support --save-script; ADR 0012 repair recording applies only to .ad scripts.`);let i=Date.now(),a={snapshotStart:0};try{return await au({host:e,command:t,bundle:r,startedAt:i,state:a})}catch(n){return await tu(e,{command:t,replayPath:r.entry,state:a,outcome:{ok:!1,error:n}})}}async function au(e){let{host:t,command:n,bundle:r,startedAt:i,state:a}=e,{request:o,session:{store:s},tracePath:c,onStep:l}=n,u=await ou({host:t,command:n,bundle:r}),d=n.publicNetworkOnly===!0,f=pu({command:n,device:u.device,platform:u.platform,runtimeHints:u.runtimeHints,sourcePath:u.filePath,publicNetworkOnly:d});a.snapshotStart=s.get()?.snapshotDiagnostics?.samples.length??0;let p=await Ga(u.flow,f,{defaults:u.defaults,env:u.env,platform:u.platform,target:u.target,runtimeHints:u.runtimeHints,signal:u.signal,from:o.flags?.replayFrom,planDigest:o.flags?.replayPlanDigest,trustedScripts:!d,readSource:e=>t.readScriptSourceFile(r,e),observer:Rl({appendTraceEvent:t.appendTraceEvent,filePath:u.filePath,tracePath:c,onStep:l})});return p.ok?eu({outcome:p,command:n,startedAt:i,snapshotStart:a.snapshotStart}):await tu(t,{command:n,replayPath:r.entry,state:a,outcome:p})}async function ou(e){let{host:t,command:n,bundle:r}=e,{request:i,session:{name:a,store:o}}=n,s=r.entry,c=Wa(t.readScriptSourceFile(r,s),s),l=o.lookup(),u=l?.session;l&&o.assertSelectorMatches(i.flags);let d=await su({host:t,req:i,env:n.host.env,sessionStore:o,sessionName:a,session:u,flow:c});return{filePath:s,flow:c,...d,defaults:du({host:t,req:i,sessionName:a,filePath:s,hostCwd:n.host.cwd,platform:d.platform,target:d.target}),env:fu(i,n.host.env),signal:t.requestSignal(i.meta?.requestId)}}async function su(e){let{host:t,req:n,env:r,sessionStore:i,sessionName:a,session:o,flow:s}=e,c=n.flags?.platform,l=o?.device??(c===`android`||c===`ios`?void 0:await t.resolveTargetDevice(n.flags??{},{appTarget:s.appTarget,platform:c},r)),u=vu(n,l),d=lu({req:n,sessionStore:i,sessionName:a,device:l,platform:u});return await cu({host:t,req:n,env:r,sessionStore:i,sessionName:a,device:l,platform:u,target:yu(n,l),runtimeHints:d,flow:s})}async function cu(e){if(e.device||!uu(e.runtimeHints))return e;let t=await e.host.resolveTargetDevice(e.req.flags??{},{appTarget:e.flow.appTarget,platform:e.platform},e.env);return{device:t,platform:e.platform,target:yu(e.req,t),runtimeHints:lu({req:e.req,sessionStore:e.sessionStore,sessionName:e.sessionName,device:t,platform:e.platform})}}function lu(e){return e.sessionStore.resolveOpenRuntimeHints({request:e.req,device:e.device,platform:e.platform})}function uu(e){return e?.metroPort!==void 0&&e.metroHost===void 0&&e.bundleUrl===void 0}function du(e){return{...e.host.buildBuiltinVars({req:e.req,sessionName:e.sessionName,resolvedPath:e.filePath,hostCwd:e.hostCwd}),AD_PLATFORM:e.platform,AD_TARGET:e.target}}function fu(e,t){return{...se(oe(e.flags?.replayShellEnv,t)),...ae(ie(e.flags?.replayEnv))}}function pu(e){let{command:t,device:n,platform:r,runtimeHints:i,sourcePath:a,publicNetworkOnly:o}=e,{request:s,invoke:c}=t,l={...s,runtime:i,...t.dispatch?{dispatch:t.dispatch}:{}};return Ll({invoke:e=>c(ql(l,e)),flags:mu(n,r,s.flags,o),publicNetworkOnly:o,platform:r,sourcePath:a,dependencies:{now:Date.now,sleep:async(e,t)=>{await ve(e,void 0,{signal:t})}}})}function mu(e,t,n,r){if(!e)return hu(t,n);let i={platform:t,target:e.target,noRecord:!0,...n?.testIme===void 0?{}:{testIme:n.testIme}};return t===`android`?{...i,serial:e.id}:{...i,udid:e.id,...!r&&e.simulatorSetPath?{iosSimulatorDeviceSet:e.simulatorSetPath}:{}}}function hu(e,t){let n={platform:e,target:t?.target??`mobile`,noRecord:!0,...t?.testIme===void 0?{}:{testIme:t.testIme}};return t?.device&&(n.device=t.device),e===`android`?gu(n,t):_u(n,t)}function gu(e,t){return t?.serial&&(e.serial=t.serial),t?.androidDeviceAllowlist&&(e.androidDeviceAllowlist=t.androidDeviceAllowlist),e}function _u(e,t){return t?.udid&&(e.udid=t.udid),t?.iosSimulatorDeviceSet&&(e.iosSimulatorDeviceSet=t.iosSimulatorDeviceSet),e}function vu(e,t){let n=e.flags?.platform;if(n===`android`||n===`ios`)return n;if(t?.platform===`android`)return`android`;if(t?.platform===`apple`&&t.appleOs===`ios`)return`ios`;throw new i(`INVALID_ARGS`,`Maestro replay requires --platform android|ios or an active mobile session.`)}function yu(e,t){return typeof e.flags?.target==`string`?e.flags.target:t?.target??`mobile`}function bu(e){return{id:`maestro`,collectSourceFiles(e){return $a(e)},inspectSource(e,t){let n=Wa(e,t);return{title:n.name,appTarget:n.appTarget}},async runReplay(t){return await iu(e,t)},exportReplayScript(e,t){return fo(e,{...t,resolveSelector:e=>b(e,Pr)})}}}const xu={create:bu};export{xu as maestroReplayBackendPlugin};
|