agent-device 0.21.29 → 0.21.30
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.29.apk → agent-device-android-ime-helper-0.21.30.apk} +0 -0
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.30.apk.sha256 +1 -0
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.29.manifest.json → agent-device-android-ime-helper-0.21.30.manifest.json} +4 -4
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.30.apk +0 -0
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.30.apk.sha256 +1 -0
- package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.29.manifest.json → agent-device-android-snapshot-helper-0.21.30.manifest.json} +7 -7
- package/apple/macos-helper/Sources/AgentDeviceMacOSHelper/AudioProbe.swift +4 -2
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandDispatch.swift +2 -1
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +12 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +25 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +8 -1
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +9 -6
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +3 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift +35 -9
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SystemModal.swift +44 -26
- package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotModels.swift +20 -1
- package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotPresentation.swift +4 -3
- package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotPresentationProjection.swift +4 -2
- package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotVisibilityFold.swift +20 -2
- package/dist/src/adapter.js +1 -1
- package/dist/src/agent-browser-lifecycle.js +1 -1
- package/dist/src/agent-browser-process-record.js +1 -1
- package/dist/src/agent-browser-provider.js +1 -1
- package/dist/src/agent-device-client.js +1 -1
- package/dist/src/alert2.js +1 -1
- package/dist/src/android.js +1 -1
- package/dist/src/app-lifecycle.js +1 -1
- package/dist/src/app-log-runtime2.js +3 -3
- package/dist/src/auth.js +1 -1
- package/dist/src/automation-helper.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 +13 -10
- package/dist/src/cli.js +3 -3
- package/dist/src/client-types.d.ts +82 -13
- package/dist/src/cloud-artifacts.d.ts +99 -3
- package/dist/src/command-metadata.js +42 -42
- package/dist/src/composed-inventory-gateways.js +1 -1
- package/dist/src/connection-runtime.js +1 -1
- package/dist/src/connection.js +1 -1
- package/dist/src/contract.d.ts +2 -2
- package/dist/src/contracts.d.ts +1 -1
- package/dist/src/daemon-client-ensure.js +1 -1
- package/dist/src/daemon-client-ensuring.js +1 -1
- package/dist/src/daemon-client-lease-beat.js +1 -1
- package/dist/src/daemon-client-lifecycle.js +1 -1
- package/dist/src/daemon-client.js +2 -2
- package/dist/src/daemon-lifecycle-errors.js +1 -1
- package/dist/src/daemon-registration-owner.js +3 -3
- package/dist/src/daemon-registration.js +1 -1
- package/dist/src/daemon-resolution.js +1 -1
- package/dist/src/daemon-shutdown-report.js +1 -1
- package/dist/src/daemon-startup-diagnostics.js +1 -1
- package/dist/src/daemon.js +3 -3
- package/dist/src/device-claim-recovery.js +1 -1
- package/dist/src/durable-capture-resource.js +1 -1
- package/dist/src/durable-resource.js +1 -1
- package/dist/src/ended-lease.js +1 -1
- package/dist/src/find.js +1 -1
- package/dist/src/finders.js +1 -1
- package/dist/src/gesture-plan-types.d.ts +14 -4
- package/dist/src/gesture-plan.js +1 -1
- package/dist/src/gesture-runtime.js +1 -1
- package/dist/src/host4.js +1 -1
- package/dist/src/index.d.ts +3 -3
- package/dist/src/input-actions.js +1 -1
- package/dist/src/input-actions2.js +1 -1
- package/dist/src/interaction-positionals.js +1 -1
- package/dist/src/interaction.js +1 -1
- package/dist/src/interaction2.js +1 -1
- package/dist/src/interactor-operation-catalog.js +1 -1
- package/dist/src/interactor.js +5 -5
- package/dist/src/interactor3.js +1 -1
- package/dist/src/interactor4.js +1 -1
- package/dist/src/internal/bin.js +1 -1
- package/dist/src/internal/daemon.js +1 -1
- package/dist/src/internal/png-worker.js +1 -1
- package/dist/src/inventory6.js +1 -1
- package/dist/src/ios-node-interpretation.js +1 -1
- package/dist/src/ios-snapshot-acquisition.js +1 -1
- package/dist/src/ios-snapshot-engine.js +1 -1
- package/dist/src/ios-snapshot-runtime.js +1 -1
- package/dist/src/keyboard-occlusion.js +1 -1
- 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/local-interactor-operation-set.js +1 -1
- package/dist/src/mechanics.js +12 -12
- package/dist/src/metro-session-hints.js +1 -1
- package/dist/src/mobile-snapshot-semantics.js +1 -1
- package/dist/src/observability.js +1 -1
- package/dist/src/observation.js +1 -1
- package/dist/src/parameterized-recorded-fill.js +1 -1
- package/dist/src/perf-facade.js +1 -1
- package/dist/src/platform-runtime-operation-host.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/plugins2.js +1 -1
- package/dist/src/png-resize.js +1 -1
- package/dist/src/png-worker-client.js +1 -1
- package/dist/src/png-worker-contract.js +1 -1
- package/dist/src/provider-device-runtime.d.ts +20 -1
- package/dist/src/provider-plugin.d.ts +1 -1
- package/dist/src/react-native-overlay2.js +1 -1
- package/dist/src/record-runtime.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 +1 -1
- package/dist/src/runner-error-classification.js +1 -1
- package/dist/src/runtime-admission.js +1 -1
- package/dist/src/runtime-deployment.js +1 -1
- package/dist/src/runtime-factory.js +1 -1
- package/dist/src/runtime-session.js +1 -1
- package/dist/src/runtime.js +5 -5
- package/dist/src/runtime10.js +2 -2
- package/dist/src/runtime3.js +5 -5
- 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 +2 -2
- package/dist/src/screenshot-image-size.js +1 -0
- package/dist/src/screenshot-image.js +1 -1
- package/dist/src/screenshot-runtime.js +1 -1
- package/dist/src/screenshot3.js +2 -2
- package/dist/src/sdk-batch.js +1 -1
- package/dist/src/sdk-contracts.d.ts +7 -1
- package/dist/src/sdk-finders.js +1 -1
- package/dist/src/sdk-selectors.d.ts +1 -1
- package/dist/src/sdk-selectors.js +1 -1
- package/dist/src/selection.js +0 -0
- package/dist/src/selector-pipeline-policy.js +1 -1
- package/dist/src/selector-runtime.js +1 -1
- package/dist/src/selectors.js +1 -1
- package/dist/src/server-startup.js +1 -1
- package/dist/src/session-replay-vars.js +1 -1
- package/dist/src/session-store.js +2 -2
- package/dist/src/session.js +1 -1
- package/dist/src/session2.js +5 -5
- package/dist/src/settle-observation-capture.js +1 -1
- package/dist/src/snapshot-capture-annotations.js +1 -1
- package/dist/src/snapshot-chrome.js +1 -1
- package/dist/src/snapshot-desktop-projection.js +1 -1
- package/dist/src/snapshot-helper-install.js +7 -5
- package/dist/src/snapshot-node-lookup.js +1 -1
- package/dist/src/snapshot-occlusion.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-state.js +1 -1
- package/dist/src/snapshot.js +1 -1
- package/dist/src/src.js +1 -1
- package/dist/src/src3.js +1 -1
- package/dist/src/src4.js +1 -1
- package/dist/src/tap-keyboard-occlusion.js +1 -1
- package/dist/src/target-evidence-tree.js +1 -1
- package/dist/src/target-evidence.js +1 -1
- package/dist/src/telephony-runtime.js +1 -1
- package/dist/src/text-entry-focus.js +1 -1
- package/dist/src/touch-reference-frame.js +1 -1
- package/dist/src/touch-runtime2.js +1 -1
- package/dist/src/tree.js +1 -1
- package/dist/src/tv-remote-runtime.js +1 -1
- package/dist/src/tv-remote.js +2 -2
- package/dist/src/type-text-runtime.js +1 -1
- package/dist/src/video.js +1 -1
- package/dist/src/webdriver-source.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.29.apk.sha256 +0 -1
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.29.apk +0 -0
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.29.apk.sha256 +0 -1
- package/dist/src/daemon-client-lifecycle-request.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{i as e,t}from"./rolldown-runtime.js";import{B as n,R as r,V as i,Z as a,et as o,s,y as c}from"./sdk-contracts.js";import{
|
|
1
|
+
import{i as e,t}from"./rolldown-runtime.js";import{B as n,R as r,V as i,Z as a,et as o,s,y as c}from"./sdk-contracts.js";import{st as l}from"./tv-remote.js";import{i as u,j as d}from"./sdk-batch-runner.js";import{a as f}from"./snapshot-diagnostics.js";import{i as p,r as m}from"./snapshot-private-evidence.js";import{K as h}from"./back-mode.js";import{ht as g,nt as _,vt as v}from"./sdk-io.js";import"./diagnostics.js";import{Ir as y,Nr as b,Pr as x,Qr as S,Wr as C,fr as w,hn as T,ii as E,ni as ee,si as te,vn as ne}from"./sdk-batch.js";import{a as re,i as ie,o as ae,r as oe}from"./vars.js";import{t as se}from"./interaction-error.js";import"./command.js";import{i as ce}from"./rect-center.js";import"./gesture-plan.js";import{t as le}from"./touch-reference-frame.js";import{t as ue}from"./png-worker-client.js";import{a as de}from"./ios-snapshot-engine.js";import{createHash as fe}from"node:crypto";import pe,{promises as me}from"node:fs";import he from"node:os";import D from"node:path";import{fileURLToPath as ge}from"node:url";import{setTimeout as _e}from"node:timers/promises";import ve from"node:vm";function O(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function ye(e){return e.trim().toLowerCase().replaceAll(/\s+/g,` `)}function be(e){return[e.label,e.value,e.identifier].find(e=>typeof e==`string`&&e.length>0)?.trim()??``}function xe(e){let t={version:2,platform:e.platform??null,target:e.target??null,runtimeHints:e.runtimeHints??null,initialStaticEnv:e.initialStaticEnv,steps:e.steps};return fe(`sha256`).update(w(t),`utf8`).digest(`hex`)}function Se(e={},t={}){let n={...t},i=Ce(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 r(`COMMAND_FAILED`,`Maestro environment scopes were left out of order.`);o=void 0}},merge(e){i={...i,...e},o=void 0},replaceOutput(e){let t={};for(let[e,n]of Object.entries(i))e===`output`||e.startsWith(`output.`)||(t[e]=n);Object.assign(t,e),i=t,o=void 0},recordObservation(e){if(e.generation!==s)throw new r(`COMMAND_FAILED`,`Maestro observation generation ${e.generation} does not match ${s}.`);c=e},invalidateObservation(){s+=1,c=void 0},resolve(e){return we(e,l())},resolveDeferred(e){return we(e,l(),new Set,!1)}};function l(){return o||(o={...a.reduce((e,t)=>({...e,...t}),{...i}),...n},o)}function u(e){let t=Ce(e),r={};for(let[e,i]of Object.entries(t))r[e]=we(i,{...l(),...t,...r,...n},new Set,!1);return r}}function Ce(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,String(t)]))}function we(e,t,n=new Set,i=!0){let a=e.replaceAll(/\$\{([A-Za-z_][A-Za-z0-9_.]*)\}/g,(e,a)=>{if(!Object.hasOwn(t,a)){if(!i)return e;throw new r(`INVALID_ARGS`,`Maestro variable "${a}" is not defined.`)}if(n.has(a)){if(!i)return e;throw new r(`INVALID_ARGS`,`Maestro variable "${a}" has a cyclic reference.`)}return we(t[a],t,new Set([...n,a]),i)});return i&&Te(a),a}function Te(e){for(let t of e.matchAll(/\$\{[^{}]*\}/g))if(!Ee(t[0]))throw new r(`INVALID_ARGS`,`Maestro interpolation "${t[0]}" is unresolved or unsupported.`)}function Ee(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})),De=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})),Oe=t((e=>{var t=k(),n=De();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})),ke=t((e=>{var t=k(),n=De();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})),Ae=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})),je=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})),Me=t((e=>{var t=Ae(),n=k(),r=je();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}}})),Ne=t((e=>{var t=ke(),n=De(),r=k(),i=Me(),a=je(),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=Me(),r=je();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})),Pe=t((e=>{var t=Ne(),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})),Fe=t((e=>{var t=Pe(),n=k(),r=Me();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})),Ie=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())}}}})),Vt=t((e=>{var t=Nt(),n=gt(),r=_t(),i=Ve(),a=k(),o=zt(),s=Bt();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=Nt(),n=gt(),r=mt(),i=_t(),a=Ne(),o=k(),s=We(),c=A(),l=Ke(),u=Je();Lt();var d=Rt(),f=zt(),p=Bt(),m=Vt(),h=De();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 Ht(e?.range?.[0],t)}function Ht(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 Ut(e){return`${e.path===void 0?``:`${e.path}:`}line ${e.line}`}function N(e,t,n){throw new r(`INVALID_ARGS`,`${e} (${Ut(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 Wt(e,t,n){return(0,j.isSeq)(e)||N(`Maestro ${t} expects a list.`,e,n),e.items}function Gt(e,t,n){return Wt(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=>qt(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 Kt(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 qt(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 Jt=/^\$\{[A-Za-z_][A-Za-z0-9_.]*\}$/,Yt=new Set([`allow`,`deny`,`unset`,`always`,`inuse`,`never`,`limited`]),Xt=/^-?\d+(\.\d+)?$/,Zt=/^-?\d+$/,Qt={"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 $t(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 en(e,t,n,r,i){let a=`Maestro ${t} expects ${$t(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 tn(e,t,n,r,i){if(typeof e==`number`)return en(e,t,n,r,i),e;if(typeof e==`string`){if(Jt.test(e))return e;if((i.integer?Zt:Xt).test(e)){let a=Number(e);return en(a,t,n,r,i),a}}N(`Maestro ${t} expects ${$t(i)} or a variable expression.`,n,r)}function U(e,t,n,r=Qt[t]??{}){let i=V(e,t,n);if(i!==null)return tn(i,t,e,n,r)}function nn(e,t,n){let r=Qt[t]??{},i=V(e,t,n);return i===null&&N(`Maestro ${t} expects ${$t(r)} or a variable expression.`,e,n),tn(i,t,e,n,r)}function rn(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("${")&&!Jt.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 an(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 on(e,t){try{return new hn(cn(sn(e)),t).parse()}catch(e){if(e instanceof r&&e.code===`INVALID_ARGS`)return;throw e}}function sn(e){let t=e.trim();return t.startsWith("${")&&t.endsWith(`}`)?t.slice(2,-1).trim():t}function cn(e){let t=[],n=0;for(;n<e.length;){let i=e.slice(n),a=/^\s+/.exec(i)?.[0].length??0;if(a>0){n+=a;continue}let o=ln(i);if(!o)throw new r(`INVALID_ARGS`,`Unsupported runFlow.when.true expression near "${i.slice(0,24)}".`);t.push(o.value),n+=o.length}return t}function ln(e){return un(e)??dn(e)??fn(e)??pn(e)??mn(e)}function un(e){return e.startsWith(`maestro.platform`)?{value:{type:`platform`},length:16}:null}function dn(e){let t=/^(==|!=|&&|\|\|)/.exec(e)?.[1];return t?{value:{type:`operator`,value:t},length:t.length}:null}function fn(e){let t=e[0];return t===`(`||t===`)`?{value:{type:`paren`,value:t},length:1}:null}function pn(e){let t=/^(['"])(.*?)\1/.exec(e);return t?{value:{type:`string`,value:t[2]??``},length:t[0].length}:null}function mn(e){let t=/^(true|false)\b/.exec(e)?.[1];return t?{value:{type:`boolean`,value:t===`true`},length:t.length}:null}var hn=class{index=0;tokens;platform;constructor(e,t){this.tokens=e,this.platform=t}parse(){let e=this.parseOr();if(this.peek())throw new r(`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 r(`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 r(`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 r(`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 r(`INVALID_ARGS`,`runFlow.when.true comparison requires == or !=.`);return this.index+=1,e}consumeStringLiteral(){let e=this.peek();if(e?.type!==`string`)throw new r(`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 gn=new Set([``,`false`,`0`,`null`,`undefined`]);function _n(e){return typeof e==`boolean`?e:typeof e==`number`?e!==0&&!Number.isNaN(e):!gn.has(e)}function vn(e){return typeof e==`boolean`||typeof e==`number`||typeof e==`string`?_n(e):typeof e==`bigint`?e!==0n:e!=null}function yn(e){switch(e.kind){case`runFlow`:return!(`include`in e);case`repeat`:case`retry`:return!(`commands`in e);default:return!1}}function bn(e,t){return{...jn(e,t),source:e.source}}function W(e,t,n){if(e===void 0)return;let i=n??Qt[t]??{},a=$t(i),o;if(typeof e==`number`)o=e;else{let n=e.trim();if(n===``)throw new r(`INVALID_ARGS`,`Maestro ${t} must be ${a}.`);o=Number(n)}if(!Number.isFinite(o)||Math.abs(o)>2**53-1||i.integer&&!Number.isSafeInteger(o)||i.nonNegative&&o<0||i.positive&&o<=0)throw new r(`INVALID_ARGS`,`Maestro ${t} must be ${a}.`);return o}function xn(e,t,n,r){return W(e===void 0?t:n.resolve(String(e)),r)}function G(e){if(e?.aborted)throw i()}async function Sn(e,t){if(e.include.kind===`commands`)return{kind:`program`,source:e.source,config:{},commands:e.include.commands};if(!t.loadProgram)throw new r(`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 Cn(e,t,n){if(e.include.kind===`file`)return D.resolve(t?D.dirname(t):n,e.include.path)}function wn(e){return e===void 0?void 0:D.resolve(e)}function Tn(e,t,n){let i=Cn(e,e.source.path,n);if(i&&t.has(i))throw new r(`INVALID_ARGS`,`Maestro runFlow cycle detected at ${i}.`);return i}function En(e,t,n,i){let a=e.include.kind===`file`?wn(t.source.path):void 0,o=new Set([n,a].filter(e=>e!==void 0)),s=[...o].find(e=>i.has(e));if(s)throw new r(`INVALID_ARGS`,`Maestro runFlow cycle detected at ${s}.`);return o.forEach(e=>i.add(e)),o}function Dn(e,t){if(e.trustedScripts===!1)throw new r(`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 On(e,t,n,r){if(e===void 0)return!0;if(typeof e==`boolean`)return e;let i=kn(e,n);if(i!==void 0){let e=on(i,r.platform);if(e!==void 0)return e;if(!i.includes("${"))return _n(i)}Dn(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),vn(o.value)}function kn(e,t){try{return t.resolve(e)}catch(e){if(e instanceof r&&e.code===`INVALID_ARGS`)return;throw e}}function An(e,t){return[...e.visible?[{kind:`visible`,selector:jn(e.visible,t)}]:[],...e.notVisible?[{kind:`notVisible`,selector:jn(e.notVisible,t)}]:[]]}function jn(e,t){return typeof e==`string`?t.resolve(e):Array.isArray(e)?e.map(e=>jn(e,t)):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,jn(n,t)])):e}async function Mn(e,t){G(t.signal);let n=wn(e.source.path),r={options:t,context:Se(t.defaults,t.env),activeIncludePaths:new Set(n===void 0?[]:[n]),staticallyExecutedControls:0,staticallySkippedControls:0};return{steps:await Nn(e,[],void 0,e.source.path,r),staticallyExecutedControls:r.staticallyExecutedControls,staticallySkippedControls:r.staticallySkippedControls}}async function Nn(e,t,n,r,i){G(i.options.signal);let a=Wn(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 Fn(s,a,o,e.source.path??r,i));return n}finally{s()}}async function Pn(e,t,n,r,i){let a=[];for(let o of e)a.push(...await Fn(o,t,n,r,i));return a}async function Fn(e,t,n,r,i){G(i.options.signal);let a=Gn(e,r);switch(a.kind){case`runFlow`:{let e=Ln(a,i);if(e===`omit`)return i.staticallySkippedControls+=1,[];let o=await In(a,t,n,r,i);return e===`flatten`?(i.staticallyExecutedControls+=1,o):[Hn(a,t,n,o)]}case`repeat`:return[Hn(a,t,n,await Pn(a.commands,t,n,r,i))];case`retry`:return[Hn(a,t,n,await Pn(a.commands,t,n,r,i))];default:return[Vn(a,t,n)]}}async function In(e,t,n,r,i){let a=zn(e,i.context),o=Tn(a,i.activeIncludePaths,i.options.baseDir),s=await Sn(a,i.options);G(i.options.signal);let c=En(a,s,o,i.activeIncludePaths),l=Wn(t,e.env),u=i.context.enter(e.env);try{return await Nn(s,l,n,s.source.path??e.source.path??r,i)}finally{u(),c.forEach(e=>i.activeIncludePaths.delete(e))}}function Ln(e,t){let n=e.when;return n?n.platform!==void 0&&n.platform!==t.options.platform?`omit`:Rn(n.true,t)||(n.visible||n.notVisible?`opaque`:`flatten`):`flatten`}function Rn(e,t){if(e===!1)return`omit`;if(typeof e!=`string`)return;let n=t.context.resolveDeferred(e);if(Bn(n))return`opaque`;let r=on(n,t.options.platform);return r===void 0?`opaque`:r?void 0:`omit`}function zn(e,t){return e.include.kind===`file`?{...e,include:{...e.include,path:t.resolve(e.include.path)}}:e}function Bn(e){return/\$\{[A-Za-z_][A-Za-z0-9_.]*\}/.test(e)}function Vn(e,t,n){return O({kind:`command`,command:e,source:e.source,scopes:t,appId:n})}function Hn(e,t,n,r){return O({kind:`opaque`,command:Un(e),source:e.source,scopes:t,body:r,appId:n})}function Un(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 Wn(e,t){return t===void 0?e:[...e,t]}function Gn(e,t){return e.source.path||!t?e:{...e,source:{...e.source,path:t}}}async function Kn(e,t){let{steps:n,staticallyExecutedControls:r,staticallySkippedControls:i}=await Mn(e,t),a=qn(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=xe(o);return Jn({...o,digest:s})}function qn(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 Jn(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;for(let t of Object.values(e))Jn(t);return Object.freeze(e)}function Yn(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 Xn(e,t={}){let n=Yn(e,t);if(!n.allowed)throw new r(`INVALID_ARGS`,n.reason);return n.startIndex}function Zn(e,t){if(!Number.isInteger(t)||t<0||t>e.total)throw new r(`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 Qn(e){return Math.trunc(1e3*(100-e)/100)+1}const $n={assertVisibleTimeoutMs:K.command.targetLookupTimeoutMs,assertNotVisibleTimeoutMs:K.command.targetLookupTimeoutMs,extendedWaitUntilTimeoutMs:K.command.targetLookupTimeoutMs,runFlowConditionTimeoutMs:K.command.optionalTargetLookupTimeoutMs},er=K.observation.pollIntervalMs*K.observation.defaultSettleAttempts,tr=`maestro-test-failure`;function nr(e,t={}){return new r(`COMMAND_FAILED`,e,{...t,reason:tr})}function rr(e){return e instanceof r&&e.code===`COMMAND_FAILED`&&e.details?.reason===tr}async function ir(e,t){G(t.options.signal);try{return await br(e,t.context,async()=>await ar(e,t))}catch(t){throw xr(t,e)}}async function ar(e,t){if(e.kind===`command`)return await or(e.command,e.appId,t);await fr(e,t)}async function or(e,t,n){if(e.kind===`evalScript`)return await lr(e,n);let r=bn(e,n.context);try{return await ur(r,t,n)}catch(e){if(G(n.options.signal),cr(r)&&rr(e)){n.warnings.push(sr(r,e)),n.skipped+=1;return}throw Sr(e,r)}}function sr(e,t){let n=`${e.source.path?`${e.source.path}:`:``}line ${e.source.line}`,i=t instanceof r?t.message:String(t);return`Optional Maestro ${e.kind} skipped at ${n}: ${i}`}function cr(e){return`optional`in e&&e.optional===!0}async function lr(e,t){let{evaluateMaestroEvalScript:n}=await import(`./engine-eval-script.js`);Dn(t.options,`evalScript`);let r=await n(e.script,t.context.values);t.context.replaceOutput(r),t.executed+=1}async function ur(e,t,n){switch(e.kind){case`assertVisible`:await _r({kind:`visible`,selector:e.target},n.timing.assertVisibleTimeoutMs,n),n.executed+=1;return;case`assertNotVisible`:await _r({kind:`notVisible`,selector:e.target},n.timing.assertNotVisibleTimeoutMs,n),n.executed+=1;return;case`assertTrue`:if(!_n(e.condition))throw nr(`Maestro assertTrue condition was falsy: ${JSON.stringify(e.condition)}`);n.executed+=1;return;case`extendedWaitUntil`:await _r(yr(e),W(e.timeout,`extendedWaitUntil.timeout`)??n.timing.extendedWaitUntilTimeoutMs,n),n.executed+=1;return;default:return await dr(e,t,n)}}async function dr(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 fr(e,t){let n=e.command;switch(n.kind){case`runFlow`:if(n.when&&!await gr(n.when,`runFlow.when`,t)){t.skipped+=1;return}t.executed+=1,await pr(e.body,t);return;case`repeat`:t.executed+=1,await mr(e.body,n.times,n.while,t);return;case`retry`:{let r=Math.min(xn(n.maxRetries,1,t.context,`retry.maxRetries`),K.control.retryMaxRetries);t.executed+=1,await hr(e.body,r,t);return}}}async function pr(e,t){for(let n of e)await ir(n,t)}async function mr(e,t,n,r){let i=t===void 0&&n?1/0:xn(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 gr(n,`repeat.while`,r))return;await pr(e,r)}}async function hr(e,t,n){let i;for(let r=0;r<=t;r+=1){G(n.options.signal);try{await pr(e,n);return}catch(t){if(G(n.options.signal),!rr(wr(t)))throw t;i=xr(t,e[0])}}throw i||new r(`COMMAND_FAILED`,`Maestro retry commands failed.`)}async function gr(e,t,n){if(e.platform&&e.platform!==n.options.platform||!await On(e.true,`${t}.true`,n.context,n.options))return!1;for(let t of An(e,n.context))if(G(n.options.signal),!(await vr(t,n.timing.runFlowConditionTimeoutMs,n)).matched)return!1;return!0}async function _r(e,t,n){if(!(await vr(e,t,n)).matched)throw nr(`Maestro ${e.kind} condition did not match.`)}async function vr(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 yr(e){if(e.visible)return{kind:`visible`,selector:e.visible};if(e.notVisible)return{kind:`notVisible`,selector:e.notVisible};throw new r(`INVALID_ARGS`,`Maestro extendedWaitUntil requires one condition.`)}async function br(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 xr(e,t){if(Cr(e))return e;let n=t?.source??{line:1};return{kind:`maestroPlanStepFailure`,error:Tr(e,t?.command),source:n,...t?{command:t.command}:{}}}function Sr(e,t){return{kind:`maestroPlanStepFailure`,error:Tr(e,t),source:t.source,command:t}}function Cr(e){return!!(e&&typeof e==`object`&&e.kind===`maestroPlanStepFailure`)}function wr(e){return Cr(e)?e.error:e}function Tr(e,t){if(!(e instanceof r)||!t||/\bline \d+\b/.test(e.message))return e;let n=t.source.path?`${t.source.path}:`:``;return new r(e.code,`${e.message} (${n}line ${t.source.line})`,e.details)}async function Er(e,t,n={}){G(n.signal);let i=n.startIndex??0;if(!Number.isInteger(i)||i<0||i>e.total)throw new r(`INVALID_ARGS`,`Maestro replay startIndex ${i} is out of range for a ${e.total}-step plan.`);let a={plan:e,port:t,options:n,context:Se(n.defaults,n.env?{...n.env}:{}),timing:$n,artifacts:new Set,warnings:[],executed:e.compatibility.staticallyExecutedControls,skipped:e.compatibility.staticallySkippedControls};for(let t=i;t<e.steps.length;t+=1)try{await Dr(e.steps[t],t,a)}catch(e){throw wr(e)}return{executed:a.executed,skipped:a.skipped,generation:a.context.generation,artifactPaths:[...a.artifacts],...a.warnings.length>0?{warnings:a.warnings}:{}}}async function Dr(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};kr(()=>n.options.observer?.commandStarted?.(s));try{let t=await ir(e,n);G(n.options.signal),kr(()=>n.options.observer?.commandCompleted?.({...s,durationMs:r()-i,...Or(a,n.port.readMetrics?.()),...t?.data?{data:t.data}:{}}))}catch(t){let o=xr(t,e);throw kr(()=>n.options.observer?.commandFailed?.({...s,...o.command?{command:o.command}:{},source:o.source,durationMs:r()-i,...Or(a,n.port.readMetrics?.()),error:o.error,artifactPaths:[...n.artifacts],warnings:[...n.warnings]})),o}}function Or(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 kr(e){try{e?.()}catch{}}async function Ar(e,t,n={}){let r=jr(e,n);return await Er(e,t,{...n,startIndex:r})}function jr(e,t){return t.from!==void 0||t.planDigest!==void 0?Xn(e,{from:t.from,planDigest:t.planDigest}):Zn(e,t.startIndex??0)}function q(e,t,n){return R(e,`label`,e=>Kt(e,`${t}.label`,n))}const J=[`id`,`text`,`enabled`,`selected`,`index`,`childOf`,`below`,`above`,`leftOf`,`rightOf`,`containsChild`,`containsDescendants`],Mr={textKeys:[`id`,`text`],booleanKeys:[`enabled`,`selected`],textAliases:{label:`text`}},Nr={id:(e,t,n,r)=>Rr(e,`id`,t,n,r),text:(e,t,n,r)=>Rr(e,`text`,t,n,r),enabled:(e,t,n,r)=>zr(e,`enabled`,t,n,r),selected:(e,t,n,r)=>zr(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=Wt(t.value,`${n}.containsDescendants`,r).map(e=>Y(e,`${n}.containsDescendants`,r))},optional:(e,t,n,r)=>zr(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),Pr(i,t,n)}function Pr(e,t,n){e.length===0&&N(`Maestro ${t} selector is empty.`,void 0,n);let r={};for(let i of e){let e=Nr[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 Fr(e,t,n,r){let i=M(t,n);if((0,j.isScalar)(e))return{source:i,entries:[],target:Vr(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=>Br(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:Vr(Pr(a.filter(e=>Br(e.key,r.selectorKeys)),r.name,n))}}function Ir(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 Lr(e,t,n){let r=Ir(e,t,n);return r.space!==`absolute`&&N(`Maestro ${t} only supports absolute coordinates.`,e,n),r}function Rr(e,t,n,r,i){let a=Kt(n.value,`${r}.${t}`,i);a!==void 0&&(e[t]=a)}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){return t.includes(e)}function Vr(e){return{space:`target`,selector:e}}function Hr(e,t,n){let r=Fr(e,t,n,{name:`tapOn`,selectorKeys:J,pointConflictingSelectorKeys:J,pointAllowedKeys:[`point`,`retryTapIfNoChange`,`repeat`,`delay`,`optional`,`label`],selectorAllowedKeys:[...J,`retryTapIfNoChange`,`repeat`,`delay`,`optional`,`label`],parsePoint:Ir});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,...Yr(r.entries,n)};let i=Yr(r.entries,n);return O({kind:`tapOn`,source:r.source,target:r.target,...i})}function Ur(e,t,n){let r=Fr(e,t,n,{name:`doubleTapOn`,selectorKeys:J,pointAllowedKeys:[`point`,`delay`,`optional`,`label`],selectorAllowedKeys:[...J,`delay`,`optional`,`label`],parsePoint:Lr}),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 Wr(e,t,n){let r=Fr(e,t,n,{name:`longPressOn`,selectorKeys:J,pointAllowedKeys:[`point`,`optional`,`label`],selectorAllowedKeys:[...J,`optional`,`label`],parsePoint:Lr});return O({kind:`longPressOn`,source:r.source,target:r.target,...z(r.entries,`longPressOn`,n),label:q(r.entries,`longPressOn`,n)})}function Gr(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{...Kr(i,r,s,t,n),...a,label:o};let c=I(i,`direction`)?Xr(L(i,`direction`),`swipe.direction`,n):void 0;return I(i,`from`)?{...qr(i,r,c,s,t,n),...a,label:o}:{...Jr(r,c,s,t,n),...a,label:o}}function Kr(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=Ir(L(e,`start`),`swipe.start`,i),o=Ir(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 qr(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 Jr(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 Yr(e,t){let n=R(e,`retryTapIfNoChange`,e=>qt(e,`tapOn.retryTapIfNoChange`,t)),r=R(e,`repeat`,e=>nn(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 Xr(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 Zr(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:Pr(a.filter(e=>e.key!==`optional`&&e.key!==`label`),e,r),...o,label:s})}const Qr=[...J,`optional`];function $r(e,t,n,r){if(!I(e,t))return;let{optional:i,...a}=Y(L(e,t),n,r,Qr);return{selector:a,optional:i}}function ei(e,t,n){let r=$r(e,`visible`,`extendedWaitUntil.visible`,n),i=$r(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 ti(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`)?an(L(i,`env`),`runScript.env`,n):void 0})}function ni(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`)?an(L(a,`env`),`runFlow.env`,n):void 0,when:I(a,`when`)?ai(L(a,`when`),`runFlow.when`,n):void 0,label:q(a,`runFlow`,n)})}function ri(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`)?ai(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`)?nn(L(a,`times`),`repeat.times`,n):void 0,while:o,commands:r(L(a,`commands`),`repeat.commands`,n)})}function ii(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`)?nn(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 ai(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=>si(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=>oi(e,n,`${t}.true`))})}function oi(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 si(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 ci(e,t,n){return Wt(e,t,n).map(e=>li(e,n))}function li(e,t){if((0,j.isScalar)(e))return typeof e.value!=`string`&&N(`Maestro command names must be strings.`,e,t),ui(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 fi(r.key,r.value,e,t)}function ui(e,t,n){return fi(e,null,t,n)}const di={launchApp:pi,tapOn:Hr,doubleTapOn:Ur,longPressOn:Wr,inputText:mi,eraseText:hi,openLink:gi,assertVisible:(e,t,n)=>Zr(`assertVisible`,e,t,n),assertNotVisible:(e,t,n)=>Zr(`assertNotVisible`,e,t,n),assertTrue:_i,extendedWaitUntil:vi,takeScreenshot:yi,scroll:bi,scrollUntilVisible:xi,swipe:Gr,hideKeyboard:Si,pressKey:Ci,back:wi,waitForAnimationToEnd:Ti,stopApp:Ei,killApp:Di,setPermissions:Oi,clearState:ji,runScript:ti,evalScript:Mi,runFlow:(e,t,n)=>ni(e,t,n,ci),repeat:(e,t,n)=>ri(e,t,n,ci),retry:(e,t,n)=>ii(e,t,n,ci)};Object.keys(di);function fi(e,t,n,r){let i=di[e];return i||N(`Maestro command "${e}" is not supported.`,n,r),i(t,n,r)}function pi(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=>Kt(e,`launchApp.appId`,n)),stopApp:R(i,`stopApp`,e=>qt(e,`launchApp.stopApp`,n)),clearState:R(i,`clearState`,e=>qt(e,`launchApp.clearState`,n)),permissions:R(i,`permissions`,e=>ki(e,n,`launchApp`)),arguments:R(i,`arguments`,e=>Ni(e,`launchApp.arguments`,n)),launchArguments:R(i,`launchArguments`,e=>Ni(e,`launchApp.launchArguments`,n))})}function mi(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 hi(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:nn(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 gi(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 _i(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:rn(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=rn(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 vi(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=ei(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 yi(e,t,n){return{kind:`takeScreenshot`,source:M(t,n),path:H(e,`takeScreenshot`,n)}}function bi(e,t,n){return B(e)||N(`Maestro scroll does not accept options yet.`,t,n),{kind:`scroll`,source:M(t,n)}}function xi(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=$r(i,`element`,`scrollUntilVisible.element`,n);s||N(`Maestro scrollUntilVisible requires element.`,t,n);let c=I(i,`direction`)?Xr(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 Si(e,t,n){return B(e)||N(`Maestro hideKeyboard does not accept options.`,t,n),{kind:`hideKeyboard`,source:M(t,n)}}function Ci(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 wi(e,t,n){return B(e)||N(`Maestro back does not accept options.`,t,n),{kind:`back`,source:M(t,n)}}function Ti(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 Ei(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 Di(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 Oi(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=>Kt(e,`setPermissions.appId`,n)),o=ki(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 ki(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]=Ai(e,t,n);return i}function Ai(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(Yt.has(a))return a;if(Jt.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 ji(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 Mi(e,t,n){return{kind:`evalScript`,source:M(t,n),script:H(e,`evalScript`,n)}}function Ni(e,t,n){if((0,j.isSeq)(e))return{kind:`list`,values:Wt(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:an(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 Pi(e,t={}){let n=new j.LineCounter,i=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=Ht(t?.pos[0],i);throw new r(`INVALID_ARGS`,`Invalid Maestro YAML flow: ${n} (${Ut(a)})`)}let o=a.map(e=>e.contents).filter(e=>e!==null);o.length===0&&N(`Maestro flow is empty.`,void 0,i);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],i);let l=s?Fi(s,i):{};return{kind:`program`,source:M(s??c,i),config:l,commands:ci(c,`commands`,i)}}function Fi(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=>Kt(e,`name`,t)),appId:R(n,`appId`,e=>Kt(e,`appId`,t)),tags:R(n,`tags`,e=>Gt(e,`tags`,t)),env:R(n,`env`,e=>an(e,`env`,t)),onFlowStart:R(n,`onFlowStart`,e=>ci(e,`onFlowStart`,t)),onFlowComplete:R(n,`onFlowComplete`,e=>ci(e,`onFlowComplete`,t))})}function Ii(e,t){let n=new Map;return async(r,a,o)=>{if(o?.aborted)throw i();let s=Li(r,a,e),c=n.get(s);if(c)return c;let l=Pi(t(s),{sourcePath:s});return n.set(s,l),l}}function Li(e,t,n){let r=t?D.dirname(t):n;return D.resolve(r,e)}function Ri(e){return yn(e)?{command:e.kind,...e.kind===`runFlow`?X(e.label??e.includePath):{}}:{command:e.kind,...zi(e)}}function zi(e){return`label`in e&&e.label?X(e.label):Bi(e)?X(qi(e.target)):Vi(e)?Hi(e):e.kind===`inputText`?X(`<text>`):Ui(e)}function Bi(e){return e.kind===`tapOn`||e.kind===`doubleTapOn`||e.kind===`longPressOn`}function Vi(e){return e.kind===`assertVisible`||e.kind===`assertNotVisible`||e.kind===`extendedWaitUntil`||e.kind===`scrollUntilVisible`}function Hi(e){switch(e.kind){case`assertVisible`:case`assertNotVisible`:return X(Ji(e.target));case`extendedWaitUntil`:return X(Ji(e.visible??e.notVisible));case`scrollUntilVisible`:return X(Ji(e.element))}}function Ui(e){return Wi(e)?Gi(e):e.kind===`swipe`?Ki(e):e.kind===`runFlow`?X(e.label??(e.include.kind===`file`?e.include.path:``)):e.kind===`assertTrue`?X(String(e.condition)):{}}function Wi(e){return e.kind===`openLink`||e.kind===`takeScreenshot`||e.kind===`runScript`||e.kind===`pressKey`}function Gi(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 Ki(e){return X(e.gesture.kind===`coordinates`?`${Yi(e.gesture.start)} to ${Yi(e.gesture.end)}`:e.gesture.direction)}function qi(e){return e.space===`target`?Ji(e.selector):`${e.x},${e.y}${e.space===`percent`?`%`:``}`}function Ji(e){return e?.id??e?.text}function Yi(e){return`${e.x},${e.y}${e.space===`percent`?`%`:``}`}function X(e){return e?{value:e}:{}}const Xi=new Set(String.raw`^$\.*+?()[]{}|`);function Zi(e,t){try{return RegExp(`^(?:${t})$`,`ims`).test(e)}catch{return e.toLocaleLowerCase()===t.toLocaleLowerCase()}}function Qi(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(Xi.has(r))return;t+=r;continue}let i=e[n+1];if(i===void 0||!Xi.has(i))return;t+=i,n+=1}return t}function $i(e,t,n){if(n===`android`&&e.visibleToUser===!1)return!1;if(y(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=>x(e,n)?e:null);return r?y(r.rect)?t.isVisibleInEffectiveViewport(r):n!==`android`&&r.hittable===!0:!1}function ea(e,t,n){return!!n.findAncestor(e,e=>e.index===t.index?e:null)}function ta(e,t){let n=[t.id===void 0?void 0:ra(e.identifier,t.id),t.text===void 0?void 0:ia(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 na(e){return e.matches.filter(t=>$i(t,e.visibility,e.platform))}function ra(e,t){let n=e??``;return ye(n)===ye(t)||Zi(n,t)}function ia(e,t){return[e.label,be(e),e.identifier].filter(e=>!!e).some(e=>ra(e,t))}function aa(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 oa(e){return e.text!==void 0||e.id!==void 0||e.enabled!==void 0||e.selected!==void 0}function sa(e,t,n){let r=[],i=0;for(let a of e)for(let e of n){let n=la(a.rect,e.rect);n===void 0||!ca(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 ca(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 la(e,t){if(!(!ua(e)||!ua(t)))return Math.fround(Math.hypot(da(e.x,e.width)-da(t.x,t.width),da(e.y,e.height)-da(t.y,t.height)))}function ua(e){return!!(e&&[e.x,e.y,e.width,e.height].every(Number.isFinite))}function da(e,t){return e+Math.trunc(t/2)}function fa(e,t={},n={}){let i=b(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:i.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=sa(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=i=>{let s=a.get(i);if(s)return s;if(o.has(i))throw new r(`INVALID_ARGS`,`Maestro selector relations cannot contain cycles.`);o.add(i),t.onSelectorComputed?.(i);try{let t=pa(e,i,l,u,m,p),r={matches:t,indexed:_a(t,i.index,n.orderUnindexed)};return a.set(i,r),r}finally{o.delete(i)}};return{visibility:i,resolve:m,resolvePosition:f}}function pa(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=oa(m)?e.nodes.filter(e=>ta(e,m)):[...e.nodes];if(s){let e=new Set(i(s).indexed.map(e=>e.index));h=h.filter(t=>ha(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=>ma(i(e).indexed,r));h=h.filter(t=>e.every(e=>e.has(t.index)))}for(let[e,n]of ga(t)){let t=a(e,n);h=h.filter(e=>t.has(e.index))}return h}function ma(e,t){let n=new Set;for(let r of e)for(let e of t(r))n.add(e);return n}function ha(e,t){for(let n of e)if(t.has(n))return!0;return!1}function ga(e){return[[`below`,e.below],[`above`,e.above],[`leftOf`,e.leftOf],[`rightOf`,e.rightOf]].filter(e=>e[1]!==void 0)}function _a(e,t,n){if(t===void 0)return n?n(e):[...e];let r=ya(e)[xa(t)];return r?[r]:[]}function va(e,t){return t===void 0?e[0]:ya(e)[xa(t)]}function ya(e){return[...e].sort((e,t)=>{let n=ba(e.rect?.y),r=ba(t.rect?.y);return n===r?ba(e.rect?.x)-ba(t.rect?.x):n-r})}function ba(e){return e!==void 0&&Number.isFinite(e)?e:2**53-1}function xa(e){let t=typeof e==`number`?e:Number(e.trim());if(!Number.isSafeInteger(t)||t<0)throw new r(`INVALID_ARGS`,`Maestro selector.index must be a non-negative integer.`);return t}const Sa={android:{kind:`exact`,provider:`android-helper`},ios:{kind:`divergence`,provider:`apple-xctest`,reason:`maestro-clickable-not-exposed-by-provider`}};function Ca(e,t){let n=Sa[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 wa(e,t){return t.kind===`exact`?e.map((e,n)=>({node:e,order:n,rank:Ta(t.clickableByNodeIndex.get(e.index))})).sort((e,t)=>t.rank-e.rank||e.order-t.order).map(({node:e})=>e):[...e]}function Ta(e){return e===!0?2:+(e===!1)}function Ea(e,t,n,r={}){let i=Ca(e,n),a=Oa(e,i,r),o=Da(t,a),s=na({visibility:a.visibility,matches:o.matches,platform:n});return{...o,visible:s,clickability:i,ranked:ka(s,t,n,a.visibility,i)}}function Da(e,t){return{matches:t.resolve(e).matches,parentMatched:e.childOf===void 0||t.resolve(e.childOf).indexed.length>0}}function Oa(e,t,n={}){return fa(e,n,t?{orderUnindexed:e=>wa(e,t)}:{})}function ka(e,t,n,r,i){let a=n!==`ios`||!Pa(t)?e:e.filter(n=>{if(Ra(n))return!0;let i=e.filter(e=>e!==n&&Fa(n,e,t));return!i.some(e=>Ra(e)&&ea(n,e,r))&&!i.some(e=>ea(e,n,r))});return t.index===void 0&&i?wa(a,i):a}function Aa(e,t){let n=t===void 0?e.find(Na):ja(e,t);return!n||!Na(n)?null:{node:n,rect:n.rect}}function ja(e,t){return va(e,t)}function Ma(e){return Na(e)?e.rect:void 0}function Na(e){return y(e.rect)}function Pa(e){return e.id!==void 0||e.text!==void 0}function Fa(e,t,n){if(n.id!==void 0&&La(e.identifier)!==La(t.identifier))return!1;if(n.text!==void 0){let n=Ia(e),r=new Set(Ia(t));if(!n.some(e=>r.has(e)))return!1}return!0}function Ia(e){return[e.label,e.value,e.identifier].map(La).filter(e=>e!==void 0)}function La(e){if(e)return ye(e)||void 0}function Ra(e){let t=S(e.type??``);return t===`button`||t===`link`||t===`switch`||t===`searchfield`||t===`textfield`||t===`securetextfield`||t===`textview`}const za=Symbol(`maestroFlowProgram`),Ba=Symbol(`maestroFailureCommand`),Va=Symbol(`maestroFailurePlan`);function Ha(e,t){let n=Pi(e,{sourcePath:t});return{sourcePath:t,name:n.config.name,appTarget:qa(n),[za]:n}}async function Ua(e,t,n){let r;try{let i=D.dirname(e.sourcePath),a=Ii(i,n.readSource),o=await Kn(e[za],{baseDir:i,defaults:n.defaults,env:n.env,platform:n.platform,target:n.target,runtimeHints:n.runtimeHints,loadProgram:a,signal:n.signal}),s=Xn(o,{from:n.from,planDigest:n.planDigest}),c=await Ar(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:Ga(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 Wa(e,t){let n=Ya(e[Ba]),r=e[Va].platform;return!n||r!==`android`&&r!==`ios`?[]:Ea(t,n.selector,r).ranked.map(e=>({node:e,basis:Xa(n.selector,e)}))}function Ga(e,t,n){return{commandStarted:e=>t?.actionStarted?.(Ka(e)),commandCompleted:e=>t?.actionCompleted?.({...Ka(e),durationMs:e.durationMs,runtimeMetrics:e.runtimeMetrics,data:e.data}),commandFailed:r=>{let i=Yn(e,{from:r.stepIndex,planDigest:e.digest}),a={...Ka(r),durationMs:r.durationMs,error:r.error,artifactPaths:r.artifactPaths,warnings:[...r.warnings],isControl:yn(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},[Ba]:r.command,[Va]:e};n(a),t?.actionFailed?.(a)}}}function Ka(e){let t=Ri(e.command);return{action:t.command,...t.value?{value:t.value}:{},source:e.source,generation:e.generation,stepIndex:e.stepIndex,stepTotal:e.stepTotal}}function qa(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(Ja)}function Ja(e){return!!(e?.trim()&&!e.includes(`$`)&&!u(e))}function Ya(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 Xa(e,t){return e.id!==void 0||e.text!==void 0&&ta({...t,label:void 0,value:void 0},{text:e.text})?`id`:e.text===void 0?`other`:`label`}function Za(e){let t={[e.entryPath]:e.entrySource},n=Qa(e.entrySource,e.entryPath);return n&&$a({program:n,sourcePath:e.entryPath,context:Se({},{...e.env}),files:t,readSource:e.readSource}),t}function Qa(e,t){try{return Pi(e,{sourcePath:t})}catch{return}}function $a(e){let t=e.context.enter(e.program.config.env??{});try{eo([...e.program.config.onFlowStart??[],...e.program.commands,...e.program.config.onFlowComplete??[]],e)}finally{t()}}function eo(e,t){for(let n of e){if(n.kind===`repeat`||n.kind===`retry`){eo(n.commands,t);continue}if(n.kind!==`runFlow`)continue;let e=t.context.enter(n.env??{});try{if(n.include.kind===`commands`){eo(n.include.commands,t);continue}to(n.include.path,t)}finally{e()}}}function to(e,t){let n=t.context.resolveDeferred(e);if(n.includes("${"))return;let r=Li(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=Qa(i,r);a&&$a({...t,program:a,sourcePath:r})}function no(e,t){return`${e},${t}`}const ro={open:io,back:()=>({kind:`commands`,commands:[`back`]}),home:()=>({kind:`commands`,commands:[{pressKey:`Home`}]}),keyboard:so};function io(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=ao(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 ao(e,t){return{launchApp:{appId:t,...oo(e)}}}function oo(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 so(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 co(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())}}}})),Vt=t((e=>{var t=Nt(),n=gt(),r=_t(),i=Ve(),a=k(),o=zt(),s=Bt();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=Nt(),n=gt(),r=mt(),i=_t(),a=Ne(),o=k(),s=We(),c=A(),l=Ke(),u=Je();Lt();var d=Rt(),f=zt(),p=Bt(),m=Vt(),h=De();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 Ht(e?.range?.[0],t)}function Ht(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 Ut(e){return`${e.path===void 0?``:`${e.path}:`}line ${e.line}`}function N(e,t,n){throw new r(`INVALID_ARGS`,`${e} (${Ut(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 Wt(e,t,n){return(0,j.isSeq)(e)||N(`Maestro ${t} expects a list.`,e,n),e.items}function Gt(e,t,n){return Wt(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=>qt(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 Kt(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 qt(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 Jt=/^\$\{[A-Za-z_][A-Za-z0-9_.]*\}$/,Yt=new Set([`allow`,`deny`,`unset`,`always`,`inuse`,`never`,`limited`]),Xt=/^-?\d+(\.\d+)?$/,Zt=/^-?\d+$/,Qt={"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 $t(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 en(e,t,n,r,i){let a=`Maestro ${t} expects ${$t(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 tn(e,t,n,r,i){if(typeof e==`number`)return en(e,t,n,r,i),e;if(typeof e==`string`){if(Jt.test(e))return e;if((i.integer?Zt:Xt).test(e)){let a=Number(e);return en(a,t,n,r,i),a}}N(`Maestro ${t} expects ${$t(i)} or a variable expression.`,n,r)}function U(e,t,n,r=Qt[t]??{}){let i=V(e,t,n);if(i!==null)return tn(i,t,e,n,r)}function nn(e,t,n){let r=Qt[t]??{},i=V(e,t,n);return i===null&&N(`Maestro ${t} expects ${$t(r)} or a variable expression.`,e,n),tn(i,t,e,n,r)}function rn(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("${")&&!Jt.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 an(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 on(e,t){try{return new hn(cn(sn(e)),t).parse()}catch(e){if(e instanceof r&&e.code===`INVALID_ARGS`)return;throw e}}function sn(e){let t=e.trim();return t.startsWith("${")&&t.endsWith(`}`)?t.slice(2,-1).trim():t}function cn(e){let t=[],n=0;for(;n<e.length;){let i=e.slice(n),a=/^\s+/.exec(i)?.[0].length??0;if(a>0){n+=a;continue}let o=ln(i);if(!o)throw new r(`INVALID_ARGS`,`Unsupported runFlow.when.true expression near "${i.slice(0,24)}".`);t.push(o.value),n+=o.length}return t}function ln(e){return un(e)??dn(e)??fn(e)??pn(e)??mn(e)}function un(e){return e.startsWith(`maestro.platform`)?{value:{type:`platform`},length:16}:null}function dn(e){let t=/^(==|!=|&&|\|\|)/.exec(e)?.[1];return t?{value:{type:`operator`,value:t},length:t.length}:null}function fn(e){let t=e[0];return t===`(`||t===`)`?{value:{type:`paren`,value:t},length:1}:null}function pn(e){let t=/^(['"])(.*?)\1/.exec(e);return t?{value:{type:`string`,value:t[2]??``},length:t[0].length}:null}function mn(e){let t=/^(true|false)\b/.exec(e)?.[1];return t?{value:{type:`boolean`,value:t===`true`},length:t.length}:null}var hn=class{index=0;tokens;platform;constructor(e,t){this.tokens=e,this.platform=t}parse(){let e=this.parseOr();if(this.peek())throw new r(`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 r(`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 r(`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 r(`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 r(`INVALID_ARGS`,`runFlow.when.true comparison requires == or !=.`);return this.index+=1,e}consumeStringLiteral(){let e=this.peek();if(e?.type!==`string`)throw new r(`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 gn=new Set([``,`false`,`0`,`null`,`undefined`]);function _n(e){return typeof e==`boolean`?e:typeof e==`number`?e!==0&&!Number.isNaN(e):!gn.has(e)}function vn(e){return typeof e==`boolean`||typeof e==`number`||typeof e==`string`?_n(e):typeof e==`bigint`?e!==0n:e!=null}function yn(e){switch(e.kind){case`runFlow`:return!(`include`in e);case`repeat`:case`retry`:return!(`commands`in e);default:return!1}}function bn(e,t){return{...Mn(e,t),source:e.source}}function xn(e,t,n){if(e===void 0)return;let i=n??Qt[t]??{},a=$t(i),o;if(typeof e==`number`)o=e;else{let n=e.trim();if(n===``)throw new r(`INVALID_ARGS`,`Maestro ${t} must be ${a}.`);o=Number(n)}if(!Number.isFinite(o)||Math.abs(o)>2**53-1||i.integer&&!Number.isSafeInteger(o)||i.nonNegative&&o<0||i.positive&&o<=0)throw new r(`INVALID_ARGS`,`Maestro ${t} must be ${a}.`);return o}function Sn(e,t,n,r){return xn(e===void 0?t:n.resolve(String(e)),r)}function W(e){if(e?.aborted)throw i()}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 r(`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 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 i=wn(e,e.source.path,n);if(i&&t.has(i))throw new r(`INVALID_ARGS`,`Maestro runFlow cycle detected at ${i}.`);return i}function Dn(e,t,n,i){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=>i.has(e));if(s)throw new r(`INVALID_ARGS`,`Maestro runFlow cycle detected at ${s}.`);return o.forEach(e=>i.add(e)),o}function On(e,t){if(e.trustedScripts===!1)throw new r(`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=on(i,r.platform);if(e!==void 0)return e;if(!i.includes("${"))return _n(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),vn(o.value)}function An(e,t){try{return t.resolve(e)}catch(e){if(e instanceof r&&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){W(t.signal);let n=Tn(e.source.path),r={options:t,context:Se(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){W(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){W(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);W(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=on(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=xe(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 r(`INVALID_ARGS`,n.reason);return n.startIndex}function Qn(e,t){if(!Number.isInteger(t)||t<0||t>e.total)throw new r(`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 $n(e){return Math.trunc(1e3*(100-e)/100)+1}const er={assertVisibleTimeoutMs:G.command.targetLookupTimeoutMs,assertNotVisibleTimeoutMs:G.command.targetLookupTimeoutMs,extendedWaitUntilTimeoutMs:G.command.targetLookupTimeoutMs,runFlowConditionTimeoutMs:G.command.optionalTargetLookupTimeoutMs},tr=G.observation.pollIntervalMs*G.observation.defaultSettleAttempts,nr=`maestro-test-failure`;function rr(e,t={}){return new r(`COMMAND_FAILED`,e,{...t,reason:nr})}function ir(e){return e instanceof r&&e.code===`COMMAND_FAILED`&&e.details?.reason===nr}async function ar(e,t){W(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=bn(e,n.context);try{return await dr(r,t,n)}catch(e){if(W(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}`,i=t instanceof r?t.message:String(t);return`Optional Maestro ${e.kind} skipped at ${n}: ${i}`}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(!_n(e.condition))throw rr(`Maestro assertTrue condition was falsy: ${JSON.stringify(e.condition)}`);n.executed+=1;return;case`extendedWaitUntil`:await vr(br(e),xn(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 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 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`),G.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)),W(r.options.signal),n&&!await _r(n,`repeat.while`,r))return;await mr(e,r)}}async function gr(e,t,n){let i;for(let r=0;r<=t;r+=1){W(n.options.signal);try{await mr(e,n);return}catch(t){if(W(n.options.signal),!ir(Tr(t)))throw t;i=Sr(t,e[0])}}throw i||new r(`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(W(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 W(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 r(`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 r)||!t||/\bline \d+\b/.test(e.message))return e;let n=t.source.path?`${t.source.path}:`:``;return new r(e.code,`${e.message} (${n}line ${t.source.line})`,e.details)}async function Dr(e,t,n={}){W(n.signal);let i=n.startIndex??0;if(!Number.isInteger(i)||i<0||i>e.total)throw new r(`INVALID_ARGS`,`Maestro replay startIndex ${i} is out of range for a ${e.total}-step plan.`);let a={plan:e,port:t,options:n,context:Se(n.defaults,n.env?{...n.env}:{}),timing:er,artifacts:new Set,warnings:[],executed:e.compatibility.staticallyExecutedControls,skipped:e.compatibility.staticallySkippedControls};for(let t=i;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){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};Ar(()=>n.options.observer?.commandStarted?.(s));try{let t=await ar(e,n);W(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 K(e,t,n){return R(e,`label`,e=>Kt(e,`${t}.label`,n))}const q=[`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=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=Wt(t.value,`${n}.containsDescendants`,r).map(e=>J(e,`${n}.containsDescendants`,r))},optional:(e,t,n,r)=>Br(e,`optional`,t,n,r)};function J(e,t,n,r=q){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(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=>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=Kt(n.value,`${r}.${t}`,i);a!==void 0&&(e[t]=a)}function Br(e,t,n,r,i){let a=qt(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:q,pointConflictingSelectorKeys:q,pointAllowedKeys:[`point`,`retryTapIfNoChange`,`repeat`,`delay`,`optional`,`label`],selectorAllowedKeys:[...q,`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:q,pointAllowedKeys:[`point`,`delay`,`optional`,`label`],selectorAllowedKeys:[...q,`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=K(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:q,pointAllowedKeys:[`point`,`optional`,`label`],selectorAllowedKeys:[...q,`optional`,`label`],parsePoint:Rr});return O({kind:`longPressOn`,source:r.source,target:r.target,...z(r.entries,`longPressOn`,n),label:K(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=K(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:J(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=>qt(e,`tapOn.retryTapIfNoChange`,t)),r=R(e,`repeat`,e=>nn(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:K(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:J(t,e,r)};let a=P(t,e,r);F(a,e,[...q,`optional`,`label`],r);let o=z(a,e,r),s=K(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=[...q,`optional`];function ei(e,t,n,r){if(!I(e,t))return;let{optional:i,...a}=J(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`)?an(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`)?an(L(a,`env`),`runFlow.env`,n):void 0,when:I(a,`when`)?oi(L(a,`when`),`runFlow.when`,n):void 0,label:K(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`)?nn(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`)?nn(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=>J(e,`${t}.visible`,n)),notVisible:R(r,`notVisible`,e=>J(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 Wt(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=>Kt(e,`launchApp.appId`,n)),stopApp:R(i,`stopApp`,e=>qt(e,`launchApp.stopApp`,n)),clearState:R(i,`clearState`,e=>qt(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:K(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:nn(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:rn(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=rn(L(i,`condition`),`assertTrue.condition`,n),o=z(i,`assertTrue`,n),s=K(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=K(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:J(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=K(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=>Kt(e,`setPermissions.appId`,n)),o=Ai(L(i,`permissions`),n),s=z(i,`setPermissions`,n),c=K(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(Yt.has(a))return a;if(Jt.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:Wt(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:an(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,i=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=Ht(t?.pos[0],i);throw new r(`INVALID_ARGS`,`Invalid Maestro YAML flow: ${n} (${Ut(a)})`)}let o=a.map(e=>e.contents).filter(e=>e!==null);o.length===0&&N(`Maestro flow is empty.`,void 0,i);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],i);let l=s?Ii(s,i):{};return{kind:`program`,source:M(s??c,i),config:l,commands:li(c,`commands`,i)}}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=>Kt(e,`name`,t)),appId:R(n,`appId`,e=>Kt(e,`appId`,t)),tags:R(n,`tags`,e=>Gt(e,`tags`,t)),env:R(n,`env`,e=>an(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 n=new Map;return async(r,a,o)=>{if(o?.aborted)throw i();let s=Ri(r,a,e),c=n.get(s);if(c)return c;let l=Fi(t(s),{sourcePath:s});return n.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 yn(e)?{command:e.kind,...e.kind===`runFlow`?Y(e.label??e.includePath):{}}:{command:e.kind,...Bi(e)}}function Bi(e){return`label`in e&&e.label?Y(e.label):Vi(e)?Y(Ji(e.target)):Hi(e)?Ui(e):e.kind===`inputText`?Y(`<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 Y(Yi(e.target));case`extendedWaitUntil`:return Y(Yi(e.visible??e.notVisible));case`scrollUntilVisible`:return Y(Yi(e.element))}}function Wi(e){return Gi(e)?Ki(e):e.kind===`swipe`?qi(e):e.kind===`runFlow`?Y(e.label??(e.include.kind===`file`?e.include.path:``)):e.kind===`assertTrue`?Y(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 Y(e.link);case`takeScreenshot`:return Y(e.path);case`runScript`:return Y(e.file);case`pressKey`:return Y(e.key)}}function qi(e){return Y(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 Y(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(ee(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=>y(e,n)?e:null);return r?ee(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 ye(n)===ye(t)||Qi(n,t)}function aa(e,t){return[e.label,be(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 i=b(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:i.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=i=>{let s=a.get(i);if(s)return s;if(o.has(i))throw new r(`INVALID_ARGS`,`Maestro selector relations cannot contain cycles.`);o.add(i),t.onSelectorComputed?.(i);try{let t=ma(e,i,l,u,m,p),r={matches:t,indexed:va(t,i.index,n.orderUnindexed)};return a.set(i,r),r}finally{o.delete(i)}};return{visibility:i,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 r(`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 ee(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 ye(e)||void 0}function za(e){let t=C(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:yn(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:Se({},{...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(`
|
|
116
116
|
---
|
|
117
|
-
`)}\n`}function lo(e,t){let n={config:uo(t.metadata),warnings:[],unsupported:[]},i=[];for(let[r,a]of e.entries()){let e=t.actionLines?.[r]??r+1,o=po(a,t.resolveSelector);switch(o.kind){case`commands`:i.push(...o.commands),Io(n,o.warnings,a,e);break;case`config`:n.config.appId??=o.appId,i.push(...o.commands),Io(n,o.warnings,a,e);break;case`unsupported`:n.unsupported.push({line:e,action:Bo(a),message:o.message})}}if(n.unsupported.length>0)throw new r(`INVALID_ARGS`,`Cannot export replay to Maestro YAML: unsupported .ad action ${zo(n.unsupported)}.`,{unsupported:n.unsupported});return{yaml:Ro(n.config,i),warnings:n.warnings}}function uo(e){return e?.env&&Object.keys(e.env).length>0?{env:e.env}:{}}const fo={...ro,click:mo,press:mo,longpress:ho,fill:yo,type:bo,wait:xo,find:Co,screenshot:wo,scroll:To,swipe:Eo};function po(e,t){return fo[e.command]?.(e,t)??{kind:`unsupported`,message:`${e.command} has no Maestro equivalent`}}function mo(e,t){let[n,r]=e.positionals;if(!n)return{kind:`unsupported`,message:`${e.command} requires a target`};let i=Ao(n,r,t);if(!i)return{kind:`unsupported`,message:`tap target is not Maestro-compatible`};let a=jo(e);return a.ok?e.flags?.doubleTap===!0?{kind:`commands`,commands:[{doubleTapOn:i}],warnings:[...So(n),...vo(e,`doubleTapOn`)]}:typeof e.flags?.holdMs==`number`?{kind:`commands`,commands:[{longPressOn:i}],warnings:[...So(n),_o(e.flags.holdMs),...vo(e,`longPressOn`)]}:{kind:`commands`,commands:[Po(i,a.options)],warnings:So(n)}:{kind:`unsupported`,message:a.message}}function ho(e,t){let[n,r]=e.positionals;if(!n)return{kind:`unsupported`,message:`longpress requires a target`};let i=Ao(n,r,t);return i?{kind:`commands`,commands:[{longPressOn:i}],warnings:[...So(n),...go(e).map(_o)]}:{kind:`unsupported`,message:`longpress target is not Maestro-compatible`}}function go(e){let[t,n,r]=e.positionals,i=Z(t)&&Z(n)?r:n;return i&&Z(i)?[Number(i)]:[]}function _o(e){return`long-press duration exports as Maestro longPressOn; Maestro uses its default long-press duration instead of ${e}ms`}function vo(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 yo(e,t){let[n,r]=e.positionals;if(!n||r===void 0)return{kind:`unsupported`,message:`fill requires a target and text`};let i=Ao(n,void 0,t);return i?r.length===0?{kind:`commands`,commands:[{tapOn:i},`eraseText`],warnings:[...So(n),`fill "" exports as tapOn + eraseText; Maestro erases at most its 50-character default`]}:{kind:`commands`,commands:[{tapOn:i},{inputText:r}],warnings:[...So(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 bo(e){let[t]=e.positionals;if(t===void 0)return{kind:`unsupported`,message:`type requires text`};let n=Fo(t);return n===null?{kind:`commands`,commands:[{inputText:t}]}:{kind:`commands`,commands:[{eraseText:n}]}}function xo(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:Lo(e,$n.extendedWaitUntilTimeoutMs)}}]};let i=t(n);return i?{kind:`commands`,commands:[{extendedWaitUntil:{visible:i,timeout:Lo(e,$n.extendedWaitUntilTimeoutMs)}}],warnings:So(n)}:{kind:`unsupported`,message:`wait selector is not Maestro-compatible`}}function So(e){return T(e,`label`)?[`label= selectors export as Maestro text; Maestro text matching is broader than agent-device label-only matching`]:[]}function Co(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 wo(e){let[t]=e.positionals;return t?{kind:`commands`,commands:[{takeScreenshot:t}]}:{kind:`unsupported`,message:`screenshot requires an output path`}}function To(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 Eo(e){let t=Do(e);if(!t)return{kind:`unsupported`,message:`only coordinate swipe exports to Maestro`};let n=Oo(e);if(n===null)return{kind:`unsupported`,message:`swipe count must be a positive integer`};let r=ko(e);return r?{kind:`unsupported`,message:r}:{kind:`commands`,commands:Array.from({length:n},()=>({swipe:t}))}}function Do(e){let[t,n,r,i]=e.positionals;if(!(!Z(t)||!Z(n)||!Z(r)||!Z(i)))return{start:no(t,n),end:no(r,i),duration:100}}function Oo(e){let t=e.flags?.count??1;return Number.isInteger(t)&&t>=1?t:null}function ko(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 Ao(e,t,n){return Z(e)&&Z(t)?{point:no(e,t)}:e.startsWith(`@`)?null:n(e)}function jo(e){let t=No(e);return t?{ok:!1,message:t}:{ok:!0,options:Mo(e)}}function Mo(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 No(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 Po(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 Fo(e){return e.length===0||![...e].every(e=>e===`\b`)?null:e.length}function Io(e,t,n,r){for(let i of t??[])e.warnings.push({line:r,action:Bo(n),message:i})}function Lo(e,t){let n=e.positionals.at(-1);return n&&Z(n)?Number(n):t}function Ro(e,t){return co(Object.keys(e).length>0?[e,t]:[t])}function zo(e){return e.map(e=>`line ${e.line} (${e.action}): ${e.message}`).join(`; `)}function Bo(e){return[e.command,...e.positionals??[]].join(` `).trim()}function Z(e){return e!==void 0&&Number.isFinite(Number(e))}function Vo(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 Ho(e){return O({env:e.env,generation:e.generation,cachedObservation:e.cachedObservation,signal:e.signal})}async function Uo(e,t){let n=Xo(await t.observe({condition:e.condition,timeoutMs:e.timeoutMs},Ho(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:Wo(e.condition,n),candidateCount:n.candidateCount,evidence:r}}function Wo(e,t){let n=t.matched&&t.visible&&t.failureReason===void 0;return e.kind===`visible`?n:!n}async function Go(e,t,n,r){let i=Xo(await r.resolveTarget({selector:e,...t},Vo(n,n.command)),n.generation);if(!i.matched||!i.visible||!i.rect)throw nr(qo(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 Ko(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 qo(e,t){let n=Jo(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 Jo(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 Yo(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 Xo(e,t){return Zo(e,t),Qo(e),$o(e),es(e),e}function Zo(e,t){if(e.generation!==t)throw new r(`COMMAND_FAILED`,`Maestro target evidence generation ${e.generation} does not match ${t}.`)}function Qo(e){if(!Number.isInteger(e.candidateCount)||e.candidateCount<0)throw new r(`COMMAND_FAILED`,`Maestro target evidence has an invalid candidate count.`)}function $o(e){if(e.rect!==void 0&&!Yo(e.rect)||e.viewport!==void 0&&!Yo(e.viewport))throw new r(`COMMAND_FAILED`,`Maestro target evidence has invalid geometry.`)}function es(e){if(e.surfaceSignature!==void 0&&typeof e.surfaceSignature!=`string`)throw new r(`COMMAND_FAILED`,`Maestro target evidence has an invalid surface signature.`)}function ts(e,t,n,r,i,a={}){let o=ns(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 ns(e,t,n,r,i){let a=n===`up`||n===`down`,o=Oa(e,Ca(e,r),i),s=o.visibility,c=na({visibility:s,matches:e.nodes.filter(e=>C(e)),platform:r}),l=ne(s.viewportRects)??is(c);if(!l||!y(l))return;let u=c.flatMap(e=>{if(!y(e.rect))return[];let t=as(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=rs(e,s.nodeByIndex),n=t?d.get(t.index):void 0;if(n)return n.viewport}return u.sort(os)[0]?.viewport}function rs(e,t){return C(e)?e:ee(e,t)}function is(e){let t;for(let n of e)y(n.rect)&&(!t||n.rect.width*n.rect.height>t.width*t.height)&&(t=n.rect);return t}function as(e,t){let n=Math.max(e.x,t.x),r=Math.max(e.y,t.y),i=Math.min(e.x+e.width,t.x+t.width)-n,a=Math.min(e.y+e.height,t.y+t.height)-r;return i>0&&a>0?{x:n,y:r,width:i,height:a}:void 0}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 i=W(e.duration,`swipe.duration`);if(e.kind===`coordinates`){if(e.start.space!==e.end.space)throw new r(`INVALID_ARGS`,`Maestro swipe endpoints must use the same coordinate space.`);let a=e.start.space===`percent`?await n.resolveGestureViewport(Vo(t,t.command)):void 0;return{authored:e,gesture:us(await ls(e.start,t,n,a),await ls(e.end,t,n,a),i),...a?{viewport:a}:{}}}if(e.kind===`screen`){let r=await n.resolveGestureViewport(Vo(t,t.command)),{start:a,end:o}=ds(r,e.direction,n.platform);return{authored:e,gesture:us(a,o,i),viewport:r}}let a=await Go(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(Vo(t,t.command)),{start:s,end:c}=ps(a,e.direction,o);return{authored:e,gesture:us(s,c,i),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(Vo(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=ce(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,Vo(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?Ko(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?Ko(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?Ko(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?Ko(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:Qn(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 r(`COMMAND_FAILED`,`Maestro ${e.kind} must be executed by the observation engine.`)}function Ps(e){throw new r(`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 r(`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 Go(e.selector,t,n,r);return{authored:e,point:ce(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):Ea(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?ja(s,t.selector.index):Aa(s,t.selector.index)?.node,l=Xs(t,o,s,c);if(!c)return qs(t,o,s,l);let u=i?Aa(i.visibleForSource(c),void 0):null,d=Ma(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=aa;function Gs(e){let t=b(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=>$i(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=Ca(e,`ios`),i=fa(e,{},{orderUnindexed:e=>wa(e,r)}),a=Da(t.selector,i),o=a.matches.filter(n.isVisible);return{...a,visible:o,clickability:r,ranked:ka(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&&ja(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=ce(e),r=ce(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:er,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=Vo(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 Uo(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:i}=e,a=pe.readFileSync(t,`utf8`),s=Object.create(null);try{ve.runInNewContext(a,tc(n,s,i),{filename:t,timeout:Qs})}catch(e){let n=o(e);throw new r(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(s,t),Object.fromEntries(Object.entries(s).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 r(`COMMAND_FAILED`,`Maestro runScript json() expected a string body, received ${typeof e}.`);if(e.trim().length===0)throw new r(`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 r(`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,i){let a=_(process.execPath,ac(),{stdin:JSON.stringify(sc(e,t,i,n)),timeoutMs:Qs,allowFailure:!0});if(a.exitCode!==0)throw new r(`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 r(`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 r(`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=ge(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=>pe.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 r(`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 me.mkdtemp(D.join(he.tmpdir(),`agent-device-maestro-${e}-`));try{return await t(n)}finally{try{await me.rm(n,{recursive:!0,force:!0})}catch{}}}async function pc(e,t,n,r){try{let[i,a]=await Promise.all([me.readFile(e),me.readFile(t)]);vc(n);let o=await ue(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 me.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||a(e))throw i()}function vc(e){if(e?.aborted)throw i()}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 r(`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=le(e.snapshot),n=e.platform===`ios`?de(e.snapshot.nodes):void 0,r=n?{...e.snapshot,nodes:c(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,Wo(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!y(e)||!y(t)?0:E(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=Qi(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,n){try{await e.sleep(t,n)}catch(e){throw n?.aborted?i():e}Rc(n)}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 i()}function zc(e,t){if(!Number.isFinite(e)||e<0)throw new r(`INVALID_ARGS`,`${t} timeout must be a non-negative number.`)}function Bc(e){return e instanceof r&&e.details?.retriable===!0}function Vc(e){return fe(`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 r(`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 r(`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 r(`UNSUPPORTED_OPERATION`,`Maestro permission "${e}" is not supported.`,{hint:`Supported: all, ${Object.keys(Qc).join(`, `)}.`});let i=el[e],a=i?rl(i,t):void 0;if(a)return a;let o=rl($c,t);if(o)return{state:o,permission:n};throw new r(`INVALID_ARGS`,`Maestro permission "${e}" does not accept "${t}".`,{hint:`Use ${[`allow`,`deny`,`unset`,...Object.keys(i??{})].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),i=await e.invoke(d({...n,flags:ml(e.flags,n.flags??{})}));if(!i.ok)throw bl(i);if(t.kind===`gestureViewport`){let e=i.data?.viewport;if(typeof e!=`object`||!e||![`x`,`y`,`width`,`height`].every(t=>typeof e[t]==`number`))throw new r(`COMMAND_FAILED`,`runtime gesture-viewport returned no valid viewport.`);return e}return i.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 i=t.source?.path??n;if(!i)throw new r(`INVALID_ARGS`,`Maestro runScript file paths require a source path.`);return D.resolve(D.dirname(i),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 r(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,i,a,o,s=0,c=0,l=async n=>{c+=1;let i=await pl(e,{kind:`snapshot`});if(!i||!Array.isArray(i.nodes))throw new r(`COMMAND_FAILED`,`Maestro snapshot did not return node data.`);let a=m(i,i);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=>{i=t?.generation===e-1?{generation:e,snapshot:t.snapshot}:void 0,t=void 0,n=void 0},requireStability:e=>{o=e,a=i?.generation===e?i:void 0,i=void 0,n=void 0},consumeStabilityFromVisualWait:e=>{if(o!==void 0){if(o!==e.generation)throw new r(`COMMAND_FAILED`,`Maestro stability generation ${o} does not match ${e.generation}.`);o=void 0,a=void 0,i=void 0,n=void 0}},prime:(e,t)=>{n={generation:e,snapshot:t}},settlePending:async i=>{if(o===void 0)return;if(o!==i.generation)throw new r(`COMMAND_FAILED`,`Maestro stability generation ${o} does not match ${i.generation}.`);let s=t?.generation===i.generation?t.snapshot:a?.snapshot,c=await Oc({timeoutMs:$.settleTimeoutMs,context:i,snapshot:l,dependencies:e.dependencies,...s?{initialSnapshot:s}:{}});return o=void 0,a=void 0,n={generation:i.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,ce(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=n(e);return t.code===`AMBIGUOUS_MATCH`||t.code===`ELEMENT_NOT_FOUND`||t.code===`ELEMENT_OFFSCREEN`||t.details?.reason===se.selectorNotFound}async function Nl(e,t,n){if(!t)throw new r(`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},i=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 i=[];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 r?new r(e.code,e.message,{...e.details,appliedPermissionMutations:i,failedPermissionMutation:Pl(a)}):e}i.push(Pl(a))}},u=a===`android`?$.androidInputTextCharacterDelayMs:void 0,f=async(n,r,a)=>{v(n),await c({kind:`typeText`,text:n,...a===void 0?{}:{delayMs:a}},r);let o=await Oc({timeoutMs:$.settleTimeoutMs,context:r,snapshot:t.capture,dependencies:e.dependencies});i(o),t.prime(r.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=ts(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 nr(`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:i}}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,i,a){let o=Wl(i);e(t,{type:`replay_action_stop`,ts:new Date().toISOString(),replayPath:n,...i.source.path&&i.source.path!==n?{sourcePath:i.source.path}:{},line:i.source.line,step:i.stepIndex,command:i.action,ok:a,durationMs:i.durationMs,...Object.keys(o).length>0?{resultTiming:o}:{},...!a&&`error`in i&&i.error instanceof r?{errorCode:i.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=>Wa(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:s,session:{store:c,observationStore:l,logPath:u}}=n,{failure:d}=a,f=o(a.error);return d?await Yl(e,{error:f,failure:d,replayPath:r,req:s,sessionStore:c,observationStore:l,logPath:u,snapshotDiagnostics:tu(c,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 Ua(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=Ha(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{...oe(ae(e.flags?.replayShellEnv,t)),...ie(re(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 _e(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 r(`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 Za(e)},inspectSource(e,t){let n=Ha(e,t);return{title:n.name,appTarget:n.appTarget}},async runReplay(t){return await ru(e,t)},exportReplayScript(e,t){return lo(e,{...t,resolveSelector:e=>w(e,Mr)})}}}const bu={create:yu};export{bu as maestroReplayBackendPlugin};
|
|
117
|
+
`)}\n`}function uo(e,t){let n={config:fo(t.metadata),warnings:[],unsupported:[]},i=[];for(let[r,a]of e.entries()){let e=t.actionLines?.[r]??r+1,o=mo(a,t.resolveSelector);switch(o.kind){case`commands`:i.push(...o.commands),Lo(n,o.warnings,a,e);break;case`config`:n.config.appId??=o.appId,i.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 r(`INVALID_ARGS`,`Cannot export replay to Maestro YAML: unsupported .ad action ${Bo(n.unsupported)}.`,{unsupported:n.unsupported});return{yaml:zo(n.config,i),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=X(t)&&X(n)?r:n;return i&&X(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(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: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 ne(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(!(!X(t)||!X(n)||!X(r)||!X(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 X(e)&&X(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&&X(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 X(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 r(`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 r(`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 r(`COMMAND_FAILED`,`Maestro target evidence has invalid geometry.`)}function ts(e){if(e.surfaceSignature!==void 0&&typeof e.surfaceSignature!=`string`)throw new r(`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}=cs(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=>S(e)),platform:r}),l=E(s.viewportRects)??as(c);if(!l||!ee(l))return;let u=c.flatMap(e=>{if(!ee(e.rect))return[];let t=os(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(ss)[0]?.viewport}function is(e,t){return S(e)?e:x(e,t)}function as(e){let t;for(let n of e)ee(n.rect)&&(!t||n.rect.width*n.rect.height>t.width*t.height)&&(t=n.rect);return t}function os(e,t){let n=Math.max(e.x,t.x),r=Math.max(e.y,t.y),i=Math.min(e.x+e.width,t.x+t.width)-n,a=Math.min(e.y+e.height,t.y+t.height)-r;return i>0&&a>0?{x:n,y:r,width:i,height:a}:void 0}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 i=xn(e.duration,`swipe.duration`);if(e.kind===`coordinates`){if(e.start.space!==e.end.space)throw new r(`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:ds(await us(e.start,t,n,a),await us(e.end,t,n,a),i),...a?{viewport:a}:{}}}if(e.kind===`screen`){let r=await n.resolveGestureViewport(Ho(t,t.command)),{start:a,end:o}=fs(r,e.direction,n.platform);return{authored:e,gesture:ds(a,o,i),viewport:r}}let a=await Ko(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(Ho(t,t.command)),{start:s,end:c}=ps(a,e.direction,o);return{authored:e,gesture:ds(s,c,i),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(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 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=ce(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,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=xn(e.delay,`doubleTapOn.delay`)??G.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?G.command.optionalTargetLookupTimeoutMs:G.command.targetLookupTimeoutMs}function Es(e,t){let n=xn(e.repeat,`tapOn.repeat`),r=xn(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?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:xn(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:xn(e.timeout,`scrollUntilVisible.timeout`)??G.command.scrollUntilVisibleTimeoutMs,durationMs:$n(G.command.scrollUntilVisibleSpeed)}}function js(e){return O({timeoutMs:xn(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 r(`COMMAND_FAILED`,`Maestro ${e.kind} must be executed by the observation engine.`)}function Ps(e){throw new r(`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 r(`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:ce(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):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=b(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=ce(e),r=ce(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: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=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:i}=e,a=pe.readFileSync(t,`utf8`),s=Object.create(null);try{ve.runInNewContext(a,tc(n,s,i),{filename:t,timeout:Qs})}catch(e){let n=o(e);throw new r(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(s,t),Object.fromEntries(Object.entries(s).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 r(`COMMAND_FAILED`,`Maestro runScript json() expected a string body, received ${typeof e}.`);if(e.trim().length===0)throw new r(`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 r(`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,i){let a=_(process.execPath,ac(),{stdin:JSON.stringify(sc(e,t,i,n)),timeoutMs:Qs,allowFailure:!0});if(a.exitCode!==0)throw new r(`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 r(`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 r(`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=ge(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=>pe.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 r(`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 me.mkdtemp(D.join(he.tmpdir(),`agent-device-maestro-${e}-`));try{return await t(n)}finally{try{await me.rm(n,{recursive:!0,force:!0})}catch{}}}async function pc(e,t,n,r){try{let[i,a]=await Promise.all([me.readFile(e),me.readFile(t)]);vc(n);let o=await ue(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 me.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||a(e))throw i()}function vc(e){if(e?.aborted)throw i()}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 r(`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=le(e.snapshot),n=e.platform===`ios`?de(e.snapshot.nodes):void 0,r=n?{...e.snapshot,nodes:c(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!ee(e)||!ee(t)?0:te(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,n){try{await e.sleep(t,n)}catch(e){throw n?.aborted?i():e}Rc(n)}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 i()}function zc(e,t){if(!Number.isFinite(e)||e<0)throw new r(`INVALID_ARGS`,`${t} timeout must be a non-negative number.`)}function Bc(e){return e instanceof r&&e.details?.retriable===!0}function Vc(e){return fe(`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 r(`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 r(`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 r(`UNSUPPORTED_OPERATION`,`Maestro permission "${e}" is not supported.`,{hint:`Supported: all, ${Object.keys(Qc).join(`, `)}.`});let i=el[e],a=i?rl(i,t):void 0;if(a)return a;let o=rl($c,t);if(o)return{state:o,permission:n};throw new r(`INVALID_ARGS`,`Maestro permission "${e}" does not accept "${t}".`,{hint:`Use ${[`allow`,`deny`,`unset`,...Object.keys(i??{})].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),i=await e.invoke(d({...n,flags:ml(e.flags,n.flags??{})}));if(!i.ok)throw bl(i);if(t.kind===`gestureViewport`){let e=i.data?.viewport;if(typeof e!=`object`||!e||![`x`,`y`,`width`,`height`].every(t=>typeof e[t]==`number`))throw new r(`COMMAND_FAILED`,`runtime gesture-viewport returned no valid viewport.`);return e}return i.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 i=t.source?.path??n;if(!i)throw new r(`INVALID_ARGS`,`Maestro runScript file paths require a source path.`);return D.resolve(D.dirname(i),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 r(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,i,a,o,s=0,c=0,l=async n=>{c+=1;let i=await pl(e,{kind:`snapshot`});if(!i||!Array.isArray(i.nodes))throw new r(`COMMAND_FAILED`,`Maestro snapshot did not return node data.`);let a=m(i,i);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=>{i=t?.generation===e-1?{generation:e,snapshot:t.snapshot}:void 0,t=void 0,n=void 0},requireStability:e=>{o=e,a=i?.generation===e?i:void 0,i=void 0,n=void 0},consumeStabilityFromVisualWait:e=>{if(o!==void 0){if(o!==e.generation)throw new r(`COMMAND_FAILED`,`Maestro stability generation ${o} does not match ${e.generation}.`);o=void 0,a=void 0,i=void 0,n=void 0}},prime:(e,t)=>{n={generation:e,snapshot:t}},settlePending:async i=>{if(o===void 0)return;if(o!==i.generation)throw new r(`COMMAND_FAILED`,`Maestro stability generation ${o} does not match ${i.generation}.`);let s=t?.generation===i.generation?t.snapshot:a?.snapshot,c=await Oc({timeoutMs:$.settleTimeoutMs,context:i,snapshot:l,dependencies:e.dependencies,...s?{initialSnapshot:s}:{}});return o=void 0,a=void 0,n={generation:i.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,ce(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=n(e);return t.code===`AMBIGUOUS_MATCH`||t.code===`ELEMENT_NOT_FOUND`||t.code===`ELEMENT_OFFSCREEN`||t.details?.reason===se.selectorNotFound}async function Nl(e,t,n){if(!t)throw new r(`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},i=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 i=[];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 r?new r(e.code,e.message,{...e.details,appliedPermissionMutations:i,failedPermissionMutation:Pl(a)}):e}i.push(Pl(a))}},u=a===`android`?$.androidInputTextCharacterDelayMs:void 0,f=async(n,r,a)=>{v(n),await c({kind:`typeText`,text:n,...a===void 0?{}:{delayMs:a}},r);let o=await Oc({timeoutMs:$.settleTimeoutMs,context:r,snapshot:t.capture,dependencies:e.dependencies});i(o),t.prime(r.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:i}}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,i,a){let o=Wl(i);e(t,{type:`replay_action_stop`,ts:new Date().toISOString(),replayPath:n,...i.source.path&&i.source.path!==n?{sourcePath:i.source.path}:{},line:i.source.line,step:i.stepIndex,command:i.action,ok:a,durationMs:i.durationMs,...Object.keys(o).length>0?{resultTiming:o}:{},...!a&&`error`in i&&i.error instanceof r?{errorCode:i.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:s,session:{store:c,observationStore:l,logPath:u}}=n,{failure:d}=a,f=o(a.error);return d?await Yl(e,{error:f,failure:d,replayPath:r,req:s,sessionStore:c,observationStore:l,logPath:u,snapshotDiagnostics:tu(c,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{...oe(ae(e.flags?.replayShellEnv,t)),...ie(re(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 _e(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 r(`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=>T(e,Nr)})}}}const bu={create:yu};export{bu as maestroReplayBackendPlugin};
|