agent-device 0.21.4 → 0.21.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.4.apk → agent-device-android-ime-helper-0.21.5.apk} +0 -0
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.5.apk.sha256 +1 -0
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.4.manifest.json → agent-device-android-ime-helper-0.21.5.manifest.json} +4 -4
- package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.4.apk → agent-device-android-snapshot-helper-0.21.5.apk} +0 -0
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.5.apk.sha256 +1 -0
- package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.4.manifest.json → agent-device-android-snapshot-helper-0.21.5.manifest.json} +6 -6
- package/dist/src/adapter.js +1 -1
- package/dist/src/app-log-runtime2.js +1 -1
- package/dist/src/device-session.js +1 -1
- package/dist/src/internal/bin.js +1 -1
- package/dist/src/runtime4.js +4 -4
- package/dist/src/semantic-index.js +1 -1
- package/dist/src/snapshot-process.js +1 -1
- package/package.json +1 -1
- package/server.json +2 -2
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.4.apk.sha256 +0 -1
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.4.apk.sha256 +0 -1
|
Binary file
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
2b8fe19f9cf38877dbc4e0bd9400e4d1aebc7b8c2f6063e04f5f198d1564c08d agent-device-android-ime-helper-0.21.5.apk
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "android-ime-helper",
|
|
3
|
-
"version": "0.21.
|
|
4
|
-
"assetName": "agent-device-android-ime-helper-0.21.
|
|
5
|
-
"sha256": "
|
|
3
|
+
"version": "0.21.5",
|
|
4
|
+
"assetName": "agent-device-android-ime-helper-0.21.5.apk",
|
|
5
|
+
"sha256": "2b8fe19f9cf38877dbc4e0bd9400e4d1aebc7b8c2f6063e04f5f198d1564c08d",
|
|
6
6
|
"packageName": "com.callstack.agentdevice.imehelper",
|
|
7
|
-
"versionCode":
|
|
7
|
+
"versionCode": 21005,
|
|
8
8
|
"serviceComponent": "com.callstack.agentdevice.imehelper/.TestInputMethodService",
|
|
9
9
|
"broadcastProtocol": "android-ime-helper-v1"
|
|
10
10
|
}
|
|
Binary file
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
e77b65f51664e95680379cd1a5c8331926b63cf506261df56151854673787514 agent-device-android-snapshot-helper-0.21.5.apk
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "android-snapshot-helper",
|
|
3
|
-
"version": "0.21.
|
|
4
|
-
"releaseTag": "v0.21.
|
|
5
|
-
"assetName": "agent-device-android-snapshot-helper-0.21.
|
|
3
|
+
"version": "0.21.5",
|
|
4
|
+
"releaseTag": "v0.21.5",
|
|
5
|
+
"assetName": "agent-device-android-snapshot-helper-0.21.5.apk",
|
|
6
6
|
"apkUrl": null,
|
|
7
|
-
"sha256": "
|
|
8
|
-
"checksumName": "agent-device-android-snapshot-helper-0.21.
|
|
7
|
+
"sha256": "e77b65f51664e95680379cd1a5c8331926b63cf506261df56151854673787514",
|
|
8
|
+
"checksumName": "agent-device-android-snapshot-helper-0.21.5.apk.sha256",
|
|
9
9
|
"packageName": "com.callstack.agentdevice.snapshothelper",
|
|
10
|
-
"versionCode":
|
|
10
|
+
"versionCode": 21005,
|
|
11
11
|
"instrumentationRunner": "com.callstack.agentdevice.snapshothelper/.SnapshotInstrumentation",
|
|
12
12
|
"minSdk": 23,
|
|
13
13
|
"targetSdk": 36,
|
package/dist/src/adapter.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{C as e,j as t}from"./sdk-contracts.js";import{Br as n,zr as r}from"./sdk-batch.js";import{c as i,r as a}from"./diagnostics.js";import{f as o,x as s}from"./owner-identity.js";import{c,l,m as u,r as d}from"./exec.js";import{t as f}from"./file.js";import"./diagnostics2.js";import"./command.js";import{n as p}from"./retry.js";import{n as m}from"./version.js";import"./process.js";import{C as ee,D as te,c as ne,f as re,h as ie,n as ae,o as oe,w as se,y as ce}from"./host-file.js";import{t as le}from"./apple-runner-platform.js";import{t as ue}from"./snapshot-process.js";import h from"node:path";import{createHash as g,randomUUID as _}from"node:crypto";import de from"node:net";import{Buffer as v}from"node:buffer";const fe={unsupported:`UNSUPPORTED_OPERATION`,"malformed-tree":`COMMAND_FAILED`,"stale-target":`COMMAND_FAILED`,timeout:`COMMAND_FAILED`,cancelled:`COMMAND_FAILED`,"process-crash":`COMMAND_FAILED`,"transport-failure":`COMMAND_FAILED`};var y=class extends e{failureKind;failureCode;constructor(e,t,n=`iOS Simulator snapshot source ${e}: ${t}`,r={},i){super(fe[e],n,{...r,bridgeFailure:e,bridgeFailureCode:t,...e===`cancelled`?{reason:`request_canceled`}:{}},i),this.name=`SnapshotSourceError`,this.failureKind=e,this.failureCode=t}};function b(e,t,n={},r){return new y(e,t,void 0,n,r)}function x(n){return n instanceof y?n:t(n)?b(`cancelled`,`abort-signal`,{},n):n instanceof e&&typeof n.details?.timeoutMs==`number`?b(`timeout`,`host-operation-timeout`,{timeoutMs:n.details.timeoutMs},n):b(`transport-failure`,`unexpected-host-error`,{error:n instanceof Error?n.message:String(n)},n)}function pe(e,t,n=Date.now){if(t?.aborted)throw b(`cancelled`,`abort-signal`);return{clock:p.fromTimeoutMs(e,n()),now:n,signal:t}}function S(e,t){if(e.signal?.aborted)throw b(`cancelled`,`abort-signal`);let n=e.clock.remainingMs(e.now());if(n<=0)throw b(`timeout`,t);return Math.max(1,Math.floor(n))}async function C(e,t,n){let r=Math.min(t,S(e,n));await new Promise((t,n)=>{let i=!1,a=setTimeout(()=>s(t),r),o=()=>{s(()=>n(b(`cancelled`,`abort-signal`)))},s=t=>{i||(i=!0,clearTimeout(a),e.signal?.removeEventListener(`abort`,o),t())};e.signal?.addEventListener(`abort`,o,{once:!0}),e.signal?.aborted&&o()})}const w=[`SnapshotBridge.m`,`SnapshotBridgeRuntime.m`,`SnapshotBridgeRuntime.h`,`SnapshotBridgeCapture.h`,`SnapshotBridgeCapture.m`],me=[`SnapshotBridge.m`,`SnapshotBridgeRuntime.m`,`SnapshotBridgeCapture.m`];async function he(e,t,n){let r=g(`sha256`);for(let i of w){let a=h.join(t,i);if(S(n,`native-source-fingerprint-deadline`),!e.exists(a))throw b(`unsupported`,`native-source-missing`,{filePath:a});r.update(i),r.update(`\0`),r.update(await e.readBinary(a)),r.update(`\0`)}return r.digest(`hex`)}async function ge(e,t,n){let r=await T(e,`xcodebuild`,[`-version`],n),i=await T(e,`sw_vers`,[`-productVersion`],n),a=await T(e,`sw_vers`,[`-buildVersion`],n),o=await T(e,`uname`,[`-m`],n),s=await T(e,`xcrun`,[`--sdk`,`iphonesimulator`,`--show-sdk-version`],n),c=t.trim();if(!c)throw b(`unsupported`,`simulator-runtime-missing`);if(o!==`arm64`&&o!==`x86_64`)throw b(`unsupported`,`simulator-architecture-unsupported`,{architecture:o});return{xcode:r,macosProductVersion:i,macosBuild:a,architecture:o,simulatorSdk:s,simulatorRuntime:c}}async function T(e,t,n,r){let i=await _e(e,t,n,r);if(i.exitCode!==0)throw b(`unsupported`,`toolchain-probe-failed`,{command:t,exitCode:i.exitCode,stderr:i.stderr.slice(0,1024)});let a=(i.stdout||i.stderr).trim();if(!a)throw b(`unsupported`,`toolchain-probe-empty`,{command:t});return a}async function _e(e,t,n,r){try{return await E(e,t,n,r)}catch(i){if(!d(i))throw i;if(r.signal?.aborted)throw b(`cancelled`,`abort-signal`);if(r.clock.remainingMs(r.now())<=0)throw i;return await E(e,t,n,r)}}function E(e,t,n,r){return e.run(t,n,{allowFailure:!0,signal:r.signal,timeoutMs:Math.min(le,S(r,`toolchain-probe-deadline`))})}const D=`agent-device-simulator-ax-v1.5.5`;Object.freeze([`verb`,`requestId`,`pid`,`generation`,`snapshotTree`,`automationMode`,`maxDepth`,`maxNodes`,`maxDurationMs`,`maxResponseBytes`,`nativeLevelsHint`]),Object.freeze([`protocolVersion`,`sourceVersion`,`requestId`,`generation`,`ok`,`pid`,`tree`,`truncated`,`automationEnabled`,`recovery`,`error_kind`,`error_code`,`error`]),Object.freeze([`XC_kAXXCAttributeElementType`,`XC_kAXXCAttributeElementBaseType`,`XC_kAXXCAttributeLabel`,`XC_kAXXCAttributeValue`,`XC_kAXXCAttributeIdentifier`,`XC_kAXXCAttributeFrame`,`XC_kAXXCAttributeAutomationType`,`XC_kAXXCAttributeChildren`]);const ve=[`requests`,`rejected`,`continuations`,`acceptedLevels`];function ye(e){let t=e.recovery;if(!P(t))throw b(`malformed-tree`,`recovery-invalid`);let n=ve.map(e=>[e,t[e]]);if(n.some(([,e])=>!Number.isSafeInteger(e)||e<0))throw b(`malformed-tree`,`recovery-invalid`);return Object.freeze(Object.fromEntries(n))}function be(e,t){let n;try{n=v.from(JSON.stringify(e),`utf8`)}catch(e){throw b(`malformed-tree`,`request-not-json`,{},e)}let r=n.length+4;if(r>t.maxRequestBytes)throw b(`transport-failure`,`request-limit-exceeded`,{frameBytes:r,maxRequestBytes:t.maxRequestBytes});let i=v.alloc(4);return i.writeUInt32BE(n.length,0),v.concat([i,n])}var O=class{header=v.alloc(4);headerBytes=0;chunks=[];payloadBytes=0;expectedBodyBytes;frame;maxFrameBytes;constructor(e){if(!Number.isSafeInteger(e)||e<=0)throw b(`malformed-tree`,`frame-limit-invalid`,{maxFrameBytes:e});this.maxFrameBytes=e}push(e){if(this.frame)return this.acceptTrailingChunk(e);let t=this.readHeader(e);if(t&&(this.appendPayload(e,t.offset,t.bodyBytes),this.payloadBytes===t.bodyBytes))return this.frame=v.concat(this.chunks,t.bodyBytes),this.frame}acceptTrailingChunk(e){if(e.length>0)throw b(`malformed-tree`,`multiple-frames`,{trailingBytes:e.length});return this.frame}readHeader(e){if(this.headerBytes===4)return{offset:0,bodyBytes:this.expectedBodyBytes};let t=Math.min(4-this.headerBytes,e.length);if(e.copy(this.header,this.headerBytes,0,t),this.headerBytes+=t,this.headerBytes<4)return;let n=this.header.readUInt32BE(0);if(n===0||n>this.maxFrameBytes)throw b(`malformed-tree`,`frame-limit-exceeded`,{bodyBytes:n,maxFrameBytes:this.maxFrameBytes});return this.expectedBodyBytes=n,{offset:t,bodyBytes:n}}appendPayload(e,t,n){let r=n-this.payloadBytes,i=e.length-t;if(i>r)throw b(`malformed-tree`,`multiple-frames`,{trailingBytes:i-r});i!==0&&(this.chunks.push(e.subarray(t)),this.payloadBytes+=i)}finish(){if(this.frame)return this.frame;throw b(`transport-failure`,`bridge-frame-incomplete`,{headerBytes:this.headerBytes,payloadBytes:this.payloadBytes,expectedBodyBytes:this.expectedBodyBytes})}};function k(e){let t;try{t=JSON.parse(e.toString(`utf8`))}catch(e){throw b(`malformed-tree`,`response-not-json`,{},e)}if(!P(t))throw b(`malformed-tree`,`response-not-object`);return t}function A(e){return Object.freeze({verb:`describe`,requestId:e.requestId,pid:e.pid,generation:e.generation,snapshotTree:!0,automationMode:!0,maxDepth:e.maxDepth,maxNodes:e.maxNodes,maxDurationMs:e.maxDurationMs,maxResponseBytes:e.maxResponseBytes,...e.nativeLevelsHint===void 0?{}:{nativeLevelsHint:e.nativeLevelsHint}})}function j(e,t){if(e.protocolVersion!==1)throw b(`transport-failure`,`protocol-version-mismatch`,{expected:1,observed:e.protocolVersion});if(e.sourceVersion!==`agent-device-simulator-ax-v1.5.5`)throw b(`transport-failure`,`source-version-mismatch`,{expected:D,observed:e.sourceVersion});if(e.requestId!==t)throw b(`transport-failure`,`request-id-mismatch`,{expected:t,observed:e.requestId})}function M(e,t){if(typeof e.pid!=`number`||e.pid!==t.pid)throw b(`stale-target`,`bridge-pid-mismatch`,{expectedPid:t.pid,observedPid:e.pid});if(e.generation!==t.generation)throw b(`stale-target`,`bridge-generation-mismatch`,{expectedGeneration:t.generation,observedGeneration:e.generation})}function N(e){let t=e.error_kind,n=typeof e.error_code==`string`?e.error_code:`guest-error`,r=typeof e.error==`string`?e.error:void 0,i=r?{guestMessage:r.slice(0,1024)}:{};throw b(t===`unsupported`?`unsupported`:t===`malformed_tree`?`malformed-tree`:t===`application_not_responding`?`timeout`:t===`application_unavailable`?`transport-failure`:t===`bad_request`?`malformed-tree`:`transport-failure`,n,i)}function P(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const F=`snapshot-bridge`,I=`manifest.json`;async function xe(e){let t=e.deadline,n=e.sourceRoot??Se(e.host),r=await he(e.host,n,t),i=await ge(e.host,e.runtime,t),a=we({schemaVersion:1,protocolVersion:1,sourceVersion:D,sourceHash:r,toolchain:i}),o=e.cacheRoot??h.join(e.host.homeDirectory(),`.agent-device`,`snapshot-source`),s=h.join(o,a),c=await e.host.acquireLock(h.join(o,`${a}.lock`),{deadline:t});try{let c=await Ce(e.host,s,{sourceHash:r,cacheKey:a,toolchain:i},t);if(c)return c;S(t,`native-build-deadline`),e.host.exists(s)&&await e.host.remove(s),S(t,`native-build-deadline`),await e.host.ensureDirectory(o);let l=h.join(o,`.${a}.${e.host.processId()}.tmp`);S(t,`native-build-deadline`),await e.host.remove(l);try{S(t,`native-build-deadline`),await e.host.ensureDirectory(l);let o=h.join(l,F),c=await e.host.run(`xcrun`,[`--sdk`,`iphonesimulator`,`clang`,`-arch`,i.architecture,`-mios-simulator-version-min=15.0`,`-fobjc-arc`,`-Werror`,`-Wall`,`-Wextra`,`-framework`,`Foundation`,`-framework`,`CoreGraphics`,...me.map(e=>h.join(n,e)),`-o`,o],{signal:t.signal,timeoutMs:Math.min(12e4,S(t,`native-build-deadline`)),allowFailure:!0});if(c.exitCode!==0||!e.host.exists(o))throw b(`unsupported`,`native-build-failed`,{exitCode:c.exitCode,stderr:c.stderr.slice(0,4096)});S(t,`native-build-deadline`),await e.host.chmod(o,493);let u=await L(e.host,o,t),d={schemaVersion:1,protocolVersion:1,sourceVersion:D,sourceHash:r,cacheKey:a,toolchain:i,binarySha256:u};return await e.host.writeText(h.join(l,I),`${JSON.stringify(d,null,2)}\n`),S(t,`native-build-deadline`),await e.host.rename(l,s),{path:h.join(s,F),sourceHash:r,cacheKey:a,protocolVersion:1,sourceVersion:D}}catch(t){throw await e.host.remove(l),t}}finally{await c()}}function Se(e){let t=e.projectRoot(),n=h.join(t,`apple`,`snapshot-bridge`);if(w.every(t=>e.exists(h.join(n,t))))return n;let r=h.join(t,`dist`,`apple`,`snapshot-bridge`);if(w.every(t=>e.exists(h.join(r,t))))return r;throw b(`unsupported`,`native-source-missing`,{projectRoot:t})}async function Ce(e,t,n,r){let i=h.join(t,F);if(!(!e.exists(i)||!e.exists(h.join(t,I))))try{let a=JSON.parse(await e.readText(h.join(t,I)));return a.schemaVersion!==1||a.protocolVersion!==1||a.sourceVersion!==`agent-device-simulator-ax-v1.5.5`||a.sourceHash!==n.sourceHash||a.cacheKey!==n.cacheKey||JSON.stringify(a.toolchain)!==JSON.stringify(n.toolchain)||typeof a.binarySha256!=`string`||await L(e,i,r)!==a.binarySha256?void 0:{path:i,sourceHash:n.sourceHash,cacheKey:n.cacheKey,protocolVersion:1,sourceVersion:D}}catch(e){if(e instanceof y&&(e.failureKind===`cancelled`||e.failureKind===`timeout`))throw e;return}}async function L(e,t,n){return S(n,`native-cache-hash-deadline`),g(`sha256`).update(await e.readBinary(t)).digest(`hex`)}function we(e){return g(`sha256`).update(JSON.stringify(e)).digest(`hex`).slice(0,32)}var Te=class{entries=new Map;probeBackAfterUses;constructor(e=8){this.probeBackAfterUses=e}consume(e,t,n){if(n)return{nativeLevels:void 0,reason:`explicit-depth`};let r=this.currentEntry(e);return r===`unidentified`?{nativeLevels:void 0,reason:`unidentified-target`}:!r||r.nativeLevels>=t?{nativeLevels:void 0,reason:`no-hint`}:r.remainingUses<=0?{nativeLevels:void 0,reason:`probe-back`}:(--r.remainingUses,{nativeLevels:r.nativeLevels,reason:`hinted`})}learn(e,t,n,r){return n||!e.targetId?`ignored`:r.rejected>0&&r.acceptedLevels<t?(this.remember(e.targetId,{generation:e.generation,nativeLevels:r.acceptedLevels,remainingUses:this.probeBackAfterUses}),`learned`):r.rejected===0&&r.acceptedLevels>=t?this.entries.delete(e.targetId)?`forgotten`:`ignored`:this.currentEntry(e)?`kept`:`ignored`}currentEntry(e){if(!e.targetId)return`unidentified`;let t=this.entries.get(e.targetId);if(t){if(t.generation!==e.generation){this.entries.delete(e.targetId);return}return t}}remember(e,t){if(this.entries.delete(e),this.entries.size>=32){let e=this.entries.keys().next().value;e!==void 0&&this.entries.delete(e)}this.entries.set(e,t)}};const R=65536;function Ee(){return{projectRoot:m,homeDirectory:re,run:async(e,t,n)=>await c(e,t,n),start:De,connect:z,readText:ce,readBinary:ie,writeText:te,ensureDirectory:oe,chmod:ae,exists:ne,rename:se,remove:ee,acquireLock:Oe,emitDiagnostic:a,withDiagnosticTimer:i,processId:o,readTargetProcessStartTime:ue}}function De(e,t,n,r={}){if(r.signal?.aborted)throw b(`cancelled`,`abort-signal`);let i=l(`xcrun`,[`simctl`,`spawn`,e,t,`serve`,n,`--idle-timeout`,`60`,`--exit-on-disconnect`,`false`],{allowFailure:!0,captureOutput:!1,detached:!0}),a=i.child.pid??0;if(a<=0)throw b(`transport-failure`,`bridge-process-pid-missing`);let o=``;return i.child.stderr?.setEncoding(`utf8`),i.child.stderr?.on(`data`,e=>{o=ke(o,String(e))}),{pid:a,wait:i.wait,isAlive:()=>i.child.exitCode===null&&i.child.signalCode===null,signal:e=>{u(a,e)||i.child.kill(e)},readLog:()=>o}}async function z(e,t){if(t.signal?.aborted)throw b(`cancelled`,`abort-signal`);let n=Math.max(1,Math.floor(t.timeoutMs));return await new Promise((r,i)=>{let a=de.createConnection({path:e}),o=!1,s=!1,c=setTimeout(()=>{p(b(`timeout`,`bridge-connect-timeout`)),a.destroy()},n),l=()=>{p(b(`cancelled`,`abort-signal`)),a.destroy()},u=()=>{o=!0,clearTimeout(c),t.signal?.removeEventListener(`abort`,l),a.off(`error`,d),a.off(`close`,f),a.setTimeout(0),r(a)},d=e=>{p(e),a.destroy()},f=()=>{o||p(b(`transport-failure`,`bridge-closed-before-connect`))},p=e=>{s||o||(s=!0,clearTimeout(c),t.signal?.removeEventListener(`abort`,l),a.off(`connect`,u),a.off(`error`,d),a.off(`close`,f),i(e))};a.once(`connect`,u),a.once(`error`,d),a.once(`close`,f),t.signal?.addEventListener(`abort`,l,{once:!0}),t.signal?.aborted&&l()})}async function Oe(e,t){let n=o(),r=t.deadline,i=f({lockDirPath:e,owner:{pid:n,startTime:s(n),acquiredAtMs:Date.now()},timeoutMs:S(r,`cache-lock-deadline`),pollMs:100,ownerGraceMs:5e3,description:`iOS Simulator snapshot bridge cache`}),a=r.signal;if(!a)return await i;let c=!1,l,u=new Promise((e,t)=>{l=()=>{c=!0,t(b(`cancelled`,`abort-signal`))},a.addEventListener(`abort`,l,{once:!0}),a.aborted&&l()});try{return await Promise.race([i,u])}catch(e){throw c&&i.then(e=>e(),()=>void 0),r.clock.isExpired()&&!(e instanceof y&&e.failureKind===`cancelled`)?b(`timeout`,`cache-lock-deadline`):e}finally{a.removeEventListener(`abort`,l)}}function ke(e,t){let n=e+t;return n.length<=R?n:n.slice(n.length-R)}function Ae(e,t,n){let r=g(`sha256`).update(t).digest(`hex`).slice(0,12),i=g(`sha256`).update(n).digest(`hex`).slice(0,12);return h.join(`/tmp`,`agent-device-ax-${r}-${e.processId()}-${i}`,`snapshot.sock`)}const B=new WeakSet;async function V(e,t){let n;try{n=(await t.wait).exitCode}catch{n=void 0}return B.has(t)||(B.add(t),e.emitDiagnostic({level:`error`,phase:`ios.snapshot-source.bridge-process-exit`,data:{pid:t.pid,...n===void 0?{}:{exitCode:n},stderr:je(t.readLog())}})),b(`process-crash`,`bridge-exited`,{pid:t.pid,...n===void 0?{}:{exitCode:n}})}function je(e){let t=v.from(e);return t.length<=65536?e:t.subarray(-65536).toString(`utf8`)}async function Me(e){let t=new O(e.limits.maxResponseBytes-4),n=S(e.deadline,`bridge-request-deadline`);return await new Promise((r,i)=>{let a=!1,o=!1,s=setTimeout(()=>{p(b(`timeout`,`bridge-request-deadline`,{dispatched:o})),e.socket.destroy()},n),c=()=>{p(b(`cancelled`,`abort-signal`,{dispatched:o})),e.socket.destroy()},l=n=>{try{if(!Buffer.isBuffer(n))throw b(`transport-failure`,`bridge-data-invalid`);let r=t.push(n);if(r){let t=k(r);if(j(t,e.requestId),M(t,{pid:e.expectedPid,generation:e.expectedGeneration}),t.ok!==!0&&N(t),typeof t.truncated!=`boolean`)throw b(`malformed-tree`,`truncated-invalid`);f(t);return}}catch(t){p(t),e.socket.destroy()}},u=e=>p(x(e)),d=()=>{a||(e.process.isAlive()?p(b(`transport-failure`,`bridge-connection-closed`)):V(e.host,e.process).then(p))};e.process.wait.then(()=>{a||V(e.host,e.process).then(p)},e=>{a||p(x(e))});let f=e=>m(()=>r(e)),p=e=>m(()=>i(e)),m=t=>{a||(a=!0,clearTimeout(s),e.deadline.signal?.removeEventListener(`abort`,c),e.socket.off(`data`,l),e.socket.off(`error`,u),e.socket.off(`close`,d),t())};e.socket.on(`data`,l),e.socket.on(`error`,u),e.socket.on(`close`,d),e.deadline.signal?.addEventListener(`abort`,c,{once:!0});try{if(e.deadline.signal?.aborted)throw b(`cancelled`,`abort-signal`);o=!0,e.socket.write(e.frame)}catch(t){p(x(t)),e.socket.destroy()}})}var Ne=class{sessions=new Map;requestQueues=new Map;ownerId=_();closed=!1;host;constructor(e){this.host=e}async request(e){if(this.closed)throw b(`unsupported`,`source-closed`);return await this.withSimulatorLock(e.target.udid,e.deadline,()=>this.requestInSimulator(e))}async requestInSimulator(e){if(this.closed)throw b(`unsupported`,`source-closed`);let t=e.deadline;S(t,`bridge-request-deadline`);let n=this.sessions.get(e.target.udid),r=await this.ensureSession(e,t);try{let n=await this.readTargetStartTime(e.target,t),i=await this.exchange(r,e,t);return await this.assertTargetStillCurrent(e.target,n,t),i}catch(e){throw await this.handleRequestFailure(e,r,n)}}async handleRequestFailure(e,t,n){let r=x(e);return Fe(r,t,n)?await this.removeSession(t,!0):r.failureKind===`process-crash`?await this.removeSession(t,!1):r.failureKind===`transport-failure`&&(t.socket?.destroy(),t.socket=void 0),r}async withSimulatorLock(e,t,n){let r=this.requestQueues.get(e)??Promise.resolve(),i,a=new Promise(e=>{i=e}),o=r.then(()=>a);this.requestQueues.set(e,o);try{return await Pe(r,t),await n()}finally{i(),this.requestQueues.get(e)===o&&this.requestQueues.delete(e)}}async close(){if(this.closed)return;this.closed=!0;let e=[...this.sessions.values()];this.sessions.clear(),await Promise.all(e.map(async e=>await this.dispose(e,!0)))}async ensureSession(e,t){let n=e.target.udid,r=this.sessions.get(n);if(r&&r.bridgePath===e.bridge.path&&r.process.isAlive())return(!r.socket||r.socket.destroyed)&&(r.socket=await this.connectUntilReady(r,t)),r;r&&await this.removeSession(r,!0);let i=Ae(this.host,e.target.udid,this.ownerId);await this.host.ensureDirectory(h.dirname(i)),await this.host.remove(i);let a=this.host.start(e.target.udid,e.bridge.path,i,{signal:t.signal}),o={udid:e.target.udid,bridgePath:e.bridge.path,socketPath:i,process:a};this.sessions.set(n,o);try{return o.socket=await this.connectUntilReady(o,t),o}catch(e){throw await this.removeSession(o,!0),x(e)}}async connectUntilReady(e,t){let n;for(;;){let r=S(t,`bridge-connect-deadline`);if(!e.process.isAlive())throw await V(this.host,e.process);try{return await this.host.connect(e.socketPath,{signal:t.signal,timeoutMs:Math.min(250,r)})}catch(e){if(n=e,e instanceof y&&e.failureKind===`cancelled`)throw e;let r=Math.min(20,S(t,`bridge-connect-deadline`));try{await C(t,r,`bridge-connect-deadline`)}catch(e){throw x(e)}}if(n instanceof y&&n.failureKind===`timeout`)throw n}}async exchange(e,t,n){(!e.socket||e.socket.destroyed)&&(e.socket=await this.connectUntilReady(e,n));let r=_(),i=be(A({requestId:r,pid:t.target.pid,generation:t.target.generation,maxDepth:Math.min(t.limits.maxTraversalDepth,t.maxDepth),maxNodes:t.limits.maxNodes,maxDurationMs:S(n,`bridge-request-deadline`),maxResponseBytes:t.limits.maxResponseBytes,...t.nativeLevelsHint===void 0?{}:{nativeLevelsHint:t.nativeLevelsHint}}),t.limits);return await Me({process:e.process,socket:e.socket,frame:i,requestId:r,deadline:n,limits:t.limits,expectedPid:t.target.pid,expectedGeneration:t.target.generation,host:this.host})}async readTargetStartTime(e,t){let n=await this.host.readTargetProcessStartTime(e.pid,{signal:t.signal,timeoutMs:S(t,`target-identity-deadline`)});if(!n)throw b(`stale-target`,`target-process-unavailable`,{pid:e.pid,generation:e.generation});if(e.processStartTime!==void 0&&e.processStartTime!==n)throw b(`stale-target`,`target-process-changed`,{pid:e.pid,generation:e.generation,expectedStartTime:e.processStartTime,observedStartTime:n});return n}async assertTargetStillCurrent(e,t,n){let r=await this.host.readTargetProcessStartTime(e.pid,{signal:n.signal,timeoutMs:S(n,`target-identity-deadline`)});if(r!==t)throw b(`stale-target`,`target-process-changed`,{pid:e.pid,generation:e.generation,expectedStartTime:t,observedStartTime:r})}async removeSession(e,t){this.sessions.get(e.udid)===e&&this.sessions.delete(e.udid),await this.dispose(e,t)}async dispose(e,t){e.socket?.destroy(),e.socket=void 0,t&&e.process.isAlive()&&(e.process.signal(`SIGTERM`),await H(e.process,500),e.process.isAlive()&&(e.process.signal(`SIGKILL`),await H(e.process,500))),await this.host.remove(e.socketPath)}};async function Pe(e,t){let n=S(t,`bridge-request-deadline`);await Promise.race([e,C(t,n,`bridge-request-deadline`).then(()=>{throw b(`timeout`,`bridge-request-deadline`)})])}function Fe(e,t,n){return(e.failureKind===`cancelled`||e.failureKind===`timeout`)&&(e.details?.dispatched===!0||n!==t)}async function H(e,t){await Promise.race([e.wait.catch(()=>void 0),new Promise(e=>setTimeout(e,t))])}const U=16777216,W=12e4,G=1e4,Ie=Object.freeze({maxRequestBytes:65536,maxResponseBytes:4194304,maxNodes:5e3,maxTraversalDepth:64,maxDurationMs:5e3});function Le(t){let n={...Ie,...t??{}};for(let[t,r]of Object.entries(n))if(!Number.isSafeInteger(r)||r<=0)throw new e(`INVALID_ARGS`,`Snapshot source limit ${t} must be a positive integer`,{name:t,value:r});if(n.maxRequestBytes>n.maxResponseBytes)throw new e(`INVALID_ARGS`,`Snapshot source request bytes cannot exceed response bytes`,{maxRequestBytes:n.maxRequestBytes,maxResponseBytes:n.maxResponseBytes});if(n.maxRequestBytes>U||n.maxResponseBytes>U)throw new e(`INVALID_ARGS`,`Snapshot source frame limits exceed the bridge bound`,{maxRequestBytes:n.maxRequestBytes,maxResponseBytes:n.maxResponseBytes,maximumFrameBytes:U});if(n.maxNodes>G||n.maxTraversalDepth>128)throw new e(`INVALID_ARGS`,`Snapshot source tree limits exceed the bridge bound`,{maxNodes:n.maxNodes,maxTraversalDepth:n.maxTraversalDepth,maximumNodes:G,maximumDepth:128});if(n.maxDurationMs>W)throw new e(`INVALID_ARGS`,`Snapshot source duration exceeds the bridge bound`,{maxDurationMs:n.maxDurationMs,maximumDurationMs:W});if(n.maxRequestBytes<=4||n.maxResponseBytes<=4)throw new e(`INVALID_ARGS`,`Snapshot source frame limits must leave room for a body`,{maxRequestBytes:n.maxRequestBytes,maxResponseBytes:n.maxResponseBytes});return Object.freeze(n)}const K=Object.freeze({elementType:`XC_kAXXCAttributeElementType`,elementBaseType:`XC_kAXXCAttributeElementBaseType`,label:`XC_kAXXCAttributeLabel`,value:`XC_kAXXCAttributeValue`,identifier:`XC_kAXXCAttributeIdentifier`,frame:`XC_kAXXCAttributeFrame`,automationType:`XC_kAXXCAttributeAutomationType`,children:`XC_kAXXCAttributeChildren`}),q=`Other.Other.Application.Group.Window.Sheet.Drawer.Alert.Dialog.Button.RadioButton.RadioGroup.CheckBox.DisclosureTriangle.PopUpButton.ComboBox.MenuButton.ToolbarButton.Popover.Keyboard.Key.NavigationBar.TabBar.TabGroup.Toolbar.StatusBar.Table.TableRow.TableColumn.Outline.OutlineRow.Browser.CollectionView.Slider.PageIndicator.ProgressIndicator.ActivityIndicator.SegmentedControl.Picker.PickerWheel.Switch.Toggle.Link.Image.Icon.SearchField.ScrollView.ScrollBar.StaticText.TextField.SecureTextField.DatePicker.TextView.Menu.MenuItem.MenuBar.MenuBarItem.Map.WebView.IncrementArrow.DecrementArrow.Timeline.RatingIndicator.ValueIndicator.SplitGroup.Splitter.RelevanceIndicator.ColorWell.HelpTag.Matte.DockItem.Ruler.RulerMarker.Grid.LevelIndicator.Cell.LayoutArea.LayoutItem.Handle.Stepper.Tab.TouchBar.StatusItem`.split(`.`),J={UIApplication:`Application`,UIWindow:`Window`},Re=new Set(Object.values(K));function ze(e,t,n){let r=Array.isArray(e)?e:[e];if(r.length===0||r.some(e=>!P(e)))throw b(`malformed-tree`,`guest-tree-root-invalid`);let i=[],a=[],o=0;for(let e of r)c(e,void 0,0,!1);if(i.length>n.maxNodes)throw b(`malformed-tree`,`node-limit-exceeded`,{nodeCount:i.length,maxNodes:n.maxNodes});if(o>n.maxTraversalDepth)throw b(`malformed-tree`,`traversal-depth-exceeded`,{maxTraversalDepth:o,maxAllowedDepth:n.maxTraversalDepth});if(typeof t.truncated!=`boolean`)throw b(`malformed-tree`,`truncated-invalid`);let s=We(i.find(e=>e.type===`Application`||e.type===`Window`));return{nodes:i,maxTraversalDepth:o,viewport:s,opaqueRemoteElements:a.filter(e=>He(e,s)).length};function c(e,t,r,s){if(i.length>=n.maxNodes)throw b(`malformed-tree`,`node-limit-exceeded`,{maxNodes:n.maxNodes});for(let t of Object.keys(e))if(!Re.has(t))throw b(`malformed-tree`,`node-contains-unknown-field`,{key:t});let l=e[K.children];if(!Array.isArray(l))throw b(`malformed-tree`,`children-invalid`);let u=i.length,d=Be(e,u,t,r);i.push(d),o=Math.max(o,r),Ve(d,l.length,s)&&a.push(d.rect);let f=s||d.type===`WebView`;for(let e of l){if(!P(e))throw b(`malformed-tree`,`child-invalid`);c(e,u,r+1,f)}}}function Be(e,t,n,r){let i=X(e[K.elementType]),a=X(e[K.elementBaseType]),o=Ge(e[K.automationType]),s=Ue(e[K.frame]);return{index:t,...n===void 0?{}:{parentIndex:n},...Y(i,o)?{type:Y(i,o)}:{},...i?{role:i}:{},...a&&a!==i?{subrole:a}:{},...X(e[K.label])?{label:X(e[K.label])}:{},...Z(e[K.value])?{value:Z(e[K.value])}:{},...X(e[K.identifier])?{identifier:X(e[K.identifier])}:{},...s?{rect:s}:{},depth:r}}function Y(e,t){if(e!==void 0&&J[e])return J[e];if(e!==void 0&&q.includes(e))return e;if(t!==void 0)return q[t]??`Other`}function Ve(e,t,n){return n&&e.role===`AXRemoteElement`&&t===0}function He(e,t){return e===void 0?!0:r(e)?t.kind!==`reported`||n(e,t.rect):!1}function Ue(e){if(e===void 0)return;if(!P(e))throw b(`malformed-tree`,`frame-invalid`);let t=[`X`,`Y`,`Width`,`Height`].map(t=>e[t]);if(!t.every(e=>typeof e==`number`&&Number.isFinite(e)))throw b(`malformed-tree`,`frame-invalid`);let[n,r,i,a]=t;if(i<0||a<0)throw b(`malformed-tree`,`frame-invalid`);return{x:n,y:r,width:i,height:a}}function We(e){return!e||e.type!==`Application`&&e.type!==`Window`?{kind:`missing`,reason:`not-provided`}:r(e.rect)?{kind:`reported`,rect:e.rect}:{kind:`missing`,reason:e.rect?`invalid`:`not-provided`}}function X(e){return typeof e==`string`&&e.length>0?e:void 0}function Z(e){if(typeof e==`string`)return e.length>0?e:void 0;if(typeof e==`number`||typeof e==`boolean`)return String(e);if(e!=null)throw b(`malformed-tree`,`scalar-invalid`)}function Ge(e){if(e!=null){if(!Number.isSafeInteger(e))throw b(`malformed-tree`,`automation-type-invalid`);return e}}const Q=`simulator-ax-bridge`;function Ke(e={}){let t=e.host??Ee(),n=new Ne(t),r=new Te,i=new Map,a=!1,o=async n=>{if(a)throw b(`unsupported`,`source-closed`);let r=i.get(n.runtime);if(r)return r;let o=await t.withDiagnosticTimer(`ios.snapshot-source.prepare`,async()=>await xe({host:t,runtime:n.runtime,limits:n.limits,deadline:n.deadline,sourceRoot:e.sourceRoot,cacheRoot:e.cacheRoot}),{producer:Q});return i.set(n.runtime,o),o};return{acquire:async i=>{try{if(a)throw b(`unsupported`,`source-closed`);qe(i);let s=Le({...e.limits,...i.limits}),c=pe(s.maxDurationMs,i.signal),l=Ye(i.hint,s.maxTraversalDepth),u=l+1,d=i.hint.rawTraversalDepth!==null;return await t.withDiagnosticTimer(`ios.snapshot-source.acquire`,async()=>{let e=await o({runtime:i.target.runtime,limits:s,deadline:c}),a=r.consume(i.target,u,d),f=await n.request({target:i.target,bridge:e,limits:s,maxDepth:l,nativeLevelsHint:a.nativeLevels,deadline:c});S(c,`snapshot-decode-deadline`);let p=Xe(i.hint,i.target,f,s);return Je(t,r,i.target,u,d,a,f),{stage:`acquired`,acquisition:p}},{producer:Q})}catch(e){let t=x(e);return{stage:`failed`,failure:{kind:t.failureKind,code:t.failureCode,...t.details?{details:t.details}:{}}}}},close:async()=>{a||(a=!0,await n.close())}}}function qe(t){if(!t.target.udid.trim()||!t.target.runtime.trim()||!t.target.generation.trim()||!Number.isSafeInteger(t.target.pid)||t.target.pid<=0)throw new e(`INVALID_ARGS`,`Simulator snapshot source target identity is incomplete`);let n=t.hint;if(n.projection!==`raw`&&n.projection!==`regular`||![`full`,`surface-observation`].includes(n.acquisitionIntent)||typeof n.interactiveOnly!=`boolean`||typeof n.customActions!=`boolean`||!$(n.rawTraversalDepth)||!$(n.regularPresentedDepth))throw new e(`INVALID_ARGS`,`Simulator snapshot source capture hint is invalid`)}function Je(e,t,n,r,i,a,o){let s=ye(o),c=o.truncated===!0,l=t.learn(n,r,i,s);e.emitDiagnostic({level:`debug`,phase:`ios_snapshot_source_recovery`,data:{producer:Q,...n.targetId?{targetId:n.targetId}:{},generation:n.generation,requestedLevels:r,hint:a.reason,...a.nativeLevels===void 0?{}:{hintedLevels:a.nativeLevels},...s,truncated:c,learning:l}})}function Ye(t,n){let r=t.rawTraversalDepth??n;if(r>n)throw new e(`INVALID_ARGS`,`Simulator snapshot source depth exceeds its bound`,{requested:r,maximum:n});return r}function $(e){return e===null||Number.isSafeInteger(e)&&e>=0}function Xe(e,t,n,r){if(n.automationEnabled!==!0)throw b(`unsupported`,`automation-mode-unavailable`);let i=n.tree,a=n.truncated;if(typeof a!=`boolean`)throw b(`malformed-tree`,`truncated-invalid`);let o=ze(i,{truncated:a},r),s=n.generation;if(typeof s!=`string`||!s)throw b(`malformed-tree`,`generation-invalid`);if(o.opaqueRemoteElements>0)throw b(`unsupported`,`remote-content-boundary`,{remoteElements:o.opaqueRemoteElements});let c=Object.freeze(o.nodes.map(e=>Object.freeze({...e,pid:t.pid}))),l=Ze(e,a,o.viewport),u=Object.freeze({...t.targetId?{targetId:t.targetId}:{},generation:s}),d={producer:Q,nodes:c,truncated:a,viewport:o.viewport,lineage:u,residue:l};return e.acquisitionIntent===`full`?{...d,intent:`full`,hint:{...e,acquisitionIntent:`full`}}:{...d,intent:`surface-observation`,hint:{...e,acquisitionIntent:`surface-observation`}}}function Ze(e,t,n){return Object.freeze([{kind:`unavailable-fact`,fact:`hittability`},...e.interactiveOnly?[{kind:`unavailable-fact`,fact:`interactive-query`}]:[],...t?[{kind:`truncated`}]:[],...n.kind===`missing`?[{kind:`missing-viewport`,reason:n.reason}]:[]])}export{Ke as createSimulatorSnapshotSource};
|
|
1
|
+
import{C as e,j as t}from"./sdk-contracts.js";import{Br as n,zr as r}from"./sdk-batch.js";import{c as i,r as a}from"./diagnostics.js";import{f as o,x as s}from"./owner-identity.js";import{c,l,m as u,r as d}from"./exec.js";import{t as f}from"./file.js";import"./diagnostics2.js";import"./command.js";import{n as p}from"./retry.js";import{n as m}from"./version.js";import"./process.js";import{C as ee,D as te,c as ne,f as re,h as ie,n as ae,o as oe,w as se,y as ce}from"./host-file.js";import{t as h}from"./apple-runner-platform.js";import{n as le,r as ue,t as de}from"./snapshot-process.js";import g from"node:path";import{createHash as _,randomUUID as v}from"node:crypto";import fe from"node:net";import{Buffer as y}from"node:buffer";const pe={unsupported:`UNSUPPORTED_OPERATION`,"malformed-tree":`COMMAND_FAILED`,"stale-target":`COMMAND_FAILED`,timeout:`COMMAND_FAILED`,cancelled:`COMMAND_FAILED`,"process-crash":`COMMAND_FAILED`,"transport-failure":`COMMAND_FAILED`,preparing:`COMMAND_FAILED`};var b=class extends e{failureKind;failureCode;constructor(e,t,n=`iOS Simulator snapshot source ${e}: ${t}`,r={},i){super(pe[e],n,{...r,bridgeFailure:e,bridgeFailureCode:t,...e===`cancelled`?{reason:`request_canceled`}:{}},i),this.name=`SnapshotSourceError`,this.failureKind=e,this.failureCode=t}};function x(e,t,n={},r){return new b(e,t,void 0,n,r)}function S(n){return n instanceof b?n:t(n)?x(`cancelled`,`abort-signal`,{},n):n instanceof e&&typeof n.details?.timeoutMs==`number`?x(`timeout`,`host-operation-timeout`,{timeoutMs:n.details.timeoutMs},n):x(`transport-failure`,`unexpected-host-error`,{error:n instanceof Error?n.message:String(n)},n)}function C(e,t,n=Date.now){if(t?.aborted)throw x(`cancelled`,`abort-signal`);return{clock:p.fromTimeoutMs(e,n()),now:n,signal:t}}function w(e,t){if(e.signal?.aborted)throw x(`cancelled`,`abort-signal`);let n=e.clock.remainingMs(e.now());if(n<=0)throw x(`timeout`,t);return Math.max(1,Math.floor(n))}async function T(e,t,n,r){let i=Math.min(t,w(e,n));await ue({waitMs:i,signal:e.signal,stop:r,cancelled:()=>x(`cancelled`,`abort-signal`)})}var me=class{entries=new Map;probeBackAfterUses;constructor(e=8){this.probeBackAfterUses=e}consume(e,t,n){if(n)return{nativeLevels:void 0,reason:`explicit-depth`};let r=this.currentEntry(e);return r===`unidentified`?{nativeLevels:void 0,reason:`unidentified-target`}:!r||r.nativeLevels>=t?{nativeLevels:void 0,reason:`no-hint`}:r.remainingUses<=0?{nativeLevels:void 0,reason:`probe-back`}:(--r.remainingUses,{nativeLevels:r.nativeLevels,reason:`hinted`})}learn(e,t,n,r){return n||!e.targetId?`ignored`:r.rejected>0&&r.acceptedLevels<t?(this.remember(e.targetId,{generation:e.generation,nativeLevels:r.acceptedLevels,remainingUses:this.probeBackAfterUses}),`learned`):r.rejected===0&&r.acceptedLevels>=t?this.entries.delete(e.targetId)?`forgotten`:`ignored`:this.currentEntry(e)?`kept`:`ignored`}currentEntry(e){if(!e.targetId)return`unidentified`;let t=this.entries.get(e.targetId);if(t){if(t.generation!==e.generation){this.entries.delete(e.targetId);return}return t}}remember(e,t){if(this.entries.delete(e),this.entries.size>=32){let e=this.entries.keys().next().value;e!==void 0&&this.entries.delete(e)}this.entries.set(e,t)}};const E=65536;function he(){return{projectRoot:m,homeDirectory:re,run:async(e,t,n)=>await c(e,t,n),start:ge,connect:_e,readText:ce,readBinary:ie,writeText:te,ensureDirectory:oe,chmod:ae,exists:ne,rename:se,remove:ee,acquireLock:ve,emitDiagnostic:a,withDiagnosticTimer:i,processId:o,readTargetProcessStartTime:de}}function ge(e,t,n,r={}){if(r.signal?.aborted)throw x(`cancelled`,`abort-signal`);let i=l(`xcrun`,[`simctl`,`spawn`,e,t,`serve`,n,`--idle-timeout`,`60`,`--exit-on-disconnect`,`false`],{allowFailure:!0,captureOutput:!1,detached:!0}),a=i.child.pid??0;if(a<=0)throw x(`transport-failure`,`bridge-process-pid-missing`);let o=``;return i.child.stderr?.setEncoding(`utf8`),i.child.stderr?.on(`data`,e=>{o=ye(o,String(e))}),{pid:a,wait:i.wait,isAlive:()=>i.child.exitCode===null&&i.child.signalCode===null,signal:e=>{u(a,e)||i.child.kill(e)},readLog:()=>o}}async function _e(e,t){if(t.signal?.aborted)throw x(`cancelled`,`abort-signal`);let n=Math.max(1,Math.floor(t.timeoutMs));return await new Promise((r,i)=>{let a=fe.createConnection({path:e}),o=!1,s=!1,c=setTimeout(()=>{p(x(`timeout`,`bridge-connect-timeout`)),a.destroy()},n),l=()=>{p(x(`cancelled`,`abort-signal`)),a.destroy()},u=()=>{o=!0,clearTimeout(c),t.signal?.removeEventListener(`abort`,l),a.off(`error`,d),a.off(`close`,f),a.setTimeout(0),r(a)},d=e=>{p(e),a.destroy()},f=()=>{o||p(x(`transport-failure`,`bridge-closed-before-connect`))},p=e=>{s||o||(s=!0,clearTimeout(c),t.signal?.removeEventListener(`abort`,l),a.off(`connect`,u),a.off(`error`,d),a.off(`close`,f),i(e))};a.once(`connect`,u),a.once(`error`,d),a.once(`close`,f),t.signal?.addEventListener(`abort`,l,{once:!0}),t.signal?.aborted&&l()})}async function ve(e,t){let n=o(),r=t.deadline,i=f({lockDirPath:e,owner:{pid:n,startTime:s(n),acquiredAtMs:Date.now()},timeoutMs:w(r,`cache-lock-deadline`),pollMs:100,ownerGraceMs:5e3,description:`iOS Simulator snapshot bridge cache`}),a=r.signal;if(!a)return await i;let c=!1,l,u=new Promise((e,t)=>{l=()=>{c=!0,t(x(`cancelled`,`abort-signal`))},a.addEventListener(`abort`,l,{once:!0}),a.aborted&&l()});try{return await Promise.race([i,u])}catch(e){throw c&&i.then(e=>e(),()=>void 0),r.clock.isExpired()&&!(e instanceof b&&e.failureKind===`cancelled`)?x(`timeout`,`cache-lock-deadline`):e}finally{a.removeEventListener(`abort`,l)}}function ye(e,t){let n=e+t;return n.length<=E?n:n.slice(n.length-E)}function be(e,t,n){let r=_(`sha256`).update(t).digest(`hex`).slice(0,12),i=_(`sha256`).update(n).digest(`hex`).slice(0,12);return g.join(`/tmp`,`agent-device-ax-${r}-${e.processId()}-${i}`,`snapshot.sock`)}const D=new WeakSet;async function O(e,t){let n;try{n=(await t.wait).exitCode}catch{n=void 0}return D.has(t)||(D.add(t),e.emitDiagnostic({level:`error`,phase:`ios.snapshot-source.bridge-process-exit`,data:{pid:t.pid,...n===void 0?{}:{exitCode:n},stderr:xe(t.readLog())}})),x(`process-crash`,`bridge-exited`,{pid:t.pid,...n===void 0?{}:{exitCode:n}})}function xe(e){let t=y.from(e);return t.length<=65536?e:t.subarray(-65536).toString(`utf8`)}const k=`agent-device-simulator-ax-v1.5.5`;Object.freeze([`verb`,`requestId`,`pid`,`generation`,`snapshotTree`,`automationMode`,`maxDepth`,`maxNodes`,`maxDurationMs`,`maxResponseBytes`,`nativeLevelsHint`]),Object.freeze([`protocolVersion`,`sourceVersion`,`requestId`,`generation`,`ok`,`pid`,`tree`,`truncated`,`automationEnabled`,`recovery`,`error_kind`,`error_code`,`error`]),Object.freeze([`XC_kAXXCAttributeElementType`,`XC_kAXXCAttributeElementBaseType`,`XC_kAXXCAttributeLabel`,`XC_kAXXCAttributeValue`,`XC_kAXXCAttributeIdentifier`,`XC_kAXXCAttributeFrame`,`XC_kAXXCAttributeAutomationType`,`XC_kAXXCAttributeChildren`]);const Se=[`requests`,`rejected`,`continuations`,`acceptedLevels`];function A(e){let t=e.recovery;if(!M(t))throw x(`malformed-tree`,`recovery-invalid`);let n=Se.map(e=>[e,t[e]]);if(n.some(([,e])=>!Number.isSafeInteger(e)||e<0))throw x(`malformed-tree`,`recovery-invalid`);return Object.freeze(Object.fromEntries(n))}function j(e,t){let n;try{n=y.from(JSON.stringify(e),`utf8`)}catch(e){throw x(`malformed-tree`,`request-not-json`,{},e)}let r=n.length+4;if(r>t.maxRequestBytes)throw x(`transport-failure`,`request-limit-exceeded`,{frameBytes:r,maxRequestBytes:t.maxRequestBytes});let i=y.alloc(4);return i.writeUInt32BE(n.length,0),y.concat([i,n])}var Ce=class{header=y.alloc(4);headerBytes=0;chunks=[];payloadBytes=0;expectedBodyBytes;frame;maxFrameBytes;constructor(e){if(!Number.isSafeInteger(e)||e<=0)throw x(`malformed-tree`,`frame-limit-invalid`,{maxFrameBytes:e});this.maxFrameBytes=e}push(e){if(this.frame)return this.acceptTrailingChunk(e);let t=this.readHeader(e);if(t&&(this.appendPayload(e,t.offset,t.bodyBytes),this.payloadBytes===t.bodyBytes))return this.frame=y.concat(this.chunks,t.bodyBytes),this.frame}acceptTrailingChunk(e){if(e.length>0)throw x(`malformed-tree`,`multiple-frames`,{trailingBytes:e.length});return this.frame}readHeader(e){if(this.headerBytes===4)return{offset:0,bodyBytes:this.expectedBodyBytes};let t=Math.min(4-this.headerBytes,e.length);if(e.copy(this.header,this.headerBytes,0,t),this.headerBytes+=t,this.headerBytes<4)return;let n=this.header.readUInt32BE(0);if(n===0||n>this.maxFrameBytes)throw x(`malformed-tree`,`frame-limit-exceeded`,{bodyBytes:n,maxFrameBytes:this.maxFrameBytes});return this.expectedBodyBytes=n,{offset:t,bodyBytes:n}}appendPayload(e,t,n){let r=n-this.payloadBytes,i=e.length-t;if(i>r)throw x(`malformed-tree`,`multiple-frames`,{trailingBytes:i-r});i!==0&&(this.chunks.push(e.subarray(t)),this.payloadBytes+=i)}finish(){if(this.frame)return this.frame;throw x(`transport-failure`,`bridge-frame-incomplete`,{headerBytes:this.headerBytes,payloadBytes:this.payloadBytes,expectedBodyBytes:this.expectedBodyBytes})}};function we(e){let t;try{t=JSON.parse(e.toString(`utf8`))}catch(e){throw x(`malformed-tree`,`response-not-json`,{},e)}if(!M(t))throw x(`malformed-tree`,`response-not-object`);return t}function Te(e){return Object.freeze({verb:`describe`,requestId:e.requestId,pid:e.pid,generation:e.generation,snapshotTree:!0,automationMode:!0,maxDepth:e.maxDepth,maxNodes:e.maxNodes,maxDurationMs:e.maxDurationMs,maxResponseBytes:e.maxResponseBytes,...e.nativeLevelsHint===void 0?{}:{nativeLevelsHint:e.nativeLevelsHint}})}function Ee(e,t){if(e.protocolVersion!==1)throw x(`transport-failure`,`protocol-version-mismatch`,{expected:1,observed:e.protocolVersion});if(e.sourceVersion!==`agent-device-simulator-ax-v1.5.5`)throw x(`transport-failure`,`source-version-mismatch`,{expected:k,observed:e.sourceVersion});if(e.requestId!==t)throw x(`transport-failure`,`request-id-mismatch`,{expected:t,observed:e.requestId})}function De(e,t){if(typeof e.pid!=`number`||e.pid!==t.pid)throw x(`stale-target`,`bridge-pid-mismatch`,{expectedPid:t.pid,observedPid:e.pid});if(e.generation!==t.generation)throw x(`stale-target`,`bridge-generation-mismatch`,{expectedGeneration:t.generation,observedGeneration:e.generation})}function Oe(e){let t=e.error_kind,n=typeof e.error_code==`string`?e.error_code:`guest-error`,r=typeof e.error==`string`?e.error:void 0,i=r?{guestMessage:r.slice(0,1024)}:{};throw x(t===`unsupported`?`unsupported`:t===`malformed_tree`?`malformed-tree`:t===`application_not_responding`?`timeout`:t===`application_unavailable`?`transport-failure`:t===`bad_request`?`malformed-tree`:`transport-failure`,n,i)}function M(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function ke(e){let t=new Ce(e.limits.maxResponseBytes-4),n=w(e.deadline,`bridge-request-deadline`);return await new Promise((r,i)=>{let a=!1,o=!1,s=setTimeout(()=>{p(x(`timeout`,`bridge-request-deadline`,{dispatched:o})),e.socket.destroy()},n),c=()=>{p(x(`cancelled`,`abort-signal`,{dispatched:o})),e.socket.destroy()},l=n=>{try{if(!Buffer.isBuffer(n))throw x(`transport-failure`,`bridge-data-invalid`);let r=t.push(n);if(r){let t=we(r);if(Ee(t,e.requestId),De(t,{pid:e.expectedPid,generation:e.expectedGeneration}),t.ok!==!0&&Oe(t),typeof t.truncated!=`boolean`)throw x(`malformed-tree`,`truncated-invalid`);f(t);return}}catch(t){p(t),e.socket.destroy()}},u=e=>p(S(e)),d=()=>{a||(e.process.isAlive()?p(x(`transport-failure`,`bridge-connection-closed`)):O(e.host,e.process).then(p))};e.process.wait.then(()=>{a||O(e.host,e.process).then(p)},e=>{a||p(S(e))});let f=e=>m(()=>r(e)),p=e=>m(()=>i(e)),m=t=>{a||(a=!0,clearTimeout(s),e.deadline.signal?.removeEventListener(`abort`,c),e.socket.off(`data`,l),e.socket.off(`error`,u),e.socket.off(`close`,d),t())};e.socket.on(`data`,l),e.socket.on(`error`,u),e.socket.on(`close`,d),e.deadline.signal?.addEventListener(`abort`,c,{once:!0});try{if(e.deadline.signal?.aborted)throw x(`cancelled`,`abort-signal`);o=!0,e.socket.write(e.frame)}catch(t){p(S(t)),e.socket.destroy()}})}var Ae=class{sessions=new Map;requestQueues=new Map;ownerId=v();closed=!1;host;constructor(e){this.host=e}async request(e){if(this.closed)throw x(`unsupported`,`source-closed`);return await this.withSimulatorLock(e.target.udid,e.deadline,()=>this.requestInSimulator(e))}async requestInSimulator(e){if(this.closed)throw x(`unsupported`,`source-closed`);let t=e.deadline;w(t,`bridge-request-deadline`);let n=this.sessions.get(e.target.udid),r=await this.ensureSession(e,t);try{let n=await this.readTargetStartTime(e.target,t),i=await this.exchange(r,e,t);return await this.assertTargetStillCurrent(e.target,n,t),i}catch(e){throw await this.handleRequestFailure(e,r,n)}}async handleRequestFailure(e,t,n){let r=S(e);return Me(r,t,n)?await this.removeSession(t,!0):r.failureKind===`process-crash`?await this.removeSession(t,!1):r.failureKind===`transport-failure`&&(t.socket?.destroy(),t.socket=void 0),r}async withSimulatorLock(e,t,n){let r=this.requestQueues.get(e)??Promise.resolve(),i,a=new Promise(e=>{i=e}),o=r.then(()=>a);this.requestQueues.set(e,o);try{return await je(r,t),await n()}finally{i(),this.requestQueues.get(e)===o&&this.requestQueues.delete(e)}}async close(){if(this.closed)return;this.closed=!0;let e=[...this.sessions.values()];this.sessions.clear(),await Promise.all(e.map(async e=>await this.dispose(e,!0)))}async ensureSession(e,t){let n=e.target.udid,r=this.sessions.get(n);if(r&&r.bridgePath===e.bridge.path&&r.process.isAlive())return(!r.socket||r.socket.destroyed)&&(r.socket=await this.connectUntilReady(r,t)),r;r&&await this.removeSession(r,!0);let i=be(this.host,e.target.udid,this.ownerId);await this.host.ensureDirectory(g.dirname(i)),await this.host.remove(i);let a=this.host.start(e.target.udid,e.bridge.path,i,{signal:t.signal}),o={udid:e.target.udid,bridgePath:e.bridge.path,socketPath:i,process:a};this.sessions.set(n,o);try{return o.socket=await this.connectUntilReady(o,t),o}catch(e){throw await this.removeSession(o,!0),S(e)}}async connectUntilReady(e,t){let n;for(;;){let r=w(t,`bridge-connect-deadline`);if(!e.process.isAlive())throw await O(this.host,e.process);try{return await this.host.connect(e.socketPath,{signal:t.signal,timeoutMs:Math.min(250,r)})}catch(e){if(n=e,e instanceof b&&e.failureKind===`cancelled`)throw e;let r=Math.min(20,w(t,`bridge-connect-deadline`));try{await T(t,r,`bridge-connect-deadline`)}catch(e){throw S(e)}}if(n instanceof b&&n.failureKind===`timeout`)throw n}}async exchange(e,t,n){(!e.socket||e.socket.destroyed)&&(e.socket=await this.connectUntilReady(e,n));let r=v(),i=j(Te({requestId:r,pid:t.target.pid,generation:t.target.generation,maxDepth:Math.min(t.limits.maxTraversalDepth,t.maxDepth),maxNodes:t.limits.maxNodes,maxDurationMs:w(n,`bridge-request-deadline`),maxResponseBytes:t.limits.maxResponseBytes,...t.nativeLevelsHint===void 0?{}:{nativeLevelsHint:t.nativeLevelsHint}}),t.limits);return await ke({process:e.process,socket:e.socket,frame:i,requestId:r,deadline:n,limits:t.limits,expectedPid:t.target.pid,expectedGeneration:t.target.generation,host:this.host})}async readTargetStartTime(e,t){let n=await this.host.readTargetProcessStartTime(e.pid,{signal:t.signal,timeoutMs:w(t,`target-identity-deadline`)});if(!n)throw x(`stale-target`,`target-process-unavailable`,{pid:e.pid,generation:e.generation});if(e.processStartTime!==void 0&&e.processStartTime!==n)throw x(`stale-target`,`target-process-changed`,{pid:e.pid,generation:e.generation,expectedStartTime:e.processStartTime,observedStartTime:n});return n}async assertTargetStillCurrent(e,t,n){let r=await this.host.readTargetProcessStartTime(e.pid,{signal:n.signal,timeoutMs:w(n,`target-identity-deadline`)});if(r!==t)throw x(`stale-target`,`target-process-changed`,{pid:e.pid,generation:e.generation,expectedStartTime:t,observedStartTime:r})}async removeSession(e,t){this.sessions.get(e.udid)===e&&this.sessions.delete(e.udid),await this.dispose(e,t)}async dispose(e,t){e.socket?.destroy(),e.socket=void 0,t&&e.process.isAlive()&&(e.process.signal(`SIGTERM`),await N(e.process,500),e.process.isAlive()&&(e.process.signal(`SIGKILL`),await N(e.process,500))),await this.host.remove(e.socketPath)}};async function je(e,t){let n=w(t,`bridge-request-deadline`);await Promise.race([e,T(t,n,`bridge-request-deadline`).then(()=>{throw x(`timeout`,`bridge-request-deadline`)})])}function Me(e,t,n){return(e.failureKind===`cancelled`||e.failureKind===`timeout`)&&(e.details?.dispatched===!0||n!==t)}async function N(e,t){await Promise.race([e.wait.catch(()=>void 0),new Promise(e=>setTimeout(e,t))])}const P=16777216,F=12e4,I=1e4,Ne=Object.freeze({maxRequestBytes:65536,maxResponseBytes:4194304,maxNodes:5e3,maxTraversalDepth:64,maxDurationMs:5e3});function L(t){let n={...Ne,...t??{}};for(let[t,r]of Object.entries(n))if(!Number.isSafeInteger(r)||r<=0)throw new e(`INVALID_ARGS`,`Snapshot source limit ${t} must be a positive integer`,{name:t,value:r});if(n.maxRequestBytes>n.maxResponseBytes)throw new e(`INVALID_ARGS`,`Snapshot source request bytes cannot exceed response bytes`,{maxRequestBytes:n.maxRequestBytes,maxResponseBytes:n.maxResponseBytes});if(n.maxRequestBytes>P||n.maxResponseBytes>P)throw new e(`INVALID_ARGS`,`Snapshot source frame limits exceed the bridge bound`,{maxRequestBytes:n.maxRequestBytes,maxResponseBytes:n.maxResponseBytes,maximumFrameBytes:P});if(n.maxNodes>I||n.maxTraversalDepth>128)throw new e(`INVALID_ARGS`,`Snapshot source tree limits exceed the bridge bound`,{maxNodes:n.maxNodes,maxTraversalDepth:n.maxTraversalDepth,maximumNodes:I,maximumDepth:128});if(n.maxDurationMs>F)throw new e(`INVALID_ARGS`,`Snapshot source duration exceeds the bridge bound`,{maxDurationMs:n.maxDurationMs,maximumDurationMs:F});if(n.maxRequestBytes<=4||n.maxResponseBytes<=4)throw new e(`INVALID_ARGS`,`Snapshot source frame limits must leave room for a body`,{maxRequestBytes:n.maxRequestBytes,maxResponseBytes:n.maxResponseBytes});return Object.freeze(n)}const R=[`SnapshotBridge.m`,`SnapshotBridgeRuntime.m`,`SnapshotBridgeRuntime.h`,`SnapshotBridgeCapture.h`,`SnapshotBridgeCapture.m`],Pe=[`SnapshotBridge.m`,`SnapshotBridgeRuntime.m`,`SnapshotBridgeCapture.m`];async function Fe(e,t,n){let r=_(`sha256`);for(let i of R){let a=g.join(t,i);if(w(n,`native-source-fingerprint-deadline`),!e.exists(a))throw x(`unsupported`,`native-source-missing`,{filePath:a});r.update(i),r.update(`\0`),r.update(await e.readBinary(a)),r.update(`\0`)}return r.digest(`hex`)}async function Ie(e,t,n){let r=await z(e,`xcodebuild`,[`-version`],n),i=await z(e,`sw_vers`,[`-productVersion`],n),a=await z(e,`sw_vers`,[`-buildVersion`],n),o=await z(e,`uname`,[`-m`],n),s=await z(e,`xcrun`,[`--sdk`,`iphonesimulator`,`--show-sdk-version`],n),c=t.trim();if(!c)throw x(`unsupported`,`simulator-runtime-missing`);if(o!==`arm64`&&o!==`x86_64`)throw x(`unsupported`,`simulator-architecture-unsupported`,{architecture:o});return{xcode:r,macosProductVersion:i,macosBuild:a,architecture:o,simulatorSdk:s,simulatorRuntime:c}}async function z(e,t,n,r){let i=await Le(e,t,n,r);if(i.exitCode!==0)throw x(`unsupported`,`toolchain-probe-failed`,{command:t,exitCode:i.exitCode,stderr:i.stderr.slice(0,1024)});let a=(i.stdout||i.stderr).trim();if(!a)throw x(`unsupported`,`toolchain-probe-empty`,{command:t});return a}async function Le(e,t,n,r){try{return await B(e,t,n,r)}catch(i){if(!d(i))throw i;if(r.signal?.aborted)throw x(`cancelled`,`abort-signal`);if(r.clock.remainingMs(r.now())<=0)throw i;return await B(e,t,n,r)}}function B(e,t,n,r){return e.run(t,n,{allowFailure:!0,signal:r.signal,timeoutMs:Math.min(h,w(r,`toolchain-probe-deadline`))})}const V=`snapshot-bridge`,H=`manifest.json`,U=12e4;async function Re(e){let t=e.deadline,n=e.sourceRoot??ze(e.host),r=await Fe(e.host,n,t),i=await Ie(e.host,e.runtime,t),a=Ve({schemaVersion:1,protocolVersion:1,sourceVersion:k,sourceHash:r,toolchain:i}),o=e.cacheRoot??g.join(e.host.homeDirectory(),`.agent-device`,`snapshot-source`),s=g.join(o,a),c=await e.host.acquireLock(g.join(o,`${a}.lock`),{deadline:t});try{let c=await Be(e.host,s,{sourceHash:r,cacheKey:a,toolchain:i},t);if(c)return c;w(t,`native-build-deadline`),e.host.exists(s)&&await e.host.remove(s),w(t,`native-build-deadline`),await e.host.ensureDirectory(o);let l=g.join(o,`.${a}.${e.host.processId()}.tmp`);w(t,`native-build-deadline`),await e.host.remove(l);try{w(t,`native-build-deadline`),await e.host.ensureDirectory(l);let o=g.join(l,V),c=await e.host.run(`xcrun`,[`--sdk`,`iphonesimulator`,`clang`,`-arch`,i.architecture,`-mios-simulator-version-min=15.0`,`-fobjc-arc`,`-Werror`,`-Wall`,`-Wextra`,`-framework`,`Foundation`,`-framework`,`CoreGraphics`,...Pe.map(e=>g.join(n,e)),`-o`,o],{signal:t.signal,timeoutMs:Math.min(U,w(t,`native-build-deadline`)),allowFailure:!0});if(c.exitCode!==0||!e.host.exists(o))throw x(`unsupported`,`native-build-failed`,{exitCode:c.exitCode,stderr:c.stderr.slice(0,4096)});w(t,`native-build-deadline`),await e.host.chmod(o,493);let u=await W(e.host,o,t),d={schemaVersion:1,protocolVersion:1,sourceVersion:k,sourceHash:r,cacheKey:a,toolchain:i,binarySha256:u};return await e.host.writeText(g.join(l,H),`${JSON.stringify(d,null,2)}\n`),w(t,`native-build-deadline`),await e.host.rename(l,s),{path:g.join(s,V),sourceHash:r,cacheKey:a,protocolVersion:1,sourceVersion:k}}catch(t){throw await e.host.remove(l),t}}finally{await c()}}function ze(e){let t=e.projectRoot(),n=g.join(t,`apple`,`snapshot-bridge`);if(R.every(t=>e.exists(g.join(n,t))))return n;let r=g.join(t,`dist`,`apple`,`snapshot-bridge`);if(R.every(t=>e.exists(g.join(r,t))))return r;throw x(`unsupported`,`native-source-missing`,{projectRoot:t})}async function Be(e,t,n,r){let i=g.join(t,V);if(!(!e.exists(i)||!e.exists(g.join(t,H))))try{let a=JSON.parse(await e.readText(g.join(t,H)));return a.schemaVersion!==1||a.protocolVersion!==1||a.sourceVersion!==`agent-device-simulator-ax-v1.5.5`||a.sourceHash!==n.sourceHash||a.cacheKey!==n.cacheKey||JSON.stringify(a.toolchain)!==JSON.stringify(n.toolchain)||typeof a.binarySha256!=`string`||await W(e,i,r)!==a.binarySha256?void 0:{path:i,sourceHash:n.sourceHash,cacheKey:n.cacheKey,protocolVersion:1,sourceVersion:k}}catch(e){if(e instanceof b&&(e.failureKind===`cancelled`||e.failureKind===`timeout`))throw e;return}}async function W(e,t,n){return w(n,`native-cache-hash-deadline`),_(`sha256`).update(await e.readBinary(t)).digest(`hex`)}function Ve(e){return _(`sha256`).update(JSON.stringify(e)).digest(`hex`).slice(0,32)}const He=h+U;function Ue(e){let t=e.now??Date.now,n=new Map,r=le({waitMs:2e3,waitGrant:`first-caller`,retryAfterMs:6e4,now:t}),i=async(r,i)=>{let a=C(He,i,t);try{let t=await e.host.withDiagnosticTimer(`ios.snapshot-source.prepare`,async()=>await Re({host:e.host,runtime:r,limits:e.limits,deadline:a,sourceRoot:e.sourceRoot,cacheRoot:e.cacheRoot}),{producer:e.producer});return n.set(r,t),t}catch(e){throw S(e)}};return{readyBinary:async(e,t,a)=>n.get(e)||await r.value(e,{start:t=>i(e,t),wait:(e,n)=>T(t,e,a,n),pending:()=>x(`preparing`,`bridge-preparation-pending`)}),close:()=>{n.clear(),r.close()}}}const G=Object.freeze({elementType:`XC_kAXXCAttributeElementType`,elementBaseType:`XC_kAXXCAttributeElementBaseType`,label:`XC_kAXXCAttributeLabel`,value:`XC_kAXXCAttributeValue`,identifier:`XC_kAXXCAttributeIdentifier`,frame:`XC_kAXXCAttributeFrame`,automationType:`XC_kAXXCAttributeAutomationType`,children:`XC_kAXXCAttributeChildren`}),K=`Other.Other.Application.Group.Window.Sheet.Drawer.Alert.Dialog.Button.RadioButton.RadioGroup.CheckBox.DisclosureTriangle.PopUpButton.ComboBox.MenuButton.ToolbarButton.Popover.Keyboard.Key.NavigationBar.TabBar.TabGroup.Toolbar.StatusBar.Table.TableRow.TableColumn.Outline.OutlineRow.Browser.CollectionView.Slider.PageIndicator.ProgressIndicator.ActivityIndicator.SegmentedControl.Picker.PickerWheel.Switch.Toggle.Link.Image.Icon.SearchField.ScrollView.ScrollBar.StaticText.TextField.SecureTextField.DatePicker.TextView.Menu.MenuItem.MenuBar.MenuBarItem.Map.WebView.IncrementArrow.DecrementArrow.Timeline.RatingIndicator.ValueIndicator.SplitGroup.Splitter.RelevanceIndicator.ColorWell.HelpTag.Matte.DockItem.Ruler.RulerMarker.Grid.LevelIndicator.Cell.LayoutArea.LayoutItem.Handle.Stepper.Tab.TouchBar.StatusItem`.split(`.`),q={UIApplication:`Application`,UIWindow:`Window`},We=new Set(Object.values(G));function Ge(e,t,n){let r=Array.isArray(e)?e:[e];if(r.length===0||r.some(e=>!M(e)))throw x(`malformed-tree`,`guest-tree-root-invalid`);let i=[],a=[],o=0;for(let e of r)c(e,void 0,0,!1);if(i.length>n.maxNodes)throw x(`malformed-tree`,`node-limit-exceeded`,{nodeCount:i.length,maxNodes:n.maxNodes});if(o>n.maxTraversalDepth)throw x(`malformed-tree`,`traversal-depth-exceeded`,{maxTraversalDepth:o,maxAllowedDepth:n.maxTraversalDepth});if(typeof t.truncated!=`boolean`)throw x(`malformed-tree`,`truncated-invalid`);let s=Xe(i.find(e=>e.type===`Application`||e.type===`Window`));return{nodes:i,maxTraversalDepth:o,viewport:s,opaqueRemoteElements:a.filter(e=>Je(e,s)).length};function c(e,t,r,s){if(i.length>=n.maxNodes)throw x(`malformed-tree`,`node-limit-exceeded`,{maxNodes:n.maxNodes});for(let t of Object.keys(e))if(!We.has(t))throw x(`malformed-tree`,`node-contains-unknown-field`,{key:t});let l=e[G.children];if(!Array.isArray(l))throw x(`malformed-tree`,`children-invalid`);let u=i.length,d=Ke(e,u,t,r);i.push(d),o=Math.max(o,r),qe(d,l.length,s)&&a.push(d.rect);let f=s||d.type===`WebView`;for(let e of l){if(!M(e))throw x(`malformed-tree`,`child-invalid`);c(e,u,r+1,f)}}}function Ke(e,t,n,r){let i=Y(e[G.elementType]),a=Y(e[G.elementBaseType]),o=Z(e[G.automationType]),s=Ye(e[G.frame]);return{index:t,...n===void 0?{}:{parentIndex:n},...J(i,o)?{type:J(i,o)}:{},...i?{role:i}:{},...a&&a!==i?{subrole:a}:{},...Y(e[G.label])?{label:Y(e[G.label])}:{},...X(e[G.value])?{value:X(e[G.value])}:{},...Y(e[G.identifier])?{identifier:Y(e[G.identifier])}:{},...s?{rect:s}:{},depth:r}}function J(e,t){if(e!==void 0&&q[e])return q[e];if(e!==void 0&&K.includes(e))return e;if(t!==void 0)return K[t]??`Other`}function qe(e,t,n){return n&&e.role===`AXRemoteElement`&&t===0}function Je(e,t){return e===void 0?!0:r(e)?t.kind!==`reported`||n(e,t.rect):!1}function Ye(e){if(e===void 0)return;if(!M(e))throw x(`malformed-tree`,`frame-invalid`);let t=[`X`,`Y`,`Width`,`Height`].map(t=>e[t]);if(!t.every(e=>typeof e==`number`&&Number.isFinite(e)))throw x(`malformed-tree`,`frame-invalid`);let[n,r,i,a]=t;if(i<0||a<0)throw x(`malformed-tree`,`frame-invalid`);return{x:n,y:r,width:i,height:a}}function Xe(e){return!e||e.type!==`Application`&&e.type!==`Window`?{kind:`missing`,reason:`not-provided`}:r(e.rect)?{kind:`reported`,rect:e.rect}:{kind:`missing`,reason:e.rect?`invalid`:`not-provided`}}function Y(e){return typeof e==`string`&&e.length>0?e:void 0}function X(e){if(typeof e==`string`)return e.length>0?e:void 0;if(typeof e==`number`||typeof e==`boolean`)return String(e);if(e!=null)throw x(`malformed-tree`,`scalar-invalid`)}function Z(e){if(e!=null){if(!Number.isSafeInteger(e))throw x(`malformed-tree`,`automation-type-invalid`);return e}}const Q=`simulator-ax-bridge`;function Ze(e={}){let t=e.host??he(),n=new Ae(t),r=new me,i=Ue({host:t,limits:L(e.limits),producer:Q,sourceRoot:e.sourceRoot,cacheRoot:e.cacheRoot}),a=!1;return{acquire:async o=>{try{if(a)throw x(`unsupported`,`source-closed`);Qe(o);let s=L({...e.limits,...o.limits}),c=C(s.maxDurationMs,o.signal),l=et(o.hint,s.maxTraversalDepth),u=l+1,d=o.hint.rawTraversalDepth!==null;return await t.withDiagnosticTimer(`ios.snapshot-source.acquire`,async()=>{let e=await i.readyBinary(o.target.runtime,c,`bridge-preparation-deadline`),a=r.consume(o.target,u,d),f=await n.request({target:o.target,bridge:e,limits:s,maxDepth:l,nativeLevelsHint:a.nativeLevels,deadline:c});w(c,`snapshot-decode-deadline`);let p=tt(o.hint,o.target,f,s);return $e(t,r,o.target,u,d,a,f),{stage:`acquired`,acquisition:p}},{producer:Q})}catch(e){let t=S(e);return{stage:`failed`,failure:{kind:t.failureKind,code:t.failureCode,...t.details?{details:t.details}:{}}}}},close:async()=>{a||(a=!0,i.close(),await n.close())}}}function Qe(t){if(!t.target.udid.trim()||!t.target.runtime.trim()||!t.target.generation.trim()||!Number.isSafeInteger(t.target.pid)||t.target.pid<=0)throw new e(`INVALID_ARGS`,`Simulator snapshot source target identity is incomplete`);let n=t.hint;if(n.projection!==`raw`&&n.projection!==`regular`||![`full`,`surface-observation`].includes(n.acquisitionIntent)||typeof n.interactiveOnly!=`boolean`||typeof n.customActions!=`boolean`||!$(n.rawTraversalDepth)||!$(n.regularPresentedDepth))throw new e(`INVALID_ARGS`,`Simulator snapshot source capture hint is invalid`)}function $e(e,t,n,r,i,a,o){let s=A(o),c=o.truncated===!0,l=t.learn(n,r,i,s);e.emitDiagnostic({level:`debug`,phase:`ios_snapshot_source_recovery`,data:{producer:Q,...n.targetId?{targetId:n.targetId}:{},generation:n.generation,requestedLevels:r,hint:a.reason,...a.nativeLevels===void 0?{}:{hintedLevels:a.nativeLevels},...s,truncated:c,learning:l}})}function et(t,n){let r=t.rawTraversalDepth??n;if(r>n)throw new e(`INVALID_ARGS`,`Simulator snapshot source depth exceeds its bound`,{requested:r,maximum:n});return r}function $(e){return e===null||Number.isSafeInteger(e)&&e>=0}function tt(e,t,n,r){if(n.automationEnabled!==!0)throw x(`unsupported`,`automation-mode-unavailable`);let i=n.tree,a=n.truncated;if(typeof a!=`boolean`)throw x(`malformed-tree`,`truncated-invalid`);let o=Ge(i,{truncated:a},r),s=n.generation;if(typeof s!=`string`||!s)throw x(`malformed-tree`,`generation-invalid`);if(o.opaqueRemoteElements>0)throw x(`unsupported`,`remote-content-boundary`,{remoteElements:o.opaqueRemoteElements});let c=Object.freeze(o.nodes.map(e=>Object.freeze({...e,pid:t.pid}))),l=nt(e,a,o.viewport),u=Object.freeze({...t.targetId?{targetId:t.targetId}:{},generation:s}),d={producer:Q,nodes:c,truncated:a,viewport:o.viewport,lineage:u,residue:l};return e.acquisitionIntent===`full`?{...d,intent:`full`,hint:{...e,acquisitionIntent:`full`}}:{...d,intent:`surface-observation`,hint:{...e,acquisitionIntent:`surface-observation`}}}function nt(e,t,n){return Object.freeze([{kind:`unavailable-fact`,fact:`hittability`},...e.interactiveOnly?[{kind:`unavailable-fact`,fact:`interactive-query`}]:[],...t?[{kind:`truncated`}]:[],...n.kind===`missing`?[{kind:`missing-viewport`,reason:n.reason}]:[]])}export{Ze as createSimulatorSnapshotSource};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{C as e}from"./sdk-contracts.js";import{l as t}from"./sdk-device.js";import{Jt as n,Xt as r}from"./sdk-batch.js";import{n as i,o as a,r as o,s}from"./request-cancellation.js";import{n as c,t as l}from"./application-lifecycle-runtime.js";import{i as u,n as d}from"./touch-runtime.js";import{A as ee,B as te,D as ne,E as re,F as ie,G as f,H as p,I as ae,L as m,M as oe,N as h,R as g,W as se,a as ce,b as _,d as v,g as y,i as le,k as ue,m as de,s as fe,t as pe,v as b,w as me,x}from"./alert-runtime.js";import{n as he}from"./audio-probe-runtime.js";import{n as ge}from"./perf-runtime.js";import{r as _e}from"./platform-runtime-unavailable.js";import{a as ve,n as ye}from"./durable-resource.js";import{t as be}from"./async-lifecycle.js";import{a as S,d as xe,f as Se,n as Ce,o as we,u as Te}from"./src7.js";import{i as Ee,t as De}from"./gesture-admission.js";import{n as Oe}from"./interactor-operation-catalog.js";import{t as C}from"./app-log-runtime.js";import{r as ke,t as Ae}from"./application-lifecycle-interaction.js";import{setTimeout as je}from"node:timers/promises";const w=Object.freeze({available:!0}),Me=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Limrun iOS direct sessions do not expose portable gesture execution yet.`}),Ne=Object.freeze({available:!1,reason:`unsupported-provider-mode`}),Pe=Object.freeze({available:!1,reason:`unsupported-provider-mode`}),Fe=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:De}),Ie=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:Ee});function T(e,t){if(!t.available)return h({unsupported:t});if(e.platform!==`android`)return h({unsupported:Me});let n=e.target===`tv`;return h({unsupported:Ne,plan:w,directionalFling:w,multiTouch:n?Fe:w,targetAuthoredDrag:n?Ie:w,viewport:w})}const Le=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Limrun iOS direct sessions do not expose home yet.`}),Re=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Limrun iOS direct sessions do not expose tv remote control.`}),ze=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`tv-remote is supported only on Android TV targets.`}),Be=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Limrun iOS direct sessions do not expose keyboard actions.`}),Ve=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Limrun iOS direct sessions do not expose clipboard access yet.`}),He=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Limrun iOS direct sessions do not expose settings changes yet.`}),Ue=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Limrun iOS direct sessions do not expose app switcher yet.`});function E(e,n){let r=n??w,i=Object.freeze({available:!1,reason:`unsupported-provider-mode`});return Object.freeze({...ae({focus:r}),...ne({type:r}),...u({unsupported:i,tap:r,longPress:
|
|
1
|
+
import{C as e}from"./sdk-contracts.js";import{l as t}from"./sdk-device.js";import{Jt as n,Xt as r}from"./sdk-batch.js";import{n as i,o as a,r as o,s}from"./request-cancellation.js";import{n as c,t as l}from"./application-lifecycle-runtime.js";import{i as u,n as d}from"./touch-runtime.js";import{A as ee,B as te,D as ne,E as re,F as ie,G as f,H as p,I as ae,L as m,M as oe,N as h,R as g,W as se,a as ce,b as _,d as v,g as y,i as le,k as ue,m as de,s as fe,t as pe,v as b,w as me,x}from"./alert-runtime.js";import{n as he}from"./audio-probe-runtime.js";import{n as ge}from"./perf-runtime.js";import{r as _e}from"./platform-runtime-unavailable.js";import{a as ve,n as ye}from"./durable-resource.js";import{t as be}from"./async-lifecycle.js";import{a as S,d as xe,f as Se,n as Ce,o as we,u as Te}from"./src7.js";import{i as Ee,t as De}from"./gesture-admission.js";import{n as Oe}from"./interactor-operation-catalog.js";import{t as C}from"./app-log-runtime.js";import{r as ke,t as Ae}from"./application-lifecycle-interaction.js";import{setTimeout as je}from"node:timers/promises";const w=Object.freeze({available:!0}),Me=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Limrun iOS direct sessions do not expose portable gesture execution yet.`}),Ne=Object.freeze({available:!1,reason:`unsupported-provider-mode`}),Pe=Object.freeze({available:!1,reason:`unsupported-provider-mode`}),Fe=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:De}),Ie=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:Ee});function T(e,t){if(!t.available)return h({unsupported:t});if(e.platform!==`android`)return h({unsupported:Me});let n=e.target===`tv`;return h({unsupported:Ne,plan:w,directionalFling:w,multiTouch:n?Fe:w,targetAuthoredDrag:n?Ie:w,viewport:w})}const Le=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Limrun iOS direct sessions do not expose home yet.`}),Re=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Limrun iOS direct sessions do not expose tv remote control.`}),ze=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`tv-remote is supported only on Android TV targets.`}),Be=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Limrun iOS direct sessions do not expose keyboard actions.`}),Ve=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Limrun iOS direct sessions do not expose clipboard access yet.`}),He=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Limrun iOS direct sessions do not expose settings changes yet.`}),Ue=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Limrun iOS direct sessions do not expose app switcher yet.`});function E(e,n){let r=n??w,i=Object.freeze({available:!1,reason:`unsupported-provider-mode`});return Object.freeze({...ae({focus:r}),...ne({type:r}),...u({unsupported:i,tap:r,longPress:r,hover:n??i,fill:r,tapElementSelector:n??(t(e)?r:i)}),...T(e,r),...ee({scroll:r})})}function We(e){let{device:t,signal:n}=e,r=n=>e.getInteractor(t,n);return Object.freeze({...te({device:t,signal:n,resolveInteractor:r,presentIosAcquisition:e.presentIosAcquisition}),...ie({device:t,signal:n,resolveInteractor:r}),...re({device:t,signal:n,resolveInteractor:r}),...d({device:t,signal:n,resolveInteractor:r,facts:E(t),pause:async e=>await je(e,void 0,{signal:n})}),...se({device:t,signal:n,resolveInteractor:r}),...oe({device:t,signal:n,facts:T(t,w),resolveInteractor:r}),...ue({device:t,signal:n,resolveInteractor:r})})}function D(e,t){return t?Object.freeze({...x({back:t}),..._({home:t}),...b({orientation:t}),...y({tvRemote:t})}):e.platform===`android`?Object.freeze({...x({back:w}),..._({home:w}),...b({orientation:w}),...y({tvRemote:e.target===`tv`?w:ze})}):Object.freeze({...x({back:w}),..._({home:Le}),...b({orientation:w}),...y({tvRemote:Re})})}function O(e,t){return t?Object.freeze({...v({unsupported:t})}):e.platform===`android`?Object.freeze({...v({unsupported:Pe,read:w,write:w})}):Object.freeze({...v({unsupported:Ve})})}const Ge=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Limrun iOS direct sessions do not expose alert inspection yet.`});function k(e,t){let n=t??(e.platform===`android`?w:Ge);return Object.freeze({...pe({read:n,wait:n,accept:n,dismiss:n})})}function A(e,t){let n=t??(e.platform===`android`?w:Ue);return Object.freeze({...fe({appSwitcher:n})})}function j(e,t){return Object.freeze({...ce({triggerAppEvent:t??w})})}function M(e,t){let n=t??(e.platform===`android`?w:He);return Object.freeze({...le({setSetting:n})})}function N(e,t){let n=t??Be,r=t===void 0&&e.platform===`android`;return Object.freeze({...de(r?{unsupported:n,status:w,dismiss:w,enter:w}:{unsupported:n})})}const P=Object.freeze({resourceKind:C,version:1,encode:e=>({...e}),decode:e=>e.transport!==`limrun-log-poller`||e.platform!==`ios`&&e.platform!==`android`||!F(e.leaseId)||!F(e.instanceId)||!F(e.appBundleId)||!F(e.outputPath)?{status:`invalid`,message:`Invalid Limrun app-log descriptor`}:{status:`decoded`,descriptor:Object.freeze({transport:`limrun-log-poller`,platform:e.platform,leaseId:e.leaseId,instanceId:e.instanceId,appBundleId:e.appBundleId,outputPath:e.outputPath})}});function Ke(e){if(e.device.platform===`apple`&&!e.device.appleOs)throw TypeError(`Limrun Apple app-log persistence requires an explicit appleOs identity`);return ye({resourceKind:C,sessionId:e.sessionId,device:{id:e.device.id,family:e.device.platform,...e.device.appleOs===void 0?{}:{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:ve(P,e.descriptor)})}function F(e){return typeof e==`string`&&e.trim().length>0}async function I(e){let t=new be,n=!1;t.defer(async()=>{n||await e.reader[Symbol.asyncDispose]()});try{let r=await e.host.outputs.readTail(e.outputPath,262144),i=await e.host.outputs.openAppend(e.outputPath);t.defer(async()=>{n||await i[Symbol.asyncDispose]()});let a=qe(e,i,Qe(r));return n=!0,a}finally{await t[Symbol.asyncDispose]()}}function qe(e,t,n){let r=et(e.reader),i=e.host.clock.now(),a=`active`,o=!1,s=n,c=(async()=>{for(;!o;){try{let n=await Je(e);if(n.status===`timeout`){a=`failed`;return}if(o)return;let r=Ye(s,n.text);s=n.text,r&&await t.write(r.endsWith(`
|
|
2
2
|
`)?r:`${r}\n`),a=`active`}catch{if(o)return;a=`recovering`}await e.host.clock.sleep(1e3)}})(),l;return Te({inspect:()=>({backend:r,state:a,startedAt:i}),finish:async()=>l??=(async()=>(o=!0,await c,(await $e([e.reader,t])).length>0?(a=`failed`,{status:`cleanup-pending`,reason:`transport-failed`,message:`Limrun app-log cleanup did not settle every owned resource`}):(a=`ended`,{status:`completed`,result:{backend:r,outputPath:e.outputPath,completedAt:e.host.clock.now()}})))()})}async function Je(e){let t=new AbortController,n=i(e.reader.readLogs(e.appBundleId,1e3),t.signal,`App-log provider read aborted`).then(e=>({status:`read`,text:e}));try{let r=await Promise.race([n,e.host.clock.sleep(5e3,t.signal).then(()=>({status:`timeout`}))]);return r.status===`timeout`&&(t.abort(),await n.catch(()=>void 0)),r}finally{t.abort()}}function Ye(e,t){if(!e||!t)return t;let n=Xe(t),r=Math.min(e.length,t.length),i=e.slice(e.length-r);return t.slice(Ze(i,t,n))}function Xe(e){let t=new Uint32Array(e.length),n=0;for(let r=1;r<e.length;r+=1){for(;n>0&&e[r]!==e[n];)n=t[n-1];e[r]===e[n]&&(n+=1),t[r]=n}return t}function Ze(e,t,n){let r=0;for(let i=0;i<e.length;i+=1){for(;r>0&&e[i]!==t[r];)r=n[r-1];e[i]===t[r]&&(r+=1),r===t.length&&i<e.length-1&&(r=n[r-1])}return r}function Qe(e){return e.split(`
|
|
3
3
|
`).filter(e=>!e.startsWith(`[agent-device][mark]`)).join(`
|
|
4
4
|
`)}async function $e(e){return(await Promise.allSettled(e.map(async e=>await e[Symbol.asyncDispose]()))).flatMap(e=>e.status===`rejected`?[e.reason]:[])}function et(e){return e.platform===`ios`?`ios-simulator`:`android`}function tt(e){let t=Ae({owner:`Limrun`,openTargetIdentity:`bundle-id`,closeBeforeRelaunch:!0,configureProviderPortReverse:async t=>await e.configurePortReverse(t),binding:ke({device:e.device,signal:e.signal,resolveInteractor:t=>e.getInteractor(e.device,t)})}),n=e.resolveAppReference;return n?Object.freeze({...t,resolveOpenTarget:async e=>await t.resolveOpenTarget(nt(e,n)),openApplication:async e=>await t.openApplication(rt(e,n)),closeApplication:async e=>await t.closeApplication(it(e,n))}):t}function nt(e,t){return e.target===void 0?e:{...e,target:t(e.target)}}function rt(e,t){return{...e,target:R(e.target,t),positionals:L(e.positionals,t),appBundleId:R(e.appBundleId,t)}}function it(e,t){return{...e,positionals:L(e.positionals,t),appBundleId:R(e.appBundleId,t)}}function L(e,t){let n=e[0];return n===void 0?e:[t(n),...e.slice(1)]}function R(e,t){return e===void 0?void 0:t(e)}function at(e){let t=s(e.id);return!t||e.target!==`mobile`?!1:t.platform===`ios`?e.platform===`apple`&&e.appleOs===`ios`&&e.kind===`simulator`&&e.iosPhysicalDeviceBackend===void 0:e.platform===`android`&&e.appleOs===void 0&&e.kind===`emulator`&&e.iosPhysicalDeviceBackend===void 0}const ot=Object.freeze({available:!0}),z=Object.freeze({available:!1,reason:`owner-capability-missing`,hint:`The Limrun provider session is no longer active for this device.`}),st=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Push notifications are unavailable for Limrun provider-owned devices.`});function B(e,t){let n=lt(e,t);return Object.freeze({deployApp:n,materializeAppSource:n,deployMaterializedApp:n,sendPushNotification:V(e,t)?st:z})}function ct(e,t,n,r){let i=e.deployApp,a=e.deployMaterializedApp;return!B(e,t).deployApp.available||!i||!a?Object.freeze({}):Object.freeze({deployApp:async e=>H(await i(t,e,n,r)),materializeAppSource:async r=>await ut(e.host,t,r,n),deployMaterializedApp:async e=>H(await a(t,e,n,r))})}function lt(e,t){return at(t)&&V(e,t)&&e.deployApp&&e.deployMaterializedApp?ot:z}function V(e,t){return e.isSessionActive?.(t)??e.ownsDevice(t)}async function ut(e,t,n,r){return await(t.platform===`apple`?e.appleDeployment:e.androidDeployment).prepareArtifact(n,{signal:r})}function H(t){if(!t)throw new e(`UNSUPPORTED_OPERATION`,`The Limrun provider session is no longer active.`);return t}const U=Object.freeze({available:!0}),W=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Custom snapshot actions are available only for Limrun iOS simulator sessions.`}),dt=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Limrun does not expose viewport resizing.`}),G=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Limrun-owned devices read element text from the captured tree only.`}),K=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Limrun does not expose an exact-owner screen-recording runtime.`}),ft=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Headless boot is unavailable for provider-owned devices.`}),q=Object.freeze({available:!1,reason:`owner-capability-missing`,hint:`Limrun requires a matching live provider session for this device.`}),pt=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Apple runner preparation is unavailable for Limrun-owned devices.`}),mt=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Limrun iOS appstate is session-owned; no sessionless provider foreground probe is exposed.`}),ht=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Limrun open requires a Limrun-owned iOS simulator or Android emulator.`}),gt=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Limrun close requires a Limrun-owned iOS simulator or Android emulator.`}),J=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Runtime hints are not applied to provider-owned devices.`}),_t=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Limrun port reverse requires an active Android Limrun session.`}),Y=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Limrun does not expose the audio probe.`});function vt(e){return{...e,isSessionActive:e.hasLiveSession}}function X(e,t){let n=yt(e,t),r=bt(e,t),i=xt(e,t);return l({resolveOpenTarget:n,prepareApplicationOpen:n,openApplication:n,applyRuntimeHints:J,clearRuntimeHints:J,closeApplication:r,finalizeApplicationClose:r,prepareAppleRunner:pt,configureProviderPortReverse:i})}function yt(e,t){return a(e)?t?U:q:ht}function bt(e,t){return a(e)?t?U:q:gt}function xt(e,t){return t?e.platform===`android`?U:_t:q}function Z(e,n){let r=B(vt(e),n),i=n.platform===`android`,a=t(n)&&n.kind===`simulator`?U:W;return Object.freeze({device:{family:n.platform,...n.appleOs===void 0?{}:{appleOs:n.appleOs},kind:n.kind,...n.target===void 0?{}:{target:n.target},...n.iosPhysicalDeviceBackend===void 0?{}:{iosPhysicalDeviceBackend:n.iosPhysicalDeviceBackend},providerMode:`provider-runtime`},operations:{appLogInspect:U,appLogDoctor:U,appLogStart:U,appLogReattach:U,appLogCleanup:U,...r,appState:i?U:mt,networkDump:U,screenRecordingStart:K,screenRecordingReattach:K,screenRecordingCleanup:K,...p({capture:U,customActions:a,withoutActiveApp:U}),...f({capture:U}),...g({findText:W}),...m({setViewport:dt}),...E(n),...me({readTextAtPoint:G}),...D(n),...N(n),...O(n),...A(n),...j(n),...M(n),...k(n),...he({capture:Y,query:Y}),...ge({frames:G,memorySample:G,memorySnapshot:G,nativeCapture:G,profileReport:G}),ensureReady:U,bootTarget:U,bootTargetHeadless:ft,listApps:U,shutdownTarget:{available:!1,reason:`unsupported-provider-mode`,hint:`Limrun owns the target lifecycle for provider-owned devices.`},...X(n,!0)}})}function St(e,t){let n=Z(e,t);return Object.freeze({device:n.device,operations:{...n.operations,appLogInspect:q,appLogDoctor:q,appLogStart:q,appLogReattach:U,appLogCleanup:U,appState:q,networkDump:q,screenRecordingStart:q,screenRecordingReattach:q,screenRecordingCleanup:q,...p({capture:q,customActions:q,withoutActiveApp:q}),...f({capture:q}),...g({findText:q}),...m({setViewport:q}),...E(t,q),...D(t,q),...N(t,q),...O(t,q),...A(t,q),...j(t,q),...M(t,q),...k(t,q),ensureReady:q,bootTarget:q,bootTargetHeadless:q,listApps:q,deployApp:q,materializeAppSource:q,deployMaterializedApp:q,sendPushNotification:q,shutdownTarget:q,...X(t,!1)}})}function Ct(t){let i=n(`limrun`,t.runtimeInstance),o=e=>a(e)&&t.ownsDevice(e),s=e=>o(e)&&t.hasLiveSession(e);return Object.freeze({owner:i,ownsDevice:o,inspectFacts:async e=>s(e)?Z(t,e):_e(e,i,{appLog:q,appState:q,appDeployment:q,network:q,screenshot:q,viewport:q,focus:q,gesture:q,scroll:q,typeText:q,touch:q,elementText:q,back:q,home:q,orientation:q,tvRemote:q,keyboard:q,clipboard:q,appSwitcher:q,triggerAppEvent:q,setSetting:q,readAlert:q,awaitAlert:q,acceptAlert:q,dismissAlert:q,audioProbeCapture:q,audioProbeQuery:q,perf:q,readiness:q,shutdown:q,lifecycle:X(e,!1)}),bind:async n=>{if(n.intent.kind===`exact-owner`&&!r(n.intent.owner,i))throw new e(`UNSUPPORTED_OPERATION`,`Limrun app-log owner identity does not match`);if(!a(n.device))throw new e(`UNSUPPORTED_PLATFORM`,`Limrun app logs require an iOS simulator or Android emulator device identity`);let o=s(n.device);if(n.intent.kind!==`exact-owner`&&!o)throw new e(`UNSUPPORTED_OPERATION`,`Limrun provider session is no longer live for the selected device`,{reason:`provider-session-unavailable`});return wt(t,i,n.device,n.scope.signal,!o)},shutdown:async()=>void 0})}function wt(t,n,r,i,a){let s=a?St(t,r):Z(t,r),l=o(),u=xe({codec:P,reattach:async(e,n)=>{if(!$(e,r)||!S(t.host,n.sessionId,e))return{status:`unreattachable`,reason:`descriptor-invalid`,message:`Limrun app-log descriptor does not match the bound device or owning session`};let a=await t.reconnect(e,i);return a.status===`missing`?{status:`missing`}:a.status===`ownership-lost`?{status:`unreattachable`,reason:`ownership-fence-lost`}:{status:`active`,handle:await I({host:t.host,reader:a.reader,appBundleId:e.appBundleId,outputPath:e.outputPath})}},cleanup:async(e,n)=>$(e,r)&&S(t.host,n.sessionId,e)?{status:`cleaned`}:{status:`cleanup-pending`,reason:`ownership-fence-lost`,message:`Limrun app-log descriptor does not match the bound device or owning session`}}),d={appLogInspect:async()=>({backend:Q(r)}),appLogDoctor:async()=>({backend:Q(r),checks:{limrunSessionAvailable:await Tt(t,r,i)},notes:[]}),appLogStart:async a=>{we(t.host,a),i.throwIfAborted();let o=await t.openCurrent(r);if(!o)throw new e(`UNSUPPORTED_OPERATION`,`Limrun app logs require an active instance`);let s={transport:`limrun-log-poller`,platform:o.platform,leaseId:o.leaseId,instanceId:o.instanceId,appBundleId:a.appBundleId,outputPath:a.outputPath},c=!1;try{i.throwIfAborted();let e=Ke({sessionId:a.sessionId,device:r,owner:n,fence:a.fence,descriptor:s});c=!0;let l=await I({host:t.host,reader:o,appBundleId:a.appBundleId,outputPath:a.outputPath});return Se(l,e)}catch(e){throw c||await o[Symbol.asyncDispose](),e}},...u,networkDump:async e=>{let n=await t.host.appLogs.readRecent(e.sessionId,e.maxScanLines),i=Q(r),{dump:a}=Ce(n.text,{...e,path:n.path,exists:n.exists,lineNumberOffset:n.skippedLines,backend:i}),o=a.entries.length===0?[`No HTTP(s) entries were found in recent session app logs.`]:[];return Object.freeze({source:`app-log`,backend:i,dump:a,notes:o})},ensureReady:async()=>({...r,booted:!0}),bootTarget:async()=>({...r,booted:!0}),listApps:async e=>await t.listApps(e.device,e.filter,i),...r.platform===`android`?{appState:async()=>await t.getAppState(r,i)}:{},...c(tt({device:r,signal:i,getInteractor:t.getInteractor,resolveAppReference:e=>t.resolveAppReference?.(r,e)??e,configurePortReverse:t.configurePortReverse}),s.operations),...We({device:r,signal:i,getInteractor:t.getInteractor,presentIosAcquisition:t.host.snapshot.presentIosAcquisition}),...Oe({device:r,signal:i,resolveInteractor:e=>t.getInteractor(r,e),facts:s.operations}),...ct(vt(t),r,i,l)};return Object.freeze({device:r,owner:n,facts:s,operations:Object.freeze(a?{appLogReattach:u.appLogReattach,appLogCleanup:u.appLogCleanup}:d),[Symbol.asyncDispose]:async()=>await l[Symbol.asyncDispose]()})}async function Tt(e,t,n){n.throwIfAborted();let r=await e.openCurrent(t);if(!r)return!1;try{n.throwIfAborted()}finally{await r[Symbol.asyncDispose]()}return!0}function Q(e){return e.platform===`apple`?`ios-simulator`:`android`}function $(e,t){if(!a(t))return!1;let n=s(t.id);return n!==void 0&&n.leaseId===e.leaseId&&n.platform===e.platform&&(t.platform===`apple`?e.platform===`ios`:e.platform===`android`)}export{Ct as createLimrunPlatformRuntimeOwner};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{C as e}from"./sdk-contracts.js";import{r as t}from"./sdk-batch-runner.js";import{n}from"./app-inventory.js";import"./device.js";import{t as r}from"./request-cancellation.js";import{n as i,t as a}from"./ios-client.js";import{a as o,i as s}from"./snapshot.js";import c from"node:path";import l from"node:fs";import u from"node:os";import{setTimeout as d}from"node:timers/promises";function f(e){return e?.trim()||void 0}async function p(e,t){let n=await i({apiUrl:e.apiUrl,adbUrl:e.adbUrl,token:e.token,logLevel:`warn`}),r={platform:`android`,lease:e.lease,instanceId:e.instanceId,device:e.device,client:n,dependencies:t},a={exec:async(e,t)=>await y(r,e,t),text:async e=>{await n.setText(e.target,e.text)}};return a.reverse=await t.android.createPortReverse(a.exec),Object.assign(r,{adbProvider:a})}function m(e){return e.dependencies.android.createInteractor(e.device,e.adbProvider)}async function h(e,t,n,i,a,o){a?.throwIfAborted();let s=f(i?.packageNameHint);i?.relaunch&&s&&await y(t,[`shell`,`am`,`force-stop`,s],{allowFailure:!0,signal:a});let c=await r(o,e.assets.getOrUpload({path:n,name:T(s,n)},{signal:a}),a);await r(o,t.client.sendAsset(c.signedDownloadUrl),a),a?.throwIfAborted();let l=s?await t.dependencies.android.inferAppName(s):void 0;return{...s?{packageName:s,launchTarget:s}:{},...l?{appName:l}:{}}}async function g(e,t){await e.adbProvider.reverse?.ensure({local:w(t.devicePort),remote:w(t.hostPort),ownerId:t.name})}async function _(e){await e.adbTunnelPromise?.catch(()=>{});let t=e.adbSerial;t&&(await v(e),await e.dependencies.host.runAdb([`disconnect`,t],{allowFailure:!0,timeoutMs:1e4}).catch(()=>{})),e.adbTunnel?.close(),e.adbTunnel=void 0,e.adbSerial=void 0,e.adbTunnelPromise=void 0}async function v(e){let t=e.adbProvider.reverse;if(!t?.list)return;let n=await t.list().catch(()=>[]),r=new Set,i=[];for(let e of n)e.ownerId?r.add(e.ownerId):i.push(e.local);await Promise.allSettled([...[...r].map(async e=>await t.removeAllOwned(e)),...i.map(async e=>await t.remove(e))])}async function y(e,t,n){let{adbArgs:r,result:i}=await b(e,t,n);return await x(r,i,n?.allowFailure,e.dependencies)}async function b(e,t,n){let r=[`-s`,await S(e),...t];return{adbArgs:r,result:await e.dependencies.host.runAdb(r,{allowFailure:n?.allowFailure,binaryStdout:n?.binaryStdout,stdin:n?.stdin,timeoutMs:n?.timeoutMs??3e4,signal:n?.signal})}}async function x(e,t,n,r){if(t.exitCode!==0&&n!==!0)throw await r.android.adbError(`Limrun Android ADB command failed`,t,{command:[`adb`,...e].join(` `)});return t}async function S(e){if(e.adbSerial)return e.adbSerial;let t=e.adbTunnelPromise??C(e);e.adbTunnelPromise=t;try{return await t}catch(n){throw e.adbTunnelPromise===t&&(e.adbTunnelPromise=void 0),n}}async function C(e){let t=await e.client.startAdbTunnel(),n=`${t.address.address}:${t.address.port}`;return e.adbTunnel=t,e.adbSerial=n,n}function w(t){if(!Number.isInteger(t)||t<1||t>65535)throw new e(`INVALID_ARGS`,`Invalid Android tcp reverse port: ${t}`);return`tcp:${t}`}function T(e,t){let n=c.extname(t)||`.apk`;return`${e?.replaceAll(/[^a-zA-Z0-9_.-]+/g,`-`)||`android-app`}${n}`}async function E(e,t){let n=await a({apiUrl:e.apiUrl,token:e.token,logLevel:`warn`});return{platform:`ios`,lease:e.lease,instanceId:e.instanceId,device:e.device,client:n,dependencies:t}}async function D(e,t,n,i,a,o){a?.throwIfAborted();let s=await j(n,t.dependencies);try{a?.throwIfAborted();let n=await r(o,e.assets.getOrUpload({path:s.uploadPath,name:s.assetName},{signal:a}),a),c=(await O(t,n.signedDownloadUrl,{md5:n.md5,relaunch:i?.relaunch,appIdentifierHint:i?.appIdentifierHint},a,o)).appId;return{...c?{bundleId:c,launchTarget:c}:{},...s.appName?{appName:s.appName}:{}}}finally{await s.cleanup()}}async function O(t,n,i,a,o){a?.throwIfAborted();let s=await r(o,t.client.listApps(),a).catch(e=>{if(a?.aborted)throw e}),c=f((await r(o,t.client.installApp(n,{md5:i?.md5,launchMode:i?.relaunch?`RelaunchIfRunning`:`ForegroundIfRunning`}),a)).bundleId),l=f(i?.appIdentifierHint),u=[];for(let e of N){e>0&&await d(e,void 0,{signal:a}),u=await r(o,t.client.listApps(),a);let n=P({resultBundleId:c,requestedBundleId:l,beforeInstallApps:s,afterInstallApps:u});if(n)return{appId:n}}throw new e(`COMMAND_FAILED`,`Limrun iOS app installation could not be verified.`,{resultBundleId:c,requestedBundleId:l,installedUserApps:u.filter(I).map(e=>e.bundleId).sort()})}function k(e){return new A(e)}var A=class{session;constructor(e){this.session=e}async open(e,n){if(n?.url){await this.session.client.launchApp(await this.session.dependencies.ios.resolveAppAlias(e)),await this.session.client.openUrl(n.url);return}if(t(e)){await this.session.client.openUrl(e);return}await this.session.client.launchApp(await this.session.dependencies.ios.resolveAppAlias(e))}async openDevice(){}async close(e){e&&await this.session.client.terminateApp(await this.session.dependencies.ios.resolveAppAlias(e)).catch(()=>{})}async tap(e,t){await this.session.client.tap(e,t)}async tapElementSelector(e){await this.session.client.tapElement(s(e))}async doubleTap(e,t){await this.tap(e,t),await this.tap(e,t)}async longPress(){throw R(`longpress`,`Limrun iOS direct sessions do not expose long press yet.`)}async focus(e,t){await this.tap(e,t)}async type(e,t){await this.enterText(e,t)}async fill(e,t,n,r){let{awaitLimrunTextEntryFocus:i,readLimrunUnambiguousTapTargets:a,readLimrunTextEntryFocus:o}=await import(`./text-entry-focus.js`),s=a(await this.session.client.elementTree(),e,t);await this.tap(e,t);let c=await i({targetsAtPoint:s,readFocus:async()=>o(await this.session.client.elementTree()),sleep:e=>d(e),x:e,y:t});return await this.session.client.pressKey(`a`,[`command`]),n.length===0?(await this.session.client.pressKey(`delete`),{textEntryReadiness:c}):(await this.enterText(n,r),{textEntryReadiness:c})}async enterText(e,t){if(t&&t>0){for(let n of Array.from(e))await this.session.client.typeText(n,!1,{requireFocus:!1}),await d(t);return}await this.session.client.typeText(e,!1,{requireFocus:!1})}async scroll(e,t){await this.session.client.scroll(e,t?.pixels??300)}async screenshot(e){let t=await this.session.client.screenshot();await o(e,t.base64)}async snapshot(){let{captureLimrunIosSnapshot:e}=await import(`./ios-snapshot-adapter.js`);return await e(this.session)}async back(){await this.session.client.pressKey(`escape`)}async home(){throw R(`home`,`Limrun iOS direct sessions do not expose home yet.`)}async setOrientation(e){if(e===`portrait-upside-down`)throw R(`orientation`,`Limrun iOS direct sessions support portrait and landscape orientation, not portrait upside-down.`);await this.session.client.setOrientation(e===`portrait`?`Portrait`:`Landscape`)}async performGesture(){throw R(`gesture`,`Limrun iOS direct sessions do not expose portable gesture execution yet.`)}async appSwitcher(){throw R(`app-switcher`,`Limrun iOS direct sessions do not expose app switcher yet.`)}async tvRemote(){throw R(`tv-remote`,`Limrun iOS direct sessions do not expose tv remote control.`)}async readAlert(){throw R(`alert`,L)}async awaitAlert(){throw R(`alert`,L)}async acceptAlert(){throw R(`alert`,L)}async dismissAlert(){throw R(`alert`,L)}async readClipboard(){throw R(`clipboard`,`Limrun iOS direct sessions do not expose clipboard read yet.`)}async writeClipboard(){throw R(`clipboard`,`Limrun iOS direct sessions do not expose clipboard write yet.`)}async setSetting(){throw R(`settings`,`Limrun iOS direct sessions do not expose settings changes yet.`)}};async function j(e,t){if(!(await l.promises.stat(e)).isDirectory())return{uploadPath:e,assetName:c.basename(e),appName:M(e),cleanup:async()=>{}};let n=await l.promises.mkdtemp(c.join(u.tmpdir(),`agent-device-limrun-ios-app-`)),r=c.join(n,`${c.basename(e)}.zip`);try{await t.host.archiveDirectory({sourceDirectory:c.dirname(e),entryName:c.basename(e),archivePath:r})}catch(e){throw await l.promises.rm(n,{recursive:!0,force:!0}),e}return{uploadPath:r,assetName:c.basename(r),appName:await t.ios.readBundleAppName(e)??M(e),cleanup:async()=>{await l.promises.rm(n,{recursive:!0,force:!0})}}}function M(e){return c.basename(e).replace(/\.(?:app|ipa|apk|aab|zip)$/i,``)||void 0}const N=[0,250];function P(e){let t=new Set(e.afterInstallApps.map(e=>e.bundleId));return(e.resultBundleId&&t.has(e.resultBundleId)?e.resultBundleId:void 0)??(e.requestedBundleId&&t.has(e.requestedBundleId)?e.requestedBundleId:void 0)??F(e.beforeInstallApps,e.afterInstallApps)}function F(e,t){if(!e)return;let n=new Set(e.map(e=>e.bundleId)),r=t.filter(e=>I(e)&&!n.has(e.bundleId));return r.length===1?r[0]?.bundleId:void 0}function I(e){return!e.bundleId.startsWith(`com.apple.`)&&!e.installType.toLowerCase().includes(`system`)}const L=`Limrun iOS direct sessions do not expose alert inspection yet.`;function R(t,n){throw new e(`UNSUPPORTED_OPERATION`,n,{command:t})}function z(e){return e.platform===`android`?B(e):V(e)}function B(e){let t=e.adbProvider.exec;return{platform:`android`,device:e.device,interactor:m(e),adb:e.adbProvider,listApps:async r=>await e.dependencies.android.listApps(t,n(r)),getForegroundApp:async n=>await e.dependencies.android.getForegroundApp(e.device,t,n),pressKey:async(t,n)=>{await e.client.pressKey(t,n)},getKeyboardState:async()=>await e.dependencies.android.getKeyboardState(t),dismissKeyboard:async()=>await e.dependencies.android.dismissKeyboard(t),readLogs:async n=>await e.dependencies.android.readLogs(t,n),...H(e.client),installRemoteApp:async t=>{await e.client.sendAsset(t)}}}function V(e){return{platform:`ios`,device:e.device,interactor:k(e),viewport:{width:e.client.deviceInfo.screenWidth,height:e.client.deviceInfo.screenHeight},listApps:async t=>(await e.client.listApps()).filter(e=>n(t)===`all`||I(e)).map(e=>({id:e.bundleId,name:e.name,installType:e.installType})).sort((e,t)=>e.id.localeCompare(t.id)),pressKey:async(t,n)=>{await e.client.pressKey(t,n)},readLogs:async(t,n)=>await e.client.appLogTail(t,n),...H(e.client),installRemoteApp:async(t,n)=>await O(e,t,n),runSimctl:t=>e.client.simctl(t)}}function H(e){return{startRecording:async t=>{await e.startRecording(t)},stopRecording:async({outPath:t})=>await e.stopRecording({localPath:t})}}export{_ as a,p as c,D as i,h as l,k as n,g as o,E as r,m as s,z as t};
|
|
1
|
+
import{C as e}from"./sdk-contracts.js";import{r as t}from"./sdk-batch-runner.js";import{n}from"./app-inventory.js";import"./device.js";import{t as r}from"./request-cancellation.js";import{n as i,t as a}from"./ios-client.js";import{a as o,i as s}from"./snapshot.js";import c from"node:path";import l from"node:fs";import u from"node:os";import{setTimeout as d}from"node:timers/promises";function f(e){return e?.trim()||void 0}async function p(e,t){let n=await i({apiUrl:e.apiUrl,adbUrl:e.adbUrl,token:e.token,logLevel:`warn`}),r={platform:`android`,lease:e.lease,instanceId:e.instanceId,device:e.device,client:n,dependencies:t},a={exec:async(e,t)=>await y(r,e,t),text:async e=>{await n.setText(e.target,e.text)}};return a.reverse=await t.android.createPortReverse(a.exec),Object.assign(r,{adbProvider:a})}function m(e){return e.dependencies.android.createInteractor(e.device,e.adbProvider)}async function h(e,t,n,i,a,o){a?.throwIfAborted();let s=f(i?.packageNameHint);i?.relaunch&&s&&await y(t,[`shell`,`am`,`force-stop`,s],{allowFailure:!0,signal:a});let c=await r(o,e.assets.getOrUpload({path:n,name:T(s,n)},{signal:a}),a);await r(o,t.client.sendAsset(c.signedDownloadUrl),a),a?.throwIfAborted();let l=s?await t.dependencies.android.inferAppName(s):void 0;return{...s?{packageName:s,launchTarget:s}:{},...l?{appName:l}:{}}}async function g(e,t){await e.adbProvider.reverse?.ensure({local:w(t.devicePort),remote:w(t.hostPort),ownerId:t.name})}async function _(e){await e.adbTunnelPromise?.catch(()=>{});let t=e.adbSerial;t&&(await v(e),await e.dependencies.host.runAdb([`disconnect`,t],{allowFailure:!0,timeoutMs:1e4}).catch(()=>{})),e.adbTunnel?.close(),e.adbTunnel=void 0,e.adbSerial=void 0,e.adbTunnelPromise=void 0}async function v(e){let t=e.adbProvider.reverse;if(!t?.list)return;let n=await t.list().catch(()=>[]),r=new Set,i=[];for(let e of n)e.ownerId?r.add(e.ownerId):i.push(e.local);await Promise.allSettled([...[...r].map(async e=>await t.removeAllOwned(e)),...i.map(async e=>await t.remove(e))])}async function y(e,t,n){let{adbArgs:r,result:i}=await b(e,t,n);return await x(r,i,n?.allowFailure,e.dependencies)}async function b(e,t,n){let r=[`-s`,await S(e),...t];return{adbArgs:r,result:await e.dependencies.host.runAdb(r,{allowFailure:n?.allowFailure,binaryStdout:n?.binaryStdout,stdin:n?.stdin,timeoutMs:n?.timeoutMs??3e4,signal:n?.signal})}}async function x(e,t,n,r){if(t.exitCode!==0&&n!==!0)throw await r.android.adbError(`Limrun Android ADB command failed`,t,{command:[`adb`,...e].join(` `)});return t}async function S(e){if(e.adbSerial)return e.adbSerial;let t=e.adbTunnelPromise??C(e);e.adbTunnelPromise=t;try{return await t}catch(n){throw e.adbTunnelPromise===t&&(e.adbTunnelPromise=void 0),n}}async function C(e){let t=await e.client.startAdbTunnel(),n=`${t.address.address}:${t.address.port}`;return e.adbTunnel=t,e.adbSerial=n,n}function w(t){if(!Number.isInteger(t)||t<1||t>65535)throw new e(`INVALID_ARGS`,`Invalid Android tcp reverse port: ${t}`);return`tcp:${t}`}function T(e,t){let n=c.extname(t)||`.apk`;return`${e?.replaceAll(/[^a-zA-Z0-9_.-]+/g,`-`)||`android-app`}${n}`}async function E(e,t){let n=await a({apiUrl:e.apiUrl,token:e.token,logLevel:`warn`});return{platform:`ios`,lease:e.lease,instanceId:e.instanceId,device:e.device,client:n,dependencies:t}}async function D(e,t,n,i,a,o){a?.throwIfAborted();let s=await j(n,t.dependencies);try{a?.throwIfAborted();let n=await r(o,e.assets.getOrUpload({path:s.uploadPath,name:s.assetName},{signal:a}),a),c=(await O(t,n.signedDownloadUrl,{md5:n.md5,relaunch:i?.relaunch,appIdentifierHint:i?.appIdentifierHint},a,o)).appId;return{...c?{bundleId:c,launchTarget:c}:{},...s.appName?{appName:s.appName}:{}}}finally{await s.cleanup()}}async function O(t,n,i,a,o){a?.throwIfAborted();let s=await r(o,t.client.listApps(),a).catch(e=>{if(a?.aborted)throw e}),c=f((await r(o,t.client.installApp(n,{md5:i?.md5,launchMode:i?.relaunch?`RelaunchIfRunning`:`ForegroundIfRunning`}),a)).bundleId),l=f(i?.appIdentifierHint),u=[];for(let e of N){e>0&&await d(e,void 0,{signal:a}),u=await r(o,t.client.listApps(),a);let n=I({resultBundleId:c,requestedBundleId:l,beforeInstallApps:s,afterInstallApps:u});if(n)return{appId:n}}throw new e(`COMMAND_FAILED`,`Limrun iOS app installation could not be verified.`,{resultBundleId:c,requestedBundleId:l,installedUserApps:u.filter(R).map(e=>e.bundleId).sort()})}function k(e){return new A(e)}var A=class{session;constructor(e){this.session=e}async open(e,n){if(n?.url){await this.session.client.launchApp(await this.session.dependencies.ios.resolveAppAlias(e)),await this.session.client.openUrl(n.url);return}if(t(e)){await this.session.client.openUrl(e);return}await this.session.client.launchApp(await this.session.dependencies.ios.resolveAppAlias(e))}async openDevice(){}async close(e){e&&await this.session.client.terminateApp(await this.session.dependencies.ios.resolveAppAlias(e)).catch(()=>{})}async tap(e,t){await this.session.client.tap(e,t)}async tapElementSelector(e){await this.session.client.tapElement(s(e))}async doubleTap(e,t){await this.session.client.performActions([{type:`tap`,x:e,y:t},{type:`wait`,durationMs:F},{type:`tap`,x:e,y:t}])}async longPress(e,t,n=P){await this.session.client.performActions([{type:`touchDown`,x:e,y:t},{type:`wait`,durationMs:n},{type:`touchUp`,x:e,y:t}])}async focus(e,t){await this.tap(e,t)}async type(e,t){await this.enterText(e,t)}async fill(e,t,n,r){let{awaitLimrunTextEntryFocus:i,readLimrunUnambiguousTapTargets:a,readLimrunTextEntryFocus:o}=await import(`./text-entry-focus.js`),s=a(await this.session.client.elementTree(),e,t);await this.tap(e,t);let c=await i({targetsAtPoint:s,readFocus:async()=>o(await this.session.client.elementTree()),sleep:e=>d(e),x:e,y:t});return await this.session.client.pressKey(`a`,[`command`]),n.length===0?(await this.session.client.pressKey(`delete`),{textEntryReadiness:c}):(await this.enterText(n,r),{textEntryReadiness:c})}async enterText(e,t){if(t&&t>0){for(let n of Array.from(e))await this.session.client.typeText(n,!1,{requireFocus:!1}),await d(t);return}await this.session.client.typeText(e,!1,{requireFocus:!1})}async scroll(e,t){await this.session.client.scroll(e,t?.pixels??300)}async screenshot(e){let t=await this.session.client.screenshot();await o(e,t.base64)}async snapshot(){let{captureLimrunIosSnapshot:e}=await import(`./ios-snapshot-adapter.js`);return await e(this.session)}async back(){await this.session.client.pressKey(`escape`)}async home(){throw B(`home`,`Limrun iOS direct sessions do not expose home yet.`)}async setOrientation(e){if(e===`portrait-upside-down`)throw B(`orientation`,`Limrun iOS direct sessions support portrait and landscape orientation, not portrait upside-down.`);await this.session.client.setOrientation(e===`portrait`?`Portrait`:`Landscape`)}async performGesture(){throw B(`gesture`,`Limrun iOS direct sessions do not expose portable gesture execution yet.`)}async appSwitcher(){throw B(`app-switcher`,`Limrun iOS direct sessions do not expose app switcher yet.`)}async tvRemote(){throw B(`tv-remote`,`Limrun iOS direct sessions do not expose tv remote control.`)}async readAlert(){throw B(`alert`,z)}async awaitAlert(){throw B(`alert`,z)}async acceptAlert(){throw B(`alert`,z)}async dismissAlert(){throw B(`alert`,z)}async readClipboard(){throw B(`clipboard`,`Limrun iOS direct sessions do not expose clipboard read yet.`)}async writeClipboard(){throw B(`clipboard`,`Limrun iOS direct sessions do not expose clipboard write yet.`)}async setSetting(){throw B(`settings`,`Limrun iOS direct sessions do not expose settings changes yet.`)}};async function j(e,t){if(!(await l.promises.stat(e)).isDirectory())return{uploadPath:e,assetName:c.basename(e),appName:M(e),cleanup:async()=>{}};let n=await l.promises.mkdtemp(c.join(u.tmpdir(),`agent-device-limrun-ios-app-`)),r=c.join(n,`${c.basename(e)}.zip`);try{await t.host.archiveDirectory({sourceDirectory:c.dirname(e),entryName:c.basename(e),archivePath:r})}catch(e){throw await l.promises.rm(n,{recursive:!0,force:!0}),e}return{uploadPath:r,assetName:c.basename(r),appName:await t.ios.readBundleAppName(e)??M(e),cleanup:async()=>{await l.promises.rm(n,{recursive:!0,force:!0})}}}function M(e){return c.basename(e).replace(/\.(?:app|ipa|apk|aab|zip)$/i,``)||void 0}const N=[0,250],P=800,F=80;function I(e){let t=new Set(e.afterInstallApps.map(e=>e.bundleId));return(e.resultBundleId&&t.has(e.resultBundleId)?e.resultBundleId:void 0)??(e.requestedBundleId&&t.has(e.requestedBundleId)?e.requestedBundleId:void 0)??L(e.beforeInstallApps,e.afterInstallApps)}function L(e,t){if(!e)return;let n=new Set(e.map(e=>e.bundleId)),r=t.filter(e=>R(e)&&!n.has(e.bundleId));return r.length===1?r[0]?.bundleId:void 0}function R(e){return!e.bundleId.startsWith(`com.apple.`)&&!e.installType.toLowerCase().includes(`system`)}const z=`Limrun iOS direct sessions do not expose alert inspection yet.`;function B(t,n){throw new e(`UNSUPPORTED_OPERATION`,n,{command:t})}function V(e){return e.platform===`android`?H(e):U(e)}function H(e){let t=e.adbProvider.exec;return{platform:`android`,device:e.device,interactor:m(e),adb:e.adbProvider,listApps:async r=>await e.dependencies.android.listApps(t,n(r)),getForegroundApp:async n=>await e.dependencies.android.getForegroundApp(e.device,t,n),pressKey:async(t,n)=>{await e.client.pressKey(t,n)},getKeyboardState:async()=>await e.dependencies.android.getKeyboardState(t),dismissKeyboard:async()=>await e.dependencies.android.dismissKeyboard(t),readLogs:async n=>await e.dependencies.android.readLogs(t,n),...W(e.client),installRemoteApp:async t=>{await e.client.sendAsset(t)}}}function U(e){return{platform:`ios`,device:e.device,interactor:k(e),viewport:{width:e.client.deviceInfo.screenWidth,height:e.client.deviceInfo.screenHeight},listApps:async t=>(await e.client.listApps()).filter(e=>n(t)===`all`||R(e)).map(e=>({id:e.bundleId,name:e.name,installType:e.installType})).sort((e,t)=>e.id.localeCompare(t.id)),pressKey:async(t,n)=>{await e.client.pressKey(t,n)},readLogs:async(t,n)=>await e.client.appLogTail(t,n),...W(e.client),installRemoteApp:async(t,n)=>await O(e,t,n),runSimctl:t=>e.client.simctl(t)}}function W(e){return{startRecording:async t=>{await e.startRecording(t)},stopRecording:async({outPath:t})=>await e.stopRecording({localPath:t})}}export{_ as a,p as c,D as i,h as l,k as n,g as o,E as r,m as s,V as t};
|
package/dist/src/internal/bin.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
async function e(e,n,r){try{await t(e,n,r)}catch(e){r.stderr(`${e instanceof Error?e.message:String(e)}\n`),await(await n.processExit()).exitAfterFlush(1)}}async function t(e,t,l){if(e.length===0)return await n(t,l);if(o(e))return await r(t,l);let u=c(e);if(u!==void 0)return await i(u,e,t,l);if(s(e))return await(await t.mcp()).runAgentDeviceMcpServer();await a(e,t)}async function n(e,t){t.stdout(`${(await e.help()).buildUsageText()}\n`),await(await e.processExit()).exitAfterFlush(1)}async function r(e,t){t.stdout(`${t.bundledVersion??(await e.version()).readVersion()}\n`)}async function i(e,t,n,r){let i=await n.help(),o=e===null?`${i.buildUsageText()}\n`:i.resolveHelpTargetUsageText(e);if(o===null)return await a(t,n);r.stdout(o)}async function a(e,t){await(await t.cli()).runCliProcess(e)}function o(e){return e.length===1&&(e[0]===`--version`||e[0]===`-V`)}function s(e){return e[0]===`mcp`&&!e.some(l)}function c(e){let[t,n]=e;if(e.length===1)return t===`help`||l(t)?null:void 0;if(e.length===2)return t===`help`?n:l(n)?t:void 0}function l(e){return e===`--help`||e===`-h`}e(process.argv.slice(2),{help:()=>import(`../cli-help.js`).then(e=>e.n),cli:()=>import(`../process-entry.js`),mcp:()=>import(`../server.js`),version:()=>import(`../version.js`).then(e=>e.t),processExit:()=>import(`../process-exit.js`)},{bundledVersion:`0.21.
|
|
1
|
+
async function e(e,n,r){try{await t(e,n,r)}catch(e){r.stderr(`${e instanceof Error?e.message:String(e)}\n`),await(await n.processExit()).exitAfterFlush(1)}}async function t(e,t,l){if(e.length===0)return await n(t,l);if(o(e))return await r(t,l);let u=c(e);if(u!==void 0)return await i(u,e,t,l);if(s(e))return await(await t.mcp()).runAgentDeviceMcpServer();await a(e,t)}async function n(e,t){t.stdout(`${(await e.help()).buildUsageText()}\n`),await(await e.processExit()).exitAfterFlush(1)}async function r(e,t){t.stdout(`${t.bundledVersion??(await e.version()).readVersion()}\n`)}async function i(e,t,n,r){let i=await n.help(),o=e===null?`${i.buildUsageText()}\n`:i.resolveHelpTargetUsageText(e);if(o===null)return await a(t,n);r.stdout(o)}async function a(e,t){await(await t.cli()).runCliProcess(e)}function o(e){return e.length===1&&(e[0]===`--version`||e[0]===`-V`)}function s(e){return e[0]===`mcp`&&!e.some(l)}function c(e){let[t,n]=e;if(e.length===1)return t===`help`||l(t)?null:void 0;if(e.length===2)return t===`help`?n:l(n)?t:void 0}function l(e){return e===`--help`||e===`-h`}e(process.argv.slice(2),{help:()=>import(`../cli-help.js`).then(e=>e.n),cli:()=>import(`../process-entry.js`),mcp:()=>import(`../server.js`),version:()=>import(`../version.js`).then(e=>e.t),processExit:()=>import(`../process-exit.js`)},{bundledVersion:`0.21.5`,stdout:e=>{process.stdout.write(e)},stderr:e=>{process.stderr.write(e)}}).catch(()=>process.exit(1));export{};
|
package/dist/src/runtime4.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{C as e,w as t}from"./sdk-contracts.js";import{r as n}from"./sdk-batch-runner.js";import{S as r,c as i,h as a,l as o,u as s,w as c}from"./sdk-device.js";import{Gt as l,Xt as u,Zt as d}from"./sdk-batch.js";import{c as f,r as p}from"./diagnostics.js";import{n as m}from"./exec.js";import"./diagnostics2.js";import"./command.js";import{n as h}from"./scoped-provider.js";import{i as ee,n as te,r as ne}from"./ios-snapshot-planning.js";import{t as re}from"./request.js";import{n as ie,r as ae,t as oe}from"./application-lifecycle-runtime.js";import{i as se,t as ce}from"./touch-runtime.js";import{A as le,C as ue,D as de,G as fe,H as pe,I as me,L as he,N as ge,O as _e,P as ve,R as ye,T as be,U as xe,V as Se,a as Ce,b as we,d as Te,g as Ee,i as De,j as Oe,m as ke,s as Ae,t as je,v as Me,w as Ne,x as Pe,z as Fe}from"./alert-runtime.js";import{n as Ie}from"./audio-probe-runtime.js";import{n as Le}from"./perf-runtime.js";import{a as Re,n as ze}from"./durable-resource.js";import{n as Be,t as Ve}from"./async-lifecycle.js";import{a as He,c as Ue,d as We,f as Ge,l as Ke,n as qe,o as Je,s as Ye,t as Xe,u as Ze}from"./src7.js";import{n as Qe,t as $e}from"./screen-recording-completion.js";import{a as et,i as tt,n as nt,r as rt,t as it}from"./stop-sequence.js";import{n as g}from"./screen-recording-runtime.js";import{t as at}from"./ios-system-surface.js";import{i as ot,r as st}from"./gesture-admission.js";import{t as ct}from"./interactor-operation-catalog.js";import{a as lt,i as ut,n as dt,r as ft,t as pt}from"./perf-runtime-operation-builder.js";import{t as mt}from"./app-log-runtime.js";import{i as ht,r as gt}from"./managed-device-scope.js";import{a as _t,n as vt,o as yt}from"./application-lifecycle-interaction.js";import{a as bt}from"./tool-provider.js";import{n as xt}from"./apps-simctl.js";import{a as St}from"./simulator.js";import{t as Ct}from"./multitouch-support.js";import{n as _,t as wt}from"./simulator-state.js";import{t as Tt}from"./snapshot-process.js";import Et from"node:path";import{randomUUID as Dt}from"node:crypto";function Ot(e){let t=ht();return Object.freeze(t?{...h({...e},e=>St(t,e))}:e)}function kt(e){return rt(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 At(e){let{resolveHost:t,device:n,owner:r}=e;return Object.freeze({...pt({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 ut(t().sampleFrames(n,e)):dt(`Apple`,`bundle ID`),sampling:await t().frameSampling(n)}),perfMemorySample:async({appId:e})=>({metric:e?await ut(t().sampleMemory(n,e)):dt(`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 lt(`Apple`,o,s,`Use perf memory snapshot --kind memgraph for supported Apple app sessions.`);if(!e)throw ft();let c=i??Et.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=Ft(`Gestures are supported only for Apple simulators and devices.`),Mt=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:st}),Nt=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:ot}),Pt=Ft(`scroll is supported only for Apple simulators and devices.`);function Ft(e){return Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:e})}function It(e){return{...ge({unsupported:Lt(e),plan:Rt(e),directionalFling:Rt(e),multiTouch:zt(e),targetAuthoredDrag:Bt(e),viewport:Vt(e)}),...le({scroll:Ht(e)})}}function Lt(e){return e.appleOs===`watchos`||e.appleOs===`visionos`?y:b}function Rt(e){return e.appleOs===`watchos`||e.appleOs===`visionos`?y:x(e)?v:b}function zt(e){if(e.appleOs===`watchos`)return y;if(!x(e))return b;let t=r(e);if(t!==`ios`&&t!==`ipados`){let e=Ct[t];return Object.freeze({available:!1,reason:`unsupported-platform-leaf`,...e===void 0?{}:{hint:e}})}return e.kind===`simulator`?v:Mt}function Bt(e){return x(e)?(e.appleOs===void 0?e.target!==`desktop`&&e.target!==`tv`:e.appleOs===`ios`||e.appleOs===`ipados`)?v:Nt:b}function Vt(e){return e.appleOs===`watchos`?y:x(e)?v:b}function Ht(e){return x(e)?v:Pt}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 Ut=Object.freeze({resourceKind:mt,version:1,encode:e=>({...e}),decode:e=>!Gt(e.transport)||!Kt(e.backend)||!Xt(e.outputPath)||!Jt(e.pidPath)||!qt(e.transport,e.backend)?Wt():{status:`decoded`,descriptor:Object.freeze({transport:e.transport,backend:e.backend,outputPath:e.outputPath,...e.pidPath===void 0?{}:{pidPath:e.pidPath}})}});function Wt(){return{status:`invalid`,message:`Invalid Apple app-log descriptor`}}function Gt(e){return e===`apple-log-stream`||e===`coredevice-console`}function Kt(e){return e===`ios-simulator`||e===`ios-device`||e===`macos`}function qt(e,t){return e===`coredevice-console`?t===`ios-device`:t!==`ios-device`}function Jt(e){return e===void 0||Xt(e)}function Yt(e){if(!e.device.appleOs)throw TypeError(`Apple app-log persistence requires an explicit appleOs identity`);return ze({resourceKind:mt,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:Re(Ut,e.descriptor)})}function Xt(e){return typeof e==`string`&&e.trim().length>0}const Zt={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.`},Qt={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 $t(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 en(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 et(async()=>tt(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 et(async()=>tt(await e.appleTools.run({tool:`devicectl`,args:[`--version`],allowFailure:!0},r)),r);let t=await $t(e,r);if(i.devicectlConsoleCapture=t.supported,!t.supported){let e=t.reason===`unsupported`?Zt:Qt;a.push(`${e.message} ${e.hint}`)}}return{backend:C(t),checks:i,notes:a}}function tn(e,t){let n=an(e),r=[`subsystem == "${n}"`,`subsystem CONTAINS "${n}"`,`processImagePath ENDSWITH[c] "/${n}"`,`senderImagePath ENDSWITH[c] "/${n}"`];if(t){let e=an(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 nn(e){return[...e.simulatorSetPath?[`simctl`,`--set`,e.simulatorSetPath]:[`simctl`],`spawn`,e.deviceId,`log`,`stream`,`--style`,`compact`,`--level`,`info`,`--predicate`,tn(e.appBundleId,e.executableName)]}function rn(e,t){return[`devicectl`,`device`,`process`,`launch`,`--device`,e,`--console`,`--terminate-existing`,t]}function an(e){return e.replaceAll(`\\`,String.raw`\\`).replaceAll(`"`,String.raw`\"`)}async function on(e,t,n,r,i){sn(t),Je(e,n);let a=C(t),o=await ln(e,t,n.appBundleId,i),s=new Ve,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=dn(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=Ge(d,Yt({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`,S,{hint:S})}async function cn(t,n,r,i,a,s){if(o(n)&&n.kind===`device`){let n=await $t(t,s);if(!n.supported){let t=n.reason===`unsupported`?Zt:Qt;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 ln(e,t,n,r){if(s(t))return{executable:`log`,args:[`stream`,`--style`,`compact`,`--predicate`,tn(n)],allowFailure:!0};if(t.kind===`device`)return{executable:`xcrun`,args:rn(t.id,n),allowFailure:!0};let i=await un(e,t,n,r);return{executable:`xcrun`,args:nn({deviceId:t.id,appBundleId:n,executableName:i,simulatorSetPath:t.simulatorSetPath}),allowFailure:!0}}async function un(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`,`-`,Et.join(o,`Info.plist`)],allowFailure:!0,timeoutMs:4e3},r);return s.exitCode===0&&s.stdout.trim()||void 0}function dn(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 Ze({inspect:()=>({backend:r,state:o,startedAt:a}),finish:async()=>s??=(async()=>(await fn([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 fn(e){let t=[];for(let n of e)try{await n()}catch(e){t.push(e)}return t}const w=l(`apple`),T=Object.freeze({available:!0});function pn(t){return Object.freeze({owner:w,ownsDevice:e=>e.platform===`apple`,inspectFacts:async e=>hn(e),bind:async n=>{if(n.intent.kind===`exact-owner`&&!u(n.intent.owner,w))throw new e(`UNSUPPORTED_OPERATION`,`Apple app-log owner identity does not match`);return mn(t,n.device,n.scope.signal)},shutdown:async()=>void 0})}function mn(t,n,r){if(n.platform!==`apple`)throw new e(`UNSUPPORTED_PLATFORM`,`Apple app-log owner cannot bind ${n.platform}`);let i=We({codec:Ut,reattach:async(e,r)=>e.backend!==C(n)||!He(t,r.sessionId,e)?{status:`unreattachable`,reason:`descriptor-invalid`,message:`Apple app-log descriptor does not match the bound device or owning session`}:await Ue(t,e.pidPath),cleanup:async(e,r)=>e.backend===C(n)&&He(t,r.sessionId,e)?await Ye(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 en(t,n,e,r),appLogStart:async e=>await on(t,n,e,w,r),...i});return Object.freeze({device:n,owner:w,facts:hn(n),operations:a,[Symbol.asyncDispose]:async()=>void 0})}function hn(e){if(e.appleOs===`watchos`)return gn(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 gn(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 _n(e,t,n,r){let i=C(t),a=await e.appLogs.readRecent(n.sessionId,n.maxScanLines),o=qe(a.text,{...n,path:a.path,exists:a.exists,lineNumberOffset:a.skippedLines,backend:i}),s=[];if(yn(t,n,o.dump)){let i=await bn(e,t,n,a.path,r);i&&(o=vn(s,o,i,n.maxEntries))}return Cn(s,t,n),Sn(s,o.dump),o.dump.entries.length===0&&s.push(wn(t)),Object.freeze({source:`app-log`,backend:i,dump:o.dump,notes:Object.freeze(s)})}function vn(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).`),Xe(n.scan,t,r))}function yn(e,t,n){return o(e)&&e.kind===`simulator`&&!!t.appBundleId&&n.entries.length===0}async function bn(e,t,n,r,i){let a=[...t.simulatorSetPath?[`--set`,t.simulatorSetPath]:[],`spawn`,t.id,`log`,`show`,`--style`,`compact`,`--info`,`--predicate`,xn(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{C as e,w as t}from"./sdk-contracts.js";import{r as n}from"./sdk-batch-runner.js";import{S as r,c as i,h as a,l as o,u as s,w as c}from"./sdk-device.js";import{Gt as l,Xt as u,Zt as d}from"./sdk-batch.js";import{c as f,r as p}from"./diagnostics.js";import{n as m}from"./exec.js";import"./diagnostics2.js";import"./command.js";import{n as h}from"./scoped-provider.js";import{i as ee,n as te,r as ne}from"./ios-snapshot-planning.js";import{t as re}from"./request.js";import{n as ie,r as ae,t as oe}from"./application-lifecycle-runtime.js";import{i as se,t as ce}from"./touch-runtime.js";import{A as le,C as ue,D as de,G as fe,H as pe,I as me,L as he,N as ge,O as _e,P as ve,R as ye,T as be,U as xe,V as Se,a as Ce,b as we,d as Te,g as Ee,i as De,j as Oe,m as ke,s as Ae,t as je,v as Me,w as Ne,x as Pe,z as Fe}from"./alert-runtime.js";import{n as Ie}from"./audio-probe-runtime.js";import{n as Le}from"./perf-runtime.js";import{a as Re,n as ze}from"./durable-resource.js";import{n as Be,t as Ve}from"./async-lifecycle.js";import{a as He,c as Ue,d as We,f as Ge,l as Ke,n as qe,o as Je,s as Ye,t as Xe,u as Ze}from"./src7.js";import{n as Qe,t as $e}from"./screen-recording-completion.js";import{a as et,i as tt,n as nt,r as rt,t as it}from"./stop-sequence.js";import{n as g}from"./screen-recording-runtime.js";import{t as at}from"./ios-system-surface.js";import{i as ot,r as st}from"./gesture-admission.js";import{t as ct}from"./interactor-operation-catalog.js";import{a as lt,i as ut,n as dt,r as ft,t as pt}from"./perf-runtime-operation-builder.js";import{t as mt}from"./app-log-runtime.js";import{i as ht,r as gt}from"./managed-device-scope.js";import{a as _t,n as vt,o as yt}from"./application-lifecycle-interaction.js";import{a as bt}from"./tool-provider.js";import{n as xt}from"./apps-simctl.js";import{a as St}from"./simulator.js";import{t as Ct}from"./multitouch-support.js";import{n as _,t as wt}from"./simulator-state.js";import{n as Tt,r as Et,t as Dt}from"./snapshot-process.js";import Ot from"node:path";import{randomUUID as kt}from"node:crypto";function At(e){let t=ht();return Object.freeze(t?{...h({...e},e=>St(t,e))}:e)}function jt(e){return rt(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 Mt(e){let{resolveHost:t,device:n,owner:r}=e;return Object.freeze({...pt({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 ut(t().sampleFrames(n,e)):dt(`Apple`,`bundle ID`),sampling:await t().frameSampling(n)}),perfMemorySample:async({appId:e})=>({metric:e?await ut(t().sampleMemory(n,e)):dt(`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 lt(`Apple`,o,s,`Use perf memory snapshot --kind memgraph for supported Apple app sessions.`);if(!e)throw ft();let c=i??Ot.join(a,`memory-memgraph-${Nt()}.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 Nt(){return new Date().toISOString().replaceAll(/[:.]/g,`-`)}const v=Object.freeze({available:!0}),y=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),b=Lt(`Gestures are supported only for Apple simulators and devices.`),Pt=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:st}),Ft=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:ot}),It=Lt(`scroll is supported only for Apple simulators and devices.`);function Lt(e){return Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:e})}function Rt(e){return{...ge({unsupported:zt(e),plan:Bt(e),directionalFling:Bt(e),multiTouch:Vt(e),targetAuthoredDrag:Ht(e),viewport:Ut(e)}),...le({scroll:Wt(e)})}}function zt(e){return e.appleOs===`watchos`||e.appleOs===`visionos`?y:b}function Bt(e){return e.appleOs===`watchos`||e.appleOs===`visionos`?y:x(e)?v:b}function Vt(e){if(e.appleOs===`watchos`)return y;if(!x(e))return b;let t=r(e);if(t!==`ios`&&t!==`ipados`){let e=Ct[t];return Object.freeze({available:!1,reason:`unsupported-platform-leaf`,...e===void 0?{}:{hint:e}})}return e.kind===`simulator`?v:Pt}function Ht(e){return x(e)?(e.appleOs===void 0?e.target!==`desktop`&&e.target!==`tv`:e.appleOs===`ios`||e.appleOs===`ipados`)?v:Ft:b}function Ut(e){return e.appleOs===`watchos`?y:x(e)?v:b}function Wt(e){return x(e)?v:It}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 Gt=Object.freeze({resourceKind:mt,version:1,encode:e=>({...e}),decode:e=>!qt(e.transport)||!Jt(e.backend)||!Qt(e.outputPath)||!Xt(e.pidPath)||!Yt(e.transport,e.backend)?Kt():{status:`decoded`,descriptor:Object.freeze({transport:e.transport,backend:e.backend,outputPath:e.outputPath,...e.pidPath===void 0?{}:{pidPath:e.pidPath}})}});function Kt(){return{status:`invalid`,message:`Invalid Apple app-log descriptor`}}function qt(e){return e===`apple-log-stream`||e===`coredevice-console`}function Jt(e){return e===`ios-simulator`||e===`ios-device`||e===`macos`}function Yt(e,t){return e===`coredevice-console`?t===`ios-device`:t!==`ios-device`}function Xt(e){return e===void 0||Qt(e)}function Zt(e){if(!e.device.appleOs)throw TypeError(`Apple app-log persistence requires an explicit appleOs identity`);return ze({resourceKind:mt,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:Re(Gt,e.descriptor)})}function Qt(e){return typeof e==`string`&&e.trim().length>0}const $t={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.`},en={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 tn(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 nn(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 et(async()=>tt(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 et(async()=>tt(await e.appleTools.run({tool:`devicectl`,args:[`--version`],allowFailure:!0},r)),r);let t=await tn(e,r);if(i.devicectlConsoleCapture=t.supported,!t.supported){let e=t.reason===`unsupported`?$t:en;a.push(`${e.message} ${e.hint}`)}}return{backend:C(t),checks:i,notes:a}}function rn(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 an(e){return[...e.simulatorSetPath?[`simctl`,`--set`,e.simulatorSetPath]:[`simctl`],`spawn`,e.deviceId,`log`,`stream`,`--style`,`compact`,`--level`,`info`,`--predicate`,rn(e.appBundleId,e.executableName)]}function on(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){ln(t),Je(e,n);let a=C(t),o=await dn(e,t,n.appBundleId,i),s=new Ve,c=!1;try{let l=await e.outputs.openAppend(n.outputPath);s.defer(async()=>{c||await l[Symbol.asyncDispose]()}),i?.throwIfAborted();let u=await un(e,t,o,l,n.pidPath,i);s.defer(async()=>{c||await u[Symbol.asyncDispose]()});let d=pn(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=Ge(d,Zt({sessionId:n.sessionId,device:t,owner:r,fence:n.fence,descriptor:f}));return c=!0,p}finally{await s[Symbol.asyncDispose]()}}function ln(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 un(t,n,r,i,a,s){if(o(n)&&n.kind===`device`){let n=await tn(t,s);if(!n.supported){let t=n.reason===`unsupported`?$t:en;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 dn(e,t,n,r){if(s(t))return{executable:`log`,args:[`stream`,`--style`,`compact`,`--predicate`,rn(n)],allowFailure:!0};if(t.kind===`device`)return{executable:`xcrun`,args:on(t.id,n),allowFailure:!0};let i=await fn(e,t,n,r);return{executable:`xcrun`,args:an({deviceId:t.id,appBundleId:n,executableName:i,simulatorSetPath:t.simulatorSetPath}),allowFailure:!0}}async function fn(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`,`-`,Ot.join(o,`Info.plist`)],allowFailure:!0,timeoutMs:4e3},r);return s.exitCode===0&&s.stdout.trim()||void 0}function pn(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 Ze({inspect:()=>({backend:r,state:o,startedAt:a}),finish:async()=>s??=(async()=>(await mn([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 mn(e){let t=[];for(let n of e)try{await n()}catch(e){t.push(e)}return t}const w=l(`apple`),T=Object.freeze({available:!0});function hn(t){return Object.freeze({owner:w,ownsDevice:e=>e.platform===`apple`,inspectFacts:async e=>_n(e),bind:async n=>{if(n.intent.kind===`exact-owner`&&!u(n.intent.owner,w))throw new e(`UNSUPPORTED_OPERATION`,`Apple app-log owner identity does not match`);return gn(t,n.device,n.scope.signal)},shutdown:async()=>void 0})}function gn(t,n,r){if(n.platform!==`apple`)throw new e(`UNSUPPORTED_PLATFORM`,`Apple app-log owner cannot bind ${n.platform}`);let i=We({codec:Gt,reattach:async(e,r)=>e.backend!==C(n)||!He(t,r.sessionId,e)?{status:`unreattachable`,reason:`descriptor-invalid`,message:`Apple app-log descriptor does not match the bound device or owning session`}:await Ue(t,e.pidPath),cleanup:async(e,r)=>e.backend===C(n)&&He(t,r.sessionId,e)?await Ye(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 nn(t,n,e,r),appLogStart:async e=>await cn(t,n,e,w,r),...i});return Object.freeze({device:n,owner:w,facts:_n(n),operations:a,[Symbol.asyncDispose]:async()=>void 0})}function _n(e){if(e.appleOs===`watchos`)return vn(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 vn(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 yn(e,t,n,r){let i=C(t),a=await e.appLogs.readRecent(n.sessionId,n.maxScanLines),o=qe(a.text,{...n,path:a.path,exists:a.exists,lineNumberOffset:a.skippedLines,backend:i}),s=[];if(xn(t,n,o.dump)){let i=await Sn(e,t,n,a.path,r);i&&(o=bn(s,o,i,n.maxEntries))}return Tn(s,t,n),wn(s,o.dump),o.dump.entries.length===0&&s.push(En(t)),Object.freeze({source:`app-log`,backend:i,dump:o.dump,notes:Object.freeze(s)})}function bn(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).`),Xe(n.scan,t,r))}function xn(e,t,n){return o(e)&&e.kind===`simulator`&&!!t.appBundleId&&n.entries.length===0}async function Sn(e,t,n,r,i){let a=[...t.simulatorSetPath?[`--set`,t.simulatorSetPath]:[],`spawn`,t.id,`log`,`show`,`--style`,`compact`,`--info`,`--predicate`,Cn(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:qe(`${c.join(`
|
|
3
|
-
`)}\n`,{...n,path:`${r} (simctl log show recovery)`,exists:!0,backend:`ios-simulator`}),lineCount:c.length}}function xn(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 Sn(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 Cn(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 wn(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 Tn(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 $e(r,{...c,...l.length>0?{warning:l.join(` `)}:{},...r.invalidatedReason?{overlayWarning:`overlay unavailable: ${r.invalidatedReason}`}:{}},{stopObservation:s,...o===void 0?{}:{nativePathDisposition:o}})}async function En(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;try{await t.screenRecording.outputs.copy({from:i,to:a}),s=await Dn(()=>t.screenRecording.finalize.complete({outputPath:a,showTouches:!n.invalidatedReason&&n.showTouches,gestureEvents:n.gestureEvents,exportQuality:n.exportQuality??`medium`,targetLabel:r}))}catch(e){throw await t.screenRecording.outputs.remove(a),e}return{...s,...n.invalidatedReason?{overlayWarning:`overlay unavailable: ${n.invalidatedReason}`}:{},nativePathDisposition:await t.screenRecording.outputs.remove(o)===`removed`?`retired`:`retirable`}}async function Dn(e){try{return await e()}catch(e){throw t(e,`COMMAND_FAILED`)}}const E=Object.freeze({resourceKind:g,version:1,encode:e=>e.backend===`simctl`?{backend:e.backend,outputPath:e.outputPath,processes:e.processes.map(e=>({...e}))}:{backend:e.backend,outputPath:e.outputPath,appBundleId:e.appBundleId,runnerSessionId:e.runnerSessionId,runnerAuthority:e.runnerAuthority,...e.remotePath===void 0?{}:{remotePath:e.remotePath}},decode:e=>Pn(e)});function On(e){let{device:t,owner:n,input:r,descriptor:i}=e;return ze({resourceKind:g,sessionId:r.sessionId,device:c(t),owner:n,fence:r.fence,lifecycle:`open`,descriptor:Re(E,i)})}async function kn(e,t,n,r){let i=E.decode(n);return i.status!==`decoded`||!Vn(t,i.descriptor)?{status:`cleanup-pending`,reason:`manual-recovery-required`}:i.descriptor.backend===`simctl`?await An(e,i.descriptor.processes,r):await Mn(e,t,i.descriptor)}async function An(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 Mn(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 Nn(e,t,n){let r=E.decode(n);if(r.status!==`decoded`)return{status:`unreattachable`,reason:`descriptor-invalid`,message:r.message};if(!Vn(t,r.descriptor))return{status:`unreattachable`,reason:`descriptor-invalid`,message:`Apple screen-recording descriptor does not match the bound device.`};let i=r.descriptor.backend===`simctl`?await Promise.all(r.descriptor.processes.map(async t=>await e.screenRecording.apple.inspectProcess(t))):[await e.screenRecording.apple.inspectRunner(t,r.descriptor.runnerSessionId,r.descriptor.runnerAuthority)];return i.every(e=>e===`missing`)?{status:`missing`}:{status:`unreattachable`,reason:`transport-not-reattachable`,message:i.includes(`ownership-lost`)?`Apple recording ownership no longer matches the durable descriptor.`:`Apple screen recordings require exact cleanup after daemon restart.`}}function Pn(e){return typeof e.outputPath!=`string`||e.outputPath.length===0?D():e.backend===`simctl`?Fn(e,e.outputPath):e.backend===`runner`?In(e,e.outputPath):D()}function Fn(e,t){let n=Hn(e.processes);return n?{status:`decoded`,descriptor:Object.freeze({backend:`simctl`,outputPath:t,processes:n})}:D()}function In(e,t){return!Ln(e.appBundleId)||!Ln(e.runnerSessionId)||!Rn(e.runnerAuthority)||!zn(e.remotePath)?D():{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 Ln(e){return typeof e==`string`&&e.length>0}function Rn(e){return e===`local-lease`||e===`scoped-provider`}function zn(e){return e===void 0||Bn(e)}function Bn(e){return typeof e==`string`&&/^tmp\/agent-device-recording-\d+\.mp4$/.test(e)}function Vn(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&&Bn(t.remotePath):t.remotePath===void 0:!1}function Hn(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 D(){return{status:`invalid`,message:`Invalid Apple screen-recording descriptor`}}async function Un(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.`)}function Wn(e){return e.appleOs===`watchos`?nr(`unsupported-platform-leaf`,`watchOS recording is not supported.`):o(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?nr(`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 Gn(e){let{host:t,device:n,owner:r,signal:i}=e;return Object.freeze({screenRecordingStart:async e=>await Kn({host:t,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async e=>await Nn(t,n,e.envelope.descriptor.body),screenRecordingCleanup:async e=>await kn(t,n,e.envelope.descriptor.body,e.envelope.sessionId)})}async function Kn(e){return e.signal.throwIfAborted(),e.device.kind===`simulator`?await qn(e):await Jn(e)}async function qn(e){let{host:t,device:n,owner:r,input:i,signal:a}=e;await Un(n,i,t.screenRecording.apple.isRunnerBundleId);let o=i.activeSessionApp?await t.screenRecording.apple.captureClockAnchor(n,i.activeSessionApp.bundleId,a):void 0,s=nt(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 O(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 O(c).catch(()=>{}),e}let u,d,f=async()=>{await c.terminate();let e=await c.wait;return d=e,u=Xn(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.`}}};return er({device:n,owner:r,input:i,descriptor:{backend:`simctl`,outputPath:s,processes:l},snapshot:tr(i,`simctl recordVideo`,{},o),finish:(e,n)=>it({snapshot:e,progress:n,steps:{stop:f,collect:async e=>{try{await t.screenRecording.outputs.copy({from:s,to:e}),await t.screenRecording.finalize.sniff({outputPath:e})}catch(e){throw Zn(e,u,d)}},finalize:async({collectedPath:n,exportPath:r})=>{try{return await En({host:t,snapshot:e,targetLabel:`iOS recording`,collectedPath:n,exportPath:r,nativePath:s})}catch(e){throw Zn(e,u,d)}},discard:async e=>{await t.screenRecording.outputs.remove(e)}}}),cleanup:async()=>{let e=await $n(c);return(e.status===`cleaned`||e.status===`already-missing`)&&t.screenRecording.ownedProcesses.clear({kind:`session`,sessionId:i.sessionId}),e}})}async function Jn(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??=Yn(()=>t.screenRecording.apple.runRunner(n,{kind:`stop`,appBundleId:o,...c}).then(()=>void 0)).catch(e=>{throw l=void 0,e}),l);if(!Qn(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 er({device:n,owner:r,input:i,descriptor:{backend:`runner`,outputPath:i.outputPath,appBundleId:o,...c,...s.remotePath===void 0?{}:{remotePath:s.remotePath}},snapshot:tr(i,`runner AVAssetWriter`,s),finish:async e=>(await u(),s.remotePath!==void 0&&await t.screenRecording.apple.retrieveRunnerRecording(n,s.remotePath,e.outPath),await Tn({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 Yn(e){try{return await e()}catch(e){throw t(e,`COMMAND_FAILED`)}}function Xn(e){if(e.exitCode!==0)return e.signal?`simctl recordVideo was killed by ${e.signal}`:`simctl recordVideo exited with code ${e.exitCode}`}function Zn(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}`,m(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 Qn(e,t){return e.appleOs===`macos`||!o(e)?t===void 0:t!==void 0&&/^tmp\/agent-device-recording-\d+\.mp4$/.test(t)}async function O(e){return await e.terminate(),await e.wait}async function $n(e){try{return await O(e),{status:`cleaned`}}catch(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:`Apple simulator cleanup failed`}}}function er(e){let{device:t,owner:n,input:r,descriptor:i,snapshot:a,finish:o,cleanup:s}=e,c=Qe(a,{finish:o,forceCleanup:s});return Object.freeze({pendingHandle:new Be(c),envelope:On({device:t,owner:n,input:r,descriptor:i})})}function tr(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 nr(e,t){return Object.freeze({available:!1,reason:e,hint:t})}const rr=15e3;async function k(e,t,n,r={}){return n.throwIfAborted(),await gt(t)||s(t)?{...t,booted:!0}:t.kind===`device`?(await e.deviceReadiness.applePhysical.ensureConnected(t,n),{...t,booted:!0}):t.kind===`simulator`?((await ir(e,t)?`Booted`:await cr(e,t,n))!==`Booted`&&(r.onColdBootStart?.(),e.deviceReadiness.appleAutomation.keepHot(t),await ar(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 ir(e,t){try{return await e.deviceReadiness.appleAutomation.wasRecentlyObservedBooted(t)}catch{return!1}}async function ar(e,t,n,r=Date.now()+12e4){let i=!1;try{i=await or(e,t,n,r),await sr(e,t,n,r)}catch(a){throw i&&n.aborted&&ur(e,t),n.throwIfAborted(),Date.now()>=r?j(t,a):a}}async function or(t,n,r,i){let a=await t.appleTools.run({tool:`simctl`,args:_(n,[`boot`,n.id]),allowFailure:!0,timeoutMs:A(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 sr(t,n,r,i){re({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:A(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 wt(t.appleTools,n,r,Math.min(rr,A(i,n)))!==`Booted`)throw new e(`COMMAND_FAILED`,`Simulator is still booting`,{deviceId:n.id});if(Date.now()>=i)throw j(n)}function A(e,t){let n=e-Date.now();if(n<=0)throw j(t);return n}function j(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 cr(e,t,n){return await wt(e.appleTools,t,n,rr)}async function lr(e,t){await e.commands.run({executable:`open`,args:[`-a`,`Simulator`],allowFailure:!0,timeoutMs:1e4},t)}function ur(e,t){e.appleTools.run({tool:`simctl`,args:_(t,[`shutdown`,t.id]),allowFailure:!0}).catch(()=>{})}const dr=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`,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`,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 fr(e){return e===void 0?`possible`:e.some(e=>dr[e]===`runner`)?`required`:`none`}const pr=new Map([[`application-element-missing`,5e3],[`application-server-unavailable`,5e3],[`foreground-owner-unverified`,1e3],[`foreground-owner-changed`,1e3]]);function M(e){return e.platform===`apple`&&e.appleOs===`ios`&&e.kind===`simulator`}function mr(e){let t=ee(ne({depth:1,interactiveOnly:!0}));return Object.freeze({awaitObservable:async(n,r,i)=>{if(!M(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 p({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=pr.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 hr(e,t,n){let r=n&&M(e),i=r?fr(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 gr(e,t,n,r){r.runnerDemand===`none`&&e.appleApplications.releaseSpeculativeRunner(t.device,n.execution).catch(()=>{})}async function _r(e,t,n,r,i,a){let o=Date.now();r&&M(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 vr(e){let t=vt({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 k(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 kr(e.host,t,n),finalizeApplicationClose:async t=>await Ar(e.host,e.device,e.signal,t),prepareAppleRunner:async t=>await jr(e.host,e.device,e.signal,t),configureProviderPortReverse:Ir})}async function yr(e,t,n,r){let i={},a=N(t.device),o=Mr(e,t,n,i),s=hr(t.device,n,a);s.runnerDemand&&(i.runnerDemand=s.runnerDemand),gr(e,t,n,s);let{shouldPrewarmRunner:c}=s,l=Or(t.device,n,a);a&&c&&!n.prewarmRunnerBeforeOpen&&o.schedule();try{await br(e,t,n,a,l,i),await xr(n,i),await Sr(o,c,n.prewarmRunnerBeforeOpen);let u=o.wasAwaited();return await Cr(t,n,a,i),await Tr(o,c,s.awaitPrewarmAfterOpen),await Er(e,t,n,a,u,l),await _r(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 br(e,t,n,r,a,o){if(!Dr(n,r)||!n.target)return;let s=Date.now();i(t.device.platform)&&!r&&!a&&await e.appleApplications.stopRunnerSession(t.device.id),await _t({device:t.device,interactor:await t.resolveInteractor(n.execution,n.appBundleId),positionals:[n.appBundleId??n.target]}),r&&await e.clock.sleep(300,t.signal),o.relaunchCloseDurationMs=P(s)}async function xr(t,n){if(!ae(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=P(r)}async function Sr(e,t,n){!t||!n||(e.schedule(!0),await e.wait())}async function Cr(e,t,n,r){let i=Pr(t,n),a=Date.now();await yt({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=P(a),await wr(e,t,i.followUpUrl,r)}async function wr(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 yt({device:e.device,interactor:await e.resolveInteractor(i,t.appBundleId),positionals:[n],appBundleId:t.appBundleId,execution:i}),r.launchUrlDurationMs=P(a)}async function Tr(e,t,n){t&&!e.wasScheduled()&&e.schedule(),n?await e.wait():e.recordUnawaited()}async function Er(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 Dr(e,t){return!!(e.relaunch&&e.target)&&!(t&&!e.execution.clearAppState)}function Or(e,t,n){return e.kind===`device`&&e.appleOs===`ios`&&Dr(t,n)}async function kr(e,t,n){n.ensureReady&&await k(e,t.device,t.signal),i(t.device.platform)&&!N(t.device)&&await e.appleApplications.stopRunnerSession(t.device.id),await _t({device:t.device,interactor:await t.resolveInteractor(n.execution,n.appBundleId),positionals:n.positionals}),N(t.device)&&await e.clock.sleep(300,t.signal)}async function Ar(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&&N(t)?await e.deviceShutdown.apple.shutdownTarget(t,n):void 0;return i===void 0?{}:{shutdown:i}}async function jr(e,t,n,r){let i=Date.now()+r.timeoutMs;await k(e,t,n,{deadlineAtMs:i});let a=Math.max(1,i-Date.now());return await e.appleApplications.prepareRunner(t,{...r,timeoutMs:a},n)}function Mr(e,t,n,r){let i,a=!1,o=Nr(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=P(e)},wasAwaited:()=>a,wasScheduled:()=>i!==void 0,recordUnawaited:()=>{i&&!a&&(r.runnerPrewarmWaited=!1)}}}function Nr(e,t){return e.kind===`device`&&e.appleOs===`ios`&&!t.hasExistingSession&&!t.relaunch&&!t.prewarmRunnerBeforeOpen}function Pr(e,t){let r=e.runtimeLaunchUrl?.trim(),i=e.positionals.length===1?e.positionals[0]?.trim():void 0;return!r||!i||n(i)?{positionals:e.positionals}:t&&!Fr(e)?{positionals:[i,r]}:{positionals:e.positionals,followUpUrl:r}}function Fr(e){return e.execution.clearAppState===!0||!!e.execution.launchConsole?.trim()||!!e.execution.launchArgs?.length}function N(e){return o(e)&&e.kind===`simulator`}function P(e){return Math.max(0,Date.now()-e)}async function Ir(){throw new e(`UNSUPPORTED_OPERATION`,`This lifecycle operation is unavailable for Apple.`)}const Lr=Object.freeze({available:!0}),Rr=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.`}),zr=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Push notifications are supported on Apple simulators only.`}),Br=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),Vr=Object.freeze({available:!1,reason:`unsupported-device-kind`});function Hr(e){let t=Xr(e);return Object.freeze({deployApp:t,materializeAppSource:t,deployMaterializedApp:t,sendPushNotification:Zr(e)})}function Ur(e){let{host:t,device:n,signal:r}=e,i=Hr(n);return Object.freeze({...i.deployApp.available?{deployApp:async e=>await Wr(t,n,e,r),materializeAppSource:async e=>await t.appleDeployment.prepareArtifact(e,{signal:r}),deployMaterializedApp:async e=>await Gr(t,n,e,r)}:{},...i.sendPushNotification.available?{sendPushNotification:async e=>(await Jr(t,n,e,r),{})}:{}})}async function Wr(e,t,n,r){if(n.replaceExisting)return await e.appleDeployment.withInvalidatedAppResolutionCache(t,async()=>{let i=await e.appleDeployment.resolveAppBundleId(t,n.app);await qr(e,t,i,r);let a=await e.appleDeployment.prepareArtifact({source:{kind:`path`,path:n.appPath}},{appIdentifierHint:n.app,signal:r});try{return await Kr(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 Gr(e,t,{artifact:i},r)}finally{await i.cleanup()}}async function Gr(e,t,n,r){return await Kr(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 Kr(e,t,n,r){await k(e,t,r),F(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 qr(e,t,n,r){await k(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||Yr(`${i.stdout}\n${i.stderr}`)||F(i,`Apple app uninstall failed for ${n}`)}async function Jr(t,n,r,i){if(n.kind!==`simulator`)throw new e(`UNSUPPORTED_OPERATION`,`Apple push notifications require a simulator`);await k(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`),F(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 Yr(e){let t=e.toLowerCase();return t.includes(`not installed`)||t.includes(`not found`)||t.includes(`no such file`)}function F(t,n){if(t.exitCode!==0)throw new e(`COMMAND_FAILED`,n,{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode})}function Xr(e){return Qr(e)?e.kind!==`simulator`&&e.kind!==`device`?Vr:e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?Rr:Lr:Br}function Zr(e){return Qr(e)?e.kind===`simulator`?Lr:zr:Br}function Qr(e){return o(e)&&e.appleOs!==`watchos`}const I=Object.freeze({available:!0}),$r=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`back is supported on Apple simulators and physical devices.`}),ei=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function ti(e){return e.kind!==`simulator`&&e.kind!==`device`?$r:r(e)===`watchos`?ei:I}const ni=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`home is supported on Apple simulators and physical devices.`}),ri=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),ii=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`app-switcher is supported on Apple simulators and physical devices.`});function ai(e,t){if(e.kind!==`simulator`&&e.kind!==`device`)return t;let n=r(e);return n===`macos`||n===`watchos`?ri:I}function L(e){if(e.kind!==`simulator`&&e.kind!==`device`)return!1;let t=r(e);return t!==`tvos`&&t!==`macos`&&t!==`watchos`}const oi=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`orientation is supported on Apple simulators and physical devices.`}),si=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function ci(e){return e.kind!==`simulator`&&e.kind!==`device`?oi:L(e)?I:si}const li=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`tv-remote is supported only on tvOS devices.`});function ui(e){return(e.kind===`simulator`||e.kind===`device`)&&a(e)?I:li}const R=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),di=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 fi(e){return L(e)?di:R}function pi(e){return L(e)?I:R}function mi(e){return L(e)?I:R}function hi(e){return Object.freeze({...Pe({back:ti(e)}),...we({home:ai(e,ni)}),...Ae({appSwitcher:ai(e,ii)}),...Me({orientation:ci(e)}),...Ee({tvRemote:ui(e)}),...ke({unsupported:R,status:fi(e),dismiss:pi(e),enter:mi(e)})})}function gi(e){let{host:t,device:n,signal:r}=e;return ct({device:n,signal:r,resolveInteractor:t.localInteractors.resolve,facts:hi(n)})}const z=Object.freeze({available:!0}),_i=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`clipboard is supported on Apple simulators and the macOS host.`}),vi=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`settings is supported on Apple simulators and the macOS host.`}),yi=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.`}),bi=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.`}),B=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function xi(e,t,n){if(e.kind!==`simulator`&&e.kind!==`device`)return t;let i=r(e);return i===`watchos`?B:e.kind===`simulator`||i===`macos`?z:n}function Si(e){return xi(e,_i,bi)}const Ci=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`trigger-app-event is supported on Apple simulators and physical devices.`}),wi=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`alert is supported on Apple simulators and physical devices.`}),Ti=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`alert is supported on Apple simulators, the macOS host, and physical iOS devices.`});function Ei(e){if(e.kind!==`simulator`&&e.kind!==`device`)return wi;let t=r(e);return t===`watchos`?B:e.kind===`simulator`||t===`ios`||t===`macos`?z:Ti}function Di(e){return e.kind!==`simulator`&&e.kind!==`device`?Ci:r(e)===`watchos`?B:z}function Oi(e){let t=Si(e);return t.available?bi:t}function ki(e){let t=Si(e),n=Ei(e);return Object.freeze({...Te({unsupported:Oi(e),read:t,write:t}),...je({read:n,wait:n,accept:n,dismiss:n}),...Ce({triggerAppEvent:Di(e)}),...De({setSetting:xi(e,vi,yi)})})}function Ai(e){let{host:t,device:n,signal:r}=e;return ct({device:n,signal:r,resolveInteractor:t.localInteractors.resolve,facts:ki(n)})}function ji(e,t,n){let r=Fe({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,Se(t.signal,i));if(!n)return await r.captureSnapshot(i);let a=Se(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 Mi(e,t){return Object.freeze({findText:async n=>{let r=await Ni(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 Ni(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 Pi(e,t.device,n.execution))return{appBundleId:r,signal:a}}async function Pi(e,t,n){return!M(t)||await e.appleApplications.hasLiveRunnerSession(t,n??{})}function Fi(){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 Ii=3e3;function Li(){let e=new Map,t=new Map,n=new Map;return async(r,i,a,o)=>{a.throwIfAborted();let s=`${r.id}:${i}`,c=e.get(s);if(c&&o!==`refresh`&&await Tt(c.pid,{signal:a,timeoutMs:Ii})===c.processStartTime)return c;e.delete(s);let l=t.get(s);return l||(l=zi(r,i,n).then(t=>(e.set(s,t),t)).finally(()=>t.delete(s)),l.catch(()=>void 0),t.set(s,l)),await Ri(l,a,r,i)}}async function Ri(e,t,n,r){let i,a,o=new Promise((e,o)=>{i=setTimeout(()=>o(H(`simulator-target-discovery-pending`,n,r)),1500),a=()=>o(t.reason),t.addEventListener(`abort`,a,{once:!0})});try{return await Promise.race([e,o])}finally{clearTimeout(i),a&&t.removeEventListener(`abort`,a)}}async function zi(e,t,n){let r=Date.now()+15e3,[i,a]=await Promise.allSettled([xt(e,[`spawn`,e.id,`launchctl`,`list`],{allowFailure:!0,timeoutMs:V(r)}),Bi(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 H(`simulator-target-probe-failed`,e,t);let c=Vi(o.stdout,t);if(!c)throw H(`simulator-target-unavailable`,e,t);let l=await Tt(c.pid,{timeoutMs:Math.min(Ii,V(r))});if(!l)throw H(`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 Bi(e,t,n){let r=t.get(e.id);if(r)return await r;let i=xt(e,[`list`,`devices`,`-j`],{allowFailure:!0,timeoutMs:V(n)}).then(t=>{if(t.exitCode!==0)throw H(`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 H(`simulator-runtime-unavailable`,e,``);return r});t.set(e.id,i);try{return await i}catch(n){throw t.delete(e.id),n}}function Vi(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 V(e){return Math.max(1,e-Date.now())}function H(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
|
|
5
|
-
`).map(e=>Number.parseInt(e.trim(),10)).filter(e=>Number.isSafeInteger(e)&&e>0):`unknown`}async function Gi(e,t,n){let r=await Ki(`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 Ki(e,t,n){try{let r=await bt(e,t,{allowFailure:!0,timeoutMs:3e3,...n?{signal:n}:{}});return{exitCode:r.exitCode,stdout:r.stdout}}catch{return`unknown`}}const qi=`system-surface-presented`,Ji=`system-surface-host-lingering`;function Yi(t,n={}){let r=n.source??Fi(),i=n.resolveTarget??Li(),a=n.systemSurfacePresent??Hi(),o=new Set,s=new Map,c=e=>(oa(e,s,o),o.has(sa(e))),l=mr({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(!Qi(n,s))return await ta(n,s,u);let d=await a(n,l);if(d===`unknown`)return await U(n.id,s,u,W(n.id,s),q(s),`system-surface-probe-unavailable`,[K()]);if(d!==`absent`)return await ea(n,s,u,d.host.bundleId);let p;try{p=await Xi(t,i,n,s,l)}catch(e){return l.throwIfAborted(),J(`target-resolution-failed`,n,void 0,e),await U(n.id,s,u,W(n.id,s),q(s),`target-resolution-failed`,[K()])}if(c(p))return await U(n.id,s,u,p,q(s),`circuit-disabled`);let m=q(s),h=await r.acquire({target:p,hint:ee(m),signal:l});if(h.stage===`failed`){if(h.failure.kind===`cancelled`)throw l.throwIfAborted(),new e(`COMMAND_FAILED`,`Simulator AX snapshot acquisition was cancelled.`,{reason:h.failure.code,...h.failure.details});let t=await aa(h.failure,p,n,s.options.appBundleId,l,i);return await $i(s,u,p,t,m,h.failure,o)}try{return await f(`ios.snapshot-source.present`,async()=>await t.snapshot.presentIosAcquisition(h,s.options),{producer:`simulator-ax-bridge`})}catch(e){return await $i(s,u,p,{lineage:p,residue:[]},m,{kind:`malformed-tree`,code:`presentation-invariant`},o,e)}}})}async function Xi(e,t,n,r,i){let a=r.options.appBundleId;for(;;)try{return await t(n,a,i)}catch(t){if(!Zi(t))throw t;let i={requestId:r.execution?.requestId};if(await e.appleApplications.hasLiveRunnerSession(n,i))throw t}}function Zi(t){return t instanceof e&&t.details?.reason===`simulator-target-discovery-pending`}function Qi(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 $i(e,t,n,r,i,a,o,s){return o.add(sa(n)),J(a.code,{id:n.udid},n.generation,s,a.details),await U(n.udid,e,t,r.lineage,i,a.code,r.residue)}async function U(e,t,n,r,i,a,o=[]){return na(e,await n(t),r,i,a,o)}async function ea(e,t,n,r){let i=await n(t),a=i.systemSurface?qi:Ji;return i.systemSurface||J(a,e,void 0,void 0,{detectedHost:r}),na(e.id,i,W(e.id,t),q(t),a)}async function ta(e,t,n){let r=await n(t),i=r.systemSurface;return i?{...r,comparisonIdentity:ra(G(e.id,i.bundleId),q(t),[])}:r}function na(e,t,n,r,i,a=[]){let o=t.systemSurface;return{...t,comparisonIdentity:ra(o?G(e,o.bundleId):n,r,[...o?[]:a,{kind:`fallback-source`,producer:`apple-runner`}]),warnings:[...t.warnings??[],ia(i,n,o!==void 0)]}}function W(e,t){return{targetId:`${e}:${t.options.appBundleId}`}}function G(e,t){return{targetId:`${e}:${t}`}}function ra(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:te(t),residue:Object.freeze([...n])})}function ia(e,t,n){return e===qi?`Simulator AX snapshot inapplicable (${e}); used XCTest to read the system surface presented over the app.`:e===Ji?`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.`:`Simulator AX snapshot unavailable (${e}); used XCTest for ${t.generation?`this app generation`:`an unverified app generation`}.`}async function aa(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:[K()]}}}function K(){return{kind:`unknown-generation`,captureId:Dt()}}function q(e){return ne({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 oa(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 sa(e){return`${e.targetId}:${e.generation}`}function J(e,t,n,r,i){p({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=l(`apple`),X=Object.freeze({available:!0}),Z=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),ca=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.`}),la=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.`}),ua=Object.freeze({available:!1,reason:`unsupported-device-backend`,hint:`perf requires an Apple simulator, macOS device, or CoreDevice-backed physical Apple device.`}),da=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`focus is supported on Apple simulators and physical devices.`}),fa=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Apple appstate reads the active session state; a sessionless runtime foreground probe is unavailable.`}),pa=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Headless boot is supported only for local Android emulators.`}),ma=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS has no XCUITest-driveable UI, so element text comes from the captured tree only.`}),ha=Object.freeze({available:!1,reason:`unsupported-device-kind`}),ga=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS open is not supported because XCUITest cannot drive watchOS UI.`}),_a=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS runner preparation is not supported because XCUITest cannot drive watchOS UI.`}),va=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS close is not supported because XCUITest cannot drive watchOS UI.`}),ya=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Runtime hints are supported only for local iOS-family simulators and Android devices.`}),ba=Q(`open is supported only for Apple simulators and devices.`),xa=Q(`prepare is supported only for Apple simulators and devices.`),Sa=Q(`close is supported only for Apple simulators and devices.`),Ca=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Port reverse is supported only by an owning provider runtime.`}),wa=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`shutdown is supported only for Apple simulators and Android emulators.`}),Ta=Q(`snapshot is supported only for Apple simulators and devices.`),Ea=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Re-run without --actions, or target an iOS simulator.`}),Da=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`screenshot is not supported on watchOS because XCUITest cannot drive watchOS UI.`}),Oa=Q(`screenshot is supported only for Apple simulators and devices.`),ka=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 Aa(e){return!o(e)||e.appleOs===`watchos`?Z:e.kind===`simulator`?X:wa}function ja(e){let t=Ma(e),n=Na(e),r=Pa(e),i=Fa(e);return oe({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:i,clearRuntimeHints:i,closeApplication:r,finalizeApplicationClose:r,prepareAppleRunner:n,configureProviderPortReverse:Ca})}function Ma(e){return r(e)===`watchos`?ga:e.kind===`simulator`||e.kind===`device`?X:ba}function Na(e){return r(e)===`watchos`?_a:e.kind===`simulator`||e.kind===`device`?X:xa}function Pa(e){return r(e)===`watchos`?va:e.kind===`simulator`||e.kind===`device`?X:Sa}function Fa(e){return r(e)!==`watchos`&&o(e)&&e.kind===`simulator`?X:ya}function Ia(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:da}function La(e){let t=pn(e),n=Yi(e),r=async n=>{let r=await t.inspectFacts(n),i=Hr(n),a=Wn(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=Ia(n);return Object.freeze({device:r.device,operations:{...r.operations,...i,appState:fa,networkDump:X,screenRecordingStart:l,screenRecordingReattach:l,screenRecordingCleanup:l,...Ha(n),...fe({capture:Va(n)}),...ye({findText:Ba(n)}),...he({setViewport:ca}),...me({focus:$(n)}),...It(n),...de({type:$(n)}),...se({unsupported:Z,tap:$(n),longPress:$(n),fill:$(n),...o(n)?{tapElementSelector:$(n)}:{}}),...Ne({readTextAtPoint:za(n)}),...hi(n),...ki(n),...Ie({capture:kt(n),query:la}),...Le(Ra(n)),ensureReady:u,bootTarget:d,bootTargetHeadless:pa,listApps:f,...ja(n),shutdownTarget:Aa(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,...Ur({host:e,device:i.device,signal:i.scope.signal}),networkDump:async t=>await _n(e,i.device,t,i.scope.signal),...d(s,()=>Gn({host:e,device:i.device,owner:Y,signal:i.scope.signal})),...d(o.operations.audioProbeStart,()=>Ke({host:e.audioProbe.hostCapture,device:i.device,owner:Y})),...d(o.operations.perfFrames,()=>At({resolveHost:()=>e.perf.apple,device:i.device,owner:Y})),...d(o.operations.captureSnapshot,()=>ji(e,{device:i.device,signal:i.scope.signal},n)),...d(o.operations.captureScreenshot,()=>xe({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...d(o.operations.focusPoint,()=>ve({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...Oe({device:i.device,signal:i.scope.signal,facts:o.operations,resolveInteractor:e.localInteractors.resolve}),...d(o.operations.scrollDirection,()=>_e({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...d(o.operations.typeText,()=>be({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...d(o.operations.tapPoint,()=>ce({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)})),...d(o.operations.readTextAtPoint,()=>ue({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...d(o.operations.findText,()=>Mi(e,{device:i.device,signal:i.scope.signal})),...gi({host:e,device:i.device,signal:i.scope.signal}),...Ai({host:e,device:i.device,signal:i.scope.signal}),...d(o.operations.ensureReady,()=>({ensureReady:async()=>await k(e,i.device,i.scope.signal)})),...d(o.operations.bootTarget,()=>({bootTarget:async()=>await k(e,i.device,i.scope.signal)})),...d(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}))}})),...ie(vr({host:e,device:i.device,signal:i.scope.signal,observation:n}),o.operations),...d(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:Ot(c),[Symbol.asyncDispose]:async()=>await a[Symbol.asyncDispose]()})},shutdown:async()=>{await Promise.all([t.shutdown(),n.shutdown()])}})}function Ra(e){let t=e.iosPhysicalDeviceBackend!==`xctest`&&r(e)!==`watchos`?X:ua;return{frames:t,memorySample:t,memorySnapshot:t,nativeCapture:t,profileReport:t}}function za(e){return r(e)===`watchos`?ma:e.kind===`simulator`||e.kind===`device`?X:ha}function Ba(e){return r(e)===`watchos`?Ta:e.kind===`simulator`||e.kind===`device`?X:Ta}function Va(e){return r(e)===`watchos`?Da:e.kind===`simulator`||e.kind===`device`?X:Oa}function Ha(e){let t=Ba(e);return pe({capture:t,customActions:t.available&&o(e)&&e.kind===`simulator`?X:Ea,withoutActiveApp:o(e)?ka:t})}export{La as createApplePlatformRuntime};
|
|
3
|
+
`)}\n`,{...n,path:`${r} (simctl log show recovery)`,exists:!0,backend:`ios-simulator`}),lineCount:c.length}}function Cn(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 wn(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 Tn(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 En(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 Dn(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 $e(r,{...c,...l.length>0?{warning:l.join(` `)}:{},...r.invalidatedReason?{overlayWarning:`overlay unavailable: ${r.invalidatedReason}`}:{}},{stopObservation:s,...o===void 0?{}:{nativePathDisposition:o}})}async function On(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;try{await t.screenRecording.outputs.copy({from:i,to:a}),s=await kn(()=>t.screenRecording.finalize.complete({outputPath:a,showTouches:!n.invalidatedReason&&n.showTouches,gestureEvents:n.gestureEvents,exportQuality:n.exportQuality??`medium`,targetLabel:r}))}catch(e){throw await t.screenRecording.outputs.remove(a),e}return{...s,...n.invalidatedReason?{overlayWarning:`overlay unavailable: ${n.invalidatedReason}`}:{},nativePathDisposition:await t.screenRecording.outputs.remove(o)===`removed`?`retired`:`retirable`}}async function kn(e){try{return await e()}catch(e){throw t(e,`COMMAND_FAILED`)}}const E=Object.freeze({resourceKind:g,version:1,encode:e=>e.backend===`simctl`?{backend:e.backend,outputPath:e.outputPath,processes:e.processes.map(e=>({...e}))}:{backend:e.backend,outputPath:e.outputPath,appBundleId:e.appBundleId,runnerSessionId:e.runnerSessionId,runnerAuthority:e.runnerAuthority,...e.remotePath===void 0?{}:{remotePath:e.remotePath}},decode:e=>In(e)});function An(e){let{device:t,owner:n,input:r,descriptor:i}=e;return ze({resourceKind:g,sessionId:r.sessionId,device:c(t),owner:n,fence:r.fence,lifecycle:`open`,descriptor:Re(E,i)})}async function jn(e,t,n,r){let i=E.decode(n);return i.status!==`decoded`||!Un(t,i.descriptor)?{status:`cleanup-pending`,reason:`manual-recovery-required`}:i.descriptor.backend===`simctl`?await Mn(e,i.descriptor.processes,r):await Pn(e,t,i.descriptor)}async function Mn(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(Nn(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(Nn(n)),i.every(e=>e===`already-missing`)?{status:`already-missing`}:{status:`cleaned`})}function Nn(e){return{kind:`session`,sessionId:e}}async function Pn(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 Fn(e,t,n){let r=E.decode(n);if(r.status!==`decoded`)return{status:`unreattachable`,reason:`descriptor-invalid`,message:r.message};if(!Un(t,r.descriptor))return{status:`unreattachable`,reason:`descriptor-invalid`,message:`Apple screen-recording descriptor does not match the bound device.`};let i=r.descriptor.backend===`simctl`?await Promise.all(r.descriptor.processes.map(async t=>await e.screenRecording.apple.inspectProcess(t))):[await e.screenRecording.apple.inspectRunner(t,r.descriptor.runnerSessionId,r.descriptor.runnerAuthority)];return i.every(e=>e===`missing`)?{status:`missing`}:{status:`unreattachable`,reason:`transport-not-reattachable`,message:i.includes(`ownership-lost`)?`Apple recording ownership no longer matches the durable descriptor.`:`Apple screen recordings require exact cleanup after daemon restart.`}}function In(e){return typeof e.outputPath!=`string`||e.outputPath.length===0?D():e.backend===`simctl`?Ln(e,e.outputPath):e.backend===`runner`?Rn(e,e.outputPath):D()}function Ln(e,t){let n=Wn(e.processes);return n?{status:`decoded`,descriptor:Object.freeze({backend:`simctl`,outputPath:t,processes:n})}:D()}function Rn(e,t){return!zn(e.appBundleId)||!zn(e.runnerSessionId)||!Bn(e.runnerAuthority)||!Vn(e.remotePath)?D():{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 zn(e){return typeof e==`string`&&e.length>0}function Bn(e){return e===`local-lease`||e===`scoped-provider`}function Vn(e){return e===void 0||Hn(e)}function Hn(e){return typeof e==`string`&&/^tmp\/agent-device-recording-\d+\.mp4$/.test(e)}function Un(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&&Hn(t.remotePath):t.remotePath===void 0:!1}function Wn(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 D(){return{status:`invalid`,message:`Invalid Apple screen-recording descriptor`}}async function Gn(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.`)}function Kn(e){return e.appleOs===`watchos`?ir(`unsupported-platform-leaf`,`watchOS recording is not supported.`):o(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?ir(`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 qn(e){let{host:t,device:n,owner:r,signal:i}=e;return Object.freeze({screenRecordingStart:async e=>await Jn({host:t,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async e=>await Fn(t,n,e.envelope.descriptor.body),screenRecordingCleanup:async e=>await jn(t,n,e.envelope.descriptor.body,e.envelope.sessionId)})}async function Jn(e){return e.signal.throwIfAborted(),e.device.kind===`simulator`?await Yn(e):await Xn(e)}async function Yn(e){let{host:t,device:n,owner:r,input:i,signal:a}=e;await Gn(n,i,t.screenRecording.apple.isRunnerBundleId);let o=i.activeSessionApp?await t.screenRecording.apple.captureClockAnchor(n,i.activeSessionApp.bundleId,a):void 0,s=nt(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 O(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 O(c).catch(()=>{}),e}let u,d,f=async()=>{await c.terminate();let e=await c.wait;return d=e,u=Qn(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.`}}};return nr({device:n,owner:r,input:i,descriptor:{backend:`simctl`,outputPath:s,processes:l},snapshot:rr(i,`simctl recordVideo`,{},o),finish:(e,n)=>it({snapshot:e,progress:n,steps:{stop:f,collect:async e=>{try{await t.screenRecording.outputs.copy({from:s,to:e}),await t.screenRecording.finalize.sniff({outputPath:e})}catch(e){throw $n(e,u,d)}},finalize:async({collectedPath:n,exportPath:r})=>{try{return await On({host:t,snapshot:e,targetLabel:`iOS recording`,collectedPath:n,exportPath:r,nativePath:s})}catch(e){throw $n(e,u,d)}},discard:async e=>{await t.screenRecording.outputs.remove(e)}}}),cleanup:async()=>{let e=await tr(c);return(e.status===`cleaned`||e.status===`already-missing`)&&t.screenRecording.ownedProcesses.clear({kind:`session`,sessionId:i.sessionId}),e}})}async function Xn(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??=Zn(()=>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 nr({device:n,owner:r,input:i,descriptor:{backend:`runner`,outputPath:i.outputPath,appBundleId:o,...c,...s.remotePath===void 0?{}:{remotePath:s.remotePath}},snapshot:rr(i,`runner AVAssetWriter`,s),finish:async e=>(await u(),s.remotePath!==void 0&&await t.screenRecording.apple.retrieveRunnerRecording(n,s.remotePath,e.outPath),await Dn({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 Zn(e){try{return await e()}catch(e){throw t(e,`COMMAND_FAILED`)}}function Qn(e){if(e.exitCode!==0)return e.signal?`simctl recordVideo was killed by ${e.signal}`:`simctl recordVideo exited with code ${e.exitCode}`}function $n(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}`,m(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 O(e){return await e.terminate(),await e.wait}async function tr(e){try{return await O(e),{status:`cleaned`}}catch(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:`Apple simulator cleanup failed`}}}function nr(e){let{device:t,owner:n,input:r,descriptor:i,snapshot:a,finish:o,cleanup:s}=e,c=Qe(a,{finish:o,forceCleanup:s});return Object.freeze({pendingHandle:new Be(c),envelope:An({device:t,owner:n,input:r,descriptor:i})})}function rr(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 ir(e,t){return Object.freeze({available:!1,reason:e,hint:t})}const ar=15e3;async function k(e,t,n,r={}){return n.throwIfAborted(),await gt(t)||s(t)?{...t,booted:!0}:t.kind===`device`?(await e.deviceReadiness.applePhysical.ensureConnected(t,n),{...t,booted:!0}):t.kind===`simulator`?((await or(e,t)?`Booted`:await ur(e,t,n))!==`Booted`&&(r.onColdBootStart?.(),e.deviceReadiness.appleAutomation.keepHot(t),await sr(e,t,n,r.deadlineAtMs),await dr(e,n)),e.deviceReadiness.appleAutomation.keepHot(t),e.deviceReadiness.appleAutomation.markBooted(t),{...t,booted:!0}):{...t,booted:!0}}async function or(e,t){try{return await e.deviceReadiness.appleAutomation.wasRecentlyObservedBooted(t)}catch{return!1}}async function sr(e,t,n,r=Date.now()+12e4){let i=!1;try{i=await cr(e,t,n,r),await lr(e,t,n,r)}catch(a){throw i&&n.aborted&&fr(e,t),n.throwIfAborted(),Date.now()>=r?j(t,a):a}}async function cr(t,n,r,i){let a=await t.appleTools.run({tool:`simctl`,args:_(n,[`boot`,n.id]),allowFailure:!0,timeoutMs:A(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){re({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:A(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 wt(t.appleTools,n,r,Math.min(ar,A(i,n)))!==`Booted`)throw new e(`COMMAND_FAILED`,`Simulator is still booting`,{deviceId:n.id});if(Date.now()>=i)throw j(n)}function A(e,t){let n=e-Date.now();if(n<=0)throw j(t);return n}function j(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 ur(e,t,n){return await wt(e.appleTools,t,n,ar)}async function dr(e,t){await e.commands.run({executable:`open`,args:[`-a`,`Simulator`],allowFailure:!0,timeoutMs:1e4},t)}function fr(e,t){e.appleTools.run({tool:`simctl`,args:_(t,[`shutdown`,t.id]),allowFailure:!0}).catch(()=>{})}const pr=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`,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`,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 mr(e){return e===void 0?`possible`:e.some(e=>pr[e]===`runner`)?`required`:`none`}const hr=new Map([[`application-element-missing`,5e3],[`application-server-unavailable`,5e3],[`foreground-owner-unverified`,1e3],[`foreground-owner-changed`,1e3]]);function M(e){return e.platform===`apple`&&e.appleOs===`ios`&&e.kind===`simulator`}function gr(e){let t=ee(ne({depth:1,interactiveOnly:!0}));return Object.freeze({awaitObservable:async(n,r,i)=>{if(!M(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 p({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=hr.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 _r(e,t,n){let r=n&&M(e),i=r?mr(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 vr(e,t,n,r){r.runnerDemand===`none`&&e.appleApplications.releaseSpeculativeRunner(t.device,n.execution).catch(()=>{})}async function yr(e,t,n,r,i,a){let o=Date.now();r&&M(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 br(e){let t=vt({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 k(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 xr(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 jr(e.host,t,n),finalizeApplicationClose:async t=>await Mr(e.host,e.device,e.signal,t),prepareAppleRunner:async t=>await Nr(e.host,e.device,e.signal,t),configureProviderPortReverse:Rr})}async function xr(e,t,n,r){let i={},a=N(t.device),o=Pr(e,t,n,i),s=_r(t.device,n,a);s.runnerDemand&&(i.runnerDemand=s.runnerDemand),vr(e,t,n,s);let{shouldPrewarmRunner:c}=s,l=Ar(t.device,n,a);a&&c&&!n.prewarmRunnerBeforeOpen&&o.schedule();try{await Sr(e,t,n,a,l,i),await Cr(n,i),await wr(o,c,n.prewarmRunnerBeforeOpen);let u=o.wasAwaited();return await Tr(t,n,a,i),await Dr(o,c,s.awaitPrewarmAfterOpen),await Or(e,t,n,a,u,l),await yr(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 Sr(e,t,n,r,a,o){if(!kr(n,r)||!n.target)return;let s=Date.now();i(t.device.platform)&&!r&&!a&&await e.appleApplications.stopRunnerSession(t.device.id),await _t({device:t.device,interactor:await t.resolveInteractor(n.execution,n.appBundleId),positionals:[n.appBundleId??n.target]}),r&&await e.clock.sleep(300,t.signal),o.relaunchCloseDurationMs=P(s)}async function Cr(t,n){if(!ae(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=P(r)}async function wr(e,t,n){!t||!n||(e.schedule(!0),await e.wait())}async function Tr(e,t,n,r){let i=Ir(t,n),a=Date.now();await yt({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=P(a),await Er(e,t,i.followUpUrl,r)}async function Er(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 yt({device:e.device,interactor:await e.resolveInteractor(i,t.appBundleId),positionals:[n],appBundleId:t.appBundleId,execution:i}),r.launchUrlDurationMs=P(a)}async function Dr(e,t,n){t&&!e.wasScheduled()&&e.schedule(),n?await e.wait():e.recordUnawaited()}async function Or(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 kr(e,t){return!!(e.relaunch&&e.target)&&!(t&&!e.execution.clearAppState)}function Ar(e,t,n){return e.kind===`device`&&e.appleOs===`ios`&&kr(t,n)}async function jr(e,t,n){n.ensureReady&&await k(e,t.device,t.signal),i(t.device.platform)&&!N(t.device)&&await e.appleApplications.stopRunnerSession(t.device.id),await _t({device:t.device,interactor:await t.resolveInteractor(n.execution,n.appBundleId),positionals:n.positionals}),N(t.device)&&await e.clock.sleep(300,t.signal)}async function Mr(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&&N(t)?await e.deviceShutdown.apple.shutdownTarget(t,n):void 0;return i===void 0?{}:{shutdown:i}}async function Nr(e,t,n,r){let i=Date.now()+r.timeoutMs;await k(e,t,n,{deadlineAtMs:i});let a=Math.max(1,i-Date.now());return await e.appleApplications.prepareRunner(t,{...r,timeoutMs:a},n)}function Pr(e,t,n,r){let i,a=!1,o=Fr(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=P(e)},wasAwaited:()=>a,wasScheduled:()=>i!==void 0,recordUnawaited:()=>{i&&!a&&(r.runnerPrewarmWaited=!1)}}}function Fr(e,t){return e.kind===`device`&&e.appleOs===`ios`&&!t.hasExistingSession&&!t.relaunch&&!t.prewarmRunnerBeforeOpen}function Ir(e,t){let r=e.runtimeLaunchUrl?.trim(),i=e.positionals.length===1?e.positionals[0]?.trim():void 0;return!r||!i||n(i)?{positionals:e.positionals}:t&&!Lr(e)?{positionals:[i,r]}:{positionals:e.positionals,followUpUrl:r}}function Lr(e){return e.execution.clearAppState===!0||!!e.execution.launchConsole?.trim()||!!e.execution.launchArgs?.length}function N(e){return o(e)&&e.kind===`simulator`}function P(e){return Math.max(0,Date.now()-e)}async function Rr(){throw new e(`UNSUPPORTED_OPERATION`,`This lifecycle operation is unavailable for Apple.`)}const zr=Object.freeze({available:!0}),Br=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.`}),Vr=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Push notifications are supported on Apple simulators only.`}),Hr=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),Ur=Object.freeze({available:!1,reason:`unsupported-device-kind`});function Wr(e){let t=Qr(e);return Object.freeze({deployApp:t,materializeAppSource:t,deployMaterializedApp:t,sendPushNotification:$r(e)})}function Gr(e){let{host:t,device:n,signal:r}=e,i=Wr(n);return Object.freeze({...i.deployApp.available?{deployApp:async e=>await Kr(t,n,e,r),materializeAppSource:async e=>await t.appleDeployment.prepareArtifact(e,{signal:r}),deployMaterializedApp:async e=>await qr(t,n,e,r)}:{},...i.sendPushNotification.available?{sendPushNotification:async e=>(await Xr(t,n,e,r),{})}:{}})}async function Kr(e,t,n,r){if(n.replaceExisting)return await e.appleDeployment.withInvalidatedAppResolutionCache(t,async()=>{let i=await e.appleDeployment.resolveAppBundleId(t,n.app);await Yr(e,t,i,r);let a=await e.appleDeployment.prepareArtifact({source:{kind:`path`,path:n.appPath}},{appIdentifierHint:n.app,signal:r});try{return await Jr(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 qr(e,t,{artifact:i},r)}finally{await i.cleanup()}}async function qr(e,t,n,r){return await Jr(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 Jr(e,t,n,r){await k(e,t,r),F(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 Yr(e,t,n,r){await k(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||Zr(`${i.stdout}\n${i.stderr}`)||F(i,`Apple app uninstall failed for ${n}`)}async function Xr(t,n,r,i){if(n.kind!==`simulator`)throw new e(`UNSUPPORTED_OPERATION`,`Apple push notifications require a simulator`);await k(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`),F(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 Zr(e){let t=e.toLowerCase();return t.includes(`not installed`)||t.includes(`not found`)||t.includes(`no such file`)}function F(t,n){if(t.exitCode!==0)throw new e(`COMMAND_FAILED`,n,{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode})}function Qr(e){return ei(e)?e.kind!==`simulator`&&e.kind!==`device`?Ur:e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?Br:zr:Hr}function $r(e){return ei(e)?e.kind===`simulator`?zr:Vr:Hr}function ei(e){return o(e)&&e.appleOs!==`watchos`}const I=Object.freeze({available:!0}),ti=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`back is supported on Apple simulators and physical devices.`}),ni=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function ri(e){return e.kind!==`simulator`&&e.kind!==`device`?ti:r(e)===`watchos`?ni:I}const ii=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`home is supported on Apple simulators and physical devices.`}),ai=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),oi=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`app-switcher is supported on Apple simulators and physical devices.`});function si(e,t){if(e.kind!==`simulator`&&e.kind!==`device`)return t;let n=r(e);return n===`macos`||n===`watchos`?ai:I}function L(e){if(e.kind!==`simulator`&&e.kind!==`device`)return!1;let t=r(e);return t!==`tvos`&&t!==`macos`&&t!==`watchos`}const ci=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 ui(e){return e.kind!==`simulator`&&e.kind!==`device`?ci:L(e)?I:li}const di=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`tv-remote is supported only on tvOS devices.`});function fi(e){return(e.kind===`simulator`||e.kind===`device`)&&a(e)?I:di}const R=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),pi=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 mi(e){return L(e)?pi:R}function hi(e){return L(e)?I:R}function gi(e){return L(e)?I:R}function _i(e){return Object.freeze({...Pe({back:ri(e)}),...we({home:si(e,ii)}),...Ae({appSwitcher:si(e,oi)}),...Me({orientation:ui(e)}),...Ee({tvRemote:fi(e)}),...ke({unsupported:R,status:mi(e),dismiss:hi(e),enter:gi(e)})})}function vi(e){let{host:t,device:n,signal:r}=e;return ct({device:n,signal:r,resolveInteractor:t.localInteractors.resolve,facts:_i(n)})}const z=Object.freeze({available:!0}),yi=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`clipboard is supported on Apple simulators and the macOS host.`}),bi=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`settings is supported on Apple simulators and the macOS host.`}),xi=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.`}),Si=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.`}),B=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function Ci(e,t,n){if(e.kind!==`simulator`&&e.kind!==`device`)return t;let i=r(e);return i===`watchos`?B:e.kind===`simulator`||i===`macos`?z:n}function wi(e){return Ci(e,yi,Si)}const Ti=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`trigger-app-event is supported on Apple simulators and physical devices.`}),Ei=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`alert is supported on Apple simulators and physical devices.`}),Di=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`alert is supported on Apple simulators, the macOS host, and physical iOS devices.`});function Oi(e){if(e.kind!==`simulator`&&e.kind!==`device`)return Ei;let t=r(e);return t===`watchos`?B:e.kind===`simulator`||t===`ios`||t===`macos`?z:Di}function ki(e){return e.kind!==`simulator`&&e.kind!==`device`?Ti:r(e)===`watchos`?B:z}function Ai(e){let t=wi(e);return t.available?Si:t}function ji(e){let t=wi(e),n=Oi(e);return Object.freeze({...Te({unsupported:Ai(e),read:t,write:t}),...je({read:n,wait:n,accept:n,dismiss:n}),...Ce({triggerAppEvent:ki(e)}),...De({setSetting:Ci(e,bi,xi)})})}function Mi(e){let{host:t,device:n,signal:r}=e;return ct({device:n,signal:r,resolveInteractor:t.localInteractors.resolve,facts:ji(n)})}function Ni(e,t,n){let r=Fe({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,Se(t.signal,i));if(!n)return await r.captureSnapshot(i);let a=Se(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 Pi(e,t){return Object.freeze({findText:async n=>{let r=await Fi(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 Fi(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 Ii(e,t.device,n.execution))return{appBundleId:r,signal:a}}async function Ii(e,t,n){return!M(t)||await e.appleApplications.hasLiveRunnerSession(t,n??{})}function Li(){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 Ri=3e3;function zi(){let e=new Map,t=new Map,n=Tt({waitMs:1500});return async(r,i,a,o)=>{a.throwIfAborted();let s=`${r.id}:${i}`,c=e.get(s);return c&&o!==`refresh`&&await Dt(c.pid,{signal:a,timeoutMs:Ri})===c.processStartTime?c:(e.delete(s),await n.value(s,{start:async()=>{let n=await Bi(r,i,t);return e.set(s,n),n},wait:(e,t)=>Et({waitMs:e,signal:a,stop:t,cancelled:()=>a.reason}),pending:()=>H(`simulator-target-discovery-pending`,r,i)}))}}async function Bi(e,t,n){let r=Date.now()+15e3,[i,a]=await Promise.allSettled([xt(e,[`spawn`,e.id,`launchctl`,`list`],{allowFailure:!0,timeoutMs:V(r)}),Vi(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 H(`simulator-target-probe-failed`,e,t);let c=Hi(o.stdout,t);if(!c)throw H(`simulator-target-unavailable`,e,t);let l=await Dt(c.pid,{timeoutMs:Math.min(Ri,V(r))});if(!l)throw H(`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 Vi(e,t,n){let r=t.get(e.id);if(r)return await r;let i=xt(e,[`list`,`devices`,`-j`],{allowFailure:!0,timeoutMs:V(n)}).then(t=>{if(t.exitCode!==0)throw H(`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 H(`simulator-runtime-unavailable`,e,``);return r});t.set(e.id,i);try{return await i}catch(n){throw t.delete(e.id),n}}function Hi(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 V(e){return Math.max(1,e-Date.now())}function H(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 Ui(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 Wi(n,r);return a!==`absent`&&a!==`unknown`&&t.set(n.id,{at:e(),host:a.host}),a}}async function Wi(e,t){let n=!1;for(let r of at){let i=await Gi(r.processExecutable,t);if(i===`unknown`){n=!0;continue}for(let a of i){let i=await Ki(a,e.id,t);if(i===`unknown`)n=!0;else if(i)return{kind:`present`,host:r}}}return n?`unknown`:`absent`}async function Gi(e,t){let n=await qi(`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 Ki(e,t,n){let r=await qi(`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 qi(e,t,n){try{let r=await bt(e,t,{allowFailure:!0,timeoutMs:3e3,...n?{signal:n}:{}});return{exitCode:r.exitCode,stdout:r.stdout}}catch{return`unknown`}}const Ji=`system-surface-presented`,Yi=`system-surface-host-lingering`;function Xi(t,n={}){let r=n.source??Li(),i=n.resolveTarget??zi(),a=n.systemSurfacePresent??Ui(),o=new Set,s=new Map,c=e=>(sa(e,s,o),o.has(ca(e))),l=gr({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(!$i(n,s))return await na(n,s,u);let d=await a(n,l);if(d===`unknown`)return await U(n.id,s,u,W(n.id,s),q(s),`system-surface-probe-unavailable`,[K()]);if(d!==`absent`)return await ta(n,s,u,d.host.bundleId);let p;try{p=await Zi(t,i,n,s,l)}catch(e){return l.throwIfAborted(),J(`target-resolution-failed`,n,void 0,e),await U(n.id,s,u,W(n.id,s),q(s),`target-resolution-failed`,[K()])}if(c(p))return await U(n.id,s,u,p,q(s),`circuit-disabled`);let m=q(s),h=await r.acquire({target:p,hint:ee(m),signal:l});if(h.stage===`failed`){if(h.failure.kind===`cancelled`)throw l.throwIfAborted(),new e(`COMMAND_FAILED`,`Simulator AX snapshot acquisition was cancelled.`,{reason:h.failure.code,...h.failure.details});let t=await oa(h.failure,p,n,s.options.appBundleId,l,i);return await ea(s,u,p,t,m,h.failure,o)}try{return await f(`ios.snapshot-source.present`,async()=>await t.snapshot.presentIosAcquisition(h,s.options),{producer:`simulator-ax-bridge`})}catch(e){return await ea(s,u,p,{lineage:p,residue:[]},m,{kind:`malformed-tree`,code:`presentation-invariant`},o,e)}}})}async function Zi(e,t,n,r,i){let a=r.options.appBundleId;for(;;)try{return await t(n,a,i)}catch(t){if(!Qi(t))throw t;let i={requestId:r.execution?.requestId};if(await e.appleApplications.hasLiveRunnerSession(n,i))throw t}}function Qi(t){return t instanceof e&&t.details?.reason===`simulator-target-discovery-pending`}function $i(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 ea(e,t,n,r,i,a,o,s){return a.kind!==`preparing`&&o.add(ca(n)),J(a.code,{id:n.udid},n.generation,s,a.details),await U(n.udid,e,t,r.lineage,i,a.code,r.residue)}async function U(e,t,n,r,i,a,o=[]){return ra(e,await n(t),r,i,a,o)}async function ta(e,t,n,r){let i=await n(t),a=i.systemSurface?Ji:Yi;return i.systemSurface||J(a,e,void 0,void 0,{detectedHost:r}),ra(e.id,i,W(e.id,t),q(t),a)}async function na(e,t,n){let r=await n(t),i=r.systemSurface;return i?{...r,comparisonIdentity:ia(G(e.id,i.bundleId),q(t),[])}:r}function ra(e,t,n,r,i,a=[]){let o=t.systemSurface;return{...t,comparisonIdentity:ia(o?G(e,o.bundleId):n,r,[...o?[]:a,{kind:`fallback-source`,producer:`apple-runner`}]),warnings:[...t.warnings??[],aa(i,n,o!==void 0)]}}function W(e,t){return{targetId:`${e}:${t.options.appBundleId}`}}function G(e,t){return{targetId:`${e}:${t}`}}function ia(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:te(t),residue:Object.freeze([...n])})}function aa(e,t,n){return e===Ji?`Simulator AX snapshot inapplicable (${e}); used XCTest to read the system surface presented over the app.`:e===Yi?`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.`:`Simulator AX snapshot unavailable (${e}); used XCTest for ${t.generation?`this app generation`:`an unverified app generation`}.`}async function oa(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:[K()]}}}function K(){return{kind:`unknown-generation`,captureId:kt()}}function q(e){return ne({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 sa(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 ca(e){return`${e.targetId}:${e.generation}`}function J(e,t,n,r,i){p({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=l(`apple`),X=Object.freeze({available:!0}),Z=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),la=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.`}),ua=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.`}),da=Object.freeze({available:!1,reason:`unsupported-device-backend`,hint:`perf requires an Apple simulator, macOS device, or CoreDevice-backed physical Apple device.`}),fa=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`focus is supported on Apple simulators and physical devices.`}),pa=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Apple appstate reads the active session state; a sessionless runtime foreground probe is unavailable.`}),ma=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Headless boot is supported only for local Android emulators.`}),ha=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS has no XCUITest-driveable UI, so element text comes from the captured tree only.`}),ga=Object.freeze({available:!1,reason:`unsupported-device-kind`}),_a=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS open is not supported because XCUITest cannot drive watchOS UI.`}),va=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS runner preparation is not supported because XCUITest cannot drive watchOS UI.`}),ya=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS close is not supported because XCUITest cannot drive watchOS UI.`}),ba=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Runtime hints are supported only for local iOS-family simulators and Android devices.`}),xa=Q(`open is supported only for Apple simulators and devices.`),Sa=Q(`prepare is supported only for Apple simulators and devices.`),Ca=Q(`close is supported only for Apple simulators and devices.`),wa=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Port reverse is supported only by an owning provider runtime.`}),Ta=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`shutdown is supported only for Apple simulators and Android emulators.`}),Ea=Q(`snapshot is supported only for Apple simulators and devices.`),Da=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Re-run without --actions, or target an iOS simulator.`}),Oa=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`screenshot is not supported on watchOS because XCUITest cannot drive watchOS UI.`}),ka=Q(`screenshot is supported only for Apple simulators and devices.`),Aa=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 ja(e){return!o(e)||e.appleOs===`watchos`?Z:e.kind===`simulator`?X:Ta}function Ma(e){let t=Na(e),n=Pa(e),r=Fa(e),i=Ia(e);return oe({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:i,clearRuntimeHints:i,closeApplication:r,finalizeApplicationClose:r,prepareAppleRunner:n,configureProviderPortReverse:wa})}function Na(e){return r(e)===`watchos`?_a:e.kind===`simulator`||e.kind===`device`?X:xa}function Pa(e){return r(e)===`watchos`?va:e.kind===`simulator`||e.kind===`device`?X:Sa}function Fa(e){return r(e)===`watchos`?ya:e.kind===`simulator`||e.kind===`device`?X:Ca}function Ia(e){return r(e)!==`watchos`&&o(e)&&e.kind===`simulator`?X:ba}function La(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:fa}function Ra(e){let t=hn(e),n=Xi(e),r=async n=>{let r=await t.inspectFacts(n),i=Wr(n),a=Kn(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=La(n);return Object.freeze({device:r.device,operations:{...r.operations,...i,appState:pa,networkDump:X,screenRecordingStart:l,screenRecordingReattach:l,screenRecordingCleanup:l,...Ua(n),...fe({capture:Ha(n)}),...ye({findText:Va(n)}),...he({setViewport:la}),...me({focus:$(n)}),...Rt(n),...de({type:$(n)}),...se({unsupported:Z,tap:$(n),longPress:$(n),fill:$(n),...o(n)?{tapElementSelector:$(n)}:{}}),...Ne({readTextAtPoint:Ba(n)}),..._i(n),...ji(n),...Ie({capture:jt(n),query:ua}),...Le(za(n)),ensureReady:u,bootTarget:d,bootTargetHeadless:ma,listApps:f,...Ma(n),shutdownTarget:ja(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,...Gr({host:e,device:i.device,signal:i.scope.signal}),networkDump:async t=>await yn(e,i.device,t,i.scope.signal),...d(s,()=>qn({host:e,device:i.device,owner:Y,signal:i.scope.signal})),...d(o.operations.audioProbeStart,()=>Ke({host:e.audioProbe.hostCapture,device:i.device,owner:Y})),...d(o.operations.perfFrames,()=>Mt({resolveHost:()=>e.perf.apple,device:i.device,owner:Y})),...d(o.operations.captureSnapshot,()=>Ni(e,{device:i.device,signal:i.scope.signal},n)),...d(o.operations.captureScreenshot,()=>xe({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...d(o.operations.focusPoint,()=>ve({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...Oe({device:i.device,signal:i.scope.signal,facts:o.operations,resolveInteractor:e.localInteractors.resolve}),...d(o.operations.scrollDirection,()=>_e({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...d(o.operations.typeText,()=>be({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...d(o.operations.tapPoint,()=>ce({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)})),...d(o.operations.readTextAtPoint,()=>ue({device:i.device,signal:i.scope.signal,resolveInteractor:e.localInteractors.resolve})),...d(o.operations.findText,()=>Pi(e,{device:i.device,signal:i.scope.signal})),...vi({host:e,device:i.device,signal:i.scope.signal}),...Mi({host:e,device:i.device,signal:i.scope.signal}),...d(o.operations.ensureReady,()=>({ensureReady:async()=>await k(e,i.device,i.scope.signal)})),...d(o.operations.bootTarget,()=>({bootTarget:async()=>await k(e,i.device,i.scope.signal)})),...d(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}))}})),...ie(br({host:e,device:i.device,signal:i.scope.signal,observation:n}),o.operations),...d(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:At(c),[Symbol.asyncDispose]:async()=>await a[Symbol.asyncDispose]()})},shutdown:async()=>{await Promise.all([t.shutdown(),n.shutdown()])}})}function za(e){let t=e.iosPhysicalDeviceBackend!==`xctest`&&r(e)!==`watchos`?X:da;return{frames:t,memorySample:t,memorySnapshot:t,nativeCapture:t,profileReport:t}}function Ba(e){return r(e)===`watchos`?ha:e.kind===`simulator`||e.kind===`device`?X:ga}function Va(e){return r(e)===`watchos`?Ea:e.kind===`simulator`||e.kind===`device`?X:Ea}function Ha(e){return r(e)===`watchos`?Oa:e.kind===`simulator`||e.kind===`device`?X:ka}function Ua(e){let t=Va(e);return pe({capture:t,customActions:t.available&&o(e)&&e.kind===`simulator`?X:Da,withoutActiveApp:o(e)?Aa:t})}export{Ra as createApplePlatformRuntime};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Br as e,Hr as t,Mr as n,Or as r,Ur as i,zr as a}from"./sdk-batch.js";import{n as o,t as s}from"./scroll-indicator.js";import{a as c,i as l,o as ee,r as u}from"./react-native-overlay.js";import{t as d}from"./rect-center.js";import{a as f,c as te,d as p,f as m,g as ne,h,i as g,l as re,m as _,n as v,o as y,p as b,r as x,s as S,t as C,u as ie}from"./tree.js";function ae(e,t){let n=g(t.sourceNodesByIndex.values());for(let r of e)oe(r,t.sourceNodesByIndex,n)&&b(t.replacements,r,{type:`Cell`})}function oe(e,t,r){return!(n(e.type??``)!==`other`||e.enabled===!1||!e.rect||!le(e.label)||!f(e,t,ce)||!se(e)||re(e.rect,r))}function se(e){return e.rect?e.rect.height>=44&&e.rect.height<=160&&e.rect.width>=120:!1}function ce(e){let t=n(e.type??``);return t===`scrollview`||t===`scrollarea`}function le(e){let t=e?.trim();return!(!t||/^(toolbar|window|application)$/i.test(t)||t.startsWith(`!,`)||/debugger|fast refresh/i.test(t))}function ue(e,t){let n=new Set;for(let r of e)de(t.replacements.get(r.index)??r)&&fe(r,t.sourceNodesByIndex,t,n);pe(e,t,n)}function de(e){let t=e.label?.trim();return!!(t&&o(t))}function fe(e,t,n,r){let i=!p(e.type)||n.isSuppressed(e),a=s(e.label?.trim()??``,e.value),o=a?y(e,t,{includeSelf:!0}):void 0;i&&n.suppressNode(e,o?[o]:[]),o&&a&&j(n,o,e,a)&&r.add(o.index)}function pe(e,t,n){let r=new Map;for(let i of e){let e=r.get(i.parentIndex??-1),a=e?.clip,o=t.replacements.get(i.index)??i,s=k(o.rect,a),c=me(o,a,s),l=w(e,c,o);T(t,i,o,a,s,c,l),r.set(i.index,E(i,o,a,s,l,n))}}function me(e,t,n){return!!(t&&a(e.rect)&&!a(n))}function w(e,t,n){return!!(e?.projectedOut||t&&O(n))}function T(e,t,n,r,i,a,o){o||a?e.suppressNode(t,[]):r&&i&&!A(n.rect,i)&&b(e.replacements,t,{rect:i})}function E(e,t,n,r,i,a){return{projectedOut:i,...D(e,t,n,r,a)?{clip:r}:n?{clip:n}:{}}}function D(e,t,n,r,i){return!!(a(r)&&(i.has(e.index)||n!==void 0&&p(t.type)))}function O(e){return e.type?.trim().toLowerCase()===`cell`||p(e.type)}function k(e,t){if(!e||!t)return e;let n=Math.max(e.x,t.x),r=Math.max(e.y,t.y),i=Math.min(e.x+e.width,t.x+t.width),a=Math.min(e.y+e.height,t.y+t.height);return{x:n,y:r,width:Math.max(0,i-n),height:Math.max(0,a-r)}}function A(e,t){return!!(e&&e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height)}function j(e,t,n,r){let i=N((e.replacements.get(t.index)??t).rect,n.rect);return ne(e.replacements,t,e=>({rect:i??e.rect,hiddenContentAbove:M(e.hiddenContentAbove,r.above),hiddenContentBelow:M(e.hiddenContentBelow,r.below)})),!!i}function M(e,t){return e===!0||t?!0:void 0}function N(e,t){if(!(!e||!t)&&!(t.height<=0||t.height>=e.height)&&!(t.y<e.y||t.y>e.y+e.height))return{...e,y:t.y,height:Math.min(t.height,e.y+e.height-t.y)}}function P(e,t){for(let r=0;r<e.length;r+=1){let i=e[r],a=i?.label?.trim();i&&a&&n(i.type??``)===`other`&&t(i,a,r)}}function F(e,t){P(e,(n,r,i)=>{if(!c(r)||!n.rect)return;let a=x(e,i,e=>!!e.rect&&ee(e.label?.trim()??``));if(!a?.rect)return;let o=L(n.rect,a.rect);if(!o)return;let s=I(e,i,o);b(t,n,{rect:s}),S(e,i,e=>{c(e.label?.trim()??``)&&b(t,e,{rect:s})})})}function I(e,n,r){let a=r;return S(e,n,e=>{let n=e.label?.trim()??``;!e.rect||!c(n)||i(r,e.rect)&&t(e.rect)<t(a)&&(a=e.rect)}),a}function L(e,t){let n=e.x+e.width,r=t.x+t.width,i={x:t.x,y:e.y,width:n-t.x,height:e.height};if(t.x>e.x&&d(t,i))return{...e,width:t.x-e.x};let a={x:e.x,y:e.y,width:r-e.x,height:e.height};if(r<n&&d(t,a))return{...e,x:r,width:n-r}}function R(e,t){P(e,(n,r,i)=>{u(n)&&l(n,z(e,i))&&t.suppressNode(n,z(e,i))})}function z(e,t){let n=[];return S(e,t,e=>{n.push(e)}),n}function he(e,t){let n=g(e),r=n?n.y+n.height:null;if(r!==null)for(let n=0;n<e.length;n+=1){let i=e[n];!i||!ge(i,r)||(t.suppressNode(i,[]),_e(i,t,r),S(e,n,e=>{t.suppressNode(e,[])}))}}function ge(e,t){return!e.rect||n(e.type??``)!==`keyboard`?!1:e.rect.y>=t}function _e(e,t,n){let r=typeof e.parentIndex==`number`?t.sourceNodesByIndex.get(e.parentIndex):void 0;for(;r?.rect&&r.rect.y>=n;)t.suppressNode(r,[]),r=typeof r.parentIndex==`number`?t.sourceNodesByIndex.get(r.parentIndex):void 0}function ve(e,t){for(let r=0;r<e.length;r+=1){let i=e[r];if(!i)continue;if(ye(i)){B(e,r,i,t);continue}if(!be(i))continue;let a=x(e,r,e=>n(e.type??``)===`searchfield`&&e.label===`Search`);a&&(t.suppressNode(i,[a]),xe(i,a,t),B(e,r,a,t))}}function ye(e){return n(e.type??``)===`searchfield`&&e.label===`Search`}function be(e){let t=n(e.type??``);return e.label===`Toolbar`&&(t===`toolbar`||t===`searchfield`)}function B(e,t,n,r){S(e,t,e=>{e.index!==n.index&&Se(e)&&r.suppressNode(e,[n])})}function xe(e,t,n){let r=e;for(;typeof r.parentIndex==`number`;){let e=n.sourceNodesByIndex.get(r.parentIndex);if(!e||e.label!==`Toolbar`)return;n.suppressNode(e,[t]),r=e}}function Se(e){let t=n(e.type??``);return t===`button`?!1:t===`image`||e.label===`Search`}function Ce(e,t){for(let n=0;n<e.length;n+=1){let r=e[n],i=r?.label?.trim();!r||t.isSuppressed(r)||!i||we(e,n,r,i,t)}}function we(e,t,r,i,a){let o=n(r.type??``);if(o===`statictext`||o===`link`){V(e,t,i,r,a);return}if(o!==`other`)return;let s=Te(e,t,i);if(s){a.suppressNode(r,[s]);return}V(e,t,i,r,a)}function Te(e,t,r){return x(e,t,e=>{let t=n(e.type??``);return(t===`link`||t===`searchfield`||p(e.type))&&e.label?.trim()===r})}function V(e,t,n,r,i){S(e,t,e=>{!i.semanticRepresentativeIndexes.has(e.index)&&ie(e,n)&&i.suppressNode(e,[r])})}function Ee(e,t){P(e,(n,r,i)=>{let a=x(e,i,e=>m(e)&&e.label?.trim()===r&&(d(e.rect,n.rect)||De(n,e)));a&&t.suppressNode(n,[a])})}function De(e,t){if(t.label?.trim()!==e.label?.trim())return!1;let r=n(t.type??``);return Oe(e,r)||r===`textfield`||ke(e,r,t)}function Oe(e,t){let n=e.label?.trim();return t===`button`&&(n===`Dismiss`||n===`Back`)}function ke(e,t,n){return t!==`button`||!e.rect||!n.rect?!1:e.rect.x===0&&e.rect.y===0&&e.rect.width>=300&&e.rect.height>=600&&n.rect.width<e.rect.width}function Ae(e,t){let r=C(e);for(let i of e)n(i.type??``)===`other`&&(i.hittable===!0||i.label?.trim()||i.value?.trim()||i.identifier?.trim()&&t.suppressNode(i,je(i,r)))}function je(e,t){let n=[],r=new Set([e.index]),i=[...t.get(e.index)??[]];for(;i.length>0;){let e=i.pop();if(!e||r.has(e.index))continue;r.add(e.index),n.push(e);let a=t.get(e.index);a&&i.push(...a)}return n}function Me(e,t){he(e,t),Ae(e,t),ue(e,t),ve(e,t),Ee(e,t),F(e,t.replacements),R(e,t),Ce(e,t)}function Ne(e,t){for(let n=0;n<e.length;n+=1){let r=e[n],i=r?Pe(e,n,r,t):void 0;!r?.rect||!i||Le(e,n,r,i,t)}}function Pe(e,t,r,i){let a=r.label?.trim();if(n(r.type??``)!==`cell`||a&&!Fe(a,r.identifier)&&!o(a))return a;let s=v(e,t).find(Ie),c=s?.label?.trim();return!s||!c?a:(b(i.replacements,r,{label:c}),i.suppressNode(s,[r]),c)}function Fe(e,t){return t?.trim()===e&&/^[A-Z_$][A-Za-z0-9_$]*Cell$/.test(e)}function Ie(e){if(!e.label?.trim())return!1;let t=n(e.type??``);return t===`statictext`||t===`text`||t===`textview`}function Le(e,t,r,i,a){let o=n(r.type??``);if(o===`button`){H(v(e,t),i,a,r);return}if(o!==`cell`)return;let s=v(e,t);Re(s,r,i,a)||ze(s,r,i,a)}function Re(e,t,n,r){let i=e.find(e=>Ve(e,t,n));if(!i)return!1;let a=e.find(e=>U(e,t,n)),o=i.identifier?void 0:a?.identifier??t.identifier;return o&&b(r.replacements,i,{identifier:o}),r.suppressNode(t,[i]),Be(e,t,n,i,r),!0}function ze(e,t,n,r){let i=e.find(e=>U(e,t,n));if(!i){e.some(te)&&H(e,n,r,t);return}!t.identifier&&i.identifier&&b(r.replacements,t,{identifier:i.identifier}),r.suppressNode(i,[t]),H(e.filter(e=>e.index!==i.index),n,r,t)}function Be(e,t,n,r,i){for(let a of e)a.index!==r.index&&(U(a,t,n)||W(a,t)||He(a,r)||h(a,n))&&i.suppressNode(a,[r])}function H(e,t,n,r){for(let i of e)(h(i,t)||r&&W(i,r))&&n.suppressNode(i,r?[r]:[])}function U(e,t,r){if(n(e.type??``)!==`button`)return!1;let i=t.identifier?.trim(),a=e.identifier?.trim();return i&&a&&i===a?!0:e.label?.trim()===r&&d(e.rect,t.rect)}function W(e,t){return n(e.type??``)===`button`&&!e.label?.trim()&&!e.value?.trim()&&d(e.rect,t.rect)}function Ve(e,t,r){if(n(e.type??``)!==`switch`)return!1;let i=t.identifier?.trim(),a=e.identifier?.trim();return i&&a&&i===a?!0:e.label?.trim()===r}function He(e,t){if(n(e.type??``)!==`switch`||e.index===t.index)return!1;let r=e.label?.trim();return r===t.value?.trim()||r===`0`||r===`1`}const G=1.15;function Ue(t,n,r){let i=new Map(t.map((e,t)=>[e.index,t]));for(let[a,o]of t.entries()){let s=We(t,i,n,o,r);if(!s)continue;q(t,a,r);let c=J(s.shelfRect,2);for(let n of s.intermediateSiblings){if($e(n)||!n.rect||!e(n.rect,c))continue;let a=i.get(n.index);a!==void 0&&q(t,a,r)}}}function We(e,t,n,r,i){let a=Ge(r,n,i.sourceNodesByIndex);if(!a)return;let o=Je(e,t,a.siblings,a.position,a.parent);if(!(o<0))return{shelfRect:a.rect,intermediateSiblings:a.siblings.slice(a.position+1,o)}}function Ge(e,t,n){let r=Ye(e,K(t,e.index));if(!r)return;let i=qe(e,n);if(!i||!i.rect)return;let a=K(t,i.index),o=a.findIndex(t=>t.index===e.index);if(Ke(a,o,e,r))return{rect:r.rect,parent:i,siblings:a,position:o}}function K(e,t){return e.get(t)??[]}function Ke(e,t,n,r){if(t<1)return!1;let i=Xe(e,t,n);return i?!r.childActionsPresented||!Ze(i,r.actionButtons):!1}function qe(e,t){return typeof e.parentIndex==`number`?t.get(e.parentIndex):void 0}function Je(e,t,n,r,i){return n.findIndex((n,a)=>a>r&&Qe(e,t.get(n.index),n,i))}function Ye(e,t){if(!p(e.type)||!e.rect)return;let r=e.rect,a=t.filter(e=>n(e.type??``)===`button`&&e.rect);if(a.length===0&&e.hiddenContentBelow===!0)return{rect:r,childActionsPresented:!1,actionButtons:a};if(a.length<3)return;let o=a.map(e=>e.rect.x+e.rect.width/2);if(o.every((e,t)=>t===0||e>o[t-1]))return{rect:r,childActionsPresented:a.some(e=>i(r,e.rect)),actionButtons:a}}function Xe(e,t,n){if(!(!n.rect||t<1))for(let r=t-1;r>=0;--r){let t=e[r];if(!(!t.rect||!m(t))&&t.rect.x+t.rect.width/2<n.rect.x&&et(t.rect,J(n.rect,2)))return t}}function Ze(e,t){if(!e.rect||t.length===0)return!1;let n=Math.max(...t.map(e=>e.rect?.width??0)),r=Math.max(...t.map(e=>e.rect?.height??0));return e.rect.width>n*G||e.rect.height>r*G}function Qe(e,t,r,i){return t!==void 0&&n(r.type??``)===`other`&&d(r.rect,i.rect)&&!!x(e,t,m)}function q(e,t,n){let r=e[t];if(r){n.suppressNode(r,[]);for(let r of v(e,t))n.suppressNode(r,[])}}function $e(e){let t=n(e.type??``);return t===`textfield`||t===`securetextfield`||t===`searchfield`||t===`textview`}function J(e,t){return{x:e.x-t,y:e.y-t,width:e.width+t*2,height:e.height+t*2}}function et(e,t){return Math.max(e.y,t.y)<=Math.min(e.y+e.height,t.y+t.height)}function tt(e,t){let n=C(e);Ue(e,n,t),nt(e,n,t)}function nt(e,t,r){for(let i of e){if(n(i.type??``)!==`navigationbar`||!i.rect)continue;let e=t.get(i.index)??[],a=e.flatMap(t=>rt(t,e,i.rect));if(a.length!==1)continue;let{field:o,title:s,image:c,label:l}=a[0];b(r.replacements,o,{type:`Button`,label:l,enabled:!0,rect:st([c.rect,o.rect,s.rect])}),r.semanticRepresentativeIndexes.add(o.index),r.suppressNode(s,[o]),r.suppressNode(c,[o])}}function rt(e,t,n){let i=r(e);if(!it(e,i))return[];let a=X(t,e=>at(e,i)),o=X(t,Y);return a?.rect&&o?.rect&&ot(o.rect,e.rect,a.rect,n)?[{field:e,title:a,image:o,label:i}]:[]}function it(e,t){return n(e.type??``)===`textfield`&&e.enabled===!1&&!!e.rect&&!!t&&e.value?.trim()===t}function at(e,t){return n(e.type??``)===`statictext`&&e.label?.trim()===t&&!!e.rect}function Y(e){return n(e.type??``)===`image`&&!!e.identifier?.trim()&&!!e.rect}function X(e,t){let n=e.filter(t);return n.length===1?n[0]:void 0}function ot(e,t,n,r){let a=t.x-(e.x+e.width),o=n.x-(t.x+t.width);return i(r,e)&&i(r,t)&&i(r,n)&&a>=0&&a<=12&&o>=0&&o<=12&&Z(e,t)&&Z(t,n)}function Z(e,t){return Math.max(e.y,t.y)<=Math.min(e.y+e.height,t.y+t.height)}function st(e){let t=Math.min(...e.map(e=>e.x)),n=Math.min(...e.map(e=>e.y)),r=Math.max(...e.map(e=>e.x+e.width)),i=Math.max(...e.map(e=>e.y+e.height));return{x:t,y:n,width:r-t,height:i-n}}function ct(e,t){let r=C(e);for(let i of e){if(n(i.type??``)===`element(58)`){b(t.replacements,i,{type:`WebView`});continue}let e=lt(i,t.sourceNodesByIndex,r);if(e?.kind===`suppress`){t.suppressNode(i,[]);continue}e&&(b(t.replacements,i,{type:e.type,...e.type===`Heading`?{value:void 0}:{}}),t.semanticRepresentativeIndexes.add(i.index))}}function lt(e,t,r){if(n(e.type??``)!==`other`)return null;let i=f(e,t,ft),a=e.label?.trim();return!i||!a?null:dt(e,i,a)?{kind:`suppress`}:ut(e,a,r)?{kind:`semantic`,type:Q(e.value)?`Heading`:`StaticText`}:null}function ut(e,t,r){let i=r.get(e.index);if(i?.length!==1)return!1;let a=i[0];return n(a.type??``)===`statictext`&&a.label?.trim()===t&&!r.has(a.index)}function dt(e,t,n){return e.parentIndex===t.index&&t.label?.trim()===n&&!Q(e.value)}function ft(e){let t=n(e.type??``);return t===`webview`||t===`element(58)`}function Q(e){return/^[1-6]$/.test(e?.trim()??``)}const pt=[ct,tt,ae,Ne,Me];function mt(e){if(e.length===0)return{nodes:e,presentedIndexesBySourceIndex:new Map};let t=new Map,n=new Map,r=new Set,i=new Map(e.map(e=>[e.index,e])),a=new Set,o={replacements:t,semanticRepresentativeIndexes:r,sourceNodesByIndex:i,isSuppressed:e=>a.has(e.index),suppressNode(e,t){if(a.add(e.index),t.length===0)return;let r=n.get(e.index)??new Set;for(let e of t)r.add(e.index);n.set(e.index,r)}};for(let t of pt)t(e,o);if(a.size===0&&t.size===0)return{nodes:e,presentedIndexesBySourceIndex:new Map(e.map(e=>[e.index,[e.index]]))};let s=e.filter(e=>!a.has(e.index)).map(e=>t.get(e.index)??e),c=_(s,a,e),l=new Map(s.map((e,t)=>[e.index,c[t].index]));return{nodes:c,presentedIndexesBySourceIndex:new Map(e.map(e=>[e.index,$(e.index,l,n)]))}}function $(e,t,n,r=new Set){let i=t.get(e);if(i!==void 0)return[i];if(r.has(e))return[];r.add(e);let a=new Set;for(let i of n.get(e)??[])for(let e of $(i,t,n,r))a.add(e);return[...a].sort((e,t)=>e-t)}export{mt as t};
|
|
1
|
+
import{Br as e,Hr as t,Mr as n,Or as r,Ur as i,zr as a}from"./sdk-batch.js";import{n as o,t as s}from"./scroll-indicator.js";import{a as c,i as l,o as ee,r as u}from"./react-native-overlay.js";import{t as d}from"./rect-center.js";import{a as f,c as te,d as p,f as m,g as ne,h,i as g,l as re,m as _,n as v,o as y,p as b,r as x,s as S,t as C,u as ie}from"./tree.js";function ae(e,t){let n=g(t.sourceNodesByIndex.values());for(let r of e)oe(r,t.sourceNodesByIndex,n)&&b(t.replacements,r,{type:`Cell`})}function oe(e,t,r){return!(n(e.type??``)!==`other`||e.enabled===!1||!e.rect||!le(e.label)||!f(e,t,ce)||!se(e)||re(e.rect,r))}function se(e){return e.rect?e.rect.height>=44&&e.rect.height<=160&&e.rect.width>=120:!1}function ce(e){let t=n(e.type??``);return t===`scrollview`||t===`scrollarea`}function le(e){let t=e?.trim();return!(!t||/^(toolbar|window|application)$/i.test(t)||t.startsWith(`!,`)||/debugger|fast refresh/i.test(t))}function ue(e,t){let n=new Set;for(let r of e)de(t.replacements.get(r.index)??r)&&fe(r,t.sourceNodesByIndex,t,n);pe(e,t,n)}function de(e){let t=e.label?.trim();return!!(t&&o(t))}function fe(e,t,n,r){let i=!p(e.type)||n.isSuppressed(e),a=s(e.label?.trim()??``,e.value),o=a?y(e,t,{includeSelf:!0}):void 0;i&&n.suppressNode(e,o?[o]:[]),o&&a&&j(n,o,e,a)&&r.add(o.index)}function pe(e,t,n){let r=new Map;for(let i of e){let e=r.get(i.parentIndex??-1),a=e?.clip,o=t.replacements.get(i.index)??i,s=k(o.rect,a),c=me(o,a,s),l=w(e,c,o);T(t,i,o,a,s,c,l),r.set(i.index,E(i,o,a,s,l,n))}}function me(e,t,n){return!!(t&&a(e.rect)&&!a(n))}function w(e,t,n){return!!(e?.projectedOut||t&&O(n))}function T(e,t,n,r,i,a,o){o||a?e.suppressNode(t,[]):r&&i&&!A(n.rect,i)&&b(e.replacements,t,{rect:i})}function E(e,t,n,r,i,a){return{projectedOut:i,...D(e,t,n,r,a)?{clip:r}:n?{clip:n}:{}}}function D(e,t,n,r,i){return!!(a(r)&&(i.has(e.index)||n!==void 0&&p(t.type)))}function O(e){return e.type?.trim().toLowerCase()===`cell`||p(e.type)}function k(e,t){if(!e||!t)return e;let n=Math.max(e.x,t.x),r=Math.max(e.y,t.y),i=Math.min(e.x+e.width,t.x+t.width),a=Math.min(e.y+e.height,t.y+t.height);return{x:n,y:r,width:Math.max(0,i-n),height:Math.max(0,a-r)}}function A(e,t){return!!(e&&e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height)}function j(e,t,n,r){let i=N((e.replacements.get(t.index)??t).rect,n.rect);return ne(e.replacements,t,e=>({rect:i??e.rect,hiddenContentAbove:M(e.hiddenContentAbove,r.above),hiddenContentBelow:M(e.hiddenContentBelow,r.below)})),!!i}function M(e,t){return e===!0||t?!0:void 0}function N(e,t){if(!(!e||!t)&&!(t.height<=0||t.height>=e.height)&&!(t.y<e.y||t.y>e.y+e.height))return{...e,y:t.y,height:Math.min(t.height,e.y+e.height-t.y)}}function P(e,t){for(let r=0;r<e.length;r+=1){let i=e[r],a=i?.label?.trim();i&&a&&n(i.type??``)===`other`&&t(i,a,r)}}function F(e,t){P(e,(n,r,i)=>{if(!c(r)||!n.rect)return;let a=x(e,i,e=>!!e.rect&&ee(e.label?.trim()??``));if(!a?.rect)return;let o=L(n.rect,a.rect);if(!o)return;let s=I(e,i,o);b(t,n,{rect:s}),S(e,i,e=>{c(e.label?.trim()??``)&&b(t,e,{rect:s})})})}function I(e,n,r){let a=r;return S(e,n,e=>{let n=e.label?.trim()??``;!e.rect||!c(n)||i(r,e.rect)&&t(e.rect)<t(a)&&(a=e.rect)}),a}function L(e,t){let n=e.x+e.width,r=t.x+t.width,i={x:t.x,y:e.y,width:n-t.x,height:e.height};if(t.x>e.x&&d(t,i))return{...e,width:t.x-e.x};let a={x:e.x,y:e.y,width:r-e.x,height:e.height};if(r<n&&d(t,a))return{...e,x:r,width:n-r}}function R(e,t){P(e,(n,r,i)=>{u(n)&&l(n,z(e,i))&&t.suppressNode(n,z(e,i))})}function z(e,t){let n=[];return S(e,t,e=>{n.push(e)}),n}function he(e,t){let n=g(e),r=n?n.y+n.height:null;if(r!==null)for(let n=0;n<e.length;n+=1){let i=e[n];!i||!ge(i,r)||(t.suppressNode(i,[]),_e(i,t,r),S(e,n,e=>{t.suppressNode(e,[])}))}}function ge(e,t){return!e.rect||n(e.type??``)!==`keyboard`?!1:e.rect.y>=t}function _e(e,t,n){let r=typeof e.parentIndex==`number`?t.sourceNodesByIndex.get(e.parentIndex):void 0;for(;r?.rect&&r.rect.y>=n;)t.suppressNode(r,[]),r=typeof r.parentIndex==`number`?t.sourceNodesByIndex.get(r.parentIndex):void 0}function ve(e,t){for(let r=0;r<e.length;r+=1){let i=e[r];if(!i)continue;if(ye(i)){B(e,r,i,t);continue}if(!be(i))continue;let a=x(e,r,e=>n(e.type??``)===`searchfield`&&e.label===`Search`);a&&(t.suppressNode(i,[a]),xe(i,a,t),B(e,r,a,t))}}function ye(e){return n(e.type??``)===`searchfield`&&e.label===`Search`}function be(e){let t=n(e.type??``);return e.label===`Toolbar`&&(t===`toolbar`||t===`searchfield`)}function B(e,t,n,r){S(e,t,e=>{e.index!==n.index&&Se(e)&&r.suppressNode(e,[n])})}function xe(e,t,n){let r=e;for(;typeof r.parentIndex==`number`;){let e=n.sourceNodesByIndex.get(r.parentIndex);if(!e||e.label!==`Toolbar`)return;n.suppressNode(e,[t]),r=e}}function Se(e){let t=n(e.type??``);return t===`button`?!1:t===`image`||e.label===`Search`}function Ce(e,t){for(let n=0;n<e.length;n+=1){let r=e[n],i=r?.label?.trim();!r||t.isSuppressed(r)||!i||we(e,n,r,i,t)}}function we(e,t,r,i,a){let o=n(r.type??``);if(o===`statictext`||o===`link`){V(e,t,i,r,a);return}if(o!==`other`)return;let s=Te(e,t,i);if(s){a.suppressNode(r,[s]);return}V(e,t,i,r,a)}function Te(e,t,r){return x(e,t,e=>{let t=n(e.type??``);return(t===`link`||t===`searchfield`||p(e.type))&&e.label?.trim()===r})}function V(e,t,n,r,i){S(e,t,e=>{!i.semanticRepresentativeIndexes.has(e.index)&&ie(e,n)&&i.suppressNode(e,[r])})}function Ee(e,t){P(e,(n,r,i)=>{let a=x(e,i,e=>m(e)&&e.label?.trim()===r&&(d(e.rect,n.rect)||De(n,e)));a&&t.suppressNode(n,[a])})}function De(e,t){if(t.label?.trim()!==e.label?.trim())return!1;let r=n(t.type??``);return Oe(e,r)||r===`textfield`||ke(e,r,t)}function Oe(e,t){let n=e.label?.trim();return t===`button`&&(n===`Dismiss`||n===`Back`)}function ke(e,t,n){return t!==`button`||!e.rect||!n.rect?!1:e.rect.x===0&&e.rect.y===0&&e.rect.width>=300&&e.rect.height>=600&&n.rect.width<e.rect.width}function Ae(e,t){let r=C(e);for(let i of e){if(n(i.type??``)!==`other`||i.hittable===!0||i.label?.trim()||i.value?.trim()||!i.identifier?.trim())continue;let e=je(i,r);(e.length!==0||i.hittable===!1)&&t.suppressNode(i,e)}}function je(e,t){let n=[],r=new Set([e.index]),i=[...t.get(e.index)??[]];for(;i.length>0;){let e=i.pop();if(!e||r.has(e.index))continue;r.add(e.index),n.push(e);let a=t.get(e.index);a&&i.push(...a)}return n}function Me(e,t){he(e,t),Ae(e,t),ue(e,t),ve(e,t),Ee(e,t),F(e,t.replacements),R(e,t),Ce(e,t)}function Ne(e,t){for(let n=0;n<e.length;n+=1){let r=e[n],i=r?Pe(e,n,r,t):void 0;!r?.rect||!i||Le(e,n,r,i,t)}}function Pe(e,t,r,i){let a=r.label?.trim();if(n(r.type??``)!==`cell`||a&&!Fe(a,r.identifier)&&!o(a))return a;let s=v(e,t).find(Ie),c=s?.label?.trim();return!s||!c?a:(b(i.replacements,r,{label:c}),i.suppressNode(s,[r]),c)}function Fe(e,t){return t?.trim()===e&&/^[A-Z_$][A-Za-z0-9_$]*Cell$/.test(e)}function Ie(e){if(!e.label?.trim())return!1;let t=n(e.type??``);return t===`statictext`||t===`text`||t===`textview`}function Le(e,t,r,i,a){let o=n(r.type??``);if(o===`button`){H(v(e,t),i,a,r);return}if(o!==`cell`)return;let s=v(e,t);Re(s,r,i,a)||ze(s,r,i,a)}function Re(e,t,n,r){let i=e.find(e=>Ve(e,t,n));if(!i)return!1;let a=e.find(e=>U(e,t,n)),o=i.identifier?void 0:a?.identifier??t.identifier;return o&&b(r.replacements,i,{identifier:o}),r.suppressNode(t,[i]),Be(e,t,n,i,r),!0}function ze(e,t,n,r){let i=e.find(e=>U(e,t,n));if(!i){e.some(te)&&H(e,n,r,t);return}!t.identifier&&i.identifier&&b(r.replacements,t,{identifier:i.identifier}),r.suppressNode(i,[t]),H(e.filter(e=>e.index!==i.index),n,r,t)}function Be(e,t,n,r,i){for(let a of e)a.index!==r.index&&(U(a,t,n)||W(a,t)||He(a,r)||h(a,n))&&i.suppressNode(a,[r])}function H(e,t,n,r){for(let i of e)(h(i,t)||r&&W(i,r))&&n.suppressNode(i,r?[r]:[])}function U(e,t,r){if(n(e.type??``)!==`button`)return!1;let i=t.identifier?.trim(),a=e.identifier?.trim();return i&&a&&i===a?!0:e.label?.trim()===r&&d(e.rect,t.rect)}function W(e,t){return n(e.type??``)===`button`&&!e.label?.trim()&&!e.value?.trim()&&d(e.rect,t.rect)}function Ve(e,t,r){if(n(e.type??``)!==`switch`)return!1;let i=t.identifier?.trim(),a=e.identifier?.trim();return i&&a&&i===a?!0:e.label?.trim()===r}function He(e,t){if(n(e.type??``)!==`switch`||e.index===t.index)return!1;let r=e.label?.trim();return r===t.value?.trim()||r===`0`||r===`1`}const G=1.15;function Ue(t,n,r){let i=new Map(t.map((e,t)=>[e.index,t]));for(let[a,o]of t.entries()){let s=We(t,i,n,o,r);if(!s)continue;q(t,a,r);let c=J(s.shelfRect,2);for(let n of s.intermediateSiblings){if($e(n)||!n.rect||!e(n.rect,c))continue;let a=i.get(n.index);a!==void 0&&q(t,a,r)}}}function We(e,t,n,r,i){let a=Ge(r,n,i.sourceNodesByIndex);if(!a)return;let o=Je(e,t,a.siblings,a.position,a.parent);if(!(o<0))return{shelfRect:a.rect,intermediateSiblings:a.siblings.slice(a.position+1,o)}}function Ge(e,t,n){let r=Ye(e,K(t,e.index));if(!r)return;let i=qe(e,n);if(!i||!i.rect)return;let a=K(t,i.index),o=a.findIndex(t=>t.index===e.index);if(Ke(a,o,e,r))return{rect:r.rect,parent:i,siblings:a,position:o}}function K(e,t){return e.get(t)??[]}function Ke(e,t,n,r){if(t<1)return!1;let i=Xe(e,t,n);return i?!r.childActionsPresented||!Ze(i,r.actionButtons):!1}function qe(e,t){return typeof e.parentIndex==`number`?t.get(e.parentIndex):void 0}function Je(e,t,n,r,i){return n.findIndex((n,a)=>a>r&&Qe(e,t.get(n.index),n,i))}function Ye(e,t){if(!p(e.type)||!e.rect)return;let r=e.rect,a=t.filter(e=>n(e.type??``)===`button`&&e.rect);if(a.length===0&&e.hiddenContentBelow===!0)return{rect:r,childActionsPresented:!1,actionButtons:a};if(a.length<3)return;let o=a.map(e=>e.rect.x+e.rect.width/2);if(o.every((e,t)=>t===0||e>o[t-1]))return{rect:r,childActionsPresented:a.some(e=>i(r,e.rect)),actionButtons:a}}function Xe(e,t,n){if(!(!n.rect||t<1))for(let r=t-1;r>=0;--r){let t=e[r];if(!(!t.rect||!m(t))&&t.rect.x+t.rect.width/2<n.rect.x&&et(t.rect,J(n.rect,2)))return t}}function Ze(e,t){if(!e.rect||t.length===0)return!1;let n=Math.max(...t.map(e=>e.rect?.width??0)),r=Math.max(...t.map(e=>e.rect?.height??0));return e.rect.width>n*G||e.rect.height>r*G}function Qe(e,t,r,i){return t!==void 0&&n(r.type??``)===`other`&&d(r.rect,i.rect)&&!!x(e,t,m)}function q(e,t,n){let r=e[t];if(r){n.suppressNode(r,[]);for(let r of v(e,t))n.suppressNode(r,[])}}function $e(e){let t=n(e.type??``);return t===`textfield`||t===`securetextfield`||t===`searchfield`||t===`textview`}function J(e,t){return{x:e.x-t,y:e.y-t,width:e.width+t*2,height:e.height+t*2}}function et(e,t){return Math.max(e.y,t.y)<=Math.min(e.y+e.height,t.y+t.height)}function tt(e,t){let n=C(e);Ue(e,n,t),nt(e,n,t)}function nt(e,t,r){for(let i of e){if(n(i.type??``)!==`navigationbar`||!i.rect)continue;let e=t.get(i.index)??[],a=e.flatMap(t=>rt(t,e,i.rect));if(a.length!==1)continue;let{field:o,title:s,image:c,label:l}=a[0];b(r.replacements,o,{type:`Button`,label:l,enabled:!0,rect:st([c.rect,o.rect,s.rect])}),r.semanticRepresentativeIndexes.add(o.index),r.suppressNode(s,[o]),r.suppressNode(c,[o])}}function rt(e,t,n){let i=r(e);if(!it(e,i))return[];let a=X(t,e=>at(e,i)),o=X(t,Y);return a?.rect&&o?.rect&&ot(o.rect,e.rect,a.rect,n)?[{field:e,title:a,image:o,label:i}]:[]}function it(e,t){return n(e.type??``)===`textfield`&&e.enabled===!1&&!!e.rect&&!!t&&e.value?.trim()===t}function at(e,t){return n(e.type??``)===`statictext`&&e.label?.trim()===t&&!!e.rect}function Y(e){return n(e.type??``)===`image`&&!!e.identifier?.trim()&&!!e.rect}function X(e,t){let n=e.filter(t);return n.length===1?n[0]:void 0}function ot(e,t,n,r){let a=t.x-(e.x+e.width),o=n.x-(t.x+t.width);return i(r,e)&&i(r,t)&&i(r,n)&&a>=0&&a<=12&&o>=0&&o<=12&&Z(e,t)&&Z(t,n)}function Z(e,t){return Math.max(e.y,t.y)<=Math.min(e.y+e.height,t.y+t.height)}function st(e){let t=Math.min(...e.map(e=>e.x)),n=Math.min(...e.map(e=>e.y)),r=Math.max(...e.map(e=>e.x+e.width)),i=Math.max(...e.map(e=>e.y+e.height));return{x:t,y:n,width:r-t,height:i-n}}function ct(e,t){let r=C(e);for(let i of e){if(n(i.type??``)===`element(58)`){b(t.replacements,i,{type:`WebView`});continue}let e=lt(i,t.sourceNodesByIndex,r);if(e?.kind===`suppress`){t.suppressNode(i,[]);continue}e&&(b(t.replacements,i,{type:e.type,...e.type===`Heading`?{value:void 0}:{}}),t.semanticRepresentativeIndexes.add(i.index))}}function lt(e,t,r){if(n(e.type??``)!==`other`)return null;let i=f(e,t,ft),a=e.label?.trim();return!i||!a?null:dt(e,i,a)?{kind:`suppress`}:ut(e,a,r)?{kind:`semantic`,type:Q(e.value)?`Heading`:`StaticText`}:null}function ut(e,t,r){let i=r.get(e.index);if(i?.length!==1)return!1;let a=i[0];return n(a.type??``)===`statictext`&&a.label?.trim()===t&&!r.has(a.index)}function dt(e,t,n){return e.parentIndex===t.index&&t.label?.trim()===n&&!Q(e.value)}function ft(e){let t=n(e.type??``);return t===`webview`||t===`element(58)`}function Q(e){return/^[1-6]$/.test(e?.trim()??``)}const pt=[ct,tt,ae,Ne,Me];function mt(e){if(e.length===0)return{nodes:e,presentedIndexesBySourceIndex:new Map};let t=new Map,n=new Map,r=new Set,i=new Map(e.map(e=>[e.index,e])),a=new Set,o={replacements:t,semanticRepresentativeIndexes:r,sourceNodesByIndex:i,isSuppressed:e=>a.has(e.index),suppressNode(e,t){if(a.add(e.index),t.length===0)return;let r=n.get(e.index)??new Set;for(let e of t)r.add(e.index);n.set(e.index,r)}};for(let t of pt)t(e,o);if(a.size===0&&t.size===0)return{nodes:e,presentedIndexesBySourceIndex:new Map(e.map(e=>[e.index,[e.index]]))};let s=e.filter(e=>!a.has(e.index)).map(e=>t.get(e.index)??e),c=_(s,a,e),l=new Map(s.map((e,t)=>[e.index,c[t].index]));return{nodes:c,presentedIndexesBySourceIndex:new Map(e.map(e=>[e.index,$(e.index,l,n)]))}}function $(e,t,n,r=new Set){let i=t.get(e);if(i!==void 0)return[i];if(r.has(e))return[];r.add(e);let a=new Set;for(let i of n.get(e)??[])for(let e of $(i,t,n,r))a.add(e);return[...a].sort((e,t)=>e-t)}export{mt as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as e}from"./tool-provider.js";
|
|
1
|
+
import{a as e}from"./tool-provider.js";function t(e){let{waitMs:t,signal:n,stop:r,cancelled:i}=e;return new Promise((e,a)=>{let o=()=>l(()=>a(i())),s=()=>l(e),c=setTimeout(()=>l(e),t);function l(e){clearTimeout(c),n?.removeEventListener(`abort`,o),r?.removeEventListener(`abort`,s),e()}n?.addEventListener(`abort`,o,{once:!0}),r?.addEventListener(`abort`,s,{once:!0}),n?.aborted?o():r?.aborted&&s()})}function n(e){let t=e.now??Date.now,n=e.waitGrant??`every-caller`,r=new Map,i=(n,i)=>{let a={status:`pending`,value:void 0,error:void 0,settledAtMs:t(),waitSpent:!1,controller:new AbortController,settled:void 0},o=()=>{};a.settled=new Promise(e=>{o=e}),r.set(n,a);let s=(i,s)=>{a.status=i,i===`ready`?a.value=s:a.error=s,a.settledAtMs=t(),(i===`ready`||e.retryAfterMs===void 0)&&r.get(n)===a&&r.delete(n),o()};try{i(a.controller.signal).then(e=>s(`ready`,e),e=>s(`failed`,e))}catch(e){s(`failed`,e)}return a},a=(n,a)=>{let o=r.get(n);if(!o)return i(n,a);if(o.status!==`failed`)return o;let s=t()-o.settledAtMs;return e.retryAfterMs===void 0||s>=e.retryAfterMs?i(n,a):o};return{value:async(t,r)=>{let i=a(t,r.start);if(i.status===`pending`&&(n===`every-caller`||!i.waitSpent)){i.waitSpent=!0;let t=new AbortController,n=r.wait(e.waitMs,t.signal);n.catch(()=>{});try{await Promise.race([i.settled,n])}finally{t.abort()}}if(i.status===`ready`)return i.value;throw i.status===`failed`?i.error:r.pending()},close:()=>{let e=[...r.values()];r.clear();for(let t of e)t.controller.abort()}}}async function r(t,n){let r=await e(`ps`,[`-p`,String(t),`-o`,`lstart=`],{allowFailure:!0,signal:n.signal,timeoutMs:n.timeoutMs});return r.exitCode===0&&r.stdout.trim()||null}export{n,t as r,r as t};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agent-device",
|
|
3
|
-
"version": "0.21.
|
|
3
|
+
"version": "0.21.5",
|
|
4
4
|
"description": "Mobile app automation and verification for AI coding agents. CLI, MCP server, and typed Node.js API for iOS, Android, HarmonyOS, TV, web, macOS, and Linux.",
|
|
5
5
|
"mcpName": "io.github.callstack/agent-device",
|
|
6
6
|
"license": "MIT",
|
package/server.json
CHANGED
|
@@ -7,12 +7,12 @@
|
|
|
7
7
|
"url": "https://github.com/callstack/agent-device",
|
|
8
8
|
"source": "github"
|
|
9
9
|
},
|
|
10
|
-
"version": "0.21.
|
|
10
|
+
"version": "0.21.5",
|
|
11
11
|
"packages": [
|
|
12
12
|
{
|
|
13
13
|
"registryType": "npm",
|
|
14
14
|
"identifier": "agent-device",
|
|
15
|
-
"version": "0.21.
|
|
15
|
+
"version": "0.21.5",
|
|
16
16
|
"transport": {
|
|
17
17
|
"type": "stdio"
|
|
18
18
|
},
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
fdf9f5946ee579efe8ef31eb43865d19706dba5f78c75bf908a0e3daf6b7a163 agent-device-android-ime-helper-0.21.4.apk
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
9fae32c14211310223ba7f6cdf19433d03f01d01e5dc24d1e5b3294cd80ad501 agent-device-android-snapshot-helper-0.21.4.apk
|