agent-device 0.21.10 → 0.21.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.10.apk → agent-device-android-ime-helper-0.21.12.apk} +0 -0
  2. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.12.apk.sha256 +1 -0
  3. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.10.manifest.json → agent-device-android-ime-helper-0.21.12.manifest.json} +4 -4
  4. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.10.apk → agent-device-android-snapshot-helper-0.21.12.apk} +0 -0
  5. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.12.apk.sha256 +1 -0
  6. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.10.manifest.json → agent-device-android-snapshot-helper-0.21.12.manifest.json} +6 -6
  7. package/apple/fold-helper/Fold.m +97 -0
  8. package/apple/macos-helper/Package.swift +1 -8
  9. package/apple/macos-helper/Sources/AgentDeviceMacOSHelper/main.swift +0 -2
  10. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotPresentationProjection.swift +2 -0
  11. package/dist/src/back-mode.js +1 -1
  12. package/dist/src/cli-help.js +4 -2
  13. package/dist/src/client-types.d.ts +2 -4
  14. package/dist/src/device-input-state.d.ts +1 -1
  15. package/dist/src/device-rotation.js +1 -1
  16. package/dist/src/helper.js +2 -2
  17. package/dist/src/interactor.js +3 -3
  18. package/dist/src/internal/bin.js +1 -1
  19. package/dist/src/internal/daemon.js +2 -2
  20. package/dist/src/macos-facade.js +1 -1
  21. package/dist/src/provider-webdriver.js +1 -1
  22. package/dist/src/registry.js +35 -35
  23. package/dist/src/runtime4.js +4 -4
  24. package/dist/src/script.js +1 -1
  25. package/dist/src/sdk-batch.js +1 -1
  26. package/dist/src/sdk-selectors.d.ts +12 -1
  27. package/dist/src/semantic-index.js +1 -1
  28. package/dist/src/simulator-facade.js +1 -1
  29. package/dist/src/simulator.js +1 -1
  30. package/package.json +2 -1
  31. package/server.json +2 -2
  32. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.10.apk.sha256 +0 -1
  33. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.10.apk.sha256 +0 -1
  34. package/apple/macos-helper/Sources/AgentDeviceMacOSDeviceHub/DeviceHubPose.swift +0 -47
  35. package/apple/macos-helper/Sources/AgentDeviceMacOSDeviceHub/DeviceHubWindowInventory.swift +0 -65
  36. package/apple/macos-helper/Sources/AgentDeviceMacOSHelper/DeviceHubPose.swift +0 -225
  37. package/apple/macos-helper/Sources/AgentDeviceMacOSHelper/DeviceHubSidebar.swift +0 -57
  38. package/apple/macos-helper/Sources/AgentDeviceMacOSHelper/DeviceHubWindowDiscovery.swift +0 -108
  39. package/apple/macos-helper/Tests/AgentDeviceMacOSDeviceHubTests/DeviceHubPoseTests.swift +0 -30
  40. package/apple/macos-helper/Tests/AgentDeviceMacOSDeviceHubTests/DeviceHubWindowInventoryTests.swift +0 -65
@@ -1,5 +1,5 @@
1
- import{D as e,O as t}from"./sdk-contracts.js";import{_ as n,i as r}from"./sdk-batch-runner.js";import{E as i,_ as a,d as o,f as s,l as c,o as l,u,w as d}from"./sdk-device.js";import{Yt as f,en as p,tn as m}from"./sdk-batch.js";import"./device.js";import{s as h}from"./device-rotation.js";import{c as ee,r as g}from"./diagnostics.js";import{n as te}from"./exec.js";import"./diagnostics2.js";import"./command.js";import{n as ne}from"./scoped-provider.js";import{i as re,n as ie,r as ae}from"./ios-snapshot-planning.js";import{n as oe,t as se}from"./fold-runtime.js";import{t as ce}from"./request.js";import{n as le,r as ue,t as de}from"./application-lifecycle-runtime.js";import{A as fe,C as pe,D as me,G as he,H as ge,I as _e,L as ve,N as ye,O as be,P as xe,R as Se,T as Ce,U as we,V as Te,a as Ee,b as De,g as Oe,j as ke,o as Ae,p as je,t as Me,u as Ne,v as Pe,w as Fe,x as Ie,z as Le}from"./alert-runtime.js";import{n as Re}from"./audio-probe-runtime.js";import{n as ze}from"./perf-runtime.js";import{i as Be,t as Ve}from"./touch-runtime.js";import{a as He,n as Ue}from"./durable-resource.js";import{n as We,t as Ge}from"./async-lifecycle.js";import{a as Ke,c as qe,d as Je,f as Ye,l as Xe,n as Ze,o as Qe,s as $e,t as et,u as tt}from"./src7.js";import{n as nt,t as rt}from"./screen-recording-completion.js";import{a as it,i as at,n as ot,o as st,r as ct,s as lt,t as ut}from"./stop-sequence.js";import{n as dt}from"./screen-recording-runtime.js";import{t as ft}from"./ios-system-surface.js";import{i as pt,r as mt}from"./gesture-admission.js";import{t as ht}from"./interactor-operation-catalog.js";import{a as gt,i as _t,n as vt,r as yt,t as bt}from"./perf-runtime-operation-builder.js";import{t as xt}from"./app-log-runtime.js";import{n as St}from"./artifact-paths.js";import{i as Ct,r as wt}from"./managed-device-scope.js";import{a as Tt,n as Et,o as Dt}from"./application-lifecycle-interaction.js";import{o as Ot,s as kt}from"./config.js";import{a as At,o as jt}from"./tool-provider.js";import{n as Mt}from"./apps-simctl.js";import{i as Nt,o as Pt,r as Ft}from"./simulator.js";import{a as It}from"./helper.js";import{r as Lt}from"./display-inventory.js";import{t as Rt}from"./multitouch-support.js";import{n as _,t as zt}from"./simulator-state.js";import{n as Bt,r as Vt,t as Ht}from"./snapshot-process.js";import Ut from"node:path";import{randomUUID as Wt}from"node:crypto";function Gt(e){let t=Ct();return Object.freeze(t?{...ne({...e},e=>Pt(t,e))}:e)}function Kt(e){return it(e)?Object.freeze({available:!0}):s(e)||o(e)&&e.kind===`simulator`?Object.freeze({available:!1,reason:`unsupported-device-backend`,hint:`audio probe capture requires a macOS host.`}):Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`audio is supported for macOS sessions and iOS simulators on macOS hosts; physical iOS devices expose no host audio tap.`})}function qt(e){let{resolveHost:t,device:n,owner:r}=e;return Object.freeze({...bt({platform:`Apple`,expectedProfileKind:`xctrace`,start:async e=>await t().start(n,r,e),reattach:async e=>await t().reattach(n,e),cleanup:async e=>await t().cleanup(n,e),writeProfileReport:async e=>await t().writeProfileReport(e)}),perfFrames:async({appId:e})=>({metric:e?await _t(t().sampleFrames(n,e)):vt(`Apple`,`bundle ID`),sampling:await t().frameSampling(n)}),perfMemorySample:async({appId:e})=>({metric:e?await _t(t().sampleMemory(n,e)):vt(`Apple`,`bundle ID`),sampling:await t().memorySampling(n)}),perfMemorySnapshot:async({appId:e,kind:r,outPath:i,artifactsDir:a})=>{let o=r??`memgraph`,s={...await t().memorySnapshotSupport(n),androidHprof:!1,heapprofd:!1};if(o!==`memgraph`)return gt(`Apple`,o,s,`Use perf memory snapshot --kind memgraph for supported Apple app sessions.`);if(!e)throw yt();let c=i??Ut.join(a,`memory-memgraph-${Jt()}.memgraph`);return{artifact:await t().captureMemorySnapshot(n,e,c),support:s,sampling:{method:`xcrun memgraph`,description:`Native Apple memory graph captured for offline inspection.`,defaultKind:`memgraph`,artifactOnly:!0}}}})}function Jt(){return new Date().toISOString().replaceAll(/[:.]/g,`-`)}const v=Object.freeze({available:!0}),y=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),b=Qt(`Gestures are supported only for Apple simulators and devices.`),Yt=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:mt}),Xt=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:pt}),Zt=Qt(`scroll is supported only for Apple simulators and devices.`);function Qt(e){return Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:e})}function $t(e){return{...ye({unsupported:en(e),plan:tn(e),directionalFling:tn(e),multiTouch:nn(e),targetAuthoredDrag:rn(e),viewport:an(e)}),...fe({scroll:on(e)})}}function en(e){return e.appleOs===`watchos`||e.appleOs===`visionos`?y:b}function tn(e){return e.appleOs===`watchos`||e.appleOs===`visionos`?y:x(e)?v:b}function nn(e){if(e.appleOs===`watchos`)return y;if(!x(e))return b;let t=d(e);if(t!==`ios`&&t!==`ipados`){let e=Rt[t];return Object.freeze({available:!1,reason:`unsupported-platform-leaf`,...e===void 0?{}:{hint:e}})}return e.kind===`simulator`?v:Yt}function rn(e){return x(e)?(e.appleOs===void 0?e.target!==`desktop`&&e.target!==`tv`:e.appleOs===`ios`||e.appleOs===`ipados`)?v:Xt:b}function an(e){return e.appleOs===`watchos`?y:x(e)?v:b}function on(e){return x(e)?v:Zt}function x(e){return e.kind===`simulator`||e.kind===`device`}const S=`This command requires a CoreDevice-backed physical iOS device. The selected XCTest backend supports open, close, interactions, snapshots, and screenshots.`;function C(e){return s(e)?`macos`:e.kind===`device`?`ios-device`:`ios-simulator`}const sn=Object.freeze({resourceKind:xt,version:1,encode:e=>({...e}),decode:e=>!ln(e.transport)||!un(e.backend)||!mn(e.outputPath)||!fn(e.pidPath)||!dn(e.transport,e.backend)?cn():{status:`decoded`,descriptor:Object.freeze({transport:e.transport,backend:e.backend,outputPath:e.outputPath,...e.pidPath===void 0?{}:{pidPath:e.pidPath}})}});function cn(){return{status:`invalid`,message:`Invalid Apple app-log descriptor`}}function ln(e){return e===`apple-log-stream`||e===`coredevice-console`}function un(e){return e===`ios-simulator`||e===`ios-device`||e===`macos`}function dn(e,t){return e===`coredevice-console`?t===`ios-device`:t!==`ios-device`}function fn(e){return e===void 0||mn(e)}function pn(e){if(!e.device.appleOs)throw TypeError(`Apple app-log persistence requires an explicit appleOs identity`);return Ue({resourceKind:xt,sessionId:e.sessionId,device:{id:e.device.id,family:`apple`,appleOs:e.device.appleOs,kind:e.device.kind,...e.device.target===void 0?{}:{target:e.device.target},...e.device.iosPhysicalDeviceBackend===void 0?{}:{iosPhysicalDeviceBackend:e.device.iosPhysicalDeviceBackend}},owner:e.owner,fence:e.fence,lifecycle:`open`,descriptor:He(sn,e.descriptor)})}function mn(e){return typeof e==`string`&&e.trim().length>0}const hn={message:`iOS physical-device app console capture is not supported by the installed devicectl.`,hint:`This devicectl does not expose process launch --console. Markers can still be written to app.log, but app output is not being captured. Use an iOS simulator for agent-device app logs or inspect physical-device logs in Console.app/Xcode until this Xcode toolchain exposes scriptable console capture.`},gn={message:`Could not verify iOS physical-device app console capture support.`,hint:`Retry logs clear --restart. If the probe keeps failing, run logs doctor and inspect the request diagnostics for the devicectl help command.`};async function _n(e,t){try{let n=await e.appleTools.run({tool:`devicectl`,args:[`device`,`process`,`launch`,`--help`],allowFailure:!0,timeoutMs:5e3},t),r=n.stderr.trim()||void 0;if(n.exitCode!==0)return{supported:!1,reason:`probe-failed`,stderr:r};let i=`${n.stdout}\n${n.stderr}`;return/\bUSAGE:\s+devicectl device process launch\b/i.test(i)&&/--console\b/.test(i)&&/--terminate-existing\b/.test(i)?{supported:!0,...r?{stderr:r}:{}}:{supported:!1,reason:`unsupported`,...r?{stderr:r}:{}}}catch(e){if(t?.aborted)throw t.reason;return{supported:!1,reason:`probe-failed`,...e instanceof Error?{stderr:e.message}:{}}}}async function vn(e,t,n,r){let i={},a=n?[]:[`No app bundle is tracked in this session. Run open <app> first for app-scoped logs.`];if(s(t))i.logAvailable=!!await e.commands.which(`log`);else if(t.kind===`simulator`)i.simctlAvailable=await lt(async()=>st(await e.appleTools.run({tool:`simctl`,args:[`help`],allowFailure:!0},r)),r);else if(t.iosPhysicalDeviceBackend===`xctest`)i.devicectlAvailable=!1,i.devicectlConsoleCapture=!1,a.push(S);else{i.devicectlAvailable=await lt(async()=>st(await e.appleTools.run({tool:`devicectl`,args:[`--version`],allowFailure:!0},r)),r);let t=await _n(e,r);if(i.devicectlConsoleCapture=t.supported,!t.supported){let e=t.reason===`unsupported`?hn:gn;a.push(`${e.message} ${e.hint}`)}}return{backend:C(t),checks:i,notes:a}}function yn(e,t){let n=Sn(e),r=[`subsystem == "${n}"`,`subsystem CONTAINS "${n}"`,`processImagePath ENDSWITH[c] "/${n}"`,`senderImagePath ENDSWITH[c] "/${n}"`];if(t){let e=Sn(t);r.push(`process == "${e}"`,`processImagePath ENDSWITH[c] "/${e}"`,`senderImagePath ENDSWITH[c] "/${e}"`,`processImagePath CONTAINS[c] "/${e}.app/"`,`senderImagePath CONTAINS[c] "/${e}.app/"`)}return r.join(` OR `)}function bn(e){return[...e.simulatorSetPath?[`simctl`,`--set`,e.simulatorSetPath]:[`simctl`],`spawn`,e.deviceId,`log`,`stream`,`--style`,`compact`,`--level`,`info`,`--predicate`,yn(e.appBundleId,e.executableName)]}function xn(e,t){return[`devicectl`,`device`,`process`,`launch`,`--device`,e,`--console`,`--terminate-existing`,t]}function Sn(e){return e.replaceAll(`\\`,String.raw`\\`).replaceAll(`"`,String.raw`\"`)}async function Cn(e,t,n,r,i){wn(t),Qe(e,n);let a=C(t),o=await En(e,t,n.appBundleId,i),s=new Ge,c=!1;try{let l=await e.outputs.openAppend(n.outputPath);s.defer(async()=>{c||await l[Symbol.asyncDispose]()}),i?.throwIfAborted();let u=await Tn(e,t,o,l,n.pidPath,i);s.defer(async()=>{c||await u[Symbol.asyncDispose]()});let d=On(e,u,l,a,n.outputPath),f={transport:a===`ios-device`?`coredevice-console`:`apple-log-stream`,backend:a,outputPath:n.outputPath,...n.pidPath===void 0?{}:{pidPath:n.pidPath}},p=Ye(d,pn({sessionId:n.sessionId,device:t,owner:r,fence:n.fence,descriptor:f}));return c=!0,p}finally{await s[Symbol.asyncDispose]()}}function wn(t){if(t.appleOs===`watchos`)throw new e(`UNSUPPORTED_PLATFORM`,`watchOS app logs are not supported`);if(o(t)&&t.kind===`device`&&t.iosPhysicalDeviceBackend===`xctest`)throw new e(`UNSUPPORTED_OPERATION`,S,{hint:S})}async function Tn(t,n,r,i,a,s){if(o(n)&&n.kind===`device`){let n=await _n(t,s);if(!n.supported){let t=n.reason===`unsupported`?hn:gn;throw new e(n.reason===`unsupported`?`UNSUPPORTED_OPERATION`:`COMMAND_FAILED`,t.message,{backend:`ios-device`,hint:t.hint,stderr:n.stderr})}}return s?.throwIfAborted(),await t.processes.start({command:{kind:`host`,request:r},output:i,...a?{markerPath:a}:{}})}async function En(e,t,n,r){if(s(t))return{executable:`log`,args:[`stream`,`--style`,`compact`,`--predicate`,yn(n)],allowFailure:!0};if(t.kind===`device`)return{executable:`xcrun`,args:xn(t.id,n),allowFailure:!0};let i=await Dn(e,t,n,r);return{executable:`xcrun`,args:bn({deviceId:t.id,appBundleId:n,executableName:i,simulatorSetPath:t.simulatorSetPath}),allowFailure:!0}}async function Dn(e,t,n,r){let i=t.simulatorSetPath?[`--set`,t.simulatorSetPath]:[],a=await e.appleTools.run({tool:`simctl`,args:[...i,`get_app_container`,t.id,n,`app`],allowFailure:!0,timeoutMs:4e3},r),o=a.exitCode===0?a.stdout.trim():``;if(!o)return;let s=await e.commands.run({executable:`plutil`,args:[`-extract`,`CFBundleExecutable`,`raw`,`-o`,`-`,Ut.join(o,`Info.plist`)],allowFailure:!0,timeoutMs:4e3},r);return s.exitCode===0&&s.stdout.trim()||void 0}function On(e,t,n,r,i){let a=e.clock.now(),o=`active`;t.wait.then(e=>{o=e.exitCode===0?`ended`:`failed`},()=>{o=`failed`});let s;return tt({inspect:()=>({backend:r,state:o,startedAt:a}),finish:async()=>s??=(async()=>(await kn([async()=>await t.terminate(),async()=>await t.wait.then(()=>void 0),async()=>await t[Symbol.asyncDispose](),async()=>await n[Symbol.asyncDispose]()])).length>0?(o=`failed`,{status:`cleanup-pending`,reason:`transport-failed`,message:`Apple app-log cleanup did not settle every owned resource`}):(o=`ended`,{status:`completed`,result:{backend:r,outputPath:i,completedAt:e.clock.now()}}))()})}async function kn(e){let t=[];for(let n of e)try{await n()}catch(e){t.push(e)}return t}const w=f(`apple`),T=Object.freeze({available:!0});function An(t){return Object.freeze({owner:w,ownsDevice:e=>e.platform===`apple`,inspectFacts:async e=>Mn(e),bind:async n=>{if(n.intent.kind===`exact-owner`&&!p(n.intent.owner,w))throw new e(`UNSUPPORTED_OPERATION`,`Apple app-log owner identity does not match`);return jn(t,n.device,n.scope.signal)},shutdown:async()=>void 0})}function jn(t,n,r){if(n.platform!==`apple`)throw new e(`UNSUPPORTED_PLATFORM`,`Apple app-log owner cannot bind ${n.platform}`);let i=Je({codec:sn,reattach:async(e,r)=>e.backend!==C(n)||!Ke(t,r.sessionId,e)?{status:`unreattachable`,reason:`descriptor-invalid`,message:`Apple app-log descriptor does not match the bound device or owning session`}:await qe(t,e.pidPath),cleanup:async(e,r)=>e.backend===C(n)&&Ke(t,r.sessionId,e)?await $e(t,e.pidPath):{status:`cleanup-pending`,reason:`ownership-fence-lost`,message:`Apple app-log descriptor does not match the bound device or owning session`}}),a=Object.freeze({appLogInspect:async()=>({backend:C(n)}),appLogDoctor:async({appBundleId:e})=>await vn(t,n,e,r),appLogStart:async e=>await Cn(t,n,e,w,r),...i});return Object.freeze({device:n,owner:w,facts:Mn(n),operations:a,[Symbol.asyncDispose]:async()=>void 0})}function Mn(e){if(e.appleOs===`watchos`)return Nn(e);let t=o(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?{available:!1,reason:`unsupported-device-backend`,hint:S}:T;return Object.freeze({device:{family:`apple`,appleOs:e.appleOs,kind:e.kind,...e.target===void 0?{}:{target:e.target},...e.iosPhysicalDeviceBackend===void 0?{}:{iosPhysicalDeviceBackend:e.iosPhysicalDeviceBackend},providerMode:`local`},operations:{appLogInspect:t,appLogDoctor:t,appLogStart:t,appLogReattach:T,appLogCleanup:T}})}function Nn(e){let t=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS app logs are not supported.`});return Object.freeze({device:{family:`apple`,appleOs:`watchos`,kind:e.kind,...e.target===void 0?{}:{target:e.target},providerMode:`local`},operations:{appLogInspect:t,appLogDoctor:t,appLogStart:t,appLogReattach:t,appLogCleanup:t}})}async function Pn(e,t,n,r){let i=C(t),a=await e.appLogs.readRecent(n.sessionId,n.maxScanLines),o=Ze(a.text,{...n,path:a.path,exists:a.exists,lineNumberOffset:a.skippedLines,backend:i}),s=[];if(In(t,n,o.dump)){let i=await Ln(e,t,n,a.path,r);i&&(o=Fn(s,o,i,n.maxEntries))}return Bn(s,t,n),zn(s,o.dump),o.dump.entries.length===0&&s.push(Vn(t)),Object.freeze({source:`app-log`,backend:i,dump:o.dump,notes:Object.freeze(s)})}function Fn(e,t,n,r){let i=n.scan.dump.entries.length;return i===0&&(n.scan.dump.unnamedRequests??0)===0?(n.lineCount>0&&e.push(`Recovered ${n.lineCount} recent iOS simulator app log lines from simctl log show, but none looked like HTTP traffic. This app may not emit request URLs, status, or timing into Unified Logging for this repro window.`),t):(i>0&&e.push(`Recovered ${i} iOS simulator HTTP entr${i===1?`y`:`ies`} from simctl log show (${n.lineCount} app log lines scanned).`),et(n.scan,t,r))}function In(e,t,n){return o(e)&&e.kind===`simulator`&&!!t.appBundleId&&n.entries.length===0}async function Ln(e,t,n,r,i){let a=[...t.simulatorSetPath?[`--set`,t.simulatorSetPath]:[],`spawn`,t.id,`log`,`show`,`--style`,`compact`,`--info`,`--predicate`,Rn(n.appBundleId)],o=n.appLogSnapshot?.startedAt;a.push(...typeof o==`number`&&Number.isFinite(o)&&o>0?[`--start`,`@${Math.floor(o/1e3)}`]:[`--last`,`5m`]);let s=await e.appleTools.run({tool:`simctl`,args:a,allowFailure:!0,timeoutMs:4e3},i);if(s.exitCode!==0||!s.stdout.trim())return;let c=s.stdout.split(`
1
+ import{D as e,O as t}from"./sdk-contracts.js";import{_ as n,i as r}from"./sdk-batch-runner.js";import{E as i,_ as a,d as o,f as s,l as c,o as l,u,w as d}from"./sdk-device.js";import{Yt as f,en as p,tn as m}from"./sdk-batch.js";import"./device.js";import{c as h}from"./device-rotation.js";import{c as ee,r as g}from"./diagnostics.js";import{n as _}from"./exec.js";import"./diagnostics2.js";import"./command.js";import{n as te}from"./version.js";import{n as ne}from"./scoped-provider.js";import{i as re,n as ie,r as ae}from"./ios-snapshot-planning.js";import{n as oe,t as se}from"./fold-runtime.js";import{t as ce}from"./request.js";import{n as le,r as ue,t as de}from"./application-lifecycle-runtime.js";import{A as fe,C as pe,D as me,G as he,H as ge,I as _e,L as ve,N as ye,O as be,P as xe,R as Se,T as Ce,U as we,V as Te,a as Ee,b as De,g as Oe,j as ke,o as Ae,p as je,t as Me,u as Ne,v as Pe,w as Fe,x as Ie,z as Le}from"./alert-runtime.js";import{n as Re}from"./audio-probe-runtime.js";import{n as ze}from"./perf-runtime.js";import{i as Be,t as Ve}from"./touch-runtime.js";import{a as He,n as Ue}from"./durable-resource.js";import{n as We,t as Ge}from"./async-lifecycle.js";import{a as Ke,c as qe,d as Je,f as Ye,l as Xe,n as Ze,o as Qe,s as $e,t as et,u as tt}from"./src7.js";import{n as nt,t as rt}from"./screen-recording-completion.js";import{a as it,i as at,n as ot,o as st,r as ct,s as lt,t as ut}from"./stop-sequence.js";import{n as dt}from"./screen-recording-runtime.js";import{t as ft}from"./ios-system-surface.js";import{i as pt,r as mt}from"./gesture-admission.js";import{t as ht}from"./interactor-operation-catalog.js";import{a as gt,i as _t,n as vt,r as yt,t as bt}from"./perf-runtime-operation-builder.js";import{t as xt}from"./app-log-runtime.js";import{n as St}from"./artifact-paths.js";import{i as Ct,r as wt}from"./managed-device-scope.js";import{a as Tt,n as Et,o as Dt}from"./application-lifecycle-interaction.js";import{m as Ot,x as kt}from"./host-file.js";import{o as At,s as jt}from"./config.js";import{a as Mt,o as v}from"./tool-provider.js";import{n as Nt}from"./apps-simctl.js";import{a as Pt,r as Ft}from"./simulator.js";import{r as It}from"./display-inventory.js";import{t as Lt}from"./multitouch-support.js";import{n as y,t as Rt}from"./simulator-state.js";import{n as zt,r as Bt,t as Vt}from"./snapshot-process.js";import b from"node:path";import{randomUUID as Ht}from"node:crypto";function Ut(e){let t=Ct();return Object.freeze(t?{...ne({...e},e=>Pt(t,e))}:e)}function Wt(e){return it(e)?Object.freeze({available:!0}):s(e)||o(e)&&e.kind===`simulator`?Object.freeze({available:!1,reason:`unsupported-device-backend`,hint:`audio probe capture requires a macOS host.`}):Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`audio is supported for macOS sessions and iOS simulators on macOS hosts; physical iOS devices expose no host audio tap.`})}function Gt(e){let{resolveHost:t,device:n,owner:r}=e;return Object.freeze({...bt({platform:`Apple`,expectedProfileKind:`xctrace`,start:async e=>await t().start(n,r,e),reattach:async e=>await t().reattach(n,e),cleanup:async e=>await t().cleanup(n,e),writeProfileReport:async e=>await t().writeProfileReport(e)}),perfFrames:async({appId:e})=>({metric:e?await _t(t().sampleFrames(n,e)):vt(`Apple`,`bundle ID`),sampling:await t().frameSampling(n)}),perfMemorySample:async({appId:e})=>({metric:e?await _t(t().sampleMemory(n,e)):vt(`Apple`,`bundle ID`),sampling:await t().memorySampling(n)}),perfMemorySnapshot:async({appId:e,kind:r,outPath:i,artifactsDir:a})=>{let o=r??`memgraph`,s={...await t().memorySnapshotSupport(n),androidHprof:!1,heapprofd:!1};if(o!==`memgraph`)return gt(`Apple`,o,s,`Use perf memory snapshot --kind memgraph for supported Apple app sessions.`);if(!e)throw yt();let c=i??b.join(a,`memory-memgraph-${Kt()}.memgraph`);return{artifact:await t().captureMemorySnapshot(n,e,c),support:s,sampling:{method:`xcrun memgraph`,description:`Native Apple memory graph captured for offline inspection.`,defaultKind:`memgraph`,artifactOnly:!0}}}})}function Kt(){return new Date().toISOString().replaceAll(/[:.]/g,`-`)}const x=Object.freeze({available:!0}),S=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),C=Xt(`Gestures are supported only for Apple simulators and devices.`),qt=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:mt}),Jt=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:pt}),Yt=Xt(`scroll is supported only for Apple simulators and devices.`);function Xt(e){return Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:e})}function Zt(e){return{...ye({unsupported:Qt(e),plan:$t(e),directionalFling:$t(e),multiTouch:en(e),targetAuthoredDrag:tn(e),viewport:nn(e)}),...fe({scroll:rn(e)})}}function Qt(e){return e.appleOs===`watchos`||e.appleOs===`visionos`?S:C}function $t(e){return e.appleOs===`watchos`||e.appleOs===`visionos`?S:w(e)?x:C}function en(e){if(e.appleOs===`watchos`)return S;if(!w(e))return C;let t=d(e);if(t!==`ios`&&t!==`ipados`){let e=Lt[t];return Object.freeze({available:!1,reason:`unsupported-platform-leaf`,...e===void 0?{}:{hint:e}})}return e.kind===`simulator`?x:qt}function tn(e){return w(e)?(e.appleOs===void 0?e.target!==`desktop`&&e.target!==`tv`:e.appleOs===`ios`||e.appleOs===`ipados`)?x:Jt:C}function nn(e){return e.appleOs===`watchos`?S:w(e)?x:C}function rn(e){return w(e)?x:Yt}function w(e){return e.kind===`simulator`||e.kind===`device`}const T=`This command requires a CoreDevice-backed physical iOS device. The selected XCTest backend supports open, close, interactions, snapshots, and screenshots.`;function E(e){return s(e)?`macos`:e.kind===`device`?`ios-device`:`ios-simulator`}const an=Object.freeze({resourceKind:xt,version:1,encode:e=>({...e}),decode:e=>!sn(e.transport)||!cn(e.backend)||!fn(e.outputPath)||!un(e.pidPath)||!ln(e.transport,e.backend)?on():{status:`decoded`,descriptor:Object.freeze({transport:e.transport,backend:e.backend,outputPath:e.outputPath,...e.pidPath===void 0?{}:{pidPath:e.pidPath}})}});function on(){return{status:`invalid`,message:`Invalid Apple app-log descriptor`}}function sn(e){return e===`apple-log-stream`||e===`coredevice-console`}function cn(e){return e===`ios-simulator`||e===`ios-device`||e===`macos`}function ln(e,t){return e===`coredevice-console`?t===`ios-device`:t!==`ios-device`}function un(e){return e===void 0||fn(e)}function dn(e){if(!e.device.appleOs)throw TypeError(`Apple app-log persistence requires an explicit appleOs identity`);return Ue({resourceKind:xt,sessionId:e.sessionId,device:{id:e.device.id,family:`apple`,appleOs:e.device.appleOs,kind:e.device.kind,...e.device.target===void 0?{}:{target:e.device.target},...e.device.iosPhysicalDeviceBackend===void 0?{}:{iosPhysicalDeviceBackend:e.device.iosPhysicalDeviceBackend}},owner:e.owner,fence:e.fence,lifecycle:`open`,descriptor:He(an,e.descriptor)})}function fn(e){return typeof e==`string`&&e.trim().length>0}const pn={message:`iOS physical-device app console capture is not supported by the installed devicectl.`,hint:`This devicectl does not expose process launch --console. Markers can still be written to app.log, but app output is not being captured. Use an iOS simulator for agent-device app logs or inspect physical-device logs in Console.app/Xcode until this Xcode toolchain exposes scriptable console capture.`},mn={message:`Could not verify iOS physical-device app console capture support.`,hint:`Retry logs clear --restart. If the probe keeps failing, run logs doctor and inspect the request diagnostics for the devicectl help command.`};async function hn(e,t){try{let n=await e.appleTools.run({tool:`devicectl`,args:[`device`,`process`,`launch`,`--help`],allowFailure:!0,timeoutMs:5e3},t),r=n.stderr.trim()||void 0;if(n.exitCode!==0)return{supported:!1,reason:`probe-failed`,stderr:r};let i=`${n.stdout}\n${n.stderr}`;return/\bUSAGE:\s+devicectl device process launch\b/i.test(i)&&/--console\b/.test(i)&&/--terminate-existing\b/.test(i)?{supported:!0,...r?{stderr:r}:{}}:{supported:!1,reason:`unsupported`,...r?{stderr:r}:{}}}catch(e){if(t?.aborted)throw t.reason;return{supported:!1,reason:`probe-failed`,...e instanceof Error?{stderr:e.message}:{}}}}async function gn(e,t,n,r){let i={},a=n?[]:[`No app bundle is tracked in this session. Run open <app> first for app-scoped logs.`];if(s(t))i.logAvailable=!!await e.commands.which(`log`);else if(t.kind===`simulator`)i.simctlAvailable=await lt(async()=>st(await e.appleTools.run({tool:`simctl`,args:[`help`],allowFailure:!0},r)),r);else if(t.iosPhysicalDeviceBackend===`xctest`)i.devicectlAvailable=!1,i.devicectlConsoleCapture=!1,a.push(T);else{i.devicectlAvailable=await lt(async()=>st(await e.appleTools.run({tool:`devicectl`,args:[`--version`],allowFailure:!0},r)),r);let t=await hn(e,r);if(i.devicectlConsoleCapture=t.supported,!t.supported){let e=t.reason===`unsupported`?pn:mn;a.push(`${e.message} ${e.hint}`)}}return{backend:E(t),checks:i,notes:a}}function _n(e,t){let n=bn(e),r=[`subsystem == "${n}"`,`subsystem CONTAINS "${n}"`,`processImagePath ENDSWITH[c] "/${n}"`,`senderImagePath ENDSWITH[c] "/${n}"`];if(t){let e=bn(t);r.push(`process == "${e}"`,`processImagePath ENDSWITH[c] "/${e}"`,`senderImagePath ENDSWITH[c] "/${e}"`,`processImagePath CONTAINS[c] "/${e}.app/"`,`senderImagePath CONTAINS[c] "/${e}.app/"`)}return r.join(` OR `)}function vn(e){return[...e.simulatorSetPath?[`simctl`,`--set`,e.simulatorSetPath]:[`simctl`],`spawn`,e.deviceId,`log`,`stream`,`--style`,`compact`,`--level`,`info`,`--predicate`,_n(e.appBundleId,e.executableName)]}function yn(e,t){return[`devicectl`,`device`,`process`,`launch`,`--device`,e,`--console`,`--terminate-existing`,t]}function bn(e){return e.replaceAll(`\\`,String.raw`\\`).replaceAll(`"`,String.raw`\"`)}async function xn(e,t,n,r,i){Sn(t),Qe(e,n);let a=E(t),o=await wn(e,t,n.appBundleId,i),s=new Ge,c=!1;try{let l=await e.outputs.openAppend(n.outputPath);s.defer(async()=>{c||await l[Symbol.asyncDispose]()}),i?.throwIfAborted();let u=await Cn(e,t,o,l,n.pidPath,i);s.defer(async()=>{c||await u[Symbol.asyncDispose]()});let d=En(e,u,l,a,n.outputPath),f={transport:a===`ios-device`?`coredevice-console`:`apple-log-stream`,backend:a,outputPath:n.outputPath,...n.pidPath===void 0?{}:{pidPath:n.pidPath}},p=Ye(d,dn({sessionId:n.sessionId,device:t,owner:r,fence:n.fence,descriptor:f}));return c=!0,p}finally{await s[Symbol.asyncDispose]()}}function Sn(t){if(t.appleOs===`watchos`)throw new e(`UNSUPPORTED_PLATFORM`,`watchOS app logs are not supported`);if(o(t)&&t.kind===`device`&&t.iosPhysicalDeviceBackend===`xctest`)throw new e(`UNSUPPORTED_OPERATION`,T,{hint:T})}async function Cn(t,n,r,i,a,s){if(o(n)&&n.kind===`device`){let n=await hn(t,s);if(!n.supported){let t=n.reason===`unsupported`?pn:mn;throw new e(n.reason===`unsupported`?`UNSUPPORTED_OPERATION`:`COMMAND_FAILED`,t.message,{backend:`ios-device`,hint:t.hint,stderr:n.stderr})}}return s?.throwIfAborted(),await t.processes.start({command:{kind:`host`,request:r},output:i,...a?{markerPath:a}:{}})}async function wn(e,t,n,r){if(s(t))return{executable:`log`,args:[`stream`,`--style`,`compact`,`--predicate`,_n(n)],allowFailure:!0};if(t.kind===`device`)return{executable:`xcrun`,args:yn(t.id,n),allowFailure:!0};let i=await Tn(e,t,n,r);return{executable:`xcrun`,args:vn({deviceId:t.id,appBundleId:n,executableName:i,simulatorSetPath:t.simulatorSetPath}),allowFailure:!0}}async function Tn(e,t,n,r){let i=t.simulatorSetPath?[`--set`,t.simulatorSetPath]:[],a=await e.appleTools.run({tool:`simctl`,args:[...i,`get_app_container`,t.id,n,`app`],allowFailure:!0,timeoutMs:4e3},r),o=a.exitCode===0?a.stdout.trim():``;if(!o)return;let s=await e.commands.run({executable:`plutil`,args:[`-extract`,`CFBundleExecutable`,`raw`,`-o`,`-`,b.join(o,`Info.plist`)],allowFailure:!0,timeoutMs:4e3},r);return s.exitCode===0&&s.stdout.trim()||void 0}function En(e,t,n,r,i){let a=e.clock.now(),o=`active`;t.wait.then(e=>{o=e.exitCode===0?`ended`:`failed`},()=>{o=`failed`});let s;return tt({inspect:()=>({backend:r,state:o,startedAt:a}),finish:async()=>s??=(async()=>(await Dn([async()=>await t.terminate(),async()=>await t.wait.then(()=>void 0),async()=>await t[Symbol.asyncDispose](),async()=>await n[Symbol.asyncDispose]()])).length>0?(o=`failed`,{status:`cleanup-pending`,reason:`transport-failed`,message:`Apple app-log cleanup did not settle every owned resource`}):(o=`ended`,{status:`completed`,result:{backend:r,outputPath:i,completedAt:e.clock.now()}}))()})}async function Dn(e){let t=[];for(let n of e)try{await n()}catch(e){t.push(e)}return t}const D=f(`apple`),O=Object.freeze({available:!0});function On(t){return Object.freeze({owner:D,ownsDevice:e=>e.platform===`apple`,inspectFacts:async e=>An(e),bind:async n=>{if(n.intent.kind===`exact-owner`&&!p(n.intent.owner,D))throw new e(`UNSUPPORTED_OPERATION`,`Apple app-log owner identity does not match`);return kn(t,n.device,n.scope.signal)},shutdown:async()=>void 0})}function kn(t,n,r){if(n.platform!==`apple`)throw new e(`UNSUPPORTED_PLATFORM`,`Apple app-log owner cannot bind ${n.platform}`);let i=Je({codec:an,reattach:async(e,r)=>e.backend!==E(n)||!Ke(t,r.sessionId,e)?{status:`unreattachable`,reason:`descriptor-invalid`,message:`Apple app-log descriptor does not match the bound device or owning session`}:await qe(t,e.pidPath),cleanup:async(e,r)=>e.backend===E(n)&&Ke(t,r.sessionId,e)?await $e(t,e.pidPath):{status:`cleanup-pending`,reason:`ownership-fence-lost`,message:`Apple app-log descriptor does not match the bound device or owning session`}}),a=Object.freeze({appLogInspect:async()=>({backend:E(n)}),appLogDoctor:async({appBundleId:e})=>await gn(t,n,e,r),appLogStart:async e=>await xn(t,n,e,D,r),...i});return Object.freeze({device:n,owner:D,facts:An(n),operations:a,[Symbol.asyncDispose]:async()=>void 0})}function An(e){if(e.appleOs===`watchos`)return jn(e);let t=o(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?{available:!1,reason:`unsupported-device-backend`,hint:T}:O;return Object.freeze({device:{family:`apple`,appleOs:e.appleOs,kind:e.kind,...e.target===void 0?{}:{target:e.target},...e.iosPhysicalDeviceBackend===void 0?{}:{iosPhysicalDeviceBackend:e.iosPhysicalDeviceBackend},providerMode:`local`},operations:{appLogInspect:t,appLogDoctor:t,appLogStart:t,appLogReattach:O,appLogCleanup:O}})}function jn(e){let t=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS app logs are not supported.`});return Object.freeze({device:{family:`apple`,appleOs:`watchos`,kind:e.kind,...e.target===void 0?{}:{target:e.target},providerMode:`local`},operations:{appLogInspect:t,appLogDoctor:t,appLogStart:t,appLogReattach:t,appLogCleanup:t}})}async function Mn(e,t,n,r){let i=E(t),a=await e.appLogs.readRecent(n.sessionId,n.maxScanLines),o=Ze(a.text,{...n,path:a.path,exists:a.exists,lineNumberOffset:a.skippedLines,backend:i}),s=[];if(Pn(t,n,o.dump)){let i=await Fn(e,t,n,a.path,r);i&&(o=Nn(s,o,i,n.maxEntries))}return Rn(s,t,n),Ln(s,o.dump),o.dump.entries.length===0&&s.push(zn(t)),Object.freeze({source:`app-log`,backend:i,dump:o.dump,notes:Object.freeze(s)})}function Nn(e,t,n,r){let i=n.scan.dump.entries.length;return i===0&&(n.scan.dump.unnamedRequests??0)===0?(n.lineCount>0&&e.push(`Recovered ${n.lineCount} recent iOS simulator app log lines from simctl log show, but none looked like HTTP traffic. This app may not emit request URLs, status, or timing into Unified Logging for this repro window.`),t):(i>0&&e.push(`Recovered ${i} iOS simulator HTTP entr${i===1?`y`:`ies`} from simctl log show (${n.lineCount} app log lines scanned).`),et(n.scan,t,r))}function Pn(e,t,n){return o(e)&&e.kind===`simulator`&&!!t.appBundleId&&n.entries.length===0}async function Fn(e,t,n,r,i){let a=[...t.simulatorSetPath?[`--set`,t.simulatorSetPath]:[],`spawn`,t.id,`log`,`show`,`--style`,`compact`,`--info`,`--predicate`,In(n.appBundleId)],o=n.appLogSnapshot?.startedAt;a.push(...typeof o==`number`&&Number.isFinite(o)&&o>0?[`--start`,`@${Math.floor(o/1e3)}`]:[`--last`,`5m`]);let s=await e.appleTools.run({tool:`simctl`,args:a,allowFailure:!0,timeoutMs:4e3},i);if(s.exitCode!==0||!s.stdout.trim())return;let c=s.stdout.split(`
2
2
  `).map(e=>e.trimEnd()).filter(e=>e.trim()&&!e.trim().startsWith(`Timestamp Ty Process[PID:TID]`));if(c.length!==0)return{scan:Ze(`${c.join(`
3
- `)}\n`,{...n,path:`${r} (simctl log show recovery)`,exists:!0,backend:`ios-simulator`}),lineCount:c.length}}function Rn(e){let t=e.replaceAll(`\\`,String.raw`\\`).replaceAll(`"`,String.raw`\"`);return[`subsystem == "${t}"`,`subsystem CONTAINS "${t}"`,`processImagePath ENDSWITH[c] "/${t}"`,`senderImagePath ENDSWITH[c] "/${t}"`].join(` OR `)}function zn(e,t){let n=t.entries.filter(e=>e.pathUnavailable).length,r=t.unnamedRequests??0,i=n+r;if(i===0)return;let a=[`${i} request${i===1?``:`s`} reused a keep-alive connection, so CFNetwork logged no request URL.`];n>0&&a.push(`${n} listed against the origin the connection was opened for, without a path.`),r>0&&a.push(`${r} opened before this scan window and are missing from the entries entirely; scan more lines, or run logs clear --restart before the repro.`),a.push(`Absence of an endpoint in this dump does not prove it was not called.`),e.push(a.join(` `))}function Bn(e,t,n){n.appLogSnapshot?n.appLogSnapshot.state!==`active`&&e.length===0&&e.push(o(t)&&t.kind===`simulator`?`Session app log stream is inactive. The iOS simulator recovery path scanned recent simctl log history, but a fresh logs clear --restart window is still the most reliable repro loop.`:`Session app log stream is inactive. Run logs clear --restart, reproduce the request window again, then rerun network dump.`):e.push(`Capture uses the session app log file. For fresh traffic, run logs clear --restart before reproducing requests.`)}function Vn(e){return o(e)&&e.kind===`simulator`?`No HTTP(s) entries were found in recent iOS simulator app logs. If the app only emits non-HTTP diagnostics, inspect logs path or add app-side URLSession/network logging for per-request timing and payload details.`:o(e)?`No HTTP(s) entries were found in recent iOS device app logs. iOS network dump only sees what the app emits into Unified Logging for this process.`:`No HTTP(s) entries were found in recent session app logs.`}async function Hn(e){let{host:n,snapshot:r,targetLabel:i,recorderWarning:a,nativePathDisposition:o}=e,s=r.invalidatedReason?{recorder:`lost`,why:`owner-session-lost`}:e.stopObservation;if(r.invalidatedReason&&!r.showTouches)throw Error(`recording invalidated: ${r.invalidatedReason}`);let c;try{c=await n.screenRecording.finalize.complete({outputPath:r.outPath,showTouches:!r.invalidatedReason&&r.showTouches,gestureEvents:r.gestureEvents,exportQuality:r.exportQuality??`medium`,targetLabel:i})}catch(e){throw t(e,`COMMAND_FAILED`)}let l=[...c.warning?[c.warning]:[],...a?[a]:[]];return rt(r,{...c,...l.length>0?{warning:l.join(` `)}:{},...r.invalidatedReason?{overlayWarning:`overlay unavailable: ${r.invalidatedReason}`}:{}},{stopObservation:s,...o===void 0?{}:{nativePathDisposition:o}})}async function Un(e){let{host:t,snapshot:n,targetLabel:r,collectedPath:i,exportPath:a,nativePath:o}=e;if(n.invalidatedReason&&!n.showTouches)throw Error(`recording invalidated: ${n.invalidatedReason}`);let s=e.overlayUnavailable??n.invalidatedReason,c;try{await t.screenRecording.outputs.copy({from:i,to:a}),c=await Wn(()=>t.screenRecording.finalize.complete({outputPath:a,showTouches:s===void 0&&n.showTouches,gestureEvents:n.gestureEvents,exportQuality:n.exportQuality??`medium`,targetLabel:r}))}catch(e){throw await t.screenRecording.outputs.remove(a),e}return{...c,...s===void 0?{}:{overlayWarning:`overlay unavailable: ${s}`},nativePathDisposition:await t.screenRecording.outputs.remove(o)===`removed`?`retired`:`retirable`}}async function Wn(e){try{return await e()}catch(e){throw t(e,`COMMAND_FAILED`)}}const Gn=[`outPath`,`startedAt`,`clientOutPath`,...ct],E=Object.freeze({resourceKind:dt,version:1,encode:e=>e.backend===`simctl`?{backend:e.backend,outputPath:e.outputPath,processes:e.processes.map(e=>({...e})),...e.recording===void 0?{}:{recording:{...e.recording}}}:{backend:e.backend,outputPath:e.outputPath,appBundleId:e.appBundleId,runnerSessionId:e.runnerSessionId,runnerAuthority:e.runnerAuthority,...e.remotePath===void 0?{}:{remotePath:e.remotePath}},decode:e=>rr(e)});function Kn(e){let{device:t,owner:n,input:r,descriptor:a}=e;return Ue({resourceKind:dt,sessionId:r.sessionId,device:i(t),owner:n,fence:r.fence,lifecycle:`open`,descriptor:He(E,a)})}function qn(e){let t={};for(let n of Gn)e[n]!==void 0&&Object.assign(t,{[n]:e[n]});return t}async function Jn(e,t,n,r){let i=E.decode(n);return i.status!==`decoded`||!pr(t,i.descriptor)?{status:`cleanup-pending`,reason:`manual-recovery-required`}:i.descriptor.backend===`simctl`?await Yn(e,i.descriptor.processes,r):await Zn(e,t,i.descriptor)}async function Yn(e,t,n){let r=await Promise.all(t.map(async t=>await e.screenRecording.apple.inspectProcess(t)));if(r.includes(`ownership-lost`))return{status:`cleanup-pending`,reason:`ownership-fence-lost`};if(r.every(e=>e===`missing`))return n!==void 0&&e.screenRecording.ownedProcesses.clear(Xn(n)),{status:`already-missing`};let i=await Promise.all(t.flatMap((t,n)=>r[n]===`owned-alive`?[e.screenRecording.apple.terminateProcess(t)]:[]));return i.includes(`ownership-lost`)?{status:`cleanup-pending`,reason:`ownership-fence-lost`}:(n!==void 0&&e.screenRecording.ownedProcesses.clear(Xn(n)),i.every(e=>e===`already-missing`)?{status:`already-missing`}:{status:`cleaned`})}function Xn(e){return{kind:`session`,sessionId:e}}async function Zn(e,t,n){try{let r=await e.screenRecording.apple.inspectRunner(t,n.runnerSessionId,n.runnerAuthority);return r===`missing`?{status:`already-missing`}:r===`ownership-lost`?{status:`cleanup-pending`,reason:`ownership-fence-lost`}:(await e.screenRecording.apple.runRunner(t,{kind:`stop`,appBundleId:n.appBundleId,runnerSessionId:n.runnerSessionId,runnerAuthority:n.runnerAuthority}),{status:`cleaned`})}catch(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:`Apple recording cleanup failed`}}}async function Qn(e){let{host:t,device:n,envelope:r}=e,i=E.decode(r.descriptor.body);return i.status===`decoded`?pr(n,i.descriptor)?i.descriptor.backend===`simctl`?await $n(e,i.descriptor):await tr(t,n,i.descriptor):D(`descriptor-invalid`,`Apple screen-recording descriptor does not match the bound device.`):D(`descriptor-invalid`,i.message)}async function $n(e,t){let n=await Promise.all(t.processes.map(async t=>await e.host.screenRecording.apple.inspectProcess(t)));if(!n.every(e=>e===`missing`))return D(`transport-not-reattachable`,n.includes(`ownership-lost`)?`Apple recording ownership no longer matches the durable descriptor.`:`Apple screen recordings require exact cleanup after daemon restart.`);let{recording:r}=t,i=er(ot(e.envelope.metadata),t.outputPath);return r===void 0||i!==void 0&&!await nr(e.host,i)?{status:`missing`}:{status:`restore-export`,recording:r,nativePath:t.outputPath,cleanup:async()=>await Yn(e.host,t.processes,e.envelope.sessionId)}}function er(e,t){if(e.finalization===void 0)return e.collectedPath??t}async function tr(e,t,n){let r=await e.screenRecording.apple.inspectRunner(t,n.runnerSessionId,n.runnerAuthority);return r===`missing`?{status:`missing`}:D(`transport-not-reattachable`,r===`ownership-lost`?`Apple recording ownership no longer matches the durable descriptor.`:`Apple screen recordings require exact cleanup after daemon restart.`)}async function nr(e,t){try{return await e.screenRecording.finalize.sniff({outputPath:t}),!0}catch{return!1}}function D(e,t){return{status:`unreattachable`,reason:e,message:t}}function rr(e){return typeof e.outputPath!=`string`||e.outputPath.length===0?k():e.backend===`simctl`?ir(e,e.outputPath):e.backend===`runner`?sr(e,e.outputPath):k()}function ir(e,t){let n=mr(e.processes),r=ar(e.recording);return!n||r===`invalid`?k():{status:`decoded`,descriptor:Object.freeze({backend:`simctl`,outputPath:t,processes:n,...r===void 0?{}:{recording:r}})}}function ar(e){if(e!==void 0)return n(e)&&or(e)?Object.freeze(e):`invalid`}function or(e){return O(e.outPath)&&lr(e.startedAt)&&cr(e.clientOutPath)&&at(e)}function sr(e,t){return!O(e.appBundleId)||!O(e.runnerSessionId)||!ur(e.runnerAuthority)||!dr(e.remotePath)?k():{status:`decoded`,descriptor:Object.freeze({backend:`runner`,outputPath:t,appBundleId:e.appBundleId,runnerSessionId:e.runnerSessionId,runnerAuthority:e.runnerAuthority,...e.remotePath===void 0?{}:{remotePath:e.remotePath}})}}function O(e){return typeof e==`string`&&e.length>0}function cr(e){return e===void 0||O(e)}function lr(e){return typeof e==`number`&&Number.isFinite(e)}function ur(e){return e===`local-lease`||e===`scoped-provider`}function dr(e){return e===void 0||fr(e)}function fr(e){return typeof e==`string`&&/^tmp\/agent-device-recording-\d+\.mp4$/.test(e)}function pr(e,t){return e.kind===`simulator`?t.backend===`simctl`:t.backend===`runner`?e.appleOs===`macos`?t.remotePath===void 0:o(e)?t.remotePath!==void 0&&fr(t.remotePath):t.remotePath===void 0:!1}function mr(e){if(!Array.isArray(e)||e.length===0)return;let t=e.filter(e=>typeof e==`object`&&!!e&&Number.isInteger(e.pid)&&(e.pid??0)>0&&typeof e.startTime==`string`&&e.startTime.length>0&&typeof e.command==`string`&&e.command.length>0);return t.length===e.length?Object.freeze([...t]):void 0}function k(){return{status:`invalid`,message:`Invalid Apple screen-recording descriptor`}}async function hr(e,t,n){if(e.kind!==`simulator`||t.scope!==`app`)return;let r=t.activeSessionApp?.bundleId;if(!r)throw TypeError(`App-scoped recording requires an active app session; open the app under test before recording.`);if(await n(r))throw TypeError(`App-scoped recording requires a real application session; open the app under test before recording.`)}const gr=`iOS recording`,_r=`simctl recordVideo`;function vr(e){return e.appleOs===`watchos`?Mr(`unsupported-platform-leaf`,`watchOS recording is not supported.`):o(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?Mr(`unsupported-device-backend`,`This command requires a CoreDevice-backed physical iOS device. The selected XCTest backend supports open, close, interactions, snapshots, and screenshots.`):Object.freeze({available:!0})}function yr(e){let{host:t,device:n,owner:r,signal:i}=e;return Object.freeze({screenRecordingStart:async e=>await br({host:t,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async e=>{let r=await Qn({host:t,device:n,envelope:e.envelope});return r.status===`restore-export`?{status:`active`,handle:Sr({host:t,restored:r})}:r},screenRecordingCleanup:async e=>await Jn(t,n,e.envelope.descriptor.body,e.envelope.sessionId)})}async function br(e){return e.signal.throwIfAborted(),e.device.kind===`simulator`?await xr(e):await wr(e)}async function xr(e){let{host:t,device:n,owner:r,input:i,signal:a}=e;await hr(n,i,t.screenRecording.apple.isRunnerBundleId);let o=i.activeSessionApp?await t.screenRecording.apple.captureClockAnchor(n,i.activeSessionApp.bundleId,a):void 0,s=St(i.outputPath);await t.screenRecording.outputs.prepare(s);let c=await t.screenRecording.apple.startSimulator(n,s,a),l=c.markers;if(!l||l.length===0)throw await A(c).catch(()=>{}),Error(`simctl recordVideo did not expose durable process identity`);try{a.throwIfAborted(),t.screenRecording.ownedProcesses.replace({kind:`session`,sessionId:i.sessionId},l.map(e=>({...e,purpose:`simctl-screen-recording`})))}catch(e){try{t.screenRecording.ownedProcesses.clear({kind:`session`,sessionId:i.sessionId})}catch{}throw await A(c).catch(()=>{}),e}let u,d,f=async()=>{await c.terminate();let e=await c.wait;return d=e,u=Er(e),t.screenRecording.ownedProcesses.clear({kind:`session`,sessionId:i.sessionId}),{observation:{recorder:`confirmed`},...u===void 0?{}:{warning:`${u} before record stop; the video covers only what the recorder wrote before it stopped.`}}},p=jr(i,_r,{},o);return Ar({device:n,owner:r,input:i,descriptor:{backend:`simctl`,outputPath:s,processes:l,recording:qn(p)},snapshot:p,finish:(e,n)=>ut({snapshot:e,progress:n,steps:{stop:f,collect:async e=>{try{await Cr(t,s,e)}catch(e){throw Dr(e,u,d)}},finalize:async({collectedPath:n,exportPath:r})=>{try{return await Un({host:t,snapshot:e,targetLabel:gr,collectedPath:n,exportPath:r,nativePath:s})}catch(e){throw Dr(e,u,d)}},discard:async e=>{await t.screenRecording.outputs.remove(e)}}}),cleanup:async()=>{let e=await kr(c);return(e.status===`cleaned`||e.status===`already-missing`)&&t.screenRecording.ownedProcesses.clear({kind:`session`,sessionId:i.sessionId}),e}})}function Sr(e){let{host:t,restored:{recording:n,nativePath:r,cleanup:i}}=e,a=Object.freeze({...n,backend:_r,gestureEvents:[]});return nt(a,{finish:(e,i)=>ut({snapshot:e,progress:i,steps:{stop:async()=>({observation:{recorder:`confirmed`},warning:`simctl recordVideo had already ended when record stop reattached to it; the video covers only what the recorder wrote before it stopped.`}),collect:async e=>{await Cr(t,r,e)},finalize:async({collectedPath:i,exportPath:a})=>await Un({host:t,snapshot:e,targetLabel:gr,collectedPath:i,exportPath:a,nativePath:r,...n.showTouches?{overlayUnavailable:`the daemon that held the touch events ended before record stop`}:{}}),discard:async e=>{await t.screenRecording.outputs.remove(e)}}}),forceCleanup:async()=>await i()})}async function Cr(e,t,n){await e.screenRecording.outputs.copy({from:t,to:n}),await e.screenRecording.finalize.sniff({outputPath:n})}async function wr(e){let{host:t,device:n,owner:r,input:i,signal:a}=e,o=i.activeSessionApp?.bundleId;if(!o)throw TypeError(`Apple runner recording requires an active app session identity`);await t.screenRecording.outputs.prepare(i.outputPath);let s=await t.screenRecording.apple.runRunner(n,{kind:`start`,appBundleId:o,outputPath:i.outputPath,...i.fps===void 0?{}:{fps:i.fps}},a);if(!s.runnerSessionId||!s.runnerAuthority)throw Error(`Apple runner recording did not expose durable session ownership`);let c={runnerSessionId:s.runnerSessionId,runnerAuthority:s.runnerAuthority},l,u=()=>(l??=Tr(()=>t.screenRecording.apple.runRunner(n,{kind:`stop`,appBundleId:o,...c}).then(()=>void 0)).catch(e=>{throw l=void 0,e}),l);if(!Or(n,s.remotePath))throw await u().catch(()=>{}),Error(`Apple runner recording did not expose coherent durable media ownership`);try{a.throwIfAborted()}catch(e){throw await u().catch(()=>{}),e}return Ar({device:n,owner:r,input:i,descriptor:{backend:`runner`,outputPath:i.outputPath,appBundleId:o,...c,...s.remotePath===void 0?{}:{remotePath:s.remotePath}},snapshot:jr(i,`runner AVAssetWriter`,s),finish:async e=>(await u(),s.remotePath!==void 0&&await t.screenRecording.apple.retrieveRunnerRecording(n,s.remotePath,e.outPath),await Hn({host:t,snapshot:e,targetLabel:n.appleOs===`macos`?`macOS recording`:`iOS recording`,stopObservation:{recorder:`confirmed`},...s.remotePath===void 0?{}:{nativePathDisposition:`retirable`}})),cleanup:async()=>(await u(),{status:`cleaned`})})}async function Tr(e){try{return await e()}catch(e){throw t(e,`COMMAND_FAILED`)}}function Er(e){if(e.exitCode!==0)return e.signal?`simctl recordVideo was killed by ${e.signal}`:`simctl recordVideo exited with code ${e.exitCode}`}function Dr(n,r,i){let a=t(n,`COMMAND_FAILED`);return r===void 0||i===void 0||a.details?.reason!==`recording-output-unplayable`?n:new e(a.code,`${a.message}; ${r}`,te(i,{...a.details??{},...i.signal===void 0?{}:{signal:i.signal},retriable:!1,hint:`The recorder exited before record stop, so the next record stop reads the same file. Close this session to release the device, then record again.`}))}function Or(e,t){return e.appleOs===`macos`||!o(e)?t===void 0:t!==void 0&&/^tmp\/agent-device-recording-\d+\.mp4$/.test(t)}async function A(e){return await e.terminate(),await e.wait}async function kr(e){try{return await A(e),{status:`cleaned`}}catch(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:`Apple simulator cleanup failed`}}}function Ar(e){let{device:t,owner:n,input:r,descriptor:i,snapshot:a,finish:o,cleanup:s}=e,c=nt(a,{finish:o,forceCleanup:s});return Object.freeze({pendingHandle:new We(c),envelope:Kn({device:t,owner:n,input:r,descriptor:i})})}function jr(e,t,n={},r){let i=Date.now();return Object.freeze({backend:t,outPath:e.outputPath,...e.clientOutputPath===void 0?{}:{clientOutPath:e.clientOutputPath},startedAt:i,scope:e.scope,showTouches:e.showTouches,recordOnlySession:e.recordOnlySession,...e.activeSessionApp===void 0?{}:{activeSessionApp:e.activeSessionApp},...e.exportQuality===void 0?{}:{exportQuality:e.exportQuality},gestureEvents:[],...r===void 0?{}:{gestureClockOriginAtMs:r.wallClockAtMs,gestureClockOriginUptimeMs:r.uptimeMs},...n.recorderStartUptimeMs===void 0?{}:{gestureClockOriginAtMs:i,gestureClockOriginUptimeMs:n.recorderStartUptimeMs,runnerStartedAtUptimeMs:n.recorderStartUptimeMs},...n.runnerSessionId===void 0?{}:{runnerSessionId:n.runnerSessionId}})}function Mr(e,t){return Object.freeze({available:!1,reason:e,hint:t})}const Nr=15e3;async function j(e,t,n,r={}){return n.throwIfAborted(),await wt(t)||s(t)?{...t,booted:!0}:t.kind===`device`?(await e.deviceReadiness.applePhysical.ensureConnected(t,n),{...t,booted:!0}):t.kind===`simulator`?((await Pr(e,t)?`Booted`:await Rr(e,t,n))!==`Booted`&&(r.onColdBootStart?.(),e.deviceReadiness.appleAutomation.keepHot(t),await Fr(e,t,n,r.deadlineAtMs),await zr(e,n)),e.deviceReadiness.appleAutomation.keepHot(t),e.deviceReadiness.appleAutomation.markBooted(t),{...t,booted:!0}):{...t,booted:!0}}async function Pr(e,t){try{return await e.deviceReadiness.appleAutomation.wasRecentlyObservedBooted(t)}catch{return!1}}async function Fr(e,t,n,r=Date.now()+12e4){let i=!1;try{i=await Ir(e,t,n,r),await Lr(e,t,n,r)}catch(a){throw i&&n.aborted&&Br(e,t),n.throwIfAborted(),Date.now()>=r?N(t,a):a}}async function Ir(t,n,r,i){let a=await t.appleTools.run({tool:`simctl`,args:_(n,[`boot`,n.id]),allowFailure:!0,timeoutMs:M(i,n)},r),o=`${a.stdout}\n${a.stderr}`.toLowerCase(),s=o.includes(`already booted`)||o.includes(`current state: booted`);if(a.exitCode!==0&&!s)throw new e(`COMMAND_FAILED`,`simctl boot failed`,{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode});return!s}async function Lr(t,n,r,i){ce({type:`command`,status:`progress`,message:`Waiting for the Simulator to finish booting...`});let a=await t.appleTools.run({tool:`simctl`,args:_(n,[`bootstatus`,n.id,`-b`]),allowFailure:!0,timeoutMs:M(i,n)},r);if(a.exitCode!==0)throw new e(`COMMAND_FAILED`,`simctl bootstatus failed`,{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode});if(await zt(t.appleTools,n,r,Math.min(Nr,M(i,n)))!==`Booted`)throw new e(`COMMAND_FAILED`,`Simulator is still booting`,{deviceId:n.id});if(Date.now()>=i)throw N(n)}function M(e,t){let n=e-Date.now();if(n<=0)throw N(t);return n}function N(t,n){return new e(`COMMAND_FAILED`,`Simulator did not finish booting within the startup budget`,{reason:`boot_timeout`,deviceId:t.id,hint:`The Simulator keeps booting in the background; a first boot can take several minutes. Retry once it is up, or pass a larger --timeout.`},n instanceof Error?n:void 0)}async function Rr(e,t,n){return await zt(e.appleTools,t,n,Nr)}async function zr(e,t){await e.commands.run({executable:`open`,args:[`-a`,`Simulator`],allowFailure:!0,timeoutMs:1e4},t)}function Br(e,t){e.appleTools.run({tool:`simctl`,args:_(t,[`shutdown`,t.id]),allowFailure:!0}).catch(()=>{})}const Vr=Object.freeze({resolveOpenTarget:`simulator`,prepareApplicationOpen:`simulator`,openApplication:`simulator`,applyRuntimeHints:`simulator`,clearRuntimeHints:`simulator`,closeApplication:`simulator`,finalizeApplicationClose:`simulator`,prepareAppleRunner:`runner`,configureProviderPortReverse:`simulator`,ensureReady:`simulator`,bootTarget:`simulator`,bootTargetHeadless:`simulator`,shutdownTarget:`simulator`,listApps:`simulator`,deployApp:`simulator`,materializeAppSource:`simulator`,deployMaterializedApp:`simulator`,sendPushNotification:`simulator`,appState:`simulator`,appLogStart:`simulator`,appLogInspect:`simulator`,appLogDoctor:`simulator`,appLogReattach:`simulator`,appLogCleanup:`simulator`,networkDump:`simulator`,audioProbeStart:`simulator`,audioProbeQuery:`simulator`,audioProbeReattach:`simulator`,audioProbeCleanup:`simulator`,readClipboard:`simulator`,writeClipboard:`simulator`,setSetting:`simulator`,readSetting:`simulator`,setFoldPose:`simulator`,captureSnapshot:`simulator`,captureSnapshotWithoutActiveApp:`simulator`,captureSnapshotWithCustomActions:`runner`,captureScreenshot:`simulator`,findText:`runner`,readTextAtPoint:`runner`,tapPoint:`runner`,tapRef:`runner`,tapElementSelector:`runner`,fillPoint:`runner`,fillRef:`runner`,longPressPoint:`runner`,hoverPoint:`runner`,hoverRef:`runner`,focusPoint:`runner`,typeText:`runner`,scrollDirection:`runner`,performGesturePlan:`runner`,performMultiTouchGesturePlan:`runner`,performTargetAuthoredDrag:`runner`,performDirectionalFlingPlan:`runner`,gestureViewport:`runner`,setViewport:`runner`,back:`runner`,home:`runner`,setOrientation:`runner`,appSwitcher:`runner`,actionButton:`runner`,tvRemote:`runner`,keyboardDismiss:`runner`,keyboardEnter:`runner`,keyboardStatus:`runner`,triggerAppEvent:`runner`,readAlert:`runner`,awaitAlert:`runner`,acceptAlert:`runner`,dismissAlert:`runner`,perfFrames:`runner`,perfMemorySample:`runner`,perfMemorySnapshot:`runner`,perfNativeCaptureStart:`runner`,perfNativeCaptureReattach:`runner`,perfNativeCaptureCleanup:`runner`,perfProfileReport:`runner`,screenRecordingStart:`runner`,screenRecordingReattach:`runner`,screenRecordingCleanup:`runner`});function Hr(e){return e===void 0?`possible`:e.some(e=>Vr[e]===`runner`)?`required`:`none`}const Ur=new Map([[`application-element-missing`,5e3],[`application-server-unavailable`,5e3],[`foreground-owner-unverified`,1e3],[`foreground-owner-changed`,1e3]]);function P(e){return e.platform===`apple`&&e.appleOs===`ios`&&e.kind===`simulator`}function Wr(e){let t=re(ae({depth:1,interactiveOnly:!0}));return Object.freeze({awaitObservable:async(n,r,i)=>{if(!P(n))return`not-eligible`;let a;for(;;){let o=await e.resolveTarget(n,r,i).catch(()=>void 0);if(i.throwIfAborted(),!o)return`unobservable`;if(e.isBridgeDisabled(o))return g({level:`debug`,phase:`ios_launch_observation_skipped`,data:{reason:`circuit-disabled`,deviceId:n.id,generation:o.generation}}),`unobservable`;let s=await e.source.acquire({target:o,hint:t,signal:i});if(s.stage!==`failed`)return`observable`;i.throwIfAborted();let c=Ur.get(s.failure.code);if(c===void 0)return`unobservable`;let l=e.clock.now();if(a=Math.min(a??1/0,l+c),l>=a)return`unobservable`;await e.clock.sleep(Math.min(150,a-l),i)}}})}function Gr(e,t,n){let r=n&&P(e),i=r?Hr(t.execution.plannedOperations):void 0,a=o(e)&&t.surface===`app`&&t.positionals.length>0&&!!t.appBundleId&&i!==`none`;return{...i?{runnerDemand:i}:{},shouldPrewarmRunner:a,awaitPrewarmAfterOpen:t.relaunch&&!r}}function Kr(e,t,n,r){r.runnerDemand===`none`&&e.appleApplications.releaseSpeculativeRunner(t.device,n.execution).catch(()=>{})}async function qr(e,t,n,r,i,a){let o=Date.now();r&&P(t.device)&&i&&n.appBundleId&&(a.postOpenObservation=await i.awaitObservable(t.device,n.appBundleId,t.signal)),r&&a.postOpenObservation!==`observable`&&await e.clock.sleep(300,t.signal),a.postOpenSettleDurationMs=Math.max(0,Date.now()-o)}function Jr(e){let t=Et({device:e.device,signal:e.signal,resolveInteractor:e.host.localInteractors.resolve});return Object.freeze({resolveOpenTarget:async t=>await e.host.appleApplications.resolveOpenTarget(e.device,t),prepareApplicationOpen:async t=>{await j(e.host,e.device,e.signal,{deadlineAtMs:t.execution.startupDeadlineAtMs,onColdBootStart:t.prewarmRunnerOnColdBoot?()=>{e.host.appleApplications.prewarmRunnerCache(e.device,t.execution,e.signal).catch(()=>{})}:void 0})},openApplication:async n=>await Yr(e.host,t,n,e.observation),applyRuntimeHints:async t=>await e.host.appleApplications.applyRuntimeHints(e.device,t),clearRuntimeHints:async t=>await e.host.appleApplications.clearRuntimeHints(e.device,t),closeApplication:async n=>await ai(e.host,t,n),finalizeApplicationClose:async t=>await oi(e.host,e.device,e.signal,t),prepareAppleRunner:async t=>await si(e.host,e.device,e.signal,t),configureProviderPortReverse:fi})}async function Yr(e,t,n,r){let i={},a=F(t.device),o=ci(e,t,n,i),s=Gr(t.device,n,a);s.runnerDemand&&(i.runnerDemand=s.runnerDemand),Kr(e,t,n,s);let{shouldPrewarmRunner:c}=s,l=ii(t.device,n,a);a&&c&&!n.prewarmRunnerBeforeOpen&&o.schedule();try{await Xr(e,t,n,a,l,i),await Zr(n,i),await Qr(o,c,n.prewarmRunnerBeforeOpen);let u=o.wasAwaited();return await $r(t,n,a,i),await ti(o,c,s.awaitPrewarmAfterOpen),await ni(e,t,n,a,u,l),await qr(e,t,n,a,r,i),{appBundleId:n.appBundleId,timing:i}}catch(n){throw l&&await e.appleApplications.stopRunnerSession(t.device.id).catch(()=>{}),n}}async function Xr(e,t,n,r,i,a){if(!ri(n,r)||!n.target)return;let o=Date.now();c(t.device.platform)&&!r&&!i&&await e.appleApplications.stopRunnerSession(t.device.id),await Tt({device:t.device,interactor:await t.resolveInteractor(n.execution,n.appBundleId),positionals:[n.appBundleId??n.target]}),r&&await e.clock.sleep(300,t.signal),a.relaunchCloseDurationMs=I(o)}async function Zr(t,n){if(!ue(t.runtimeHints))return;if(!t.applyRuntimeHints)throw new e(`COMMAND_FAILED`,`Runtime hint operation was not admitted for this open.`,{reason:`runtime-hints-operation-missing`});let r=Date.now();await t.applyRuntimeHints({appId:t.appBundleId,values:t.runtimeHints}),n.runtimeHintsDurationMs=I(r)}async function Qr(e,t,n){!t||!n||(e.schedule(!0),await e.wait())}async function $r(e,t,n,r){let i=ui(t,n),a=Date.now();await Dt({device:e.device,interactor:await e.resolveInteractor(t.execution,t.appBundleId),positionals:i.positionals,appBundleId:t.appBundleId,execution:t.execution,...n&&t.relaunch&&!t.execution.clearAppState?{terminateRunningApp:!0}:{}}),r.openDispatchDurationMs=I(a),await ei(e,t,i.followUpUrl,r)}async function ei(e,t,n,r){if(!n){r.launchUrlDurationMs=0;return}let i={...t.execution,clearAppState:void 0,launchConsole:void 0,launchArgs:void 0},a=Date.now();await Dt({device:e.device,interactor:await e.resolveInteractor(i,t.appBundleId),positionals:[n],appBundleId:t.appBundleId,execution:i}),r.launchUrlDurationMs=I(a)}async function ti(e,t,n){t&&!e.wasScheduled()&&e.schedule(),n?await e.wait():e.recordUnawaited()}async function ni(e,t,n,r,i,a){!o(t.device)||!r&&!a||!n.relaunch&&!i||r&&!i&&!await e.appleApplications.hasLiveRunnerSession(t.device,n.execution)||await e.appleApplications.notifyRunnerAppRelaunched(t.device,n.execution,t.signal)}function ri(e,t){return!!(e.relaunch&&e.target)&&!(t&&!e.execution.clearAppState)}function ii(e,t,n){return e.kind===`device`&&e.appleOs===`ios`&&ri(t,n)}async function ai(e,t,n){n.ensureReady&&await j(e,t.device,t.signal),c(t.device.platform)&&!F(t.device)&&await e.appleApplications.stopRunnerSession(t.device.id),await Tt({device:t.device,interactor:await t.resolveInteractor(n.execution,n.appBundleId),positionals:n.positionals}),F(t.device)&&await e.clock.sleep(300,t.signal)}async function oi(e,t,n,r){r.daemonShutdown||await e.appleApplications.releaseRunnerOnClose(t.id,{retain:r.retainRunner}),await e.appleApplications.dismissCloseAlerts(t,r).catch(()=>{});let i=r.shutdownTarget&&F(t)?await e.deviceShutdown.apple.shutdownTarget(t,n):void 0;return i===void 0?{}:{shutdown:i}}async function si(e,t,n,r){let i=Date.now()+r.timeoutMs;await j(e,t,n,{deadlineAtMs:i});let a=Math.max(1,i-Date.now());return await e.appleApplications.prepareRunner(t,{...r,timeoutMs:a},n)}function ci(e,t,n,r){let i,a=!1,o=li(t.device,n)?{healthCheck:!1}:void 0;return{schedule:(a=!1)=>{i||=(r.runnerPrewarmKind=`session`,r.runnerPrewarmScheduled=!0,o?e.appleApplications.prewarmRunnerSession(t.device,n.execution,t.signal,a,o):e.appleApplications.prewarmRunnerSession(t.device,n.execution,t.signal,a))},wait:async()=>{if(!i||a)return;a=!0;let e=Date.now();await i,r.runnerPrewarmWaited=!0,r.runnerPrewarmDurationMs=I(e)},wasAwaited:()=>a,wasScheduled:()=>i!==void 0,recordUnawaited:()=>{i&&!a&&(r.runnerPrewarmWaited=!1)}}}function li(e,t){return e.kind===`device`&&e.appleOs===`ios`&&!t.hasExistingSession&&!t.relaunch&&!t.prewarmRunnerBeforeOpen}function ui(e,t){let n=e.runtimeLaunchUrl?.trim(),i=e.positionals.length===1?e.positionals[0]?.trim():void 0;return!n||!i||r(i)?{positionals:e.positionals}:t&&!di(e)?{positionals:[i,n]}:{positionals:e.positionals,followUpUrl:n}}function di(e){return e.execution.clearAppState===!0||!!e.execution.launchConsole?.trim()||!!e.execution.launchArgs?.length}function F(e){return o(e)&&e.kind===`simulator`}function I(e){return Math.max(0,Date.now()-e)}async function fi(){throw new e(`UNSUPPORTED_OPERATION`,`This lifecycle operation is unavailable for Apple.`)}const pi=Object.freeze({available:!0}),mi=Object.freeze({available:!1,reason:`unsupported-device-backend`,hint:`This command requires a CoreDevice-backed physical iOS device. The selected XCTest backend supports open, close, interactions, snapshots, and screenshots.`}),hi=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Push notifications are supported on Apple simulators only.`}),gi=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),_i=Object.freeze({available:!1,reason:`unsupported-device-kind`});function vi(e){let t=Ei(e);return Object.freeze({deployApp:t,materializeAppSource:t,deployMaterializedApp:t,sendPushNotification:Di(e)})}function yi(e){let{host:t,device:n,signal:r}=e,i=vi(n);return Object.freeze({...i.deployApp.available?{deployApp:async e=>await bi(t,n,e,r),materializeAppSource:async e=>await t.appleDeployment.prepareArtifact(e,{signal:r}),deployMaterializedApp:async e=>await xi(t,n,e,r)}:{},...i.sendPushNotification.available?{sendPushNotification:async e=>(await wi(t,n,e,r),{})}:{}})}async function bi(e,t,n,r){if(n.replaceExisting)return await e.appleDeployment.withInvalidatedAppResolutionCache(t,async()=>{let i=await e.appleDeployment.resolveAppBundleId(t,n.app);await Ci(e,t,i,r);let a=await e.appleDeployment.prepareArtifact({source:{kind:`path`,path:n.appPath}},{appIdentifierHint:n.app,signal:r});try{return await Si(e,t,a.installablePath,r),{bundleId:i,launchTarget:i}}finally{await a.cleanup()}});let i=await e.appleDeployment.prepareArtifact({source:{kind:`path`,path:n.appPath}},{appIdentifierHint:n.app,signal:r});try{return await xi(e,t,{artifact:i},r)}finally{await i.cleanup()}}async function xi(e,t,n,r){return await Si(e,t,n.artifact.installablePath,r),{...n.artifact.bundleId?{bundleId:n.artifact.bundleId}:{},...n.artifact.appName?{appName:n.artifact.appName}:{},...n.artifact.bundleId?{launchTarget:n.artifact.bundleId}:{}}}async function Si(e,t,n,r){await j(e,t,r),L(await e.appleTools.run(t.kind===`simulator`?{tool:`simctl`,args:_(t,[`install`,t.id,n])}:{tool:`devicectl`,args:[`device`,`install`,`app`,`--device`,t.id,n],timeoutMs:12e4},r),`Apple app install failed`)}async function Ci(e,t,n,r){await j(e,t,r);let i=await e.appleTools.run(t.kind===`simulator`?{tool:`simctl`,args:_(t,[`uninstall`,t.id,n]),allowFailure:!0}:{tool:`devicectl`,args:[`device`,`uninstall`,`app`,`--device`,t.id,n],allowFailure:!0},r);i.exitCode===0||Ti(`${i.stdout}\n${i.stderr}`)||L(i,`Apple app uninstall failed for ${n}`)}async function wi(t,n,r,i){if(n.kind!==`simulator`)throw new e(`UNSUPPORTED_OPERATION`,`Apple push notifications require a simulator`);await j(t,n,i);let a=await t.temporaryFiles.create({prefix:`agent-device-ios-push-`,suffix:`.apns`});try{await a.writeText(`${JSON.stringify(r.payload)}\n`),L(await t.appleTools.run({tool:`simctl`,args:_(n,[`push`,n.id,r.appId,a.path])},i),`Apple push notification failed`)}finally{await a[Symbol.asyncDispose]()}}function Ti(e){let t=e.toLowerCase();return t.includes(`not installed`)||t.includes(`not found`)||t.includes(`no such file`)}function L(t,n){if(t.exitCode!==0)throw new e(`COMMAND_FAILED`,n,{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode})}function Ei(e){return Oi(e)?e.kind!==`simulator`&&e.kind!==`device`?_i:e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?mi:pi:gi}function Di(e){return Oi(e)?e.kind===`simulator`?pi:hi:gi}function Oi(e){return o(e)&&e.appleOs!==`watchos`}const R=Object.freeze({available:!0}),ki=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`back is supported on Apple simulators and physical devices.`}),Ai=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function ji(e){return e.kind!==`simulator`&&e.kind!==`device`?ki:d(e)===`watchos`?Ai:R}const Mi=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`home is supported on Apple simulators and physical devices.`}),Ni=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),Pi=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`app-switcher is supported on Apple simulators and physical devices.`});function Fi(e,t){if(e.kind!==`simulator`&&e.kind!==`device`)return t;let n=d(e);return n===`macos`||n===`watchos`?Ni:R}function z(e){if(e.kind!==`simulator`&&e.kind!==`device`)return!1;let t=d(e);return t!==`tvos`&&t!==`macos`&&t!==`watchos`}const Ii=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`orientation is supported on Apple simulators and physical devices.`}),Li=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function Ri(e){return e.kind!==`simulator`&&e.kind!==`device`?Ii:z(e)?R:Li}const zi=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`tv-remote is supported only on tvOS devices.`});function Bi(e){return(e.kind===`simulator`||e.kind===`device`)&&a(e)?R:zi}const B=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),Vi=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`keyboard status/get is currently supported only on Android; use keyboard dismiss or enter on iOS`});function Hi(e){return z(e)?Vi:B}function Ui(e){return z(e)?R:B}function Wi(e){return z(e)?R:B}const Gi=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`No Apple leaf carries this system button.`}),Ki=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`action-button is supported on iPhone and iPad simulators and physical devices.`}),qi=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`The Action Button is iPhone and iPad hardware; tvOS, macOS, watchOS and visionOS have no such control.`});function Ji(e){return e.kind!==`simulator`&&e.kind!==`device`?Ki:l(e)?R:qi}function Yi(e){return Object.freeze({...Ie({back:ji(e)}),...Ne({unsupported:Gi,home:Fi(e,Mi),appSwitcher:Fi(e,Pi),actionButton:Ji(e)}),...De({orientation:Ri(e)}),...Pe({tvRemote:Bi(e)}),...Oe({unsupported:B,status:Hi(e),dismiss:Ui(e),enter:Wi(e)})})}function Xi(e){let{host:t,device:n,signal:r}=e;return ht({device:n,signal:r,resolveInteractor:t.localInteractors.resolve,facts:Yi(n)})}const V=Object.freeze({available:!0}),Zi=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`clipboard is supported on Apple simulators and the macOS host.`}),Qi=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`settings is supported on Apple simulators and the macOS host.`}),$i=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`settings is supported on Apple simulators and the macOS host, not on physical devices of this OS.`}),ea=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:"Apple targets answer a settings read only on iPhone and iPad simulators, where `simctl ui` reports the value the device holds."}),ta=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`clipboard is supported on Apple simulators and the macOS host, not on physical devices of this OS.`}),H=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function na(e,t,n){if(e.kind!==`simulator`&&e.kind!==`device`)return t;let r=d(e);return r===`watchos`?H:e.kind===`simulator`||r===`macos`?V:n}function ra(e){return na(e,Zi,ta)}const ia=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`trigger-app-event is supported on Apple simulators and physical devices.`}),aa=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`alert is supported on Apple simulators and physical devices.`}),oa=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`alert is supported on Apple simulators, the macOS host, and physical iOS devices.`});function sa(e){if(e.kind!==`simulator`&&e.kind!==`device`)return aa;let t=d(e);return t===`watchos`?H:e.kind===`simulator`||t===`ios`||t===`macos`?V:oa}function ca(e){return e.kind!==`simulator`&&e.kind!==`device`?ia:d(e)===`watchos`?H:V}function la(e){let t=ra(e);return t.available?ta:t}function ua(e){return e.kind!==`simulator`&&e.kind!==`device`?Qi:d(e)===`watchos`?H:u(e)?V:ea}function da(e){let t=ra(e),n=sa(e);return Object.freeze({...je({unsupported:la(e),read:t,write:t}),...Me({read:n,wait:n,accept:n,dismiss:n}),...Ae({triggerAppEvent:ca(e)}),...Ee({setSetting:na(e,Qi,$i),readSetting:ua(e)})})}function fa(e){let{host:t,device:n,signal:r}=e;return ht({device:n,signal:r,resolveInteractor:t.localInteractors.resolve,facts:da(n)})}const pa=/Angle:\s*(-?\d+(?:[.,]\d+)?)\s*°/g;async function ma(t,n={}){let r=[`devicectl`,`device`,`motion`,`hinge-angle`,`--device`,t.id,`--session-timeout`,`1`,`--timeout`,`5`],i=await jt(r,{allowFailure:!0,signal:n.signal,timeoutMs:kt}),a=ha(i.stdout)??ha(i.stderr);if(a!==void 0)return a;throw new e(`COMMAND_FAILED`,`CoreDevice reported no hinge angle sample`,te(i,{cmd:`xcrun`,args:r,stdout:i.stdout,stderr:i.stderr,deviceId:t.id,hint:`This Xcode/CoreDevice toolchain does not stream 'devicectl device motion hinge-angle' for this device. Foldable poses can be verified only through that stream; update Xcode to a version that ships it.`}))}function ha(e){let t;for(let n of e.matchAll(pa)){let e=Number.parseFloat(n[1].replace(`,`,`.`));Number.isFinite(e)&&(t=e)}return t}const ga={closed:`closed`,"half-open":`book`,open:`open`};async function _a(e,t,n={}){Nt(e,`fold`),va(e,await Lt(e,{signal:n.signal})),await Ft({deviceHub:!0,background:!0,signal:n.signal});let r=await It({udid:e.id,deviceName:e.name,pose:ga[t],signal:n.signal});g({level:`info`,phase:`apple_fold_pose_pressed`,data:{deviceId:e.id,pose:t,control:r.control,windowTitle:r.windowTitle,reopened:r.reopened,selected:r.selected}});let i=await ya(e,t,n.signal),a=await wa(e,n.signal);return{pose:t,hingeAngleDegrees:i,...a?{screen:Ta(a)}:{}}}function va(t,n){if(n.unresolved)throw new e(`COMMAND_FAILED`,`CoreDevice reported no display table for this simulator`,{deviceId:t.id,hint:`fold needs 'devicectl device info displays' to tell a foldable from a single-panel simulator; update Xcode to a version that ships the display-information feature.`});if(!n.multiScreen)throw new e(`UNSUPPORTED_OPERATION`,`${t.name} is not a foldable simulator: fold requires more than one integrated panel`,{deviceId:t.id,reason:`single-panel-device`,hint:`fold drives the pose controls Xcode Device Hub shows for a foldable simulator such as iPhone Duo; this simulator reports one integrated panel, so it has no hinge to pose.`})}async function ya(e,t,n){let r,i;for(let a=1;a<=4;a+=1)if(n?.throwIfAborted(),i=r,r=await ma(e,{signal:n}),h(r)===t&&(t!==`half-open`||i!==void 0&&ba(r,i)))return r;throw r!==void 0&&t===`half-open`&&h(r)===t?Ca(e,r,i):Sa(e,t,r)}function ba(e,t){return h(e)===`half-open`&&h(t)===`half-open`&&Math.abs(e-t)<=.5}function xa(e,t,n){return{deviceId:e.id,requestedPose:t,observedPose:n===void 0?void 0:h(n),hingeAngleDegrees:n}}function Sa(t,n,r){return new e(`COMMAND_FAILED`,`${t.name} did not reach the ${n} pose: CoreDevice still reports a hinge angle of ${r}°`,{...xa(t,n,r),reason:`fold-pose-unverified`,hint:`The Device Hub pose control was pressed, but the hinge did not follow. If several Device Hub windows are titled with this device name, close the ones for other simulators so the press reaches this one, then retry.`})}function Ca(t,n,r){return new e(`COMMAND_FAILED`,`${t.name} was observed half-open at ${n}° but did not settle: 4 hinge reads never held two consecutive half-open angles within ${Ot}° of each other`,{...xa(t,`half-open`,n),reason:`fold-pose-unsettled`,...r===void 0?{}:{previousHingeAngleDegrees:r},hint:`The hinge reached the requested pose and was still moving when the read budget ended. Retry the fold, then read the angle directly with xcrun devicectl device motion hinge-angle --device <udid> --session-timeout 1 --timeout 5 to see whether the simulator holds the pose.`})}async function wa(e,t){let n=await Lt(e,{signal:t});if(!(n.unresolved||n.ambiguous))return n.activeDisplay}function Ta(e){return{display:e.name,coordinateSpace:se,widthPt:Math.round(e.widthPx/e.pointScale),heightPt:Math.round(e.heightPx/e.pointScale)}}const Ea=Object.freeze({available:!0}),Da=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`fold is supported on foldable iPhone simulators driven by Xcode Device Hub; a physical device is folded by hand.`}),Oa=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`fold poses the hinge of a foldable iPhone; tvOS, macOS, watchOS and visionOS simulators have no hinge.`});function ka(e){if(e.kind!==`simulator`)return Da;let t=d(e);return t===`ios`||t===`ipados`?Ea:Oa}function Aa(e){return oe({fold:ka(e)})}function ja(e){let{device:t,signal:n}=e;return m(Aa(t).setFoldPose,()=>({setFoldPose:async e=>(n.throwIfAborted(),await _a(t,e.pose,{signal:n}))}))}function Ma(e,t,n){let r=Le({device:t.device,signal:t.signal,resolveInteractor:e.localInteractors.resolve}),i=async i=>{if(s(t.device)&&i.options?.surface!==void 0&&i.options.surface!==`app`)return await e.snapshot.captureSurface(t.device,i.options,Te(t.signal,i));if(!n)return await r.captureSnapshot(i);let a=Te(t.signal,i);return await n.capture(t.device,i,a,async e=>await r.captureSnapshot(e))};return Object.freeze({captureSnapshot:i,captureSnapshotWithCustomActions:i,captureSnapshotWithoutActiveApp:i})}function Na(e,t){return Object.freeze({findText:async n=>{let r=await Pa(e,t,n);if(!r)return{found:!1};let i=await e.localInteractors.resolve(t.device,{...n.execution,...r});return i.findText?await i.findText(n.text,r):{found:!1}}})}async function Pa(e,t,n){let r=n.options?.appBundleId;if(r===void 0)return;let i=n.options?.surface;if(s(t.device)&&i!==void 0&&i!==`app`)return;let a=n.signal?AbortSignal.any([t.signal,n.signal]):t.signal;if(a.throwIfAborted(),await Fa(e,t.device,n.execution))return{appBundleId:r,signal:a}}async function Fa(e,t,n){return!P(t)||await e.appleApplications.hasLiveRunnerSession(t,n??{})}function Ia(){let e,t=!1,n=async()=>(e??=import(`./adapter.js`).then(({createSimulatorSnapshotSource:e})=>e()),await e);return{acquire:async e=>t?{stage:`failed`,failure:{kind:`unsupported`,code:`source-closed`}}:await(await n()).acquire(e),close:async()=>{t=!0,e&&await(await e).close()}}}const La=3e3;function Ra(){let e=new Map,t=new Map,n=Bt({waitMs:1500});return async(r,i,a,o)=>{a.throwIfAborted();let s=`${r.id}:${i}`,c=e.get(s);return c&&o!==`refresh`&&await Ht(c.pid,{signal:a,timeoutMs:La})===c.processStartTime?c:(e.delete(s),await n.value(s,{start:async()=>{let n=await za(r,i,t);return e.set(s,n),n},wait:(e,t)=>Vt({waitMs:e,signal:a,stop:t,cancelled:()=>a.reason}),pending:()=>W(`simulator-target-discovery-pending`,r,i)}))}}async function za(e,t,n){let r=Date.now()+15e3,[i,a]=await Promise.allSettled([Mt(e,[`spawn`,e.id,`launchctl`,`list`],{allowFailure:!0,timeoutMs:U(r)}),Ba(e,n,r)]);if(i.status===`rejected`)throw i.reason;if(a.status===`rejected`)throw a.reason;let o=i.value,s=a.value;if(o.exitCode!==0)throw W(`simulator-target-probe-failed`,e,t);let c=Va(o.stdout,t);if(!c)throw W(`simulator-target-unavailable`,e,t);let l=await Ht(c.pid,{timeoutMs:Math.min(La,U(r))});if(!l)throw W(`simulator-target-identity-unavailable`,e,t);return Object.freeze({udid:e.id,runtime:s,pid:c.pid,generation:`${c.pid}:${c.label}:${l}`,targetId:`${e.id}:${t}`,processStartTime:l})}async function Ba(e,t,n){let r=t.get(e.id);if(r)return await r;let i=Mt(e,[`list`,`devices`,`-j`],{allowFailure:!0,timeoutMs:U(n)}).then(t=>{if(t.exitCode!==0)throw W(`simulator-runtime-probe-failed`,e,``);let n=JSON.parse(t.stdout),r=Object.entries(n.devices??{}).find(([,t])=>t.some(t=>t.udid===e.id))?.[0];if(!r)throw W(`simulator-runtime-unavailable`,e,``);return r});t.set(e.id,i);try{return await i}catch(n){throw t.delete(e.id),n}}function Va(e,t){for(let n of e.split(`
4
- `)){let[e,,r]=n.trim().split(/\s+/);if(!e||!r||!r.startsWith(`UIKitApplication:${t}[`))continue;let i=Number(e);if(Number.isSafeInteger(i)&&i>0)return{pid:i,label:r}}}function U(e){return Math.max(1,e-Date.now())}function W(t,n,r){return new e(`COMMAND_FAILED`,`Unable to resolve the running iOS Simulator app (${t}).`,{reason:t,deviceId:n.id,appBundleId:r})}function Ha(e=Date.now){let t=new Map;return async(n,r)=>{if(n.kind!==`simulator`)return`absent`;let i=t.get(n.id);if(i!==void 0&&e()-i.at<1e3)return{kind:`present`,host:i.host};t.delete(n.id);let a=await Ua(n,r);return a!==`absent`&&a!==`unknown`&&t.set(n.id,{at:e(),host:a.host}),a}}async function Ua(e,t){let n=!1;for(let r of ft){let i=await Wa(r.processExecutable,t);if(i===`unknown`){n=!0;continue}for(let a of i){let i=await Ga(a,e.id,t);if(i===`unknown`)n=!0;else if(i)return{kind:`present`,host:r}}}return n?`unknown`:`absent`}async function Wa(e,t){let n=await Ka(`pgrep`,[`-f`,e],t);return n===`unknown`?`unknown`:n.exitCode===1?[]:n.exitCode===0?n.stdout.split(`
5
- `).map(e=>Number.parseInt(e.trim(),10)).filter(e=>Number.isSafeInteger(e)&&e>0):`unknown`}async function Ga(e,t,n){let r=await Ka(`ps`,[`eww`,`-p`,String(e),`-o`,`command=`],n);return r===`unknown`||r.exitCode!==0?`unknown`:r.stdout.includes(`SIMULATOR_UDID=${t}`)?!0:!r.stdout.includes(`SIMULATOR_UDID=`)&&`unknown`}async function Ka(e,t,n){try{let r=await At(e,t,{allowFailure:!0,timeoutMs:3e3,...n?{signal:n}:{}});return{exitCode:r.exitCode,stdout:r.stdout}}catch{return`unknown`}}const qa=`system-surface-presented`,Ja=`system-surface-host-lingering`,Ya=`window-coordinate-space-unresolved`;function Xa(t,n={}){let r=n.source??Ia(),i=n.resolveTarget??Ra(),a=n.systemSurfacePresent??Ha(),o=new Set,s=new Map,c=e=>(uo(e,s,o),o.has(fo(e))),l=Wr({source:r,resolveTarget:i,clock:t.clock,isBridgeDisabled:c});return Object.freeze({awaitObservable:l.awaitObservable,shutdown:async()=>await r.close(),capture:async(n,s,l,u)=>{if(!$a(n,s))return await ro(n,s,u);let d=await a(n,l);if(d===`unknown`)return await G(n.id,s,u,K(n.id,s),q(s),`system-surface-probe-unavailable`,[lo()]);if(d!==`absent`)return await no(n,s,u,d.host.bundleId);let f;try{f=await Za(t,i,n,s,l)}catch(e){return l.throwIfAborted(),J(`target-resolution-failed`,n,void 0,e),await G(n.id,s,u,K(n.id,s),q(s),`target-resolution-failed`,[lo()])}if(c(f))return await G(n.id,s,u,f,q(s),`circuit-disabled`);let p=q(s),m=await r.acquire({target:f,hint:re(p),signal:l});if(m.stage===`failed`){if(m.failure.kind===`cancelled`)throw l.throwIfAborted(),new e(`COMMAND_FAILED`,`Simulator AX snapshot acquisition was cancelled.`,{reason:m.failure.code,...m.failure.details});let t=await co(m.failure,f,n,s.options.appBundleId,l,i);return await eo(s,u,f,t,p,m.failure,o)}try{return await ee(`ios.snapshot-source.present`,async()=>await t.snapshot.presentIosAcquisition(m,s.options),{producer:`simulator-ax-bridge`})}catch(e){return await eo(s,u,f,{lineage:f,residue:[]},p,{kind:`malformed-tree`,code:`presentation-invariant`},o,e)}}})}async function Za(e,t,n,r,i){let a=r.options.appBundleId;for(;;)try{return await t(n,a,i)}catch(t){if(!Qa(t))throw t;let i={requestId:r.execution?.requestId};if(await e.appleApplications.hasLiveRunnerSession(n,i))throw t}}function Qa(t){return t instanceof e&&t.details?.reason===`simulator-target-discovery-pending`}function $a(e,t){return e.platform===`apple`&&e.appleOs===`ios`&&e.kind===`simulator`&&!!t.options?.appBundleId&&t.options?.customActions!==!0&&t.options?.preferredBackend===void 0}async function eo(e,t,n,r,i,a,o,s){return to(a)&&o.add(fo(n)),J(a.code,{id:n.udid},n.generation,s,a.details),await G(n.udid,e,t,r.lineage,i,a.code,r.residue)}function to(e){return e.kind!==`preparing`&&e.code!==Ya}async function G(e,t,n,r,i,a,o=[]){return io(e,await n(t),r,i,a,o)}async function no(e,t,n,r){let i=await n(t),a=i.systemSurface?qa:Ja;return i.systemSurface||J(a,e,void 0,void 0,{detectedHost:r}),io(e.id,i,K(e.id,t),q(t),a)}async function ro(e,t,n){let r=await n(t),i=r.systemSurface;return i?{...r,comparisonIdentity:oo(ao(e.id,i.bundleId),q(t),[])}:r}function io(e,t,n,r,i,a=[]){let o=t.systemSurface;return{...t,comparisonIdentity:oo(o?ao(e,o.bundleId):n,r,[...o?[]:a,{kind:`fallback-source`,producer:`apple-runner`}]),warnings:[...t.warnings??[],so(i,n,o!==void 0)]}}function K(e,t){return{targetId:`${e}:${t.options.appBundleId}`}}function ao(e,t){return{targetId:`${e}:${t}`}}function oo(e,t,n){return Object.freeze({producer:`apple-runner`,intent:t.acquisitionIntent,lineage:Object.freeze({...e.targetId?{targetId:e.targetId}:{},...e.generation?{generation:e.generation}:{}}),presentationKey:ie(t),residue:Object.freeze([...n])})}function so(e,t,n){return e===qa?`Simulator AX snapshot inapplicable (${e}); used XCTest to read the system surface presented over the app.`:e===Ja?`Simulator AX snapshot inapplicable (${e}); used XCTest, which read app content: the system surface host process was still running but no longer presenting.`:n?`Simulator AX snapshot unavailable (${e}); used XCTest, which read the system surface presented over the app.`:e===`bridge-preparation-pending`?`Simulator AX snapshot unavailable (${e}); used XCTest for this capture while the bridge is still being prepared.`:e===Ya?`Simulator AX snapshot unavailable (${e}); used XCTest for this capture, which reports captured geometry in the app's own orientation space.`:`Simulator AX snapshot unavailable (${e}); used XCTest for ${t.generation?`this app generation`:`an unverified app generation`}.`}async function co(e,t,n,r,i,a){if(e.kind!==`stale-target`)return{lineage:t,residue:[]};try{return{lineage:await a(n,r,i,`refresh`),residue:[]}}catch(e){return i.throwIfAborted(),J(`fallback-target-resolution-failed`,n,void 0,e),{lineage:{targetId:t.targetId},residue:[lo()]}}}function lo(){return{kind:`unknown-generation`,captureId:Wt()}}function q(e){return ae({raw:e.options?.raw,interactiveOnly:e.options?.interactiveOnly,depth:e.options?.depth,scope:e.options?.scope,customActions:e.options?.customActions,acquisitionIntent:e.options?.acquisitionIntent})}function uo(e,t,n){let r=t.get(e.targetId);r&&r!==e.generation&&n.delete(`${e.targetId}:${r}`),t.set(e.targetId,e.generation)}function fo(e){return`${e.targetId}:${e.generation}`}function J(e,t,n,r,i){g({level:`debug`,phase:`ios_snapshot_route_fallback`,data:{reason:e,deviceId:t.id,...n?{generation:n}:{},...r?{error:r instanceof Error?r.message:String(r)}:{},...i?{details:i}:{}}})}const Y=f(`apple`),X=Object.freeze({available:!0}),Z=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),po=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`viewport resizes web targets only (--platform web). Apple screen geometry is fixed by the selected simulator or device type — open a different simulator to test another screen size.`}),mo=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`the stateless audio page probe is a web-session operation; Apple targets use the host capture.`}),ho=Object.freeze({available:!1,reason:`unsupported-device-backend`,hint:`perf requires an Apple simulator, macOS device, or CoreDevice-backed physical Apple device.`}),go=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`focus is supported on Apple simulators and physical devices.`}),_o=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Apple appstate is unavailable: the Apple target answers no sessionless foreground probe, and a session-scoped guess about the foreground is not a fact. The per-command answer is the targetActivation disclosure, which a capture carries when its command had to re-activate the session app (#2682).`}),vo=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Headless boot is supported only for local Android emulators.`}),yo=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS has no XCUITest-driveable UI, so element text comes from the captured tree only.`}),bo=Object.freeze({available:!1,reason:`unsupported-device-kind`}),xo=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS open is not supported because XCUITest cannot drive watchOS UI.`}),So=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS runner preparation is not supported because XCUITest cannot drive watchOS UI.`}),Co=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS close is not supported because XCUITest cannot drive watchOS UI.`}),wo=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Runtime hints are supported only for local iOS-family simulators and Android devices.`}),To=Q(`open is supported only for Apple simulators and devices.`),Eo=Q(`prepare is supported only for Apple simulators and devices.`),Do=Q(`close is supported only for Apple simulators and devices.`),Oo=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Port reverse is supported only by an owning provider runtime.`}),ko=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`shutdown is supported only for Apple simulators and Android emulators.`}),Ao=Q(`snapshot is supported only for Apple simulators and devices.`),jo=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Re-run without --actions, or target an iOS simulator.`}),Mo=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`screenshot is not supported on watchOS because XCUITest cannot drive watchOS UI.`}),No=Q(`screenshot is supported only for Apple simulators and devices.`),Po=Object.freeze({available:!1,reason:`owner-capability-missing`,hint:`Open the app under test before capturing its snapshot.`});function Q(e){return Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:e})}function Fo(e){return!o(e)||e.appleOs===`watchos`?Z:e.kind===`simulator`?X:ko}function Io(e){let t=Lo(e),n=Ro(e),r=zo(e),i=Bo(e);return de({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:i,clearRuntimeHints:i,closeApplication:r,finalizeApplicationClose:r,prepareAppleRunner:n,configureProviderPortReverse:Oo})}function Lo(e){return d(e)===`watchos`?xo:e.kind===`simulator`||e.kind===`device`?X:To}function Ro(e){return d(e)===`watchos`?So:e.kind===`simulator`||e.kind===`device`?X:Eo}function zo(e){return d(e)===`watchos`?Co:e.kind===`simulator`||e.kind===`device`?X:Do}function Bo(e){return d(e)!==`watchos`&&o(e)&&e.kind===`simulator`?X:wo}function Vo(e){return e.appleOs===`watchos`?Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS app inventory is not supported.`}):e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?Object.freeze({available:!1,reason:`unsupported-device-backend`,hint:`App inventory is available only on CoreDevice-backed physical iOS devices.`}):X}function $(e){return e.kind===`simulator`||e.kind===`device`?X:go}function Ho(e){let t=An(e),n=Xa(e),r=async n=>{let r=await t.inspectFacts(n),i=vi(n),a=vr(n),c=a.available?await e.screenRecording.apple.availability(n):void 0,l=a.available&&c?.available===!1?Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:c.hint}):a,u=n.appleOs===`watchos`?Z:X,d=s(n)||n.appleOs===`watchos`?Z:X,f=Vo(n);return Object.freeze({device:r.device,operations:{...r.operations,...i,appState:_o,networkDump:X,screenRecordingStart:l,screenRecordingReattach:l,screenRecordingCleanup:l,...qo(n),...he({capture:Ko(n)}),...Se({findText:Go(n)}),...ve({setViewport:po}),..._e({focus:$(n)}),...$t(n),...me({type:$(n)}),...Be({unsupported:Z,tap:$(n),longPress:$(n),fill:$(n),...o(n)?{tapElementSelector:$(n)}:{}}),...Fe({readTextAtPoint:Wo(n)}),...Yi(n),...Aa(n),...da(n),...Re({capture:Kt(n),query:mo}),...ze(Uo(n)),ensureReady:u,bootTarget:d,bootTargetHeadless:vo,listApps:f,...Io(n),shutdownTarget:Fo(n)}})};return Object.freeze({owner:Y,ownsDevice:e=>e.platform===`apple`,inspectFacts:r,bind:async i=>{let a=await t.bind(i),o=await r(i.device),s=o.operations.screenRecordingStart,c={...a.operations,...yi({host:e,device:i.device,signal:i.scope.signal}),networkDump:async t=>await Pn(e,i.device,t,i.scope.signal),...m(s,()=>yr({host:e,device:i.device,owner:Y,signal:i.scope.signal})),...m(o.operations.audioProbeStart,()=>Xe({host:e.audioProbe.hostCapture,device:i.device,owner:Y})),...m(o.operations.perfFrames,()=>qt({resolveHost:()=>e.perf.apple,device:i.device,owner:Y})),...m(o.operations.captureSnapshot,()=>Ma(e,{device:i.device,signal:i.scope.signal},n)),...m(o.operations.captureScreenshot,()=>we({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...m(o.operations.focusPoint,()=>xe({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...ke({device:i.device,signal:i.scope.signal,facts:o.operations,resolveInteractor:e.localInteractors.resolve}),...m(o.operations.scrollDirection,()=>be({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...m(o.operations.typeText,()=>Ce({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...m(o.operations.tapPoint,()=>Ve({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve,facts:o.operations,pause:async t=>await e.clock.sleep(t,i.scope.signal)})),...m(o.operations.readTextAtPoint,()=>pe({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...m(o.operations.findText,()=>Na(e,{device:i.device,signal:i.scope.signal})),...Xi({host:e,device:i.device,signal:i.scope.signal}),...fa({host:e,device:i.device,signal:i.scope.signal}),...ja({device:i.device,signal:i.scope.signal}),...m(o.operations.ensureReady,()=>({ensureReady:async()=>await j(e,i.device,i.scope.signal)})),...m(o.operations.bootTarget,()=>({bootTarget:async()=>await j(e,i.device,i.scope.signal)})),...m(o.operations.listApps,()=>({listApps:async e=>{i.scope.signal.throwIfAborted();let{listIosApps:t}=await import(`./app-resolution.js`).then(e=>e.t);return(await t(e.device,e.filter)).map(e=>({id:e.bundleId,name:e.name}))}})),...le(Jr({host:e,device:i.device,signal:i.scope.signal,observation:n}),o.operations),...m(o.operations.shutdownTarget,()=>({shutdownTarget:async()=>await e.deviceShutdown.apple.shutdownTarget(i.device,i.scope.signal)}))};return Object.freeze({device:a.device,owner:Y,facts:o,operations:Gt(c),[Symbol.asyncDispose]:async()=>await a[Symbol.asyncDispose]()})},shutdown:async()=>{await Promise.all([t.shutdown(),n.shutdown()])}})}function Uo(e){let t=e.iosPhysicalDeviceBackend!==`xctest`&&d(e)!==`watchos`?X:ho;return{frames:t,memorySample:t,memorySnapshot:t,nativeCapture:t,profileReport:t}}function Wo(e){return d(e)===`watchos`?yo:e.kind===`simulator`||e.kind===`device`?X:bo}function Go(e){return d(e)===`watchos`?Ao:e.kind===`simulator`||e.kind===`device`?X:Ao}function Ko(e){return d(e)===`watchos`?Mo:e.kind===`simulator`||e.kind===`device`?X:No}function qo(e){let t=Go(e);return ge({capture:t,customActions:t.available&&o(e)&&e.kind===`simulator`?X:jo,withoutActiveApp:o(e)?Po:t})}export{Ho as createApplePlatformRuntime};
3
+ `)}\n`,{...n,path:`${r} (simctl log show recovery)`,exists:!0,backend:`ios-simulator`}),lineCount:c.length}}function In(e){let t=e.replaceAll(`\\`,String.raw`\\`).replaceAll(`"`,String.raw`\"`);return[`subsystem == "${t}"`,`subsystem CONTAINS "${t}"`,`processImagePath ENDSWITH[c] "/${t}"`,`senderImagePath ENDSWITH[c] "/${t}"`].join(` OR `)}function Ln(e,t){let n=t.entries.filter(e=>e.pathUnavailable).length,r=t.unnamedRequests??0,i=n+r;if(i===0)return;let a=[`${i} request${i===1?``:`s`} reused a keep-alive connection, so CFNetwork logged no request URL.`];n>0&&a.push(`${n} listed against the origin the connection was opened for, without a path.`),r>0&&a.push(`${r} opened before this scan window and are missing from the entries entirely; scan more lines, or run logs clear --restart before the repro.`),a.push(`Absence of an endpoint in this dump does not prove it was not called.`),e.push(a.join(` `))}function Rn(e,t,n){n.appLogSnapshot?n.appLogSnapshot.state!==`active`&&e.length===0&&e.push(o(t)&&t.kind===`simulator`?`Session app log stream is inactive. The iOS simulator recovery path scanned recent simctl log history, but a fresh logs clear --restart window is still the most reliable repro loop.`:`Session app log stream is inactive. Run logs clear --restart, reproduce the request window again, then rerun network dump.`):e.push(`Capture uses the session app log file. For fresh traffic, run logs clear --restart before reproducing requests.`)}function zn(e){return o(e)&&e.kind===`simulator`?`No HTTP(s) entries were found in recent iOS simulator app logs. If the app only emits non-HTTP diagnostics, inspect logs path or add app-side URLSession/network logging for per-request timing and payload details.`:o(e)?`No HTTP(s) entries were found in recent iOS device app logs. iOS network dump only sees what the app emits into Unified Logging for this process.`:`No HTTP(s) entries were found in recent session app logs.`}async function Bn(e){let{host:n,snapshot:r,targetLabel:i,recorderWarning:a,nativePathDisposition:o}=e,s=r.invalidatedReason?{recorder:`lost`,why:`owner-session-lost`}:e.stopObservation;if(r.invalidatedReason&&!r.showTouches)throw Error(`recording invalidated: ${r.invalidatedReason}`);let c;try{c=await n.screenRecording.finalize.complete({outputPath:r.outPath,showTouches:!r.invalidatedReason&&r.showTouches,gestureEvents:r.gestureEvents,exportQuality:r.exportQuality??`medium`,targetLabel:i})}catch(e){throw t(e,`COMMAND_FAILED`)}let l=[...c.warning?[c.warning]:[],...a?[a]:[]];return rt(r,{...c,...l.length>0?{warning:l.join(` `)}:{},...r.invalidatedReason?{overlayWarning:`overlay unavailable: ${r.invalidatedReason}`}:{}},{stopObservation:s,...o===void 0?{}:{nativePathDisposition:o}})}async function Vn(e){let{host:t,snapshot:n,targetLabel:r,collectedPath:i,exportPath:a,nativePath:o}=e;if(n.invalidatedReason&&!n.showTouches)throw Error(`recording invalidated: ${n.invalidatedReason}`);let s=e.overlayUnavailable??n.invalidatedReason,c;try{await t.screenRecording.outputs.copy({from:i,to:a}),c=await Hn(()=>t.screenRecording.finalize.complete({outputPath:a,showTouches:s===void 0&&n.showTouches,gestureEvents:n.gestureEvents,exportQuality:n.exportQuality??`medium`,targetLabel:r}))}catch(e){throw await t.screenRecording.outputs.remove(a),e}return{...c,...s===void 0?{}:{overlayWarning:`overlay unavailable: ${s}`},nativePathDisposition:await t.screenRecording.outputs.remove(o)===`removed`?`retired`:`retirable`}}async function Hn(e){try{return await e()}catch(e){throw t(e,`COMMAND_FAILED`)}}const Un=[`outPath`,`startedAt`,`clientOutPath`,...ct],k=Object.freeze({resourceKind:dt,version:1,encode:e=>e.backend===`simctl`?{backend:e.backend,outputPath:e.outputPath,processes:e.processes.map(e=>({...e})),...e.recording===void 0?{}:{recording:{...e.recording}}}:{backend:e.backend,outputPath:e.outputPath,appBundleId:e.appBundleId,runnerSessionId:e.runnerSessionId,runnerAuthority:e.runnerAuthority,...e.remotePath===void 0?{}:{remotePath:e.remotePath}},decode:e=>tr(e)});function Wn(e){let{device:t,owner:n,input:r,descriptor:a}=e;return Ue({resourceKind:dt,sessionId:r.sessionId,device:i(t),owner:n,fence:r.fence,lifecycle:`open`,descriptor:He(k,a)})}function Gn(e){let t={};for(let n of Un)e[n]!==void 0&&Object.assign(t,{[n]:e[n]});return t}async function Kn(e,t,n,r){let i=k.decode(n);return i.status!==`decoded`||!dr(t,i.descriptor)?{status:`cleanup-pending`,reason:`manual-recovery-required`}:i.descriptor.backend===`simctl`?await qn(e,i.descriptor.processes,r):await Yn(e,t,i.descriptor)}async function qn(e,t,n){let r=await Promise.all(t.map(async t=>await e.screenRecording.apple.inspectProcess(t)));if(r.includes(`ownership-lost`))return{status:`cleanup-pending`,reason:`ownership-fence-lost`};if(r.every(e=>e===`missing`))return n!==void 0&&e.screenRecording.ownedProcesses.clear(Jn(n)),{status:`already-missing`};let i=await Promise.all(t.flatMap((t,n)=>r[n]===`owned-alive`?[e.screenRecording.apple.terminateProcess(t)]:[]));return i.includes(`ownership-lost`)?{status:`cleanup-pending`,reason:`ownership-fence-lost`}:(n!==void 0&&e.screenRecording.ownedProcesses.clear(Jn(n)),i.every(e=>e===`already-missing`)?{status:`already-missing`}:{status:`cleaned`})}function Jn(e){return{kind:`session`,sessionId:e}}async function Yn(e,t,n){try{let r=await e.screenRecording.apple.inspectRunner(t,n.runnerSessionId,n.runnerAuthority);return r===`missing`?{status:`already-missing`}:r===`ownership-lost`?{status:`cleanup-pending`,reason:`ownership-fence-lost`}:(await e.screenRecording.apple.runRunner(t,{kind:`stop`,appBundleId:n.appBundleId,runnerSessionId:n.runnerSessionId,runnerAuthority:n.runnerAuthority}),{status:`cleaned`})}catch(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:`Apple recording cleanup failed`}}}async function Xn(e){let{host:t,device:n,envelope:r}=e,i=k.decode(r.descriptor.body);return i.status===`decoded`?dr(n,i.descriptor)?i.descriptor.backend===`simctl`?await Zn(e,i.descriptor):await $n(t,n,i.descriptor):A(`descriptor-invalid`,`Apple screen-recording descriptor does not match the bound device.`):A(`descriptor-invalid`,i.message)}async function Zn(e,t){let n=await Promise.all(t.processes.map(async t=>await e.host.screenRecording.apple.inspectProcess(t)));if(!n.every(e=>e===`missing`))return A(`transport-not-reattachable`,n.includes(`ownership-lost`)?`Apple recording ownership no longer matches the durable descriptor.`:`Apple screen recordings require exact cleanup after daemon restart.`);let{recording:r}=t,i=Qn(ot(e.envelope.metadata),t.outputPath);return r===void 0||i!==void 0&&!await er(e.host,i)?{status:`missing`}:{status:`restore-export`,recording:r,nativePath:t.outputPath,cleanup:async()=>await qn(e.host,t.processes,e.envelope.sessionId)}}function Qn(e,t){if(e.finalization===void 0)return e.collectedPath??t}async function $n(e,t,n){let r=await e.screenRecording.apple.inspectRunner(t,n.runnerSessionId,n.runnerAuthority);return r===`missing`?{status:`missing`}:A(`transport-not-reattachable`,r===`ownership-lost`?`Apple recording ownership no longer matches the durable descriptor.`:`Apple screen recordings require exact cleanup after daemon restart.`)}async function er(e,t){try{return await e.screenRecording.finalize.sniff({outputPath:t}),!0}catch{return!1}}function A(e,t){return{status:`unreattachable`,reason:e,message:t}}function tr(e){return typeof e.outputPath!=`string`||e.outputPath.length===0?M():e.backend===`simctl`?nr(e,e.outputPath):e.backend===`runner`?ar(e,e.outputPath):M()}function nr(e,t){let n=fr(e.processes),r=rr(e.recording);return!n||r===`invalid`?M():{status:`decoded`,descriptor:Object.freeze({backend:`simctl`,outputPath:t,processes:n,...r===void 0?{}:{recording:r}})}}function rr(e){if(e!==void 0)return n(e)&&ir(e)?Object.freeze(e):`invalid`}function ir(e){return j(e.outPath)&&sr(e.startedAt)&&or(e.clientOutPath)&&at(e)}function ar(e,t){return!j(e.appBundleId)||!j(e.runnerSessionId)||!cr(e.runnerAuthority)||!lr(e.remotePath)?M():{status:`decoded`,descriptor:Object.freeze({backend:`runner`,outputPath:t,appBundleId:e.appBundleId,runnerSessionId:e.runnerSessionId,runnerAuthority:e.runnerAuthority,...e.remotePath===void 0?{}:{remotePath:e.remotePath}})}}function j(e){return typeof e==`string`&&e.length>0}function or(e){return e===void 0||j(e)}function sr(e){return typeof e==`number`&&Number.isFinite(e)}function cr(e){return e===`local-lease`||e===`scoped-provider`}function lr(e){return e===void 0||ur(e)}function ur(e){return typeof e==`string`&&/^tmp\/agent-device-recording-\d+\.mp4$/.test(e)}function dr(e,t){return e.kind===`simulator`?t.backend===`simctl`:t.backend===`runner`?e.appleOs===`macos`?t.remotePath===void 0:o(e)?t.remotePath!==void 0&&ur(t.remotePath):t.remotePath===void 0:!1}function fr(e){if(!Array.isArray(e)||e.length===0)return;let t=e.filter(e=>typeof e==`object`&&!!e&&Number.isInteger(e.pid)&&(e.pid??0)>0&&typeof e.startTime==`string`&&e.startTime.length>0&&typeof e.command==`string`&&e.command.length>0);return t.length===e.length?Object.freeze([...t]):void 0}function M(){return{status:`invalid`,message:`Invalid Apple screen-recording descriptor`}}async function pr(e,t,n){if(e.kind!==`simulator`||t.scope!==`app`)return;let r=t.activeSessionApp?.bundleId;if(!r)throw TypeError(`App-scoped recording requires an active app session; open the app under test before recording.`);if(await n(r))throw TypeError(`App-scoped recording requires a real application session; open the app under test before recording.`)}const mr=`iOS recording`,hr=`simctl recordVideo`;function gr(e){return e.appleOs===`watchos`?Ar(`unsupported-platform-leaf`,`watchOS recording is not supported.`):o(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?Ar(`unsupported-device-backend`,`This command requires a CoreDevice-backed physical iOS device. The selected XCTest backend supports open, close, interactions, snapshots, and screenshots.`):Object.freeze({available:!0})}function _r(e){let{host:t,device:n,owner:r,signal:i}=e;return Object.freeze({screenRecordingStart:async e=>await vr({host:t,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async e=>{let r=await Xn({host:t,device:n,envelope:e.envelope});return r.status===`restore-export`?{status:`active`,handle:br({host:t,restored:r})}:r},screenRecordingCleanup:async e=>await Kn(t,n,e.envelope.descriptor.body,e.envelope.sessionId)})}async function vr(e){return e.signal.throwIfAborted(),e.device.kind===`simulator`?await yr(e):await Sr(e)}async function yr(e){let{host:t,device:n,owner:r,input:i,signal:a}=e;await pr(n,i,t.screenRecording.apple.isRunnerBundleId);let o=i.activeSessionApp?await t.screenRecording.apple.captureClockAnchor(n,i.activeSessionApp.bundleId,a):void 0,s=St(i.outputPath);await t.screenRecording.outputs.prepare(s);let c=await t.screenRecording.apple.startSimulator(n,s,a),l=c.markers;if(!l||l.length===0)throw await N(c).catch(()=>{}),Error(`simctl recordVideo did not expose durable process identity`);try{a.throwIfAborted(),t.screenRecording.ownedProcesses.replace({kind:`session`,sessionId:i.sessionId},l.map(e=>({...e,purpose:`simctl-screen-recording`})))}catch(e){try{t.screenRecording.ownedProcesses.clear({kind:`session`,sessionId:i.sessionId})}catch{}throw await N(c).catch(()=>{}),e}let u,d,f=async()=>{await c.terminate();let e=await c.wait;return d=e,u=wr(e),t.screenRecording.ownedProcesses.clear({kind:`session`,sessionId:i.sessionId}),{observation:{recorder:`confirmed`},...u===void 0?{}:{warning:`${u} before record stop; the video covers only what the recorder wrote before it stopped.`}}},p=kr(i,hr,{},o);return Or({device:n,owner:r,input:i,descriptor:{backend:`simctl`,outputPath:s,processes:l,recording:Gn(p)},snapshot:p,finish:(e,n)=>ut({snapshot:e,progress:n,steps:{stop:f,collect:async e=>{try{await xr(t,s,e)}catch(e){throw Tr(e,u,d)}},finalize:async({collectedPath:n,exportPath:r})=>{try{return await Vn({host:t,snapshot:e,targetLabel:mr,collectedPath:n,exportPath:r,nativePath:s})}catch(e){throw Tr(e,u,d)}},discard:async e=>{await t.screenRecording.outputs.remove(e)}}}),cleanup:async()=>{let e=await Dr(c);return(e.status===`cleaned`||e.status===`already-missing`)&&t.screenRecording.ownedProcesses.clear({kind:`session`,sessionId:i.sessionId}),e}})}function br(e){let{host:t,restored:{recording:n,nativePath:r,cleanup:i}}=e,a=Object.freeze({...n,backend:hr,gestureEvents:[]});return nt(a,{finish:(e,i)=>ut({snapshot:e,progress:i,steps:{stop:async()=>({observation:{recorder:`confirmed`},warning:`simctl recordVideo had already ended when record stop reattached to it; the video covers only what the recorder wrote before it stopped.`}),collect:async e=>{await xr(t,r,e)},finalize:async({collectedPath:i,exportPath:a})=>await Vn({host:t,snapshot:e,targetLabel:mr,collectedPath:i,exportPath:a,nativePath:r,...n.showTouches?{overlayUnavailable:`the daemon that held the touch events ended before record stop`}:{}}),discard:async e=>{await t.screenRecording.outputs.remove(e)}}}),forceCleanup:async()=>await i()})}async function xr(e,t,n){await e.screenRecording.outputs.copy({from:t,to:n}),await e.screenRecording.finalize.sniff({outputPath:n})}async function Sr(e){let{host:t,device:n,owner:r,input:i,signal:a}=e,o=i.activeSessionApp?.bundleId;if(!o)throw TypeError(`Apple runner recording requires an active app session identity`);await t.screenRecording.outputs.prepare(i.outputPath);let s=await t.screenRecording.apple.runRunner(n,{kind:`start`,appBundleId:o,outputPath:i.outputPath,...i.fps===void 0?{}:{fps:i.fps}},a);if(!s.runnerSessionId||!s.runnerAuthority)throw Error(`Apple runner recording did not expose durable session ownership`);let c={runnerSessionId:s.runnerSessionId,runnerAuthority:s.runnerAuthority},l,u=()=>(l??=Cr(()=>t.screenRecording.apple.runRunner(n,{kind:`stop`,appBundleId:o,...c}).then(()=>void 0)).catch(e=>{throw l=void 0,e}),l);if(!Er(n,s.remotePath))throw await u().catch(()=>{}),Error(`Apple runner recording did not expose coherent durable media ownership`);try{a.throwIfAborted()}catch(e){throw await u().catch(()=>{}),e}return Or({device:n,owner:r,input:i,descriptor:{backend:`runner`,outputPath:i.outputPath,appBundleId:o,...c,...s.remotePath===void 0?{}:{remotePath:s.remotePath}},snapshot:kr(i,`runner AVAssetWriter`,s),finish:async e=>(await u(),s.remotePath!==void 0&&await t.screenRecording.apple.retrieveRunnerRecording(n,s.remotePath,e.outPath),await Bn({host:t,snapshot:e,targetLabel:n.appleOs===`macos`?`macOS recording`:`iOS recording`,stopObservation:{recorder:`confirmed`},...s.remotePath===void 0?{}:{nativePathDisposition:`retirable`}})),cleanup:async()=>(await u(),{status:`cleaned`})})}async function Cr(e){try{return await e()}catch(e){throw t(e,`COMMAND_FAILED`)}}function wr(e){if(e.exitCode!==0)return e.signal?`simctl recordVideo was killed by ${e.signal}`:`simctl recordVideo exited with code ${e.exitCode}`}function Tr(n,r,i){let a=t(n,`COMMAND_FAILED`);return r===void 0||i===void 0||a.details?.reason!==`recording-output-unplayable`?n:new e(a.code,`${a.message}; ${r}`,_(i,{...a.details??{},...i.signal===void 0?{}:{signal:i.signal},retriable:!1,hint:`The recorder exited before record stop, so the next record stop reads the same file. Close this session to release the device, then record again.`}))}function Er(e,t){return e.appleOs===`macos`||!o(e)?t===void 0:t!==void 0&&/^tmp\/agent-device-recording-\d+\.mp4$/.test(t)}async function N(e){return await e.terminate(),await e.wait}async function Dr(e){try{return await N(e),{status:`cleaned`}}catch(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:`Apple simulator cleanup failed`}}}function Or(e){let{device:t,owner:n,input:r,descriptor:i,snapshot:a,finish:o,cleanup:s}=e,c=nt(a,{finish:o,forceCleanup:s});return Object.freeze({pendingHandle:new We(c),envelope:Wn({device:t,owner:n,input:r,descriptor:i})})}function kr(e,t,n={},r){let i=Date.now();return Object.freeze({backend:t,outPath:e.outputPath,...e.clientOutputPath===void 0?{}:{clientOutPath:e.clientOutputPath},startedAt:i,scope:e.scope,showTouches:e.showTouches,recordOnlySession:e.recordOnlySession,...e.activeSessionApp===void 0?{}:{activeSessionApp:e.activeSessionApp},...e.exportQuality===void 0?{}:{exportQuality:e.exportQuality},gestureEvents:[],...r===void 0?{}:{gestureClockOriginAtMs:r.wallClockAtMs,gestureClockOriginUptimeMs:r.uptimeMs},...n.recorderStartUptimeMs===void 0?{}:{gestureClockOriginAtMs:i,gestureClockOriginUptimeMs:n.recorderStartUptimeMs,runnerStartedAtUptimeMs:n.recorderStartUptimeMs},...n.runnerSessionId===void 0?{}:{runnerSessionId:n.runnerSessionId}})}function Ar(e,t){return Object.freeze({available:!1,reason:e,hint:t})}const jr=15e3;async function P(e,t,n,r={}){return n.throwIfAborted(),await wt(t)||s(t)?{...t,booted:!0}:t.kind===`device`?(await e.deviceReadiness.applePhysical.ensureConnected(t,n),{...t,booted:!0}):t.kind===`simulator`?((await Mr(e,t)?`Booted`:await Ir(e,t,n))!==`Booted`&&(r.onColdBootStart?.(),e.deviceReadiness.appleAutomation.keepHot(t),await Nr(e,t,n,r.deadlineAtMs),await Lr(e,n)),e.deviceReadiness.appleAutomation.keepHot(t),e.deviceReadiness.appleAutomation.markBooted(t),{...t,booted:!0}):{...t,booted:!0}}async function Mr(e,t){try{return await e.deviceReadiness.appleAutomation.wasRecentlyObservedBooted(t)}catch{return!1}}async function Nr(e,t,n,r=Date.now()+12e4){let i=!1;try{i=await Pr(e,t,n,r),await Fr(e,t,n,r)}catch(a){throw i&&n.aborted&&Rr(e,t),n.throwIfAborted(),Date.now()>=r?I(t,a):a}}async function Pr(t,n,r,i){let a=await t.appleTools.run({tool:`simctl`,args:y(n,[`boot`,n.id]),allowFailure:!0,timeoutMs:F(i,n)},r),o=`${a.stdout}\n${a.stderr}`.toLowerCase(),s=o.includes(`already booted`)||o.includes(`current state: booted`);if(a.exitCode!==0&&!s)throw new e(`COMMAND_FAILED`,`simctl boot failed`,{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode});return!s}async function Fr(t,n,r,i){ce({type:`command`,status:`progress`,message:`Waiting for the Simulator to finish booting...`});let a=await t.appleTools.run({tool:`simctl`,args:y(n,[`bootstatus`,n.id,`-b`]),allowFailure:!0,timeoutMs:F(i,n)},r);if(a.exitCode!==0)throw new e(`COMMAND_FAILED`,`simctl bootstatus failed`,{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode});if(await Rt(t.appleTools,n,r,Math.min(jr,F(i,n)))!==`Booted`)throw new e(`COMMAND_FAILED`,`Simulator is still booting`,{deviceId:n.id});if(Date.now()>=i)throw I(n)}function F(e,t){let n=e-Date.now();if(n<=0)throw I(t);return n}function I(t,n){return new e(`COMMAND_FAILED`,`Simulator did not finish booting within the startup budget`,{reason:`boot_timeout`,deviceId:t.id,hint:`The Simulator keeps booting in the background; a first boot can take several minutes. Retry once it is up, or pass a larger --timeout.`},n instanceof Error?n:void 0)}async function Ir(e,t,n){return await Rt(e.appleTools,t,n,jr)}async function Lr(e,t){await e.commands.run({executable:`open`,args:[`-a`,`Simulator`],allowFailure:!0,timeoutMs:1e4},t)}function Rr(e,t){e.appleTools.run({tool:`simctl`,args:y(t,[`shutdown`,t.id]),allowFailure:!0}).catch(()=>{})}const zr=Object.freeze({resolveOpenTarget:`simulator`,prepareApplicationOpen:`simulator`,openApplication:`simulator`,applyRuntimeHints:`simulator`,clearRuntimeHints:`simulator`,closeApplication:`simulator`,finalizeApplicationClose:`simulator`,prepareAppleRunner:`runner`,configureProviderPortReverse:`simulator`,ensureReady:`simulator`,bootTarget:`simulator`,bootTargetHeadless:`simulator`,shutdownTarget:`simulator`,listApps:`simulator`,deployApp:`simulator`,materializeAppSource:`simulator`,deployMaterializedApp:`simulator`,sendPushNotification:`simulator`,appState:`simulator`,appLogStart:`simulator`,appLogInspect:`simulator`,appLogDoctor:`simulator`,appLogReattach:`simulator`,appLogCleanup:`simulator`,networkDump:`simulator`,audioProbeStart:`simulator`,audioProbeQuery:`simulator`,audioProbeReattach:`simulator`,audioProbeCleanup:`simulator`,readClipboard:`simulator`,writeClipboard:`simulator`,setSetting:`simulator`,readSetting:`simulator`,setFoldPose:`simulator`,captureSnapshot:`simulator`,captureSnapshotWithoutActiveApp:`simulator`,captureSnapshotWithCustomActions:`runner`,captureScreenshot:`simulator`,findText:`runner`,readTextAtPoint:`runner`,tapPoint:`runner`,tapRef:`runner`,tapElementSelector:`runner`,fillPoint:`runner`,fillRef:`runner`,longPressPoint:`runner`,hoverPoint:`runner`,hoverRef:`runner`,focusPoint:`runner`,typeText:`runner`,scrollDirection:`runner`,performGesturePlan:`runner`,performMultiTouchGesturePlan:`runner`,performTargetAuthoredDrag:`runner`,performDirectionalFlingPlan:`runner`,gestureViewport:`runner`,setViewport:`runner`,back:`runner`,home:`runner`,setOrientation:`runner`,appSwitcher:`runner`,actionButton:`runner`,tvRemote:`runner`,keyboardDismiss:`runner`,keyboardEnter:`runner`,keyboardStatus:`runner`,triggerAppEvent:`runner`,readAlert:`runner`,awaitAlert:`runner`,acceptAlert:`runner`,dismissAlert:`runner`,perfFrames:`runner`,perfMemorySample:`runner`,perfMemorySnapshot:`runner`,perfNativeCaptureStart:`runner`,perfNativeCaptureReattach:`runner`,perfNativeCaptureCleanup:`runner`,perfProfileReport:`runner`,screenRecordingStart:`runner`,screenRecordingReattach:`runner`,screenRecordingCleanup:`runner`});function Br(e){return e===void 0?`possible`:e.some(e=>zr[e]===`runner`)?`required`:`none`}const Vr=new Map([[`application-element-missing`,5e3],[`application-server-unavailable`,5e3],[`foreground-owner-unverified`,1e3],[`foreground-owner-changed`,1e3]]);function L(e){return e.platform===`apple`&&e.appleOs===`ios`&&e.kind===`simulator`}function Hr(e){let t=re(ae({depth:1,interactiveOnly:!0}));return Object.freeze({awaitObservable:async(n,r,i)=>{if(!L(n))return`not-eligible`;let a;for(;;){let o=await e.resolveTarget(n,r,i).catch(()=>void 0);if(i.throwIfAborted(),!o)return`unobservable`;if(e.isBridgeDisabled(o))return g({level:`debug`,phase:`ios_launch_observation_skipped`,data:{reason:`circuit-disabled`,deviceId:n.id,generation:o.generation}}),`unobservable`;let s=await e.source.acquire({target:o,hint:t,signal:i});if(s.stage!==`failed`)return`observable`;i.throwIfAborted();let c=Vr.get(s.failure.code);if(c===void 0)return`unobservable`;let l=e.clock.now();if(a=Math.min(a??1/0,l+c),l>=a)return`unobservable`;await e.clock.sleep(Math.min(150,a-l),i)}}})}function Ur(e,t,n){let r=n&&L(e),i=r?Br(t.execution.plannedOperations):void 0,a=o(e)&&t.surface===`app`&&t.positionals.length>0&&!!t.appBundleId&&i!==`none`;return{...i?{runnerDemand:i}:{},shouldPrewarmRunner:a,awaitPrewarmAfterOpen:t.relaunch&&!r}}function Wr(e,t,n,r){r.runnerDemand===`none`&&e.appleApplications.releaseSpeculativeRunner(t.device,n.execution).catch(()=>{})}async function Gr(e,t,n,r,i,a){let o=Date.now();r&&L(t.device)&&i&&n.appBundleId&&(a.postOpenObservation=await i.awaitObservable(t.device,n.appBundleId,t.signal)),r&&a.postOpenObservation!==`observable`&&await e.clock.sleep(300,t.signal),a.postOpenSettleDurationMs=Math.max(0,Date.now()-o)}function Kr(e){let t=Et({device:e.device,signal:e.signal,resolveInteractor:e.host.localInteractors.resolve});return Object.freeze({resolveOpenTarget:async t=>await e.host.appleApplications.resolveOpenTarget(e.device,t),prepareApplicationOpen:async t=>{await P(e.host,e.device,e.signal,{deadlineAtMs:t.execution.startupDeadlineAtMs,onColdBootStart:t.prewarmRunnerOnColdBoot?()=>{e.host.appleApplications.prewarmRunnerCache(e.device,t.execution,e.signal).catch(()=>{})}:void 0})},openApplication:async n=>await qr(e.host,t,n,e.observation),applyRuntimeHints:async t=>await e.host.appleApplications.applyRuntimeHints(e.device,t),clearRuntimeHints:async t=>await e.host.appleApplications.clearRuntimeHints(e.device,t),closeApplication:async n=>await ri(e.host,t,n),finalizeApplicationClose:async t=>await ii(e.host,e.device,e.signal,t),prepareAppleRunner:async t=>await ai(e.host,e.device,e.signal,t),configureProviderPortReverse:ui})}async function qr(e,t,n,r){let i={},a=R(t.device),o=oi(e,t,n,i),s=Ur(t.device,n,a);s.runnerDemand&&(i.runnerDemand=s.runnerDemand),Wr(e,t,n,s);let{shouldPrewarmRunner:c}=s,l=ni(t.device,n,a);a&&c&&!n.prewarmRunnerBeforeOpen&&o.schedule();try{await Jr(e,t,n,a,l,i),await Yr(n,i),await Xr(o,c,n.prewarmRunnerBeforeOpen);let u=o.wasAwaited();return await Zr(t,n,a,i),await $r(o,c,s.awaitPrewarmAfterOpen),await ei(e,t,n,a,u,l),await Gr(e,t,n,a,r,i),{appBundleId:n.appBundleId,timing:i}}catch(n){throw l&&await e.appleApplications.stopRunnerSession(t.device.id).catch(()=>{}),n}}async function Jr(e,t,n,r,i,a){if(!ti(n,r)||!n.target)return;let o=Date.now();c(t.device.platform)&&!r&&!i&&await e.appleApplications.stopRunnerSession(t.device.id),await Tt({device:t.device,interactor:await t.resolveInteractor(n.execution,n.appBundleId),positionals:[n.appBundleId??n.target]}),r&&await e.clock.sleep(300,t.signal),a.relaunchCloseDurationMs=z(o)}async function Yr(t,n){if(!ue(t.runtimeHints))return;if(!t.applyRuntimeHints)throw new e(`COMMAND_FAILED`,`Runtime hint operation was not admitted for this open.`,{reason:`runtime-hints-operation-missing`});let r=Date.now();await t.applyRuntimeHints({appId:t.appBundleId,values:t.runtimeHints}),n.runtimeHintsDurationMs=z(r)}async function Xr(e,t,n){!t||!n||(e.schedule(!0),await e.wait())}async function Zr(e,t,n,r){let i=ci(t,n),a=Date.now();await Dt({device:e.device,interactor:await e.resolveInteractor(t.execution,t.appBundleId),positionals:i.positionals,appBundleId:t.appBundleId,execution:t.execution,...n&&t.relaunch&&!t.execution.clearAppState?{terminateRunningApp:!0}:{}}),r.openDispatchDurationMs=z(a),await Qr(e,t,i.followUpUrl,r)}async function Qr(e,t,n,r){if(!n){r.launchUrlDurationMs=0;return}let i={...t.execution,clearAppState:void 0,launchConsole:void 0,launchArgs:void 0},a=Date.now();await Dt({device:e.device,interactor:await e.resolveInteractor(i,t.appBundleId),positionals:[n],appBundleId:t.appBundleId,execution:i}),r.launchUrlDurationMs=z(a)}async function $r(e,t,n){t&&!e.wasScheduled()&&e.schedule(),n?await e.wait():e.recordUnawaited()}async function ei(e,t,n,r,i,a){!o(t.device)||!r&&!a||!n.relaunch&&!i||r&&!i&&!await e.appleApplications.hasLiveRunnerSession(t.device,n.execution)||await e.appleApplications.notifyRunnerAppRelaunched(t.device,n.execution,t.signal)}function ti(e,t){return!!(e.relaunch&&e.target)&&!(t&&!e.execution.clearAppState)}function ni(e,t,n){return e.kind===`device`&&e.appleOs===`ios`&&ti(t,n)}async function ri(e,t,n){n.ensureReady&&await P(e,t.device,t.signal),c(t.device.platform)&&!R(t.device)&&await e.appleApplications.stopRunnerSession(t.device.id),await Tt({device:t.device,interactor:await t.resolveInteractor(n.execution,n.appBundleId),positionals:n.positionals}),R(t.device)&&await e.clock.sleep(300,t.signal)}async function ii(e,t,n,r){r.daemonShutdown||await e.appleApplications.releaseRunnerOnClose(t.id,{retain:r.retainRunner}),await e.appleApplications.dismissCloseAlerts(t,r).catch(()=>{});let i=r.shutdownTarget&&R(t)?await e.deviceShutdown.apple.shutdownTarget(t,n):void 0;return i===void 0?{}:{shutdown:i}}async function ai(e,t,n,r){let i=Date.now()+r.timeoutMs;await P(e,t,n,{deadlineAtMs:i});let a=Math.max(1,i-Date.now());return await e.appleApplications.prepareRunner(t,{...r,timeoutMs:a},n)}function oi(e,t,n,r){let i,a=!1,o=si(t.device,n)?{healthCheck:!1}:void 0;return{schedule:(a=!1)=>{i||=(r.runnerPrewarmKind=`session`,r.runnerPrewarmScheduled=!0,o?e.appleApplications.prewarmRunnerSession(t.device,n.execution,t.signal,a,o):e.appleApplications.prewarmRunnerSession(t.device,n.execution,t.signal,a))},wait:async()=>{if(!i||a)return;a=!0;let e=Date.now();await i,r.runnerPrewarmWaited=!0,r.runnerPrewarmDurationMs=z(e)},wasAwaited:()=>a,wasScheduled:()=>i!==void 0,recordUnawaited:()=>{i&&!a&&(r.runnerPrewarmWaited=!1)}}}function si(e,t){return e.kind===`device`&&e.appleOs===`ios`&&!t.hasExistingSession&&!t.relaunch&&!t.prewarmRunnerBeforeOpen}function ci(e,t){let n=e.runtimeLaunchUrl?.trim(),i=e.positionals.length===1?e.positionals[0]?.trim():void 0;return!n||!i||r(i)?{positionals:e.positionals}:t&&!li(e)?{positionals:[i,n]}:{positionals:e.positionals,followUpUrl:n}}function li(e){return e.execution.clearAppState===!0||!!e.execution.launchConsole?.trim()||!!e.execution.launchArgs?.length}function R(e){return o(e)&&e.kind===`simulator`}function z(e){return Math.max(0,Date.now()-e)}async function ui(){throw new e(`UNSUPPORTED_OPERATION`,`This lifecycle operation is unavailable for Apple.`)}const di=Object.freeze({available:!0}),fi=Object.freeze({available:!1,reason:`unsupported-device-backend`,hint:`This command requires a CoreDevice-backed physical iOS device. The selected XCTest backend supports open, close, interactions, snapshots, and screenshots.`}),pi=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Push notifications are supported on Apple simulators only.`}),mi=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),hi=Object.freeze({available:!1,reason:`unsupported-device-kind`});function gi(e){let t=Ti(e);return Object.freeze({deployApp:t,materializeAppSource:t,deployMaterializedApp:t,sendPushNotification:Ei(e)})}function _i(e){let{host:t,device:n,signal:r}=e,i=gi(n);return Object.freeze({...i.deployApp.available?{deployApp:async e=>await vi(t,n,e,r),materializeAppSource:async e=>await t.appleDeployment.prepareArtifact(e,{signal:r}),deployMaterializedApp:async e=>await yi(t,n,e,r)}:{},...i.sendPushNotification.available?{sendPushNotification:async e=>(await Si(t,n,e,r),{})}:{}})}async function vi(e,t,n,r){if(n.replaceExisting)return await e.appleDeployment.withInvalidatedAppResolutionCache(t,async()=>{let i=await e.appleDeployment.resolveAppBundleId(t,n.app);await xi(e,t,i,r);let a=await e.appleDeployment.prepareArtifact({source:{kind:`path`,path:n.appPath}},{appIdentifierHint:n.app,signal:r});try{return await bi(e,t,a.installablePath,r),{bundleId:i,launchTarget:i}}finally{await a.cleanup()}});let i=await e.appleDeployment.prepareArtifact({source:{kind:`path`,path:n.appPath}},{appIdentifierHint:n.app,signal:r});try{return await yi(e,t,{artifact:i},r)}finally{await i.cleanup()}}async function yi(e,t,n,r){return await bi(e,t,n.artifact.installablePath,r),{...n.artifact.bundleId?{bundleId:n.artifact.bundleId}:{},...n.artifact.appName?{appName:n.artifact.appName}:{},...n.artifact.bundleId?{launchTarget:n.artifact.bundleId}:{}}}async function bi(e,t,n,r){await P(e,t,r),wi(await e.appleTools.run(t.kind===`simulator`?{tool:`simctl`,args:y(t,[`install`,t.id,n])}:{tool:`devicectl`,args:[`device`,`install`,`app`,`--device`,t.id,n],timeoutMs:12e4},r),`Apple app install failed`)}async function xi(e,t,n,r){await P(e,t,r);let i=await e.appleTools.run(t.kind===`simulator`?{tool:`simctl`,args:y(t,[`uninstall`,t.id,n]),allowFailure:!0}:{tool:`devicectl`,args:[`device`,`uninstall`,`app`,`--device`,t.id,n],allowFailure:!0},r);i.exitCode===0||Ci(`${i.stdout}\n${i.stderr}`)||wi(i,`Apple app uninstall failed for ${n}`)}async function Si(t,n,r,i){if(n.kind!==`simulator`)throw new e(`UNSUPPORTED_OPERATION`,`Apple push notifications require a simulator`);await P(t,n,i);let a=await t.temporaryFiles.create({prefix:`agent-device-ios-push-`,suffix:`.apns`});try{await a.writeText(`${JSON.stringify(r.payload)}\n`),wi(await t.appleTools.run({tool:`simctl`,args:y(n,[`push`,n.id,r.appId,a.path])},i),`Apple push notification failed`)}finally{await a[Symbol.asyncDispose]()}}function Ci(e){let t=e.toLowerCase();return t.includes(`not installed`)||t.includes(`not found`)||t.includes(`no such file`)}function wi(t,n){if(t.exitCode!==0)throw new e(`COMMAND_FAILED`,n,{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode})}function Ti(e){return Di(e)?e.kind!==`simulator`&&e.kind!==`device`?hi:e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?fi:di:mi}function Ei(e){return Di(e)?e.kind===`simulator`?di:pi:mi}function Di(e){return o(e)&&e.appleOs!==`watchos`}const B=Object.freeze({available:!0}),Oi=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`back is supported on Apple simulators and physical devices.`}),ki=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function Ai(e){return e.kind!==`simulator`&&e.kind!==`device`?Oi:d(e)===`watchos`?ki:B}const ji=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`home is supported on Apple simulators and physical devices.`}),Mi=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),Ni=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`app-switcher is supported on Apple simulators and physical devices.`});function Pi(e,t){if(e.kind!==`simulator`&&e.kind!==`device`)return t;let n=d(e);return n===`macos`||n===`watchos`?Mi:B}function V(e){if(e.kind!==`simulator`&&e.kind!==`device`)return!1;let t=d(e);return t!==`tvos`&&t!==`macos`&&t!==`watchos`}const Fi=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`orientation is supported on Apple simulators and physical devices.`}),Ii=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function Li(e){return e.kind!==`simulator`&&e.kind!==`device`?Fi:V(e)?B:Ii}const Ri=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`tv-remote is supported only on tvOS devices.`});function zi(e){return(e.kind===`simulator`||e.kind===`device`)&&a(e)?B:Ri}const H=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),Bi=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`keyboard status/get is currently supported only on Android; use keyboard dismiss or enter on iOS`});function Vi(e){return V(e)?Bi:H}function Hi(e){return V(e)?B:H}function Ui(e){return V(e)?B:H}const Wi=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`No Apple leaf carries this system button.`}),Gi=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`action-button is supported on iPhone and iPad simulators and physical devices.`}),Ki=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`The Action Button is iPhone and iPad hardware; tvOS, macOS, watchOS and visionOS have no such control.`});function qi(e){return e.kind!==`simulator`&&e.kind!==`device`?Gi:l(e)?B:Ki}function Ji(e){return Object.freeze({...Ie({back:Ai(e)}),...Ne({unsupported:Wi,home:Pi(e,ji),appSwitcher:Pi(e,Ni),actionButton:qi(e)}),...De({orientation:Li(e)}),...Pe({tvRemote:zi(e)}),...Oe({unsupported:H,status:Vi(e),dismiss:Hi(e),enter:Ui(e)})})}function Yi(e){let{host:t,device:n,signal:r}=e;return ht({device:n,signal:r,resolveInteractor:t.localInteractors.resolve,facts:Ji(n)})}const U=Object.freeze({available:!0}),Xi=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`clipboard is supported on Apple simulators and the macOS host.`}),Zi=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`settings is supported on Apple simulators and the macOS host.`}),Qi=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`settings is supported on Apple simulators and the macOS host, not on physical devices of this OS.`}),$i=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:"Apple targets answer a settings read only on iPhone and iPad simulators, where `simctl ui` reports the value the device holds."}),ea=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`clipboard is supported on Apple simulators and the macOS host, not on physical devices of this OS.`}),W=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function ta(e,t,n){if(e.kind!==`simulator`&&e.kind!==`device`)return t;let r=d(e);return r===`watchos`?W:e.kind===`simulator`||r===`macos`?U:n}function na(e){return ta(e,Xi,ea)}const ra=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`trigger-app-event is supported on Apple simulators and physical devices.`}),ia=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`alert is supported on Apple simulators and physical devices.`}),aa=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`alert is supported on Apple simulators, the macOS host, and physical iOS devices.`});function oa(e){if(e.kind!==`simulator`&&e.kind!==`device`)return ia;let t=d(e);return t===`watchos`?W:e.kind===`simulator`||t===`ios`||t===`macos`?U:aa}function sa(e){return e.kind!==`simulator`&&e.kind!==`device`?ra:d(e)===`watchos`?W:U}function ca(e){let t=na(e);return t.available?ea:t}function la(e){return e.kind!==`simulator`&&e.kind!==`device`?Zi:d(e)===`watchos`?W:u(e)?U:$i}function ua(e){let t=na(e),n=oa(e);return Object.freeze({...je({unsupported:ca(e),read:t,write:t}),...Me({read:n,wait:n,accept:n,dismiss:n}),...Ae({triggerAppEvent:sa(e)}),...Ee({setSetting:ta(e,Zi,Qi),readSetting:la(e)})})}function da(e){let{host:t,device:n,signal:r}=e;return ht({device:n,signal:r,resolveInteractor:t.localInteractors.resolve,facts:ua(n)})}const fa=/Angle:\s*(-?\d+(?:[.,]\d+)?)\s*°/g;async function pa(t,n={}){let r=[`devicectl`,`device`,`motion`,`hinge-angle`,`--device`,t.id,`--session-timeout`,`1`,`--timeout`,`5`],i=await v(r,{allowFailure:!0,signal:n.signal,timeoutMs:jt}),a=ma(i.stdout)??ma(i.stderr);if(a!==void 0)return a;throw new e(`COMMAND_FAILED`,`CoreDevice reported no hinge angle sample`,_(i,{cmd:`xcrun`,args:r,stdout:i.stdout,stderr:i.stderr,deviceId:t.id,hint:`This Xcode/CoreDevice toolchain does not stream 'devicectl device motion hinge-angle' for this device. Foldable poses can be verified only through that stream; update Xcode to a version that ships it.`}))}function ma(e){let t;for(let n of e.matchAll(fa)){let e=Number.parseFloat(n[1].replace(`,`,`.`));Number.isFinite(e)&&(t=e)}return t}async function ha(t,n,r){r?.throwIfAborted();let i=await Ot(`agent-device-fold-`);try{let a=b.join(i,`fold`),o=await v([`--sdk`,`iphonesimulator`,`clang`,`-mios-simulator-version-min=15.0`,`-fobjc-arc`,`-Wall`,`-Wextra`,`-Werror`,`-framework`,`Foundation`,`-framework`,`IOKit`,b.join(te(),`apple`,`fold-helper`,`Fold.m`),`-o`,a],{signal:r,timeoutMs:3e4,allowFailure:!0});if(o.exitCode!==0)throw new e(`COMMAND_FAILED`,`Unable to build the simulator fold helper`,_(o,{reason:`fold-helper-build-failed`,hint:`Select an Xcode with the iOS simulator SDK and foldable HID support using DEVELOPER_DIR.`}));r?.throwIfAborted();let s=typeof n==`string`?0:n.at(-1).atMs,c=typeof n==`string`?n:JSON.stringify(n),l=await v([`simctl`,`spawn`,t,a,c],{signal:r,timeoutMs:s+1e4,kill:{signal:`SIGTERM`,graceMs:1e3},allowFailure:!0});if(l.exitCode!==0)throw new e(`COMMAND_FAILED`,`Unable to send the simulator hinge pose`,_(l,{reason:`fold-hid-dispatch-failed`,deviceId:t}))}finally{await kt(i)}}async function ga(e,t,n={}){n.signal?.throwIfAborted(),Ft(e,`fold`);let r=t,i=r.keyframes?.at(-1)?.angle,a=r.pose??h(i);_a(e,await It(e,{signal:n.signal})),await ha(e.id,r.keyframes??a,n.signal),g({level:`info`,phase:`apple_fold_pose_dispatched`,data:{deviceId:e.id,pose:a}});let o=await va(e,a,n.signal,i),s=await Da(e,n.signal);return{pose:h(o),hingeAngleDegrees:o,...s?{screen:Oa(s)}:{}}}function _a(t,n){if(n.unresolved)throw new e(`COMMAND_FAILED`,`CoreDevice reported no display table for this simulator`,{deviceId:t.id,hint:`fold needs 'devicectl device info displays' to tell a foldable from a single-panel simulator; update Xcode to a version that ships the display-information feature.`});if(!n.multiScreen)throw new e(`UNSUPPORTED_OPERATION`,`${t.name} is not a foldable simulator: fold requires more than one integrated panel`,{deviceId:t.id,reason:`single-panel-device`,hint:`fold sets the hinge angle of a foldable simulator such as iPhone Duo; this simulator reports one integrated panel, so it has no hinge to pose.`})}async function va(e,t,n,r){let i,a;for(let o=1;o<=4;o+=1)if(n?.throwIfAborted(),a=i,i=await pa(e,{signal:n}),ya(i,a,t,r))return i;throw Sa(e,t,i,a,r)}function ya(e,t,n,r){return r===void 0?h(e)===n?n!==`half-open`||t!==void 0&&Ca(e,t):!1:ba(e,t,r)}function ba(e,t,n){return xa(e,n)?n===0||n===180||t!==void 0&&xa(t,n)&&Math.abs(e-t)<=.5:!1}function xa(e,t){return t===void 0||e!==void 0&&Math.abs(e-t)<=.5}function Sa(t,n,r,i,a){return xa(r,a)?a!==void 0&&r!==void 0?Ea(t,h(r),r,i):r!==void 0&&n===`half-open`&&h(r)===n?Ea(t,n,r,i):Ta(t,n,r):new e(`COMMAND_FAILED`,`The hinge did not reach the final keyframe angle`,{reason:`fold-angle-unverified`,targetAngleDegrees:a,hingeAngleDegrees:r,deviceId:t.id})}function Ca(e,t){return h(e)===`half-open`&&h(t)===`half-open`&&Math.abs(e-t)<=.5}function wa(e,t,n){return{deviceId:e.id,requestedPose:t,observedPose:n===void 0?void 0:h(n),hingeAngleDegrees:n}}function Ta(t,n,r){return new e(`COMMAND_FAILED`,`${t.name} did not reach the ${n} pose: CoreDevice still reports a hinge angle of ${r}°`,{...wa(t,n,r),reason:`fold-pose-unverified`,hint:`The simulator HID command completed, but the hinge did not follow. Verify that the selected Xcode and simulator runtime support foldable HID control, then retry.`})}function Ea(t,n,r,i){return new e(`COMMAND_FAILED`,`${t.name} was observed ${n} at ${r}° but did not settle: 4 hinge reads never held two consecutive angles within ${At}° of each other`,{...wa(t,n,r),reason:`fold-pose-unsettled`,...i===void 0?{}:{previousHingeAngleDegrees:i},hint:`The hinge reached the requested pose and was still moving when the read budget ended. Retry the fold, then read the angle directly with xcrun devicectl device motion hinge-angle --device <udid> --session-timeout 1 --timeout 5 to see whether the simulator holds the pose.`})}async function Da(e,t){let n=await It(e,{signal:t});if(!(n.unresolved||n.ambiguous))return n.activeDisplay}function Oa(e){return{display:e.name,coordinateSpace:se,widthPt:Math.round(e.widthPx/e.pointScale),heightPt:Math.round(e.heightPx/e.pointScale)}}const ka=Object.freeze({available:!0}),Aa=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`fold is supported on foldable iPhone simulators controlled through simulator HID; a physical device is folded by hand.`}),ja=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`fold poses the hinge of a foldable iPhone; tvOS, macOS, watchOS and visionOS simulators have no hinge.`});function Ma(e){if(e.kind!==`simulator`)return Aa;let t=d(e);return t===`ios`||t===`ipados`?ka:ja}function Na(e){return oe({fold:Ma(e)})}function Pa(e){let{device:t,signal:n}=e;return m(Na(t).setFoldPose,()=>({setFoldPose:async e=>(n.throwIfAborted(),await ga(t,e,{signal:n}))}))}function Fa(e,t,n){let r=Le({device:t.device,signal:t.signal,resolveInteractor:e.localInteractors.resolve}),i=async i=>{if(s(t.device)&&i.options?.surface!==void 0&&i.options.surface!==`app`)return await e.snapshot.captureSurface(t.device,i.options,Te(t.signal,i));if(!n)return await r.captureSnapshot(i);let a=Te(t.signal,i);return await n.capture(t.device,i,a,async e=>await r.captureSnapshot(e))};return Object.freeze({captureSnapshot:i,captureSnapshotWithCustomActions:i,captureSnapshotWithoutActiveApp:i})}function Ia(e,t){return Object.freeze({findText:async n=>{let r=await La(e,t,n);if(!r)return{found:!1};let i=await e.localInteractors.resolve(t.device,{...n.execution,...r});return i.findText?await i.findText(n.text,r):{found:!1}}})}async function La(e,t,n){let r=n.options?.appBundleId;if(r===void 0)return;let i=n.options?.surface;if(s(t.device)&&i!==void 0&&i!==`app`)return;let a=n.signal?AbortSignal.any([t.signal,n.signal]):t.signal;if(a.throwIfAborted(),await Ra(e,t.device,n.execution))return{appBundleId:r,signal:a}}async function Ra(e,t,n){return!L(t)||await e.appleApplications.hasLiveRunnerSession(t,n??{})}function za(){let e,t=!1,n=async()=>(e??=import(`./adapter.js`).then(({createSimulatorSnapshotSource:e})=>e()),await e);return{acquire:async e=>t?{stage:`failed`,failure:{kind:`unsupported`,code:`source-closed`}}:await(await n()).acquire(e),close:async()=>{t=!0,e&&await(await e).close()}}}const Ba=3e3;function Va(){let e=new Map,t=new Map,n=zt({waitMs:1500});return async(r,i,a,o)=>{a.throwIfAborted();let s=`${r.id}:${i}`,c=e.get(s);return c&&o!==`refresh`&&await Vt(c.pid,{signal:a,timeoutMs:Ba})===c.processStartTime?c:(e.delete(s),await n.value(s,{start:async()=>{let n=await Ha(r,i,t);return e.set(s,n),n},wait:(e,t)=>Bt({waitMs:e,signal:a,stop:t,cancelled:()=>a.reason}),pending:()=>G(`simulator-target-discovery-pending`,r,i)}))}}async function Ha(e,t,n){let r=Date.now()+15e3,[i,a]=await Promise.allSettled([Nt(e,[`spawn`,e.id,`launchctl`,`list`],{allowFailure:!0,timeoutMs:Ga(r)}),Ua(e,n,r)]);if(i.status===`rejected`)throw i.reason;if(a.status===`rejected`)throw a.reason;let o=i.value,s=a.value;if(o.exitCode!==0)throw G(`simulator-target-probe-failed`,e,t);let c=Wa(o.stdout,t);if(!c)throw G(`simulator-target-unavailable`,e,t);let l=await Vt(c.pid,{timeoutMs:Math.min(Ba,Ga(r))});if(!l)throw G(`simulator-target-identity-unavailable`,e,t);return Object.freeze({udid:e.id,runtime:s,pid:c.pid,generation:`${c.pid}:${c.label}:${l}`,targetId:`${e.id}:${t}`,processStartTime:l})}async function Ua(e,t,n){let r=t.get(e.id);if(r)return await r;let i=Nt(e,[`list`,`devices`,`-j`],{allowFailure:!0,timeoutMs:Ga(n)}).then(t=>{if(t.exitCode!==0)throw G(`simulator-runtime-probe-failed`,e,``);let n=JSON.parse(t.stdout),r=Object.entries(n.devices??{}).find(([,t])=>t.some(t=>t.udid===e.id))?.[0];if(!r)throw G(`simulator-runtime-unavailable`,e,``);return r});t.set(e.id,i);try{return await i}catch(n){throw t.delete(e.id),n}}function Wa(e,t){for(let n of e.split(`
4
+ `)){let[e,,r]=n.trim().split(/\s+/);if(!e||!r||!r.startsWith(`UIKitApplication:${t}[`))continue;let i=Number(e);if(Number.isSafeInteger(i)&&i>0)return{pid:i,label:r}}}function Ga(e){return Math.max(1,e-Date.now())}function G(t,n,r){return new e(`COMMAND_FAILED`,`Unable to resolve the running iOS Simulator app (${t}).`,{reason:t,deviceId:n.id,appBundleId:r})}function Ka(e=Date.now){let t=new Map;return async(n,r)=>{if(n.kind!==`simulator`)return`absent`;let i=t.get(n.id);if(i!==void 0&&e()-i.at<1e3)return{kind:`present`,host:i.host};t.delete(n.id);let a=await qa(n,r);return a!==`absent`&&a!==`unknown`&&t.set(n.id,{at:e(),host:a.host}),a}}async function qa(e,t){let n=!1;for(let r of ft){let i=await Ja(r.processExecutable,t);if(i===`unknown`){n=!0;continue}for(let a of i){let i=await Ya(a,e.id,t);if(i===`unknown`)n=!0;else if(i)return{kind:`present`,host:r}}}return n?`unknown`:`absent`}async function Ja(e,t){let n=await Xa(`pgrep`,[`-f`,e],t);return n===`unknown`?`unknown`:n.exitCode===1?[]:n.exitCode===0?n.stdout.split(`
5
+ `).map(e=>Number.parseInt(e.trim(),10)).filter(e=>Number.isSafeInteger(e)&&e>0):`unknown`}async function Ya(e,t,n){let r=await Xa(`ps`,[`eww`,`-p`,String(e),`-o`,`command=`],n);return r===`unknown`||r.exitCode!==0?`unknown`:r.stdout.includes(`SIMULATOR_UDID=${t}`)?!0:!r.stdout.includes(`SIMULATOR_UDID=`)&&`unknown`}async function Xa(e,t,n){try{let r=await Mt(e,t,{allowFailure:!0,timeoutMs:3e3,...n?{signal:n}:{}});return{exitCode:r.exitCode,stdout:r.stdout}}catch{return`unknown`}}const Za=`system-surface-presented`,Qa=`system-surface-host-lingering`,$a=`window-coordinate-space-unresolved`;function eo(t,n={}){let r=n.source??za(),i=n.resolveTarget??Va(),a=n.systemSurfacePresent??Ka(),o=new Set,s=new Map,c=e=>(go(e,s,o),o.has(_o(e))),l=Hr({source:r,resolveTarget:i,clock:t.clock,isBridgeDisabled:c});return Object.freeze({awaitObservable:l.awaitObservable,shutdown:async()=>await r.close(),capture:async(n,s,l,u)=>{if(!ro(n,s))return await so(n,s,u);let d=await a(n,l);if(d===`unknown`)return await K(n.id,s,u,lo(n.id,s),q(s),`system-surface-probe-unavailable`,[ho()]);if(d!==`absent`)return await oo(n,s,u,d.host.bundleId);let f;try{f=await to(t,i,n,s,l)}catch(e){return l.throwIfAborted(),J(`target-resolution-failed`,n,void 0,e),await K(n.id,s,u,lo(n.id,s),q(s),`target-resolution-failed`,[ho()])}if(c(f))return await K(n.id,s,u,f,q(s),`circuit-disabled`);let p=q(s),m=await r.acquire({target:f,hint:re(p),signal:l});if(m.stage===`failed`){if(m.failure.kind===`cancelled`)throw l.throwIfAborted(),new e(`COMMAND_FAILED`,`Simulator AX snapshot acquisition was cancelled.`,{reason:m.failure.code,...m.failure.details});let t=await mo(m.failure,f,n,s.options.appBundleId,l,i);return await io(s,u,f,t,p,m.failure,o)}try{return await ee(`ios.snapshot-source.present`,async()=>await t.snapshot.presentIosAcquisition(m,s.options),{producer:`simulator-ax-bridge`})}catch(e){return await io(s,u,f,{lineage:f,residue:[]},p,{kind:`malformed-tree`,code:`presentation-invariant`},o,e)}}})}async function to(e,t,n,r,i){let a=r.options.appBundleId;for(;;)try{return await t(n,a,i)}catch(t){if(!no(t))throw t;let i={requestId:r.execution?.requestId};if(await e.appleApplications.hasLiveRunnerSession(n,i))throw t}}function no(t){return t instanceof e&&t.details?.reason===`simulator-target-discovery-pending`}function ro(e,t){return e.platform===`apple`&&e.appleOs===`ios`&&e.kind===`simulator`&&!!t.options?.appBundleId&&t.options?.customActions!==!0&&t.options?.preferredBackend===void 0}async function io(e,t,n,r,i,a,o,s){return ao(a)&&o.add(_o(n)),J(a.code,{id:n.udid},n.generation,s,a.details),await K(n.udid,e,t,r.lineage,i,a.code,r.residue)}function ao(e){return e.kind!==`preparing`&&e.code!==$a}async function K(e,t,n,r,i,a,o=[]){return co(e,await n(t),r,i,a,o)}async function oo(e,t,n,r){let i=await n(t),a=i.systemSurface?Za:Qa;return i.systemSurface||J(a,e,void 0,void 0,{detectedHost:r}),co(e.id,i,lo(e.id,t),q(t),a)}async function so(e,t,n){let r=await n(t),i=r.systemSurface;return i?{...r,comparisonIdentity:fo(uo(e.id,i.bundleId),q(t),[])}:r}function co(e,t,n,r,i,a=[]){let o=t.systemSurface;return{...t,comparisonIdentity:fo(o?uo(e,o.bundleId):n,r,[...o?[]:a,{kind:`fallback-source`,producer:`apple-runner`}]),warnings:[...t.warnings??[],po(i,n,o!==void 0)]}}function lo(e,t){return{targetId:`${e}:${t.options.appBundleId}`}}function uo(e,t){return{targetId:`${e}:${t}`}}function fo(e,t,n){return Object.freeze({producer:`apple-runner`,intent:t.acquisitionIntent,lineage:Object.freeze({...e.targetId?{targetId:e.targetId}:{},...e.generation?{generation:e.generation}:{}}),presentationKey:ie(t),residue:Object.freeze([...n])})}function po(e,t,n){return e===Za?`Simulator AX snapshot inapplicable (${e}); used XCTest to read the system surface presented over the app.`:e===Qa?`Simulator AX snapshot inapplicable (${e}); used XCTest, which read app content: the system surface host process was still running but no longer presenting.`:n?`Simulator AX snapshot unavailable (${e}); used XCTest, which read the system surface presented over the app.`:e===`bridge-preparation-pending`?`Simulator AX snapshot unavailable (${e}); used XCTest for this capture while the bridge is still being prepared.`:e===$a?`Simulator AX snapshot unavailable (${e}); used XCTest for this capture, which reports captured geometry in the app's own orientation space.`:`Simulator AX snapshot unavailable (${e}); used XCTest for ${t.generation?`this app generation`:`an unverified app generation`}.`}async function mo(e,t,n,r,i,a){if(e.kind!==`stale-target`)return{lineage:t,residue:[]};try{return{lineage:await a(n,r,i,`refresh`),residue:[]}}catch(e){return i.throwIfAborted(),J(`fallback-target-resolution-failed`,n,void 0,e),{lineage:{targetId:t.targetId},residue:[ho()]}}}function ho(){return{kind:`unknown-generation`,captureId:Ht()}}function q(e){return ae({raw:e.options?.raw,interactiveOnly:e.options?.interactiveOnly,depth:e.options?.depth,scope:e.options?.scope,customActions:e.options?.customActions,acquisitionIntent:e.options?.acquisitionIntent})}function go(e,t,n){let r=t.get(e.targetId);r&&r!==e.generation&&n.delete(`${e.targetId}:${r}`),t.set(e.targetId,e.generation)}function _o(e){return`${e.targetId}:${e.generation}`}function J(e,t,n,r,i){g({level:`debug`,phase:`ios_snapshot_route_fallback`,data:{reason:e,deviceId:t.id,...n?{generation:n}:{},...r?{error:r instanceof Error?r.message:String(r)}:{},...i?{details:i}:{}}})}const Y=f(`apple`),X=Object.freeze({available:!0}),Z=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),vo=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`viewport resizes web targets only (--platform web). Apple screen geometry is fixed by the selected simulator or device type — open a different simulator to test another screen size.`}),yo=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`the stateless audio page probe is a web-session operation; Apple targets use the host capture.`}),bo=Object.freeze({available:!1,reason:`unsupported-device-backend`,hint:`perf requires an Apple simulator, macOS device, or CoreDevice-backed physical Apple device.`}),xo=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`focus is supported on Apple simulators and physical devices.`}),So=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Apple appstate is unavailable: the Apple target answers no sessionless foreground probe, and a session-scoped guess about the foreground is not a fact. The per-command answer is the targetActivation disclosure, which a capture carries when its command had to re-activate the session app (#2682).`}),Co=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Headless boot is supported only for local Android emulators.`}),wo=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS has no XCUITest-driveable UI, so element text comes from the captured tree only.`}),To=Object.freeze({available:!1,reason:`unsupported-device-kind`}),Eo=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS open is not supported because XCUITest cannot drive watchOS UI.`}),Do=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS runner preparation is not supported because XCUITest cannot drive watchOS UI.`}),Oo=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS close is not supported because XCUITest cannot drive watchOS UI.`}),ko=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Runtime hints are supported only for local iOS-family simulators and Android devices.`}),Ao=Q(`open is supported only for Apple simulators and devices.`),jo=Q(`prepare is supported only for Apple simulators and devices.`),Mo=Q(`close is supported only for Apple simulators and devices.`),No=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Port reverse is supported only by an owning provider runtime.`}),Po=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`shutdown is supported only for Apple simulators and Android emulators.`}),Fo=Q(`snapshot is supported only for Apple simulators and devices.`),Io=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Re-run without --actions, or target an iOS simulator.`}),Lo=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`screenshot is not supported on watchOS because XCUITest cannot drive watchOS UI.`}),Ro=Q(`screenshot is supported only for Apple simulators and devices.`),zo=Object.freeze({available:!1,reason:`owner-capability-missing`,hint:`Open the app under test before capturing its snapshot.`});function Q(e){return Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:e})}function Bo(e){return!o(e)||e.appleOs===`watchos`?Z:e.kind===`simulator`?X:Po}function Vo(e){let t=Ho(e),n=Uo(e),r=Wo(e),i=Go(e);return de({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:i,clearRuntimeHints:i,closeApplication:r,finalizeApplicationClose:r,prepareAppleRunner:n,configureProviderPortReverse:No})}function Ho(e){return d(e)===`watchos`?Eo:e.kind===`simulator`||e.kind===`device`?X:Ao}function Uo(e){return d(e)===`watchos`?Do:e.kind===`simulator`||e.kind===`device`?X:jo}function Wo(e){return d(e)===`watchos`?Oo:e.kind===`simulator`||e.kind===`device`?X:Mo}function Go(e){return d(e)!==`watchos`&&o(e)&&e.kind===`simulator`?X:ko}function Ko(e){return e.appleOs===`watchos`?Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS app inventory is not supported.`}):e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?Object.freeze({available:!1,reason:`unsupported-device-backend`,hint:`App inventory is available only on CoreDevice-backed physical iOS devices.`}):X}function $(e){return e.kind===`simulator`||e.kind===`device`?X:xo}function qo(e){let t=On(e),n=eo(e),r=async n=>{let r=await t.inspectFacts(n),i=gi(n),a=gr(n),c=a.available?await e.screenRecording.apple.availability(n):void 0,l=a.available&&c?.available===!1?Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:c.hint}):a,u=n.appleOs===`watchos`?Z:X,d=s(n)||n.appleOs===`watchos`?Z:X,f=Ko(n);return Object.freeze({device:r.device,operations:{...r.operations,...i,appState:So,networkDump:X,screenRecordingStart:l,screenRecordingReattach:l,screenRecordingCleanup:l,...Qo(n),...he({capture:Zo(n)}),...Se({findText:Xo(n)}),...ve({setViewport:vo}),..._e({focus:$(n)}),...Zt(n),...me({type:$(n)}),...Be({unsupported:Z,tap:$(n),longPress:$(n),fill:$(n),...o(n)?{tapElementSelector:$(n)}:{}}),...Fe({readTextAtPoint:Yo(n)}),...Ji(n),...Na(n),...ua(n),...Re({capture:Wt(n),query:yo}),...ze(Jo(n)),ensureReady:u,bootTarget:d,bootTargetHeadless:Co,listApps:f,...Vo(n),shutdownTarget:Bo(n)}})};return Object.freeze({owner:Y,ownsDevice:e=>e.platform===`apple`,inspectFacts:r,bind:async i=>{let a=await t.bind(i),o=await r(i.device),s=o.operations.screenRecordingStart,c={...a.operations,..._i({host:e,device:i.device,signal:i.scope.signal}),networkDump:async t=>await Mn(e,i.device,t,i.scope.signal),...m(s,()=>_r({host:e,device:i.device,owner:Y,signal:i.scope.signal})),...m(o.operations.audioProbeStart,()=>Xe({host:e.audioProbe.hostCapture,device:i.device,owner:Y})),...m(o.operations.perfFrames,()=>Gt({resolveHost:()=>e.perf.apple,device:i.device,owner:Y})),...m(o.operations.captureSnapshot,()=>Fa(e,{device:i.device,signal:i.scope.signal},n)),...m(o.operations.captureScreenshot,()=>we({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...m(o.operations.focusPoint,()=>xe({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...ke({device:i.device,signal:i.scope.signal,facts:o.operations,resolveInteractor:e.localInteractors.resolve}),...m(o.operations.scrollDirection,()=>be({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...m(o.operations.typeText,()=>Ce({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...m(o.operations.tapPoint,()=>Ve({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve,facts:o.operations,pause:async t=>await e.clock.sleep(t,i.scope.signal)})),...m(o.operations.readTextAtPoint,()=>pe({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...m(o.operations.findText,()=>Ia(e,{device:i.device,signal:i.scope.signal})),...Yi({host:e,device:i.device,signal:i.scope.signal}),...da({host:e,device:i.device,signal:i.scope.signal}),...Pa({device:i.device,signal:i.scope.signal}),...m(o.operations.ensureReady,()=>({ensureReady:async()=>await P(e,i.device,i.scope.signal)})),...m(o.operations.bootTarget,()=>({bootTarget:async()=>await P(e,i.device,i.scope.signal)})),...m(o.operations.listApps,()=>({listApps:async e=>{i.scope.signal.throwIfAborted();let{listIosApps:t}=await import(`./app-resolution.js`).then(e=>e.t);return(await t(e.device,e.filter)).map(e=>({id:e.bundleId,name:e.name}))}})),...le(Kr({host:e,device:i.device,signal:i.scope.signal,observation:n}),o.operations),...m(o.operations.shutdownTarget,()=>({shutdownTarget:async()=>await e.deviceShutdown.apple.shutdownTarget(i.device,i.scope.signal)}))};return Object.freeze({device:a.device,owner:Y,facts:o,operations:Ut(c),[Symbol.asyncDispose]:async()=>await a[Symbol.asyncDispose]()})},shutdown:async()=>{await Promise.all([t.shutdown(),n.shutdown()])}})}function Jo(e){let t=e.iosPhysicalDeviceBackend!==`xctest`&&d(e)!==`watchos`?X:bo;return{frames:t,memorySample:t,memorySnapshot:t,nativeCapture:t,profileReport:t}}function Yo(e){return d(e)===`watchos`?wo:e.kind===`simulator`||e.kind===`device`?X:To}function Xo(e){return d(e)===`watchos`?Fo:e.kind===`simulator`||e.kind===`device`?X:Fo}function Zo(e){return d(e)===`watchos`?Lo:e.kind===`simulator`||e.kind===`device`?X:Ro}function Qo(e){let t=Xo(e);return ge({capture:t,customActions:t.available&&o(e)&&e.kind===`simulator`?X:Io,withoutActiveApp:o(e)?zo:t})}export{qo as createApplePlatformRuntime};
@@ -1 +1 @@
1
- import{D as e,T as t}from"./sdk-contracts.js";import{o as n,s as r,t as i}from"./capture.js";import{p as a}from"./sdk-batch-runner.js";import{r as o}from"./sdk-device.js";import{er as s,tr as c}from"./sdk-batch.js";import{i as l}from"./recording-export-quality.js";import{n as u,s as d}from"./scroll-gesture.js";import{t as f}from"./gesture-plan-types.js";const p=[`pan`,`fling`,`swipe`,`pinch`,`rotate`,`transform`,`drag`];function m(t){let n=g(t),r=x(n,`kind`,p);if(r===`pan`)return{kind:r,origin:_(n,`origin`),delta:_(n,`delta`),pointerCount:a(n,`pointerCount`,{min:1,max:2}),durationMs:h(n)};if(r===`drag`)return ee(n);if(n.pointerCount!==void 0)throw new e(`INVALID_ARGS`,`pointerCount is supported only for gesture pan`);if(r===`fling`){if(n.durationMs!==void 0)throw new e(`INVALID_ARGS`,`gesture fling does not accept durationMs; use gesture pan for timed movement`);return{kind:r,direction:x(n,`direction`,u),origin:_(n,`origin`),distance:a(n,`distance`,{min:0})}}if(r===`swipe`){if(n.durationMs!==void 0)throw new e(`INVALID_ARGS`,`gesture swipe does not accept durationMs; use gesture pan for timed movement`);return{kind:r,preset:x(n,`preset`,d)}}if(r===`pinch`)return{kind:r,scale:y(n,`scale`),origin:v(n,`origin`)};if(r===`rotate`){if(n.velocity!==void 0)throw new e(`INVALID_ARGS`,`gesture rotate does not accept velocity; rotation pacing derives from degrees`);return{kind:r,degrees:y(n,`degrees`),origin:v(n,`origin`)}}return{kind:r,origin:_(n,`origin`),delta:_(n,`delta`),scale:y(n,`scale`),degrees:y(n,`degrees`),durationMs:h(n)}}function ee(t){let n=a(t,`sourceHoldMs`,{min:1,max:1e4}),r=a(t,`moveMs`,{min:16,max:1e4}),i=a(t,`destinationHoldMs`,{min:0,max:1e4});if((n??800)+(r??500)+(i??0)>1e4)throw new e(`INVALID_ARGS`,`gesture drag total duration must be at most ${f}`);return{kind:`drag`,source:b(t,`source`),destination:b(t,`destination`),sourceHoldMs:n,moveMs:r,destinationHoldMs:i}}function h(t){let n=a(t,`durationMs`);if(n!==void 0){if(n<16||n>1e4)throw new e(`INVALID_ARGS`,`Expected durationMs to be an integer between 16 and ${f}.`);return n}}function g(t){if(!t||typeof t!=`object`||Array.isArray(t))throw new e(`INVALID_ARGS`,`gesture requires structured object input`);return t}function _(e,t){let n=g(e[t]);return{x:y(n,`x`),y:y(n,`y`)}}function v(e,t){return e[t]===void 0?void 0:_(e,t)}function y(t,n){let r=t[n];if(typeof r!=`number`||!Number.isFinite(r))throw new e(`INVALID_ARGS`,`Expected ${n} to be a finite number.`);return r}function b(t,n){let r=t[n];if(typeof r!=`string`||r.trim().length===0)throw new e(`INVALID_ARGS`,`Expected ${n} to be a non-empty string.`);return r.trim()}function x(t,n,r){let i=t[n];if(typeof i!=`string`||!r.includes(i))throw new e(`INVALID_ARGS`,`Expected ${n} to be one of: ${r.join(`, `)}.`);return i}const S={swipe:{max:4,usage:`swipe accepts 4 arguments: x1 y1 x2 y2`,retired:{positional:`durationMs`,migrate:te}},"gesture pan":{max:5,usage:`gesture pan accepts at most 5 arguments: x y dx dy [durationMs]`},"gesture fling":{max:4,usage:`gesture fling accepts at most 4 arguments: direction x y [distance]`,retired:{positional:`durationMs`,migrate:(e,t)=>`use "${t}", or gesture pan for timed movement.`}},"gesture swipe":{max:1,usage:`gesture swipe accepts 1 argument: preset`,retired:{positional:`durationMs`,migrate:(e,t)=>`use "${t}", or gesture pan for timed movement.`}},"gesture pinch":{max:3,usage:`gesture pinch accepts at most 3 arguments: scale [x] [y]`},"gesture rotate":{max:3,usage:`gesture rotate accepts at most 3 arguments: degrees [x] [y]`,retired:{positional:`velocity`,migrate:(e,t)=>`use "${t}"; rotation pacing derives from degrees.`}},"gesture transform":{max:7,usage:`gesture transform accepts at most 7 arguments: x y dx dy scale degrees [durationMs]`},"gesture drag":{max:5,usage:`gesture drag accepts at most 5 arguments: source destination [sourceHoldMs] [moveMs] [destinationHoldMs]`}};function te(e,t){let[n,r,i,a,o]=e,s=C(n,i),c=C(r,a);return s===void 0||c===void 0?`use "gesture pan x1 y1 dx dy durationMs" for the same timed drag, or "${t}" for a default-duration swipe.`:`use "gesture pan ${n} ${r} ${s} ${c} ${o}" for the same timed drag, or "${t}" for a default-duration swipe.`}function C(e,t){let n=Number(t)-Number(e);return Number.isFinite(n)?n:void 0}function w(e,t){let n=S[e];if(t.length<=n.max)return;let r=n.retired;if(!r||t.length!==n.max+1||!T(t[n.max]))return{usage:n.usage};let i=`${e} ${t.slice(0,n.max).join(` `)}`;return{usage:n.usage,migration:`The trailing ${r.positional} positional was removed: ${r.migrate(t,i)}`}}function T(e){return e===void 0||e.trim().length===0?!1:e.startsWith("${")||Number.isFinite(Number(e))}function ne(t){if(!(!t||typeof t!=`object`||Array.isArray(t))&&t.durationMs!==void 0)throw new e(`INVALID_ARGS`,`swipe does not accept durationMs; use gesture pan for timed movement`)}function E(e,t){let n=t?`${e.usage} (${t})`:e.usage;return e.migration?`${n}. ${e.migration}`:`${n}.`}function D(t,n){let r=w(t,n);if(r)throw new e(`INVALID_ARGS`,E(r))}function re(e,t,n){let r=ie(e,t);return r?E(r,n):void 0}function ie(e,t){if(e===`swipe`)return w(`swipe`,t);if(e!==`gesture`)return;let n=`gesture ${t[0]}`;if(Object.hasOwn(S,n))return w(n,t.slice(1))}function O(e){return{origin:{x:Number(e[0]),y:Number(e[1])},delta:{x:Number(e[2]),y:Number(e[3])}}}function k(e,t){let n=e[0],r=e.slice(1);switch(n){case`pan`:{D(`gesture pan`,r);let{origin:e,delta:i}=O(r);return m({kind:n,origin:e,delta:i,pointerCount:t,durationMs:A(r[4])})}case`fling`:return D(`gesture fling`,r),m({kind:n,direction:r[0],origin:{x:Number(r[1]),y:Number(r[2])},distance:A(r[3])});case`swipe`:return D(`gesture swipe`,r),m({kind:n,preset:r[0]});case`pinch`:return D(`gesture pinch`,r),m({kind:n,scale:Number(r[0]),origin:j(r[1],r[2])});case`rotate`:return D(`gesture rotate`,r),m({kind:n,degrees:Number(r[0]),origin:j(r[1],r[2])});case`transform`:{D(`gesture transform`,r);let{origin:e,delta:t}=O(r);return m({kind:n,origin:e,delta:t,scale:Number(r[4]),degrees:Number(r[5]),durationMs:A(r[6])})}case`drag`:return D(`gesture drag`,r),m({kind:n,source:r[0],destination:r[1],sourceHoldMs:A(r[2]),moveMs:A(r[3]),destinationHoldMs:A(r[4])});default:return m({kind:n})}}function ae(e){if(e[0]!==`drag`)return;let t=k(e);return t.kind===`drag`?t:void 0}function oe(e){switch(e.kind){case`pan`:return M([e.kind,e.origin.x,e.origin.y,e.delta.x,e.delta.y,e.durationMs]);case`fling`:return M([e.kind,e.direction,e.origin.x,e.origin.y,e.distance]);case`swipe`:return[e.kind,e.preset];case`pinch`:return M([e.kind,e.scale,e.origin?.x,e.origin?.y]);case`rotate`:return e.origin?M([e.kind,e.degrees,e.origin.x,e.origin.y]):[e.kind,String(e.degrees)];case`transform`:return M([e.kind,e.origin.x,e.origin.y,e.delta.x,e.delta.y,e.scale,e.degrees,e.durationMs]);case`drag`:return[e.kind,e.source,e.destination,String(e.sourceHoldMs??800),String(e.moveMs??500),String(e.destinationHoldMs??0)]}}function se(e,t={}){return D(`swipe`,e),{from:{x:Number(e[0]),y:Number(e[1])},to:{x:Number(e[2]),y:Number(e[3])},...t.count===void 0?{}:{count:t.count},...t.pauseMs===void 0?{}:{pauseMs:t.pauseMs},...t.pattern===void 0?{}:{pattern:t.pattern}}}function ce(t){switch(t.kind){case`pan`:return{gesture:{intent:`pan`,origin:t.origin,delta:t.delta,pointerCount:t.pointerCount,durationMs:t.durationMs}};case`fling`:return{gesture:{intent:`fling`,direction:t.direction,origin:t.origin,distance:t.distance}};case`swipe`:return{gesture:{intent:`fling`,preset:t.preset}};case`pinch`:return{gesture:{intent:`pinch`,origin:t.origin,scale:t.scale}};case`rotate`:return{gesture:{intent:`rotate`,origin:t.origin,degrees:t.degrees}};case`transform`:return{gesture:{intent:`transform`,origin:t.origin,delta:t.delta,scale:t.scale,degrees:t.degrees,durationMs:t.durationMs}};case`drag`:throw new e(`INVALID_ARGS`,`gesture drag targets must be resolved before coordinate normalization`)}}function le(e){return e.kind===`drag`?{intent:`drag`,source:e.source,destination:e.destination,sourceHoldMs:e.sourceHoldMs,moveMs:e.moveMs,destinationHoldMs:e.destinationHoldMs}:ce(e).gesture}function ue(e){return{gesture:{intent:`fling`,from:e.from,to:e.to}}}function A(e){return e===void 0?void 0:Number(e)}function j(t,n){if(t===void 0!=(n===void 0))throw new e(`INVALID_ARGS`,`gesture origin requires both x and y coordinates`);return t===void 0?void 0:{x:Number(t),y:Number(n)}}function M(e){return e.filter(e=>e!==void 0).map(String)}const de={ios:!0,android:!0,harmonyos:!0};function N(e){return typeof e==`string`&&Object.hasOwn(de,e)}function P(e){return e.startsWith(`@`)?t(e)?.base??e:e}const F=/^-?\d+(\.\d+)?$/,fe=/^[^\s"\\]+$/,pe=new Map([[`--count`,`count`],[`--interval-ms`,`intervalMs`],[`--hold-ms`,`holdMs`],[`--jitter-px`,`jitterPx`]]),me=new Map([[`--count`,`count`],[`--pause-ms`,`pauseMs`]]),he=new Map([[`--pointer-count`,`pointerCount`]]),ge=new Map([[`--delay-ms`,`delayMs`]]);function I(e){return e===`click`||e===`press`}function L(e){return I(e)||e===`longpress`||e===`hover`}function R(e){return e===`type`||e===`fill`}function z(e){return H(e,_e)}function B(e){return JSON.stringify(e)}function V(e){return H(e,U)}function H(e,t){return t(e)?e:B(e)}function _e(e){return U(e)&&e.startsWith(`@`)||F.test(e)}function U(e){return fe.test(e)}const ve=new Set([`fill`,`type`]);function ye(e){if(!ve.has(e.command)){let t=(e.positionals??[]).map(e=>z(e));return[e.command,...t].join(` `)}let t=be(e).map(e=>z(e)).join(` `);return[e.command,t,`<text>`].filter(e=>e.length>0).join(` `)}function be(e){if(e.command===`type`)return[];let t=e.positionals??[],n=t[0];return n===void 0?[]:n.startsWith(`@`)?[n]:t.length>=3&&F.test(n)&&F.test(t[1]??``)?[n,t[1]]:[n]}function W(e,t){let n=t.flags??{};if(I(t.command)){typeof n.count==`number`&&e.push(`--count`,String(n.count)),typeof n.intervalMs==`number`&&e.push(`--interval-ms`,String(n.intervalMs)),typeof n.holdMs==`number`&&e.push(`--hold-ms`,String(n.holdMs)),typeof n.jitterPx==`number`&&e.push(`--jitter-px`,String(n.jitterPx)),n.doubleTap===!0&&e.push(`--double-tap`);let t=n.clickButton;t&&t!==`primary`&&e.push(`--button`,t);return}if(t.command===`swipe`){typeof n.count==`number`&&e.push(`--count`,String(n.count)),typeof n.pauseMs==`number`&&e.push(`--pause-ms`,String(n.pauseMs)),(n.pattern===`one-way`||n.pattern===`ping-pong`)&&e.push(`--pattern`,n.pattern);return}if(t.command===`gesture`){typeof n.pointerCount==`number`&&e.push(`--pointer-count`,String(n.pointerCount));return}R(t.command)&&typeof n.delayMs==`number`&&e.push(`--delay-ms`,String(n.delayMs))}function G(e,t){t&&(N(t.platform)&&e.push(`--platform`,t.platform),typeof t.metroHost==`string`&&t.metroHost.length>0&&e.push(`--metro-host`,V(t.metroHost)),typeof t.metroPort==`number`&&e.push(`--metro-port`,String(t.metroPort)),typeof t.bundleUrl==`string`&&t.bundleUrl.length>0&&e.push(`--bundle-url`,V(t.bundleUrl)),typeof t.launchUrl==`string`&&t.launchUrl.length>0&&e.push(`--launch-url`,V(t.launchUrl)))}function xe(e,t){let[n,...r]=t.positionals??[];n&&e.push(V(n));for(let t of r)e.push(z(t));typeof t.flags?.fps==`number`&&e.push(`--fps`,String(t.flags.fps)),(typeof t.flags?.quality==`number`||typeof t.flags?.quality==`string`)&&e.push(`--quality`,String(t.flags.quality)),t.flags?.hideTouches&&e.push(`--hide-touches`)}function Se(e,t){t.flags?.snapshotInteractiveOnly&&e.push(`-i`),typeof t.flags?.snapshotDepth==`number`&&e.push(`-d`,String(t.flags.snapshotDepth)),t.flags?.snapshotScope&&e.push(`-s`,z(t.flags.snapshotScope)),t.flags?.snapshotRaw&&e.push(`--raw`)}function Ce(e,t){for(let n of t.positionals??[])e.push(z(n));let r=t.flags?.screenshotCropOn;typeof r==`string`&&r.length>0&&e.push(`--crop-on`,V(r)),n(e,t.flags)}function we(e,t,n={}){let r=t.positionals??[],i=n.includeAllPositionals?r:r.slice(0,1);for(let t of i)e.push(V(t));G(e,t.flags)}function Te(e,t){for(let n of t.positionals??[])e.push(z(t.command===`wait`?P(n):n));W(e,t)}function K(e,t){let n=[],r={},i=I(e)?pe:e===`swipe`?me:e===`gesture`?he:R(e)?ge:void 0;for(let a=0;a<t.length;a+=1){let o=t[a];if(I(e)&&o===`--double-tap`){r.doubleTap=!0;continue}let s=t[a+1];if(I(e)&&o===`--button`&&s!==void 0){let e=s;(e===`primary`||e===`secondary`||e===`middle`)&&(r.clickButton=e),a+=1;continue}let c=i?.get(o);if(c&&s!==void 0){let e=J(s);if(e!==null){r[c]=e,a+=1;continue}}if(e===`swipe`&&o===`--pattern`&&s!==void 0){let e=s;(e===`one-way`||e===`ping-pong`)&&(r.pattern=e),a+=1;continue}n.push(o)}return{positionals:n,flags:r}}function q(e){let t=[],n={};for(let r=0;r<e.length;r+=1){let i=e[r],a=e[r+1];if(i===`--platform`&&a!==void 0){let e=a;N(e)&&(n.platform=e),r+=1;continue}if(i===`--metro-host`&&a!==void 0){n.metroHost=a,r+=1;continue}if(i===`--metro-port`&&a!==void 0){let e=J(a);e!==null&&(n.metroPort=e),r+=1;continue}if(i===`--bundle-url`&&a!==void 0){n.bundleUrl=a,r+=1;continue}if(i===`--launch-url`&&a!==void 0){n.launchUrl=a,r+=1;continue}t.push(i)}return{positionals:t,flags:n}}function J(e){if(!e)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}function Ee(e){let t;for(let n of e){if(n.command===`runtime`&&typeof n.flags.platform==`string`){t=n.flags.platform;continue}if(n.command===`open`)return n.runtime?.platform??t}return t}function De(e,t){for(let n of t.positionals??[])e.push(z(n));t.flags?.relaunch&&e.push(`--relaunch`),t.flags?.testIme===!0?e.push(`--test-ime`):t.flags?.testIme===!1&&e.push(`--no-test-ime`),G(e,t.runtime)}function Oe(e){let t=[],n={};for(let r of e){if(r===`--relaunch`){n.relaunch=!0;continue}if(r===`--test-ime`){n.testIme=!0;continue}if(r===`--no-test-ime`){n.testIme=!1;continue}t.push(r)}let r=q(t);return{positionals:r.positionals,flags:n,runtime:ke(r.flags)?r.flags:void 0}}function ke(e){return!!(e.platform||e.metroHost||e.metroPort!==void 0||e.bundleUrl||e.launchUrl)}const Y=/^[A-Z_][A-Z0-9_]*$/,Ae=new Set(o.filter(e=>e!==`web`)),je=new Set([`mobile`,`tv`,`desktop`]);function Me(t){let n=[],r=[],i=t.split(/\r?\n/),a=!1,o,l=(t,n,r)=>{let i=t.kind===`multiple`?`targets-v1`:`target-v1`;throw new e(`INVALID_ARGS`,`${i} annotation on line ${t.line} must be immediately followed by its action line (line ${n+1} ${r}).`)};for(let[t,u]of i.entries()){let i=u.trim();if(i.length===0){o&&l(o,t,`is blank`);continue}if(i.startsWith(`#`)){let e=s(i);if(e.kind===`v1`){o&&l(o,t,`is another target annotation`),o={kind:`multiple`,evidence:e.evidence,line:t+1};continue}let n=c(i);if(n.kind===`v1`){o&&l(o,t,`is another target annotation`),o={kind:`single`,evidence:n.evidence,line:t+1};continue}o&&l(o,t,`is a comment`);continue}if(X(i)){if(o&&l(o,t,`is an env directive`),a)throw new e(`INVALID_ARGS`,`env directives must precede all actions (line ${t+1}).`);continue}let d=Le(u);if(!d){o&&l(o,t,`did not parse as an action`);continue}let f=re(d.command,d.positionals??[],`line ${t+1}`);if(f)throw new e(`INVALID_ARGS`,f);o&&=(o.kind===`single`?d.targetEvidence=o.evidence:d.targetEvidences=o.evidence,void 0),n.push(d),r.push(t+1),a=!0}if(o){let t=o.kind===`multiple`?`targets-v1`:`target-v1`;throw new e(`INVALID_ARGS`,`${t} annotation on line ${o.line} must be immediately followed by its action line (end of script reached).`)}return{actions:n,actionLines:r}}function Ne(e){let t=e.split(/\r?\n/),n={};for(let[e,r]of t.entries()){let t=r.trim();if(t.length===0||t.startsWith(`#`))continue;if(X(t)){Ie(n,t,e+1);continue}if(!t.startsWith(`context `))break;let i=t.match(/(?:^|\s)platform=([^\s]+)/);if(i){let e=i[1];e&&Ae.has(e)&&Z(n,`platform`,e)}let a=t.match(/(?:^|\s)target=([^\s]+)/);if(a){let e=a[1];e&&je.has(e)&&Z(n,`target`,e)}let o=t.match(/(?:^|\s)timeout=(\d+)/);if(o){let e=Number(o[1]);Number.isFinite(e)&&e>=1&&Z(n,`timeoutMs`,Math.floor(e))}let s=t.match(/(?:^|\s)retries=(\d+)/);if(s){let e=Number(s[1]);Number.isFinite(e)&&e>=0&&Z(n,`retries`,Math.floor(e))}}return n}function X(e){return e===`env`||e.startsWith(`env `)||e.startsWith(`env `)}function Pe(t,n){let r=t.slice(3).replace(/^[\s]+/,``),i=r.indexOf(`=`);if(i<=0)throw new e(`INVALID_ARGS`,`Invalid env directive on line ${n}: expected "env KEY=VALUE".`);let a=r.slice(0,i);if(!Y.test(a))throw new e(`INVALID_ARGS`,`Invalid env key "${a}" on line ${n}: keys must be uppercase letters, digits, and underscores (e.g. APP_ID).`);if(a.startsWith(`AD_`))throw new e(`INVALID_ARGS`,`Invalid env key "${a}" on line ${n}: the AD_* namespace is reserved for built-in variables. Rename ${a} to avoid the AD_ prefix.`);return{key:a,value:Fe(r.slice(i+1),n)}}function Fe(t,n){if(t.length===0)return``;if(t.startsWith(`"`))try{let e=JSON.parse(t);if(typeof e!=`string`)throw Error(`not a string literal`);return e}catch{throw new e(`INVALID_ARGS`,`Invalid quoted env value on line ${n}.`)}return t}function Ie(t,n,r){let{key:i,value:a}=Pe(n,r),o=t.env??{};if(Object.prototype.hasOwnProperty.call(o,i))throw new e(`INVALID_ARGS`,`Duplicate env directive "${i}" on line ${r}.`);o[i]=a,t.env=o}function Z(t,n,r){let i=t[n];if(i!==void 0){let t=i===r?`Duplicate replay test metadata "${n}" in context header.`:`Conflicting replay test metadata "${n}" in context header: ${String(i)} vs ${String(r)}.`;throw new e(`INVALID_ARGS`,t)}t[n]=r}function Le(t){let n=t.trim();if(n.length===0||n.startsWith(`#`))return null;let[a,...o]=Re(n);if(a===void 0||a===`context`)return null;let s={ts:Date.now(),command:a,positionals:[],flags:{}};if(a===`snapshot`){s.positionals=[];for(let e=0;e<o.length;e+=1){let t=o[e];if(t===`-i`){s.flags.snapshotInteractiveOnly=!0;continue}if(t!==`-c`){if(t===`--raw`){s.flags.snapshotRaw=!0;continue}if(t===`--force-full`){s.flags.snapshotForceFull=!0;continue}if((t===`-d`||t===`--depth`)&&e+1<o.length){let t=Number(o[e+1]);Number.isFinite(t)&&t>=0&&(s.flags.snapshotDepth=Math.floor(t)),e+=1;continue}if((t===`-s`||t===`--scope`)&&e+1<o.length){s.flags.snapshotScope=o[e+1],e+=1;continue}if(t===`--backend`&&e+1<o.length){e+=1;continue}}}return s}if(a===`open`){let e=Oe(o);return s.positionals=e.positionals,Object.assign(s.flags,e.flags),s.runtime=e.runtime,s}if(a===`runtime`){let e=q(o);return s.positionals=e.positionals,Object.assign(s.flags,e.flags),s}if(I(a)){let e=K(a,o);Object.assign(s.flags,e.flags);let t=e.positionals[0];if(t===void 0)return s;if(t.startsWith(`@`))return s.positionals=[P(t)],e.positionals[1]&&(s.result={refLabel:e.positionals[1]}),s;let n=e.positionals[0],r=e.positionals[1];return $(n)&&$(r)&&e.positionals.length>=2?(s.positionals=[n,r],s):(s.positionals=[e.positionals.join(` `)],s)}if(a===`fill`){let e=K(a,o);if(Object.assign(s.flags,e.flags),!Q(e.positionals))return s.positionals=e.positionals,s;let[t,n,...r]=e.positionals;if($(t)&&$(n))return s.positionals=[t,n,r.join(` `)],s;let[i,c,...l]=e.positionals;if(i.startsWith(`@`)){let e=P(i);return l.length>0?(s.positionals=[e,l.join(` `)],s.result={refLabel:c},s):(s.positionals=[e,c],s)}return s.positionals=[i,[c,...l].join(` `)],s}if(a===`get`){let e=o[0],t=o[1];return e===void 0||t===void 0?(s.positionals=o,s):t.startsWith(`@`)?(s.positionals=[e,P(t)],o[2]&&(s.result={refLabel:o[2]}),s):(s.positionals=[e,o.slice(1).join(` `)],s)}if(a===`swipe`||a===`type`||a===`gesture`){let e=K(a,o);return Object.assign(s.flags,e.flags),s.positionals=e.positionals,s}if(a===`record`){let t=[];for(let n=0;n<o.length;n+=1){let r=o[n];if(r===i.cliToken)throw new e(`INVALID_ARGS`,i.migration.record);if(r===`--hide-touches`){s.flags.hideTouches=!0;continue}if(r===`--fps`&&n+1<o.length){let e=Number(o[n+1]);Number.isFinite(e)&&(s.flags.fps=Math.floor(e)),n+=1;continue}if(r===`--quality`&&n+1<o.length){let e=o[n+1],t=l(e);t!==void 0&&(s.flags.quality=t),n+=1;continue}t.push(r)}return s.positionals=t,s}if(a===`screenshot`){let e=[];for(let t=0;t<o.length;t+=1){let n=o[t],i=r({args:o,index:t,flags:s.flags});if(i.handled){t=i.nextIndex;continue}e.push(n)}return s.positionals=e,s}return s.positionals=a===`wait`||a===`longpress`||a===`hover`?o.map(e=>P(e)):o,s}function Q(e){return e.length>=2}function $(e){return e?!Number.isNaN(Number(e)):!1}function Re(e){let t=[],n=0;for(;n<e.length&&(n=ze(e,n),!(n>=e.length));){let r=e[n]===`"`?Be(e,n):Ve(e,n);t.push(r.value),n=r.nextCursor}return t}function ze(e,t){let n=t;for(;n<e.length&&/\s/.test(e.charAt(n));)n+=1;return n}function Be(t,n){let r=n+1,i=!1,a=r;for(;a<t.length;a+=1){let e=t.charAt(a);if(e===`"`&&!i)break;if(i){i=!1;continue}i=e===`\\`}if(a>=t.length)throw new e(`INVALID_ARGS`,`Invalid replay script line: ${t}`);let o=t.slice(n,a+1),s;try{s=JSON.parse(o)}catch{throw new e(`INVALID_ARGS`,`Invalid quoted value ${o} in replay script line: ${t}`,{hint:`Quoted replay values are JSON strings: escape backslashes, quotes, tabs, and newlines (\\\\, \\", \\t, \\n).`})}return{value:s,nextCursor:a+1}}function Ve(e,t){let n=t;for(;n<e.length&&!/\s/.test(e.charAt(n));)n+=1;return{value:e.slice(t,n),nextCursor:n}}export{ue as C,m as E,le as S,p as T,P as _,Ee as a,k as b,we as c,Se as d,ye as f,L as g,I as h,De as i,Ce as l,B as m,Me as n,Te as o,z as p,Ne as r,xe as s,Y as t,W as u,ne as v,se as w,oe as x,ae as y};
1
+ import{D as e,T as t}from"./sdk-contracts.js";import{o as n,s as r,t as i}from"./capture.js";import{p as a}from"./sdk-batch-runner.js";import{r as o}from"./sdk-device.js";import{er as s,tr as c}from"./sdk-batch.js";import{i as l}from"./recording-export-quality.js";import{n as u,s as d}from"./scroll-gesture.js";import{t as f}from"./gesture-plan-types.js";const p=[`pan`,`fling`,`swipe`,`pinch`,`rotate`,`transform`,`drag`];function m(t){let n=g(t),r=x(n,`kind`,p);if(r===`pan`)return{kind:r,origin:_(n,`origin`),delta:_(n,`delta`),pointerCount:a(n,`pointerCount`,{min:1,max:2}),durationMs:h(n)};if(r===`drag`)return ee(n);if(n.pointerCount!==void 0)throw new e(`INVALID_ARGS`,`pointerCount is supported only for gesture pan`);if(r===`fling`){if(n.durationMs!==void 0)throw new e(`INVALID_ARGS`,`gesture fling does not accept durationMs; use gesture pan for timed movement`);return{kind:r,direction:x(n,`direction`,u),origin:_(n,`origin`),distance:a(n,`distance`,{min:0})}}if(r===`swipe`){if(n.durationMs!==void 0)throw new e(`INVALID_ARGS`,`gesture swipe does not accept durationMs; use gesture pan for timed movement`);return{kind:r,preset:x(n,`preset`,d)}}if(r===`pinch`)return{kind:r,scale:y(n,`scale`),origin:v(n,`origin`)};if(r===`rotate`){if(n.velocity!==void 0)throw new e(`INVALID_ARGS`,`gesture rotate does not accept velocity; rotation pacing derives from degrees`);return{kind:r,degrees:y(n,`degrees`),origin:v(n,`origin`)}}return{kind:r,origin:_(n,`origin`),delta:_(n,`delta`),scale:y(n,`scale`),degrees:y(n,`degrees`),durationMs:h(n)}}function ee(t){let n=a(t,`sourceHoldMs`,{min:1,max:1e4}),r=a(t,`moveMs`,{min:16,max:1e4}),i=a(t,`destinationHoldMs`,{min:0,max:1e4});if((n??800)+(r??500)+(i??0)>1e4)throw new e(`INVALID_ARGS`,`gesture drag total duration must be at most ${f}`);return{kind:`drag`,source:b(t,`source`),destination:b(t,`destination`),sourceHoldMs:n,moveMs:r,destinationHoldMs:i}}function h(t){let n=a(t,`durationMs`);if(n!==void 0){if(n<16||n>1e4)throw new e(`INVALID_ARGS`,`Expected durationMs to be an integer between 16 and ${f}.`);return n}}function g(t){if(!t||typeof t!=`object`||Array.isArray(t))throw new e(`INVALID_ARGS`,`gesture requires structured object input`);return t}function _(e,t){let n=g(e[t]);return{x:y(n,`x`),y:y(n,`y`)}}function v(e,t){return e[t]===void 0?void 0:_(e,t)}function y(t,n){let r=t[n];if(typeof r!=`number`||!Number.isFinite(r))throw new e(`INVALID_ARGS`,`Expected ${n} to be a finite number.`);return r}function b(t,n){let r=t[n];if(typeof r!=`string`||r.trim().length===0)throw new e(`INVALID_ARGS`,`Expected ${n} to be a non-empty string.`);return r.trim()}function x(t,n,r){let i=t[n];if(typeof i!=`string`||!r.includes(i))throw new e(`INVALID_ARGS`,`Expected ${n} to be one of: ${r.join(`, `)}.`);return i}const S={swipe:{max:4,usage:`swipe accepts 4 arguments: x1 y1 x2 y2`,retired:{positional:`durationMs`,migrate:te}},"gesture pan":{max:5,usage:`gesture pan accepts at most 5 arguments: x y dx dy [durationMs]`},"gesture fling":{max:4,usage:`gesture fling accepts at most 4 arguments: direction x y [distance]`,retired:{positional:`durationMs`,migrate:(e,t)=>`use "${t}", or gesture pan for timed movement.`}},"gesture swipe":{max:1,usage:`gesture swipe accepts 1 argument: preset`,retired:{positional:`durationMs`,migrate:(e,t)=>`use "${t}", or gesture pan for timed movement.`}},"gesture pinch":{max:3,usage:`gesture pinch accepts at most 3 arguments: scale [x] [y]`},"gesture rotate":{max:3,usage:`gesture rotate accepts at most 3 arguments: degrees [x] [y]`,retired:{positional:`velocity`,migrate:(e,t)=>`use "${t}"; rotation pacing derives from degrees.`}},"gesture transform":{max:7,usage:`gesture transform accepts at most 7 arguments: x y dx dy scale degrees [durationMs]`},"gesture drag":{max:5,usage:`gesture drag accepts at most 5 arguments: source destination [sourceHoldMs] [moveMs] [destinationHoldMs]`}};function te(e,t){let[n,r,i,a,o]=e,s=C(n,i),c=C(r,a);return s===void 0||c===void 0?`use "gesture pan x1 y1 dx dy durationMs" for the same timed drag, or "${t}" for a default-duration swipe.`:`use "gesture pan ${n} ${r} ${s} ${c} ${o}" for the same timed drag, or "${t}" for a default-duration swipe.`}function C(e,t){let n=Number(t)-Number(e);return Number.isFinite(n)?n:void 0}function w(e,t){let n=S[e];if(t.length<=n.max)return;let r=n.retired;if(!r||t.length!==n.max+1||!T(t[n.max]))return{usage:n.usage};let i=`${e} ${t.slice(0,n.max).join(` `)}`;return{usage:n.usage,migration:`The trailing ${r.positional} positional was removed: ${r.migrate(t,i)}`}}function T(e){return e===void 0||e.trim().length===0?!1:e.startsWith("${")||Number.isFinite(Number(e))}function ne(t){if(!(!t||typeof t!=`object`||Array.isArray(t))&&t.durationMs!==void 0)throw new e(`INVALID_ARGS`,`swipe does not accept durationMs; use gesture pan for timed movement`)}function E(e,t){let n=t?`${e.usage} (${t})`:e.usage;return e.migration?`${n}. ${e.migration}`:`${n}.`}function D(t,n){let r=w(t,n);if(r)throw new e(`INVALID_ARGS`,E(r))}function re(e,t,n){let r=ie(e,t);return r?E(r,n):void 0}function ie(e,t){if(e===`swipe`)return w(`swipe`,t);if(e!==`gesture`)return;let n=`gesture ${t[0]}`;if(Object.hasOwn(S,n))return w(n,t.slice(1))}function O(e){return{origin:{x:Number(e[0]),y:Number(e[1])},delta:{x:Number(e[2]),y:Number(e[3])}}}function k(e,t){let n=e[0],r=e.slice(1);switch(n){case`pan`:{D(`gesture pan`,r);let{origin:e,delta:i}=O(r);return m({kind:n,origin:e,delta:i,pointerCount:t,durationMs:A(r[4])})}case`fling`:return D(`gesture fling`,r),m({kind:n,direction:r[0],origin:{x:Number(r[1]),y:Number(r[2])},distance:A(r[3])});case`swipe`:return D(`gesture swipe`,r),m({kind:n,preset:r[0]});case`pinch`:return D(`gesture pinch`,r),m({kind:n,scale:Number(r[0]),origin:j(r[1],r[2])});case`rotate`:return D(`gesture rotate`,r),m({kind:n,degrees:Number(r[0]),origin:j(r[1],r[2])});case`transform`:{D(`gesture transform`,r);let{origin:e,delta:t}=O(r);return m({kind:n,origin:e,delta:t,scale:Number(r[4]),degrees:Number(r[5]),durationMs:A(r[6])})}case`drag`:return D(`gesture drag`,r),m({kind:n,source:r[0],destination:r[1],sourceHoldMs:A(r[2]),moveMs:A(r[3]),destinationHoldMs:A(r[4])});default:return m({kind:n})}}function ae(e){if(e[0]!==`drag`)return;let t=k(e);return t.kind===`drag`?t:void 0}function oe(e){switch(e.kind){case`pan`:return M([e.kind,e.origin.x,e.origin.y,e.delta.x,e.delta.y,e.durationMs]);case`fling`:return M([e.kind,e.direction,e.origin.x,e.origin.y,e.distance]);case`swipe`:return[e.kind,e.preset];case`pinch`:return M([e.kind,e.scale,e.origin?.x,e.origin?.y]);case`rotate`:return e.origin?M([e.kind,e.degrees,e.origin.x,e.origin.y]):[e.kind,String(e.degrees)];case`transform`:return M([e.kind,e.origin.x,e.origin.y,e.delta.x,e.delta.y,e.scale,e.degrees,e.durationMs]);case`drag`:return[e.kind,e.source,e.destination,String(e.sourceHoldMs??800),String(e.moveMs??500),String(e.destinationHoldMs??0)]}}function se(e,t={}){return D(`swipe`,e),{from:{x:Number(e[0]),y:Number(e[1])},to:{x:Number(e[2]),y:Number(e[3])},...t.count===void 0?{}:{count:t.count},...t.pauseMs===void 0?{}:{pauseMs:t.pauseMs},...t.pattern===void 0?{}:{pattern:t.pattern}}}function ce(t){switch(t.kind){case`pan`:return{gesture:{intent:`pan`,origin:t.origin,delta:t.delta,pointerCount:t.pointerCount,durationMs:t.durationMs}};case`fling`:return{gesture:{intent:`fling`,direction:t.direction,origin:t.origin,distance:t.distance}};case`swipe`:return{gesture:{intent:`fling`,preset:t.preset}};case`pinch`:return{gesture:{intent:`pinch`,origin:t.origin,scale:t.scale}};case`rotate`:return{gesture:{intent:`rotate`,origin:t.origin,degrees:t.degrees}};case`transform`:return{gesture:{intent:`transform`,origin:t.origin,delta:t.delta,scale:t.scale,degrees:t.degrees,durationMs:t.durationMs}};case`drag`:throw new e(`INVALID_ARGS`,`gesture drag targets must be resolved before coordinate normalization`)}}function le(e){return e.kind===`drag`?{intent:`drag`,source:e.source,destination:e.destination,sourceHoldMs:e.sourceHoldMs,moveMs:e.moveMs,destinationHoldMs:e.destinationHoldMs}:ce(e).gesture}function ue(e){return{gesture:{intent:`fling`,from:e.from,to:e.to}}}function A(e){return e===void 0?void 0:Number(e)}function j(t,n){if(t===void 0!=(n===void 0))throw new e(`INVALID_ARGS`,`gesture origin requires both x and y coordinates`);return t===void 0?void 0:{x:Number(t),y:Number(n)}}function M(e){return e.filter(e=>e!==void 0).map(String)}const de={ios:!0,android:!0,harmonyos:!0};function N(e){return typeof e==`string`&&Object.hasOwn(de,e)}function P(e){return e.startsWith(`@`)?t(e)?.base??e:e}const F=/^-?\d+(\.\d+)?$/,fe=/^[^\s"\\]+$/,pe=new Map([[`--count`,`count`],[`--interval-ms`,`intervalMs`],[`--hold-ms`,`holdMs`],[`--jitter-px`,`jitterPx`]]),me=new Map([[`--count`,`count`],[`--pause-ms`,`pauseMs`]]),he=new Map([[`--pointer-count`,`pointerCount`]]),ge=new Map([[`--delay-ms`,`delayMs`]]);function I(e){return e===`click`||e===`press`}function L(e){return I(e)||e===`longpress`||e===`hover`}function R(e){return e===`type`||e===`fill`}function z(e){return H(e,_e)}function B(e){return JSON.stringify(e)}function V(e){return H(e,U)}function H(e,t){return t(e)?e:B(e)}function _e(e){return U(e)&&e.startsWith(`@`)||F.test(e)}function U(e){return fe.test(e)}const ve=new Set([`fill`,`type`]);function ye(e){if(!ve.has(e.command)){let t=(e.positionals??[]).map(e=>z(e));return[e.command,...t].join(` `)}let t=be(e).map(e=>z(e)).join(` `);return[e.command,t,`<text>`].filter(e=>e.length>0).join(` `)}function be(e){if(e.command===`type`)return[];let t=e.positionals??[],n=t[0];return n===void 0?[]:n.startsWith(`@`)?[n]:t.length>=3&&F.test(n)&&F.test(t[1]??``)?[n,t[1]]:[n]}function W(e,t){let n=t.flags??{};if(I(t.command)){typeof n.count==`number`&&e.push(`--count`,String(n.count)),typeof n.intervalMs==`number`&&e.push(`--interval-ms`,String(n.intervalMs)),typeof n.holdMs==`number`&&e.push(`--hold-ms`,String(n.holdMs)),typeof n.jitterPx==`number`&&e.push(`--jitter-px`,String(n.jitterPx)),n.doubleTap===!0&&e.push(`--double-tap`);let t=n.clickButton;t&&t!==`primary`&&e.push(`--button`,t);return}if(t.command===`swipe`){typeof n.count==`number`&&e.push(`--count`,String(n.count)),typeof n.pauseMs==`number`&&e.push(`--pause-ms`,String(n.pauseMs)),(n.pattern===`one-way`||n.pattern===`ping-pong`)&&e.push(`--pattern`,n.pattern);return}if(t.command===`gesture`){typeof n.pointerCount==`number`&&e.push(`--pointer-count`,String(n.pointerCount));return}R(t.command)&&typeof n.delayMs==`number`&&e.push(`--delay-ms`,String(n.delayMs))}function G(e,t){t&&(N(t.platform)&&e.push(`--platform`,t.platform),typeof t.metroHost==`string`&&t.metroHost.length>0&&e.push(`--metro-host`,V(t.metroHost)),typeof t.metroPort==`number`&&e.push(`--metro-port`,String(t.metroPort)),typeof t.bundleUrl==`string`&&t.bundleUrl.length>0&&e.push(`--bundle-url`,V(t.bundleUrl)),typeof t.launchUrl==`string`&&t.launchUrl.length>0&&e.push(`--launch-url`,V(t.launchUrl)))}function xe(e,t){let[n,...r]=t.positionals??[];n&&e.push(V(n));for(let t of r)e.push(z(t));typeof t.flags?.fps==`number`&&e.push(`--fps`,String(t.flags.fps)),(typeof t.flags?.quality==`number`||typeof t.flags?.quality==`string`)&&e.push(`--quality`,String(t.flags.quality)),t.flags?.hideTouches&&e.push(`--hide-touches`)}function Se(e,t){t.flags?.snapshotInteractiveOnly&&e.push(`-i`),typeof t.flags?.snapshotDepth==`number`&&e.push(`-d`,String(t.flags.snapshotDepth)),t.flags?.snapshotScope&&e.push(`-s`,z(t.flags.snapshotScope)),t.flags?.snapshotRaw&&e.push(`--raw`)}function Ce(e,t){for(let n of t.positionals??[])e.push(z(n));let r=t.flags?.screenshotCropOn;typeof r==`string`&&r.length>0&&e.push(`--crop-on`,V(r)),n(e,t.flags)}function we(e,t,n={}){let r=t.positionals??[],i=n.includeAllPositionals?r:r.slice(0,1);for(let t of i)e.push(V(t));G(e,t.flags)}function Te(e,t){for(let n of t.positionals??[])e.push(z(t.command===`wait`?P(n):n));t.command===`fold`&&t.flags?.keyframes!==void 0&&e.push(`--keyframes`,z(t.flags.keyframes)),W(e,t)}function K(e,t){let n=[],r={},i=I(e)?pe:e===`swipe`?me:e===`gesture`?he:R(e)?ge:void 0;for(let a=0;a<t.length;a+=1){let o=t[a];if(I(e)&&o===`--double-tap`){r.doubleTap=!0;continue}let s=t[a+1];if(e===`fold`&&o===`--keyframes`&&s!==void 0){r.keyframes=s,a+=1;continue}if(I(e)&&o===`--button`&&s!==void 0){let e=s;(e===`primary`||e===`secondary`||e===`middle`)&&(r.clickButton=e),a+=1;continue}let c=i?.get(o);if(c&&s!==void 0){let e=J(s);if(e!==null){r[c]=e,a+=1;continue}}if(e===`swipe`&&o===`--pattern`&&s!==void 0){let e=s;(e===`one-way`||e===`ping-pong`)&&(r.pattern=e),a+=1;continue}n.push(o)}return{positionals:n,flags:r}}function q(e){let t=[],n={};for(let r=0;r<e.length;r+=1){let i=e[r],a=e[r+1];if(i===`--platform`&&a!==void 0){let e=a;N(e)&&(n.platform=e),r+=1;continue}if(i===`--metro-host`&&a!==void 0){n.metroHost=a,r+=1;continue}if(i===`--metro-port`&&a!==void 0){let e=J(a);e!==null&&(n.metroPort=e),r+=1;continue}if(i===`--bundle-url`&&a!==void 0){n.bundleUrl=a,r+=1;continue}if(i===`--launch-url`&&a!==void 0){n.launchUrl=a,r+=1;continue}t.push(i)}return{positionals:t,flags:n}}function J(e){if(!e)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}function Ee(e){let t;for(let n of e){if(n.command===`runtime`&&typeof n.flags.platform==`string`){t=n.flags.platform;continue}if(n.command===`open`)return n.runtime?.platform??t}return t}function De(e,t){for(let n of t.positionals??[])e.push(z(n));t.flags?.relaunch&&e.push(`--relaunch`),t.flags?.testIme===!0?e.push(`--test-ime`):t.flags?.testIme===!1&&e.push(`--no-test-ime`),G(e,t.runtime)}function Oe(e){let t=[],n={};for(let r of e){if(r===`--relaunch`){n.relaunch=!0;continue}if(r===`--test-ime`){n.testIme=!0;continue}if(r===`--no-test-ime`){n.testIme=!1;continue}t.push(r)}let r=q(t);return{positionals:r.positionals,flags:n,runtime:ke(r.flags)?r.flags:void 0}}function ke(e){return!!(e.platform||e.metroHost||e.metroPort!==void 0||e.bundleUrl||e.launchUrl)}const Y=/^[A-Z_][A-Z0-9_]*$/,Ae=new Set(o.filter(e=>e!==`web`)),je=new Set([`mobile`,`tv`,`desktop`]);function Me(t){let n=[],r=[],i=t.split(/\r?\n/),a=!1,o,l=(t,n,r)=>{let i=t.kind===`multiple`?`targets-v1`:`target-v1`;throw new e(`INVALID_ARGS`,`${i} annotation on line ${t.line} must be immediately followed by its action line (line ${n+1} ${r}).`)};for(let[t,u]of i.entries()){let i=u.trim();if(i.length===0){o&&l(o,t,`is blank`);continue}if(i.startsWith(`#`)){let e=s(i);if(e.kind===`v1`){o&&l(o,t,`is another target annotation`),o={kind:`multiple`,evidence:e.evidence,line:t+1};continue}let n=c(i);if(n.kind===`v1`){o&&l(o,t,`is another target annotation`),o={kind:`single`,evidence:n.evidence,line:t+1};continue}o&&l(o,t,`is a comment`);continue}if(X(i)){if(o&&l(o,t,`is an env directive`),a)throw new e(`INVALID_ARGS`,`env directives must precede all actions (line ${t+1}).`);continue}let d=Le(u);if(!d){o&&l(o,t,`did not parse as an action`);continue}let f=re(d.command,d.positionals??[],`line ${t+1}`);if(f)throw new e(`INVALID_ARGS`,f);o&&=(o.kind===`single`?d.targetEvidence=o.evidence:d.targetEvidences=o.evidence,void 0),n.push(d),r.push(t+1),a=!0}if(o){let t=o.kind===`multiple`?`targets-v1`:`target-v1`;throw new e(`INVALID_ARGS`,`${t} annotation on line ${o.line} must be immediately followed by its action line (end of script reached).`)}return{actions:n,actionLines:r}}function Ne(e){let t=e.split(/\r?\n/),n={};for(let[e,r]of t.entries()){let t=r.trim();if(t.length===0||t.startsWith(`#`))continue;if(X(t)){Ie(n,t,e+1);continue}if(!t.startsWith(`context `))break;let i=t.match(/(?:^|\s)platform=([^\s]+)/);if(i){let e=i[1];e&&Ae.has(e)&&Z(n,`platform`,e)}let a=t.match(/(?:^|\s)target=([^\s]+)/);if(a){let e=a[1];e&&je.has(e)&&Z(n,`target`,e)}let o=t.match(/(?:^|\s)timeout=(\d+)/);if(o){let e=Number(o[1]);Number.isFinite(e)&&e>=1&&Z(n,`timeoutMs`,Math.floor(e))}let s=t.match(/(?:^|\s)retries=(\d+)/);if(s){let e=Number(s[1]);Number.isFinite(e)&&e>=0&&Z(n,`retries`,Math.floor(e))}}return n}function X(e){return e===`env`||e.startsWith(`env `)||e.startsWith(`env `)}function Pe(t,n){let r=t.slice(3).replace(/^[\s]+/,``),i=r.indexOf(`=`);if(i<=0)throw new e(`INVALID_ARGS`,`Invalid env directive on line ${n}: expected "env KEY=VALUE".`);let a=r.slice(0,i);if(!Y.test(a))throw new e(`INVALID_ARGS`,`Invalid env key "${a}" on line ${n}: keys must be uppercase letters, digits, and underscores (e.g. APP_ID).`);if(a.startsWith(`AD_`))throw new e(`INVALID_ARGS`,`Invalid env key "${a}" on line ${n}: the AD_* namespace is reserved for built-in variables. Rename ${a} to avoid the AD_ prefix.`);return{key:a,value:Fe(r.slice(i+1),n)}}function Fe(t,n){if(t.length===0)return``;if(t.startsWith(`"`))try{let e=JSON.parse(t);if(typeof e!=`string`)throw Error(`not a string literal`);return e}catch{throw new e(`INVALID_ARGS`,`Invalid quoted env value on line ${n}.`)}return t}function Ie(t,n,r){let{key:i,value:a}=Pe(n,r),o=t.env??{};if(Object.prototype.hasOwnProperty.call(o,i))throw new e(`INVALID_ARGS`,`Duplicate env directive "${i}" on line ${r}.`);o[i]=a,t.env=o}function Z(t,n,r){let i=t[n];if(i!==void 0){let t=i===r?`Duplicate replay test metadata "${n}" in context header.`:`Conflicting replay test metadata "${n}" in context header: ${String(i)} vs ${String(r)}.`;throw new e(`INVALID_ARGS`,t)}t[n]=r}function Le(t){let n=t.trim();if(n.length===0||n.startsWith(`#`))return null;let[a,...o]=Re(n);if(a===void 0||a===`context`)return null;let s={ts:Date.now(),command:a,positionals:[],flags:{}};if(a===`snapshot`){s.positionals=[];for(let e=0;e<o.length;e+=1){let t=o[e];if(t===`-i`){s.flags.snapshotInteractiveOnly=!0;continue}if(t!==`-c`){if(t===`--raw`){s.flags.snapshotRaw=!0;continue}if(t===`--force-full`){s.flags.snapshotForceFull=!0;continue}if((t===`-d`||t===`--depth`)&&e+1<o.length){let t=Number(o[e+1]);Number.isFinite(t)&&t>=0&&(s.flags.snapshotDepth=Math.floor(t)),e+=1;continue}if((t===`-s`||t===`--scope`)&&e+1<o.length){s.flags.snapshotScope=o[e+1],e+=1;continue}if(t===`--backend`&&e+1<o.length){e+=1;continue}}}return s}if(a===`open`){let e=Oe(o);return s.positionals=e.positionals,Object.assign(s.flags,e.flags),s.runtime=e.runtime,s}if(a===`runtime`){let e=q(o);return s.positionals=e.positionals,Object.assign(s.flags,e.flags),s}if(I(a)){let e=K(a,o);Object.assign(s.flags,e.flags);let t=e.positionals[0];if(t===void 0)return s;if(t.startsWith(`@`))return s.positionals=[P(t)],e.positionals[1]&&(s.result={refLabel:e.positionals[1]}),s;let n=e.positionals[0],r=e.positionals[1];return $(n)&&$(r)&&e.positionals.length>=2?(s.positionals=[n,r],s):(s.positionals=[e.positionals.join(` `)],s)}if(a===`fill`){let e=K(a,o);if(Object.assign(s.flags,e.flags),!Q(e.positionals))return s.positionals=e.positionals,s;let[t,n,...r]=e.positionals;if($(t)&&$(n))return s.positionals=[t,n,r.join(` `)],s;let[i,c,...l]=e.positionals;if(i.startsWith(`@`)){let e=P(i);return l.length>0?(s.positionals=[e,l.join(` `)],s.result={refLabel:c},s):(s.positionals=[e,c],s)}return s.positionals=[i,[c,...l].join(` `)],s}if(a===`get`){let e=o[0],t=o[1];return e===void 0||t===void 0?(s.positionals=o,s):t.startsWith(`@`)?(s.positionals=[e,P(t)],o[2]&&(s.result={refLabel:o[2]}),s):(s.positionals=[e,o.slice(1).join(` `)],s)}if(a===`swipe`||a===`type`||a===`gesture`||a===`fold`){let e=K(a,o);return Object.assign(s.flags,e.flags),s.positionals=e.positionals,s}if(a===`record`){let t=[];for(let n=0;n<o.length;n+=1){let r=o[n];if(r===i.cliToken)throw new e(`INVALID_ARGS`,i.migration.record);if(r===`--hide-touches`){s.flags.hideTouches=!0;continue}if(r===`--fps`&&n+1<o.length){let e=Number(o[n+1]);Number.isFinite(e)&&(s.flags.fps=Math.floor(e)),n+=1;continue}if(r===`--quality`&&n+1<o.length){let e=o[n+1],t=l(e);t!==void 0&&(s.flags.quality=t),n+=1;continue}t.push(r)}return s.positionals=t,s}if(a===`screenshot`){let e=[];for(let t=0;t<o.length;t+=1){let n=o[t],i=r({args:o,index:t,flags:s.flags});if(i.handled){t=i.nextIndex;continue}e.push(n)}return s.positionals=e,s}return s.positionals=a===`wait`||a===`longpress`||a===`hover`?o.map(e=>P(e)):o,s}function Q(e){return e.length>=2}function $(e){return e?!Number.isNaN(Number(e)):!1}function Re(e){let t=[],n=0;for(;n<e.length&&(n=ze(e,n),!(n>=e.length));){let r=e[n]===`"`?Be(e,n):Ve(e,n);t.push(r.value),n=r.nextCursor}return t}function ze(e,t){let n=t;for(;n<e.length&&/\s/.test(e.charAt(n));)n+=1;return n}function Be(t,n){let r=n+1,i=!1,a=r;for(;a<t.length;a+=1){let e=t.charAt(a);if(e===`"`&&!i)break;if(i){i=!1;continue}i=e===`\\`}if(a>=t.length)throw new e(`INVALID_ARGS`,`Invalid replay script line: ${t}`);let o=t.slice(n,a+1),s;try{s=JSON.parse(o)}catch{throw new e(`INVALID_ARGS`,`Invalid quoted value ${o} in replay script line: ${t}`,{hint:`Quoted replay values are JSON strings: escape backslashes, quotes, tabs, and newlines (\\\\, \\", \\t, \\n).`})}return{value:s,nextCursor:a+1}}function Ve(e,t){let n=t;for(;n<e.length&&!/\s/.test(e.charAt(n));)n+=1;return{value:e.slice(t,n),nextCursor:n}}export{ue as C,m as E,le as S,p as T,P as _,Ee as a,k as b,we as c,Se as d,ye as f,L as g,I as h,De as i,Ce as l,B as m,Me as n,Te as o,z as p,Ne as r,xe as s,Y as t,W as u,ne as v,se as w,oe as x,ae as y};