agent-device 0.20.8 → 0.20.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +94 -31
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.20.8.apk → agent-device-android-ime-helper-0.20.9.apk} +0 -0
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.20.9.apk.sha256 +1 -0
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.20.8.manifest.json → agent-device-android-ime-helper-0.20.9.manifest.json} +4 -4
- package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.20.8.apk → agent-device-android-snapshot-helper-0.20.9.apk} +0 -0
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.20.9.apk.sha256 +1 -0
- package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.20.8.manifest.json → agent-device-android-snapshot-helper-0.20.9.manifest.json} +6 -6
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.h +3 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.m +13 -7
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AXSnapshotFallback.swift +4 -112
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+FlatSnapshotFiltering.swift +9 -1
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+PrivateAXPresentation.swift +90 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +46 -10
- package/dist/src/agent-browser-tool.js +1 -1
- package/dist/src/agent-device-client.js +2 -2
- package/dist/src/android-adb.d.ts +5 -5
- package/dist/src/android-adb.js +1 -1
- package/dist/src/android.js +1 -1
- package/dist/src/app-helpers.js +1 -1
- package/dist/src/app-lifecycle.js +6 -7
- package/dist/src/app-lifecycle2.js +2 -2
- package/dist/src/app-log-reconnect.js +1 -1
- package/dist/src/app-log-runtime.js +3 -3
- package/dist/src/app-resolution.js +2 -2
- package/dist/src/app-state.js +2 -0
- package/dist/src/appearance.js +1 -0
- package/dist/src/apps.js +5 -5
- package/dist/src/artifacts.d.ts +1 -1
- package/dist/src/audio-probe.js +1 -1
- package/dist/src/auth-session.js +1 -1
- package/dist/src/backend-snapshot-options.js +1 -0
- package/dist/src/boot-diagnostics.js +2 -2
- package/dist/src/bounds.js +1 -0
- package/dist/src/byte-limit-stream.js +1 -0
- package/dist/src/cancel.js +1 -0
- package/dist/src/cli-config.js +1 -1
- package/dist/src/cli-help.js +25 -20
- package/dist/src/cli.js +6 -6
- package/dist/src/client-metro.js +1 -1
- package/dist/src/command-catalog.js +1 -0
- package/dist/src/command-metadata.js +1 -1
- package/dist/src/command-schema.js +1 -1
- package/dist/src/command-surface.js +1 -1
- package/dist/src/config.js +1 -0
- package/dist/src/connection-runtime.js +1 -1
- package/dist/src/connection.js +3 -3
- package/dist/src/contracts.js +1 -1
- package/dist/src/debug-symbols.js +3 -3
- package/dist/src/device-claim-inspection.js +1 -1
- package/dist/src/device-input-state.js +1 -1
- package/dist/src/device-ready.js +1 -1
- package/dist/src/device2.js +2 -2
- package/dist/src/dispatch.js +1 -1
- package/dist/src/entities.js +1 -1
- package/dist/src/find.js +1 -1
- package/dist/src/finders.js +1 -1
- package/dist/src/generic-settle.js +1 -1
- package/dist/src/generic.js +1 -1
- package/dist/src/harmonyos.js +1 -1
- package/dist/src/hdc.js +1 -1
- package/dist/src/helper-package-install.js +1 -0
- package/dist/src/helper.js +2 -2
- package/dist/src/host-process.js +1 -1
- package/dist/src/ime-lifecycle.js +2 -9
- package/dist/src/ime-recovery-marker.js +1 -0
- package/dist/src/index.d.ts +24 -15
- package/dist/src/index.js +1 -1
- package/dist/src/input-actions.js +4 -4
- package/dist/src/input-actions2.js +1 -1
- package/dist/src/input-actions3.js +1 -1
- package/dist/src/install-artifact.js +1 -1
- package/dist/src/install-artifact2.js +1 -1
- package/dist/src/install-source2.js +1 -1
- package/dist/src/interaction-common.js +1 -0
- package/dist/src/interaction-runtime.js +1 -1
- package/dist/src/interaction-snapshot.js +1 -1
- package/dist/src/interaction.js +1 -1
- package/dist/src/interaction2.js +1 -0
- package/dist/src/interactor.js +2 -2
- package/dist/src/interactor2.js +1 -1
- package/dist/src/interactors.js +1 -0
- package/dist/src/internal/bin.js +1 -1
- package/dist/src/internal/daemon.js +4 -7
- package/dist/src/internal/png-worker.js +1 -1
- package/dist/src/inventory.js +1 -1
- package/dist/src/keyed-lock.js +1 -0
- package/dist/src/lease-context.js +1 -1
- package/dist/src/lease.js +1 -1
- package/dist/src/limrun-runtime-dependencies.js +1 -1
- package/dist/src/limrun.d.ts +3 -1
- package/dist/src/limrun.js +1 -1
- package/dist/src/linux.js +1 -1
- package/dist/src/location-coordinates.js +1 -0
- package/dist/src/logcat.js +1 -1
- package/dist/src/manifest.js +1 -1
- package/dist/src/observability.js +1 -0
- package/dist/src/owner-identity.js +1 -1
- package/dist/src/perf.js +4 -0
- package/dist/src/physical-device-control.js +1 -1
- package/dist/src/platform-runtime-app-log-process.js +1 -1
- package/dist/src/platform-runtime-host.js +1 -1
- package/dist/src/platform-runtime-network-web-transport.js +1 -1
- package/dist/src/platform-runtime-open-target.js +1 -0
- package/dist/src/platform-runtime-operation-host.js +4 -4
- package/dist/src/platform-runtime-runtime-hints.js +2 -0
- package/dist/src/platform-runtime-screen-recording-apple-runner-host.js +1 -1
- package/dist/src/platform-runtime-screen-recording-apple-runner-transport.js +1 -1
- package/dist/src/platform-runtime-screen-recording-apple-transport.js +1 -1
- package/dist/src/platform-runtime-screen-recording-finalizer-host.js +1 -1
- package/dist/src/platform-runtime-screen-recording-web-host.js +1 -1
- package/dist/src/platform-runtime.js +1 -1
- package/dist/src/platform-runtime2.js +1 -0
- package/dist/src/plist.js +1 -1
- package/dist/src/png-resize.js +1 -0
- package/dist/src/png-worker-contract.js +1 -1
- package/dist/src/prepare-kind.js +13 -13
- package/dist/src/process-lock.js +1 -1
- package/dist/src/project-runtime.js +1 -0
- package/dist/src/provider-webdriver.js +1 -1
- package/dist/src/provider.js +1 -0
- package/dist/src/proxy.js +1 -1
- package/dist/src/react-native.js +1 -1
- package/dist/src/record-runtime.js +1 -1
- package/dist/src/record-trace.js +1 -1
- package/dist/src/recording-export-quality.js +1 -0
- package/dist/src/registry.js +29 -26
- package/dist/src/remote-config2.js +1 -1
- package/dist/src/replay.js +1 -1
- package/dist/src/reporting.js +3 -3
- package/dist/src/rolldown-runtime.js +1 -0
- package/dist/src/runner-client.js +1 -0
- package/dist/src/runner-disposal.js +1 -1
- package/dist/src/runner-lease.js +1 -1
- package/dist/src/runner-sequence.js +1 -1
- package/dist/src/runtime-transport.js +1 -1
- package/dist/src/runtime.js +3 -3
- package/dist/src/runtime2.js +4 -3
- package/dist/src/runtime3.js +1 -3
- package/dist/src/runtime4.js +3 -1
- package/dist/src/runtime5.js +1 -1
- package/dist/src/runtime6.js +1 -1
- package/dist/src/runtime7.js +1 -1
- package/dist/src/runtime8.js +1 -0
- package/dist/src/runtime9.js +1 -0
- package/dist/src/scoped-provider.js +1 -0
- package/dist/src/screenshot-density.js +1 -0
- package/dist/src/screenshot-geometry.js +1 -0
- package/dist/src/screenshot-result.js +4 -4
- package/dist/src/screenshot.js +1 -1
- package/dist/src/sdk-android-adb.d.ts +20 -2
- package/dist/src/sdk-android-adb.js +3 -3
- package/dist/src/sdk-batch-runner.js +3 -3
- package/dist/src/sdk-contracts.d.ts +3 -3
- package/dist/src/sdk-contracts.js +2 -2
- package/dist/src/sdk-device.js +1 -1
- package/dist/src/sdk-finders.js +1 -1
- package/dist/src/sdk-io.js +1 -1
- package/dist/src/sdk-remote-config.js +1 -1
- package/dist/src/sdk-selectors.d.ts +19 -19
- package/dist/src/sdk-selectors.js +1 -1
- package/dist/src/sdk.js +1 -0
- package/dist/src/selector-runtime.js +1 -1
- package/dist/src/selectors.d.ts +1 -1
- package/dist/src/selectors.js +1 -1
- package/dist/src/server.js +2 -2
- package/dist/src/session-target-evidence.js +1 -1
- package/dist/src/session.js +1 -30
- package/dist/src/session2.js +28 -0
- package/dist/src/setting-state.js +1 -1
- package/dist/src/shared.js +1 -1
- package/dist/src/simctl.js +1 -0
- package/dist/src/simulator-state.js +1 -0
- package/dist/src/simulator.js +1 -1
- package/dist/src/snapshot-runtime.js +1 -1
- package/dist/src/snapshot-session.js +1 -1
- package/dist/src/snapshot.js +8 -1
- package/dist/src/snapshot2.js +1 -1
- package/dist/src/snapshot3.js +1 -0
- package/dist/src/src.js +1 -1
- package/dist/src/src2.js +1 -2
- package/dist/src/src3.js +2 -1
- package/dist/src/string-enum.js +1 -0
- package/dist/src/tool-provider.js +3 -3
- package/dist/src/tool-provider2.js +1 -1
- package/dist/src/update-check.js +1 -1
- package/dist/src/verdict.js +1 -0
- package/dist/src/verified-file.js +1 -0
- package/dist/src/version.js +1 -1
- package/dist/src/video.js +1 -1
- package/dist/src/web.js +1 -1
- package/package.json +8 -4
- package/server.json +3 -3
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.20.8.apk.sha256 +0 -1
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.20.8.apk.sha256 +0 -1
- package/dist/src/interaction-touch-reference-frame.js +0 -1
- package/dist/src/notifications.js +0 -1
- package/dist/src/platform-runtime-toolchain-host.js +0 -1
- package/dist/src/text-surface.js +0 -1
- package/dist/src/tool-provider3.js +0 -1
package/dist/src/src2.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
import{_ as e}from"./sdk-contracts.js";import{H as t,I as n,L as r,W as i,z as a}from"./sdk-batch-runner.js";import{T as o,d as s,o as c}from"./sdk-device.js";const l=4096;function u(e){return f(e,{seen:new WeakSet,nodes:0},0)}function d(e){return Object.freeze(Object.fromEntries(Object.entries(e).map(([e,t])=>[e,m(t)])))}function f(e,t,n){if(!te(e)||n>32||t.seen.has(e))return!1;t.seen.add(e),t.nodes+=1;let r=t.nodes<=l&&Object.values(e).every(e=>p(e,t,n+1));return t.seen.delete(e),r}function p(e,t,n){return ne(e)?!0:n>32?!1:Array.isArray(e)?ee(e,t,n):f(e,t,n)}function ee(e,t,n){if(t.seen.has(e))return!1;t.seen.add(e),t.nodes+=1;let r=t.nodes<=l&&e.every(e=>p(e,t,n+1));return t.seen.delete(e),r}function te(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ne(e){return e===null?!0:typeof e==`number`?Number.isFinite(e):typeof e==`string`||typeof e==`boolean`}function m(e){return Array.isArray(e)?Object.freeze(e.map(m)):typeof e==`object`&&e?d(e):e}function h(e){if(!x(e))return g(`Durable resource envelope must be an object`);let t=e.envelopeVersion;if(!b(t))return g(`Durable resource envelopeVersion must be a non-negative integer`);if(t!==1)return{status:`unreattachable`,reason:`descriptor-version-unsupported`,message:`Unsupported durable resource envelope version: ${t}`,version:t};if(!y(e.resourceKind))return g(`Durable resource resourceKind must be a non-empty string`);if(!y(e.sessionId))return g(`Durable resource sessionId must be a non-empty string`);let n=oe(e.device);if(!n)return g(`Durable resource device identity is invalid`);let r=ae(e.owner);if(!r)return g(`Durable resource owner reference is invalid`);if(r.kind===`local-family`&&r.family!==n.family)return g(`Durable resource local owner does not match the device family`);let i=fe(e.fence);if(!i)return g(`Durable resource ownership fence is invalid`);if(!me(e.lifecycle))return g(`Durable resource lifecycle state is invalid`);let a=pe(e.descriptor);return a?e.metadata!==void 0&&!u(e.metadata)?g(`Durable resource metadata must be a JSON object`):{status:`decoded`,envelope:Object.freeze({envelopeVersion:1,resourceKind:e.resourceKind,sessionId:e.sessionId,device:n,owner:r,fence:i,lifecycle:e.lifecycle,descriptor:a,...e.metadata===void 0?{}:{metadata:d(e.metadata)}})}:g(`Durable resource descriptor is invalid`)}function re(e,t){return Object.freeze({version:e.version,body:d(e.encode(t))})}function ie(e){let t=h({envelopeVersion:1,...e});if(t.status!==`decoded`)throw TypeError(t.message);return t.envelope}function g(e){return{status:`unreattachable`,reason:`descriptor-invalid`,message:e}}function ae(e){return x(e)?e.kind===`local-family`&&s(e.family)?r(e.family):e.kind===`provider-runtime`&&y(e.provider)&&y(e.instance)?a(e.provider,e.instance):null:null}function oe(e){if(!x(e))return null;let t=ce(e.id),n=_(e.family),r=v(e.kind),i=le(e.target);return!t||!n||!r||i===null||!ue(e,n,r)?null:se(e,t,n,r,i)}function se(e,t,n,r,i){return Object.freeze({id:t,family:n,...e.appleOs===void 0?{}:{appleOs:e.appleOs},kind:r,...i===void 0?{}:{target:i},...e.iosPhysicalDeviceBackend===void 0?{}:{iosPhysicalDeviceBackend:e.iosPhysicalDeviceBackend}})}function ce(e){return y(e)?e:null}function _(e){return s(e)?e:null}function v(e){return he(e)?e:null}function le(e){if(e!==void 0)return ge(e)?e:null}function ue(e,t,n){if(t===`apple`){if(!c(e.appleOs))return!1}else if(e.appleOs!==void 0||e.iosPhysicalDeviceBackend!==void 0)return!1;return de(e.iosPhysicalDeviceBackend,n)}function de(e,t){return e===void 0?!0:t===`device`?e===`coredevice`||e===`xctest`:!1}function fe(e){return!x(e)||!y(e.token)||!b(e.generation)?null:Object.freeze({token:e.token,generation:e.generation})}function pe(e){return!x(e)||!b(e.version)||!u(e.body)?null:Object.freeze({version:e.version,body:d(e.body)})}function me(e){return e===`open`||e===`completed`}function he(e){return e===`simulator`||e===`emulator`||e===`device`}function ge(e){return e===`mobile`||e===`tv`||e===`desktop`}function y(e){return typeof e==`string`&&e.trim().length>0}function b(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0}function x(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function S(e,t){if(e.resourceKind!==t.resourceKind)return{status:`unreattachable`,reason:`descriptor-invalid`,message:`Durable resource kind ${e.resourceKind} does not match ${t.resourceKind}`};if(e.descriptor.version!==t.version)return{status:`unreattachable`,reason:`descriptor-version-unsupported`,message:`Unsupported ${t.resourceKind} descriptor version: ${e.descriptor.version}`,version:e.descriptor.version};try{let n=t.decode(e.descriptor.body);return n.status===`decoded`?n:{status:`unreattachable`,reason:`descriptor-invalid`,message:n.message}}catch(e){return{status:`unreattachable`,reason:`descriptor-invalid`,message:e instanceof Error?e.message:`Descriptor codec rejected the body`}}}function C(e,t){return Object.freeze({pendingHandle:new i(e),envelope:t})}function w(e){return Object.freeze({appLogReattach:async({envelope:t})=>{let n=S(t,e.codec);return n.status===`unreattachable`?n:await e.reattach(n.descriptor,T(t))},appLogCleanup:async({envelope:t})=>{let n=S(t,e.codec);return n.status===`decoded`?await e.cleanup(n.descriptor,T(t)):{status:`cleanup-pending`,reason:`manual-recovery-required`,message:n.message}}})}function T(e){return Object.freeze({sessionId:e.sessionId,fence:e.fence})}function _e(e){if(typeof e!=`object`||!e||Array.isArray(e))return{status:`invalid`,message:`App-log process marker must be an object`};let t=e;return!Number.isInteger(t.pid)||Number(t.pid)<=0?{status:`invalid`,message:`App-log process marker pid must be a positive integer`}:typeof t.startTime!=`string`||t.startTime.trim().length===0?{status:`invalid`,message:`App-log process marker startTime must be a non-empty string`}:typeof t.command!=`string`||t.command.trim().length===0?{status:`invalid`,message:`App-log process marker command must be a non-empty string`}:{status:`decoded`,marker:Object.freeze({pid:Number(t.pid),startTime:t.startTime,command:t.command})}}function ve(e){let t,n,r,i=()=>n??=e.forceCleanup();return Object.freeze({inspect:()=>e.inspect(),finish:()=>t??=e.finish(),forceCleanup:i,[Symbol.asyncDispose]:async()=>{r??=i().then(ye),await r}})}function E(e){return ve({inspect:e.inspect,finish:e.finish,forceCleanup:async()=>{let t=await e.finish();return t.status===`completed`?{status:`cleaned`}:{status:`cleanup-pending`,reason:t.reason,message:t.message}}})}function ye(t){if(!n(t))throw new e(`COMMAND_FAILED`,t.message??`Durable resource cleanup could not be confirmed`,{reason:t.reason,retriable:t.reason!==`ownership-fence-lost`,hint:t.reason===`ownership-fence-lost`?`Use the current resource owner or recovery record before retrying cleanup.`:`Keep the recovery record and retry cleanup through the exact runtime owner.`})}function be(e,t){let n=D(e),r,i,a,o=()=>r??=t.finish(n),s=()=>i??=r?r.then(async e=>e.status===`completed`?{status:`cleaned`}:await t.forceCleanup(n),async()=>await t.forceCleanup(n)):t.forceCleanup(n);return Object.freeze({inspect:()=>n,appendGestureEvents:e=>{e.length===0||r||i||(n=D({...n,gestureEvents:[...n.gestureEvents,...e]}))},setTouchReferenceFrame:e=>{r||i||(n=D({...n,...e?{touchReferenceFrame:e}:{}}))},setRunnerSessionId:e=>{r||i||e.trim().length===0||(n=D({...n,runnerSessionId:e}))},invalidate:e=>{r||i||n.invalidatedReason||(n=D({...n,invalidatedReason:e}))},finish:o,forceCleanup:s,[Symbol.asyncDispose]:async()=>{a??=s().then(xe),await a}})}function D(e){return Object.freeze({...e,gestureEvents:Object.freeze([...e.gestureEvents])})}function xe(t){if(!n(t))throw new e(`COMMAND_FAILED`,t.message??`Screen recording cleanup could not be confirmed`,{reason:t.reason,retriable:t.reason!==`ownership-fence-lost`,hint:t.reason===`ownership-fence-lost`?`Use the current recording owner or recovery record before retrying cleanup.`:`Keep the recovery record and retry cleanup through the exact runtime owner.`})}function O(e,t,n=e.showTouches){return Object.freeze({status:`completed`,result:Object.freeze({backend:e.backend,outPath:e.outPath,...e.clientOutPath===void 0?{}:{clientOutPath:e.clientOutPath},startedAt:e.startedAt,completedAt:Date.now(),scope:e.scope,showTouches:n,recordOnlySession:e.recordOnlySession,...e.activeSessionApp===void 0?{}:{activeSessionApp:e.activeSessionApp},...t})})}function k(t,n,r){let i=A(t,n);if(i.length>0)throw new e(`INVALID_ARGS`,r(i))}function A(e,t){return Object.freeze([...t.scopes.includes(e.scope)?[]:[`--scope`],...t.fps||e.fps===void 0?[]:[`--fps`],...t.exportQuality||e.exportQuality===void 0?[]:[`--quality`],...t.hideTouches||!e.hideTouchesRequested?[]:[`--hide-touches`]])}async function j(e,t){let n=await N(e,t);if(n.status===`missing`)return{status:`missing`};if(n.status===`invalid`)return{status:`unreattachable`,reason:`ownership-fence-lost`,message:n.message};let r=await e.processes.inspect(n.marker);return r===`missing`?(t&&await e.processes.clearMarker(t),{status:`missing`}):r===`ownership-lost`?{status:`unreattachable`,reason:`ownership-fence-lost`}:{status:`unreattachable`,reason:`transport-not-reattachable`}}async function M(e,t){if(!t)return{status:`cleanup-pending`,reason:`manual-recovery-required`,message:`App-log process marker path is missing`};let n=await N(e,t);if(n.status===`missing`)return{status:`already-missing`};if(n.status===`invalid`)return{status:`cleanup-pending`,reason:`manual-recovery-required`,message:n.message};let r=await e.processes.inspect(n.marker);if(r===`ownership-lost`)return P();if(r===`missing`)return await e.processes.clearMarker(t),{status:`already-missing`};let i=await e.processes.terminate(n.marker);return i===`ownership-lost`?P():(await e.processes.clearMarker(t),{status:i===`terminated`?`cleaned`:`already-missing`})}async function N(e,t){return t?await e.processes.readMarker(t):{status:`invalid`,message:`App-log process marker path is missing`}}function P(){return{status:`cleanup-pending`,reason:`ownership-fence-lost`}}async function Se(e){let t=e.initialProcess;for(;!e.stopped();){if(t){await Ce(e,t),t=void 0,await Ae(e);continue}let n=await je(e);if(n.status===`stopped`)return;n.status!==`waiting`&&(t=n.process)}}async function Ce(e,t){let{process:n}=t;e.setActive(n);try{e.setState(`active`),await we(e,t)}finally{await F(e,n)}}async function we(e,t){let n=Te(t.process);try{await Ee(e,t,n),await Oe(e,t.process,n),await ke(n.outcome)}finally{n.controller.abort()}}function Te(e){let t=new AbortController,n=!1,r=()=>{n=!0,t.abort()};return{controller:t,outcome:e.wait.then(()=>(r(),{status:`exited`}),e=>(r(),{status:`failed`,error:e})),settled:()=>n}}async function Ee(e,t,n){for(;!e.stopped()&&!n.settled();){if(!await De(e,n))return;let r=await e.resolvePid();if(e.stopped())return;if(r!==t.pid){await t.process.terminate();return}}}async function De(e,t){try{await e.sleep(500,t.controller.signal)}catch(e){if(!t.settled())throw e}return!t.settled()}async function Oe(e,t,n){e.stopped()&&!n.settled()&&await t.terminate()}async function ke(e){let t=await e;if(t.status===`failed`)throw t.error}async function Ae(e){e.stopped()||(e.setState(`recovering`),await e.sleep(500))}async function je(e){let t=await e.resolvePid();if(e.stopped())return{status:`stopped`};if(!t)return e.setState(`recovering`),await e.sleep(1e3),{status:`waiting`};let n=await e.startProcess(t);return e.setActive(n),e.stopped()?(await Me(e,n),{status:`stopped`}):{status:`started`,process:{pid:t,process:n}}}async function Me(e,t){try{await t.terminate(),await t.wait}finally{await F(e,t)}}async function F(e,t){try{await t[Symbol.asyncDispose]()}finally{e.setActive(void 0)}}async function Ne(e){let t=await e.resolvePid(e.setupSignal);e.setupSignal.throwIfAborted();let n=await e.host.outputs.openAppend(e.outputPath),r=`recovering`,i=!1,a;try{if(e.setupSignal.throwIfAborted(),t){e.setupSignal.throwIfAborted();let i=new AbortController,o=()=>i.abort(e.setupSignal.reason);e.setupSignal.addEventListener(`abort`,o,{once:!0});try{a=await e.processStart({command:e.command(t),output:n,markerPath:e.pidPath},i.signal)}finally{e.setupSignal.removeEventListener(`abort`,o)}e.setupSignal.throwIfAborted(),r=`active`}}catch(e){throw await I([async()=>await a?.terminate(),async()=>{await a?.wait},async()=>await a?.[Symbol.asyncDispose](),async()=>await n[Symbol.asyncDispose]()]),e}let o=Se({initialProcess:a&&t?{pid:t,process:a}:void 0,stopped:()=>i,setActive:e=>{a=e},setState:e=>{r=e},resolvePid:async()=>await e.resolvePid(),startProcess:async t=>await e.processStart({command:e.command(t),output:n,markerPath:e.pidPath}),sleep:async(t,n)=>await e.host.clock.sleep(t,n)}).catch(()=>{r=`failed`}),s,c=async()=>s??=Pe({options:e,monitor:o,active:()=>a,stop:()=>{i=!0},setState:e=>{r=e},output:n}),l=e.host.clock.now();return E({inspect:()=>({backend:e.backend,state:r,startedAt:l}),finish:c})}async function Pe(e){return e.stop(),(await I([async()=>await e.active()?.terminate(),async()=>await e.monitor,async()=>await e.output[Symbol.asyncDispose]()])).length>0?(e.setState(`failed`),{status:`cleanup-pending`,reason:`transport-failed`,message:e.options.cleanupFailureMessage}):(e.setState(`ended`),{status:`completed`,result:{backend:e.options.backend,outputPath:e.options.outputPath,completedAt:e.options.host.clock.now()}})}async function I(e){let t=[];for(let n of e)try{await n()}catch(e){t.push(e)}return t}function L(e,t,n){let r=e.artifacts.resolveSession(t);return n.outputPath===r.outputPath&&(n.pidPath===void 0||n.pidPath===r.pidPath)}function R(t,n){if(!L(t,n.sessionId,n))throw new e(`INVALID_ARGS`,`App-log paths do not match the owning session`)}const z=Object.freeze({available:!0});async function Fe(e,t,n){let r=(await e.commands.run(t,n)).stdout.trim().split(/\s+/)[0]??``;return/^\d+$/.test(r)?r:``}function Ie(n,i){let a=r(i.family);return Object.freeze({owner:a,ownsDevice:e=>e.platform===i.family,bind:async r=>{if(r.intent.kind===`exact-owner`&&!t(r.intent.owner,a))throw new e(`UNSUPPORTED_OPERATION`,`${i.label} app-log owner identity does not match`);if(r.device.platform!==i.family)throw new e(`UNSUPPORTED_PLATFORM`,`${i.label} app-log owner cannot bind ${r.device.platform}`);let o=await n.processTransports.resolve(r.device);return Le(n,r.device,r.scope.signal,o,a,i)},shutdown:async()=>void 0})}function Le(e,t,n,r,i,a){let o=w({codec:a.codec,reattach:async(t,n)=>L(e,n.sessionId,t)?await j(e,t.pidPath):{status:`unreattachable`,reason:`descriptor-invalid`,message:`${a.label} app-log descriptor paths do not match the owning session`},cleanup:async(t,n)=>L(e,n.sessionId,t)?await M(e,t.pidPath):{status:`cleanup-pending`,reason:`ownership-fence-lost`,message:`${a.label} app-log descriptor paths do not match the owning session`}}),s=Object.freeze({appLogInspect:async()=>({backend:a.backend}),appLogDoctor:async({appBundleId:r})=>await a.doctor({host:e,device:t,signal:n},r),...r.start?{appLogStart:async o=>await ze(e,t,n,r,i,o,a)}:{},...o});return Object.freeze({device:t,owner:i,facts:Re(t,r,a),operations:s,[Symbol.asyncDispose]:async()=>void 0})}function Re(e,t,n){let r=t.start?z:{available:!1,reason:`owner-capability-missing`,hint:n.startUnavailableHint};return Object.freeze({device:{family:n.family,kind:e.kind,...e.target===void 0?{}:{target:e.target},providerMode:t.mode},operations:{appLogInspect:z,appLogDoctor:z,appLogStart:r,appLogReattach:z,appLogCleanup:z}})}async function ze(t,n,r,i,a,o,s){if(!i.start)throw new e(`UNSUPPORTED_OPERATION`,s.startUnavailableHint);R(t,o);let c=t.artifacts.resolveSession(o.sessionId),l={host:t,device:n,signal:r,input:o,artifacts:c,transport:i};s.validateStart?.(l),r.throwIfAborted();let u=await s.process(l);r.throwIfAborted();let d=await Ne({host:t,backend:s.backend,outputPath:c.outputPath,pidPath:c.pidPath,processStart:i.start,setupSignal:r,resolvePid:u.resolvePid,command:u.command,cleanupFailureMessage:s.cleanupFailureMessage}),f=s.descriptor({artifacts:c,transport:i});return C(d,s.envelope({input:o,device:n,owner:a,descriptor:f}))}async function Be(e,t){try{return await e()}catch{if(t?.aborted)throw t.reason;return!1}}function Ve(e){return e.exitCode===0}function He(n,i){let a=r(n),o=V(i);return Object.freeze({owner:a,ownsDevice:e=>e.platform===n,bind:async r=>{if(r.intent.kind===`exact-owner`&&!t(r.intent.owner,a))throw new e(`UNSUPPORTED_OPERATION`,`${n} platform runtime owner identity does not match`);if(r.device.platform!==n)throw new e(`UNSUPPORTED_PLATFORM`,`${n} platform runtime cannot bind ${r.device.platform}`);return B(r.device,a,o)},shutdown:async()=>void 0})}function B(e,t,n){let{appLog:r,network:i,screenRecording:a}=V(n),s=Object.freeze({device:{...o(e),providerMode:t.kind===`local-family`?`local`:`provider-runtime`},operations:{appLogInspect:r,appLogDoctor:r,appLogStart:r,appLogReattach:r,appLogCleanup:r,networkDump:i,screenRecordingStart:a,screenRecordingReattach:a,screenRecordingCleanup:a}});return Object.freeze({device:e,owner:t,facts:s,operations:Object.freeze({}),[Symbol.asyncDispose]:async()=>void 0})}function V(e){return Object.freeze({appLog:Object.freeze({...e.appLog}),network:Object.freeze({...e.network}),screenRecording:Object.freeze({...e.screenRecording??e.network})})}function H(e){for(let t of[/\bstatus(?:Code)?["'=: ]+([1-5]\d{2})\b/i,/\bresponse(?:\s+code)?["'=: ]+([1-5]\d{2})\b/i,/\bHTTP\/[0-9.]+\s+([1-5]\d{2})\b/i]){let n=t.exec(e);if(!n)continue;let r=Number.parseInt(n[1]??``,10);if(Number.isInteger(r))return r}return null}function U(e){return/\b\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z)?\b/.exec(e)?.[0]??/\b\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d+\b/.exec(e)?.[0]}function Ue(e){let t=e.indexOf(`{`),n=e.lastIndexOf(`}`);if(t<0||n<=t)return null;try{let r=JSON.parse(e.slice(t,n+1));return r&&typeof r==`object`&&!Array.isArray(r)?r:null}catch{return null}}function W(e,t){for(let n of t){let t=e?.[n];if(typeof t==`string`&&t.trim())return t.trim()}}function We(e,t){for(let n of t){let t=e?.[n];if(typeof t==`number`&&Number.isInteger(t))return t;if(typeof t==`string`&&/^\d{3}$/.test(t.trim()))return Number.parseInt(t,10)}return null}function Ge(e,t){let n=t?.headers??t?.requestHeaders??t?.responseHeaders;return n===void 0?/\bheaders?["'=: ]+(\{.*\})/i.exec(e)?.[1]?.trim():K(n)}function G(e,t,n){for(let r of n){if(t?.[r]!==void 0)return K(t[r]);let n=r.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),i=RegExp(`\\b${n}["'=: ]+(.+)$`,`i`).exec(e);if(i?.[1])return i[1].trim()}}function K(e){if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}function Ke(e,t,n){let r=Y(t,n,5),i=e.packetId??r.map(q).find(e=>typeof e==`string`&&e.length>0);i&&(e.packetId=i);let a=i?Y(t,n,12).filter(e=>q(e)===i):r;e.timestamp??=a.map(U).find(e=>typeof e==`string`&&e.length>0),e.status??=a.map(H).find(e=>typeof e==`number`)??void 0,e.durationMs??=a.map(J).find(e=>typeof e==`number`)??void 0}function q(e){return/\bpacket id (\d+)\b/i.exec(e)?.[1]??null}function J(e){let t=/\b(?:duration|elapsed request\/response time, ms)[:= ]+(\d+)\b/i.exec(e);return t?Number.parseInt(t[1]??``,10):null}function Y(e,t,n){return e.slice(Math.max(0,t-n),Math.min(e.length,t+n+1)).map(e=>e.trim()).filter(Boolean)}const qe=RegExp(`\\b(${[`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`,`OPTIONS`].join(`|`)})\\b\\s+https?:\\/\\/`,`i`),Je=/https?:\/\/[^\s"'<>\])]+/i;function Ye(e,t,n=e.limits.maxEntries){let r=[...e.entries],i=new Set(r.map(Z));for(let e of t.entries){let t=Z(e);if(!i.has(t)&&(i.add(t),r.push(e),r.length>=n))break}return Object.freeze({...e,matchedLines:r.length,entries:Object.freeze(r)})}function Xe(e,t){let n=$(t.maxEntries,25,1,200),r=t.include??`summary`,i=$(t.maxPayloadChars,2048,64,16384),a=$(t.maxScanLines,4e3,100,2e4),o=Ze(t.lineNumberOffset);if(!t.exists)return Object.freeze({path:t.path,exists:!1,scannedLines:0,matchedLines:0,entries:Object.freeze([]),include:r,limits:Object.freeze({maxEntries:n,maxPayloadChars:i,maxScanLines:a})});let s=e.split(`
|
|
2
|
-
`),c=Math.max(0,s.length-a),l=s.slice(c),u=[];for(let e=l.length-1;e>=0&&u.length<n;--e){if(!l[e]?.trim())continue;let n=X(l,e,o+c+e+1,t.backend,r,i);n&&u.push(n)}return Object.freeze({path:t.path,exists:!0,scannedLines:l.length,matchedLines:u.length,entries:Object.freeze(u),include:r,limits:Object.freeze({maxEntries:n,maxPayloadChars:i,maxScanLines:a})})}function Ze(e){if(e===void 0)return 0;if(!Number.isInteger(e)||e<0)throw TypeError(`Network line number offset must be a non-negative integer`);return e}function X(e,t,n,r,i,a){let o=e[t]?.trim();if(!o)return null;let s=Ue(o),c=Qe(o,s);if(!c)return null;let l=rt(o,n,c,a);return r===`android`&&Ke(l,e,t),it(l,o,s,i,a),l}function Qe(e,t){let n=$e(e,t),r=et(e,t);if(!r)return null;let i=tt(e,t);return nt(e,n.explicit,i)?{method:n.value,url:r,status:i}:null}function $e(e,t){let n=W(t,[`method`,`httpMethod`]),r=/\bmethod["'=: ]+([A-Z]+)\b/i.exec(e)?.[1],i=qe.exec(e)?.[1],a=n??r??i;return{value:a?.toUpperCase(),explicit:!!a}}function et(e,t){return W(t,[`url`,`requestUrl`])??Je.exec(e)?.[0]}function tt(e,t){return We(t,[`status`,`statusCode`,`responseCode`])??H(e)??void 0}function nt(e,t,n){return t||n!==void 0||/\bURL["'=: ]+https?:\/\//i.test(e)||/\bheaders?["'=: ]+/i.test(e)||/\b(?:requestBody|responseBody|payload|request|response)["'=: ]+/i.test(e)}function rt(e,t,n,r){return{...n,timestamp:U(e),packetId:q(e)??void 0,durationMs:J(e)??void 0,raw:Q(e,r),line:t}}function it(e,t,n,r,i){if(at(r)){let r=Ge(t,n);r&&(e.headers=Q(r,i))}if(ot(r)){let r=G(t,n,[`requestBody`,`body`,`payload`,`request`]),a=G(t,n,[`responseBody`,`response`]);r&&(e.requestBody=Q(r,i)),a&&(e.responseBody=Q(a,i))}}function at(e){return e===`headers`||e===`all`}function ot(e){return e===`body`||e===`all`}function Z(e){return`${e.timestamp??``}|${e.method??``}|${e.url}|${e.status??``}|${e.raw}`}function Q(e,t){return e.length<=t?e:`${e.slice(0,t)}...<truncated>`}function $(e,t,n,r){return e===void 0||!Number.isInteger(e)?t:Math.max(n,Math.min(r,e))}export{re as S,w as _,Ve as a,ie as b,Fe as c,M as d,j as f,E as g,be as h,He as i,L as l,O as m,Xe as n,Be as o,k as p,B as r,Ie as s,Ye as t,R as u,C as v,h as x,_e as y};
|
|
1
|
+
import{_ as e}from"./sdk-contracts.js";import{St as t}from"./sdk-batch-runner.js";import{_ as n,a as r}from"./sdk-device.js";import{z as i}from"./interaction.js";import{a}from"./sdk-remote-config.js";import{i as o,r as s}from"./device.js";import{t as c}from"./bounds.js";import{t as l}from"./parser.js";import u from"node:path";import ee from"node:fs";import d from"node:fs/promises";import{setTimeout as f}from"node:timers/promises";const p={support:`supported`},m={support:`unsupported`},te={lease:p,inventory:{support:`partial`,note:`Inventory exposes only the leased cloud device, not the provider catalog.`},install:{support:`partial`,note:`Requires provider-specific upload or a path visible to the remote Appium server.`},snapshot:{support:`partial`,note:`Uses Appium page source XML, not agent-device native snapshot backends.`},screenshot:p,tap:p,doubleTap:p,longPress:p,swipe:p,scroll:{support:`partial`,note:`Implemented as viewport-relative W3C pointer gestures.`},fill:p,type:p,back:p,home:{support:`partial`,note:`Uses provider/Appium mobile pressButton support where available.`},orientation:{support:`partial`,note:`Uses the WebDriver rotation/orientation endpoints; four-way rotation collapses to portrait/landscape on drivers that only accept the two-way endpoint. Rotates the current display, so an activity that does not pin its orientation may need rotating again once it is foreground.`},appSwitcher:{support:`partial`,note:`Uses provider/Appium mobile pressButton support where available.`},tvRemote:m,"clipboard.read":{support:`partial`,note:`Uses provider/Appium clipboard extension support where available.`},"clipboard.write":{support:`partial`,note:`Uses provider/Appium clipboard extension support where available.`},settings:m,pinch:m,rotateGesture:m,transformGesture:m,logs:m,record:m,artifacts:m,portReverse:m,nativeSnapshotBackend:{support:`unsupported`,note:`Cloud WebDriver cannot upload or run agent-device native runner/helper backends.`}};function ne(e){return{provider:e.provider,platform:e.platform,snapshotBackend:e.platform===`ios`?`xctest`:`android`,snapshotSource:`appium-page-source`,operations:re(te,e.overrides)}}function h(e,t){return e.operations[t].support!==`unsupported`}function g(e,t){let n=e.operations[t],r=n.note?` ${n.note}`:``;return`${e.provider} WebDriver runtime does not support ${t}.${r}`}function re(e,t){let n={...e};for(let[r,i]of Object.entries(t??{}))n[r]=typeof i==`string`?{...e[r],support:i}:{...e[r],...i};return n}function ie(e,t){let n=e?.bundleId??t?.appIdentifierHint,r=e?.packageName??t?.packageNameHint;return{bundleId:n,packageName:r,appName:e?.appName,launchTarget:oe(e?.launchTarget,n,r)}}function ae(e){return e===`ios`?`xctest`:`android`}function oe(...e){return e.find(e=>e!==void 0)}function se(e){let t=async(t,n,r,i,a)=>{let o=e.findSessionForDevice(t);if(!o)return;let s=await le(e,o,t,n,r,i,a);return await o.client.installApp(s?.appReference??r,a),ie(s,i)};return Object.freeze({fact:t=>ce(e.findSessionForDevice(t)),installApp:t,installInstallablePath:async(e,n,r,i)=>await t(e,``,n,r,i),deployApp:async(e,n,r)=>_(await t(e,n.app,n.appPath,{relaunch:n.replaceExisting,appIdentifierHint:n.app,packageNameHint:n.app},r),n.app),deployMaterializedApp:async(e,n,r)=>_(await t(e,``,n.artifact.installablePath,{appIdentifierHint:n.artifact.bundleId,packageNameHint:n.artifact.packageName},r))})}function ce(e){return e?h(e.capabilities,`install`)?Object.freeze({available:!0}):Object.freeze({available:!1,reason:`owner-capability-missing`,hint:g(e.capabilities,`install`)}):Object.freeze({available:!1,reason:`owner-capability-missing`,hint:`The WebDriver provider session is no longer active for this device.`})}async function le(t,r,i,a,o,s,c){if(!h(r.capabilities,`install`))throw new e(`UNSUPPORTED_OPERATION`,g(r.capabilities,`install`),{provider:t.provider,deviceId:i.id,platform:n(i)});let l=r.prepared.uploadApp??t.uploadApp;if(l)return await l({provider:t.provider,lease:r.lease,device:i,app:a,appPath:o,options:s,signal:c})}function _(t,n){if(!t)throw new e(`UNSUPPORTED_OPERATION`,`The WebDriver provider session no longer supports app deployment.`);return{...t.bundleId?{bundleId:t.bundleId}:{},...t.packageName?{packageName:t.packageName}:{},...t.appName?{appName:t.appName}:{},...t.launchTarget??n?{launchTarget:t.launchTarget??n}:{}}}function v(e){return{provider:e.provider,providerSessionId:e.providerSessionId,status:e.artifacts.length>0?`ready`:`pending`,cloudArtifacts:e.artifacts,...e.artifacts.length>0?{}:{message:e.pendingMessage}}}function ue(e){return{provider:e.provider,providerSessionId:e.providerSessionId,status:`unavailable`,cloudArtifacts:[],message:e.error instanceof Error?e.error.message:String(e.error)}}function y(e){return{"x-agent-device-client":`agent-device-cli`,"x-agent-device-version":e}}function de(e,t){return typeof e==`function`?e(t):e}function b(e){return`Basic ${Buffer.from(`${e.username}:${e.accessKey}`).toString(`base64`)}`}function fe(e){let t=0;for(;t<e.length&&e.charCodeAt(t)===47;)t+=1;return t===0?e:e.slice(t)}function pe(e){let t=e.length-1;for(;t>=0&&e.charCodeAt(t)===47;)--t;return t===e.length-1?e:e.slice(0,t+1)}function me(e){if(e.pathname.endsWith(`/`))return e;let t=new URL(e);return t.pathname=`${t.pathname}/`,t}var he=class{endpoint;headers;requestPolicy;constructor(e){this.endpoint=me(new URL(e.endpoint)),this.headers={...y(e.clientVersion),...e.auth?{Authorization:b(e.auth)}:{},...e.headers},this.requestPolicy={timeoutMs:e.requestPolicy?.timeoutMs??3e4,retryAttempts:e.requestPolicy?.retryAttempts??1,retryDelayMs:e.requestPolicy?.retryDelayMs??250}}async requestValue(e,t,n,r){return await this.requestValueWithRetries(e,t,n,{retryAttempts:r?.retryAttempts??this.requestPolicy.retryAttempts,timeoutMs:r?.timeoutMs??this.requestPolicy.timeoutMs,signal:r?.signal})}async requestValueWithRetries(e,t,n,r){let i;for(let a=0;a<=r.retryAttempts;a+=1)try{return await this.requestValueOnce(e,t,n,r.timeoutMs,r.signal)}catch(e){if(i=e,!ge(e,a,r.retryAttempts,r.signal))throw e;await f(this.requestPolicy.retryDelayMs,void 0,{signal:r.signal})}throw i}async requestValueOnce(e,t,n,r,i){let a=AbortSignal.timeout(r),o=i?AbortSignal.any([i,a]):a,s=await fetch(new URL(fe(t),this.endpoint),{method:e,headers:{Accept:`application/json`,...n===void 0?{}:{"Content-Type":`application/json`},...this.headers},body:n===void 0?void 0:JSON.stringify(n),signal:o}),c=await s.text(),l=c?ve(c):{};if(!s.ok)throw ye(s.status,l);return _e(l)}};function ge(e,t,n,r){return!r?.aborted&&be(e)&&t<n}function _e(e){if(!e||typeof e!=`object`)return e;let t=e;return`value`in t?t.value:e}function ve(t){try{return JSON.parse(t)}catch(n){throw new e(`COMMAND_FAILED`,`WebDriver response was not valid JSON.`,{text:t},n)}}function ye(t,n){let r=n&&typeof n==`object`&&`value`in n?n.value:n;return new e(`COMMAND_FAILED`,r&&typeof r==`object`&&typeof r.message==`string`?r.message:`WebDriver request failed with HTTP ${t}.`,{status:t,response:n})}function be(t){if(t instanceof e){let e=t.details?.status;return typeof e==`number`&&e>=500}return t instanceof TypeError||t instanceof Error&&t.name===`TimeoutError`}var xe=class{transport;sessionId;constructor(e){this.transport=new he(e)}async createSession(e){let t=Ce(await this.requestValue(`POST`,`/session`,{capabilities:Se(e)}));return this.sessionId=t.sessionId,t}async deleteSession(){let e=this.requireSessionId();await this.requestValue(`DELETE`,`/session/${e}`),this.sessionId=void 0}async installApp(e,t){await this.sessionRequest(`POST`,`/appium/device/install_app`,{appPath:e},{signal:t})}async activateApp(e){try{await this.sessionRequest(`POST`,`/appium/device/activate_app`,{appId:e})}catch{await this.executeScript(`mobile: activateApp`,[{appId:e,bundleId:e}])}}async terminateApp(e){try{await this.sessionRequest(`POST`,`/appium/device/terminate_app`,{appId:e})}catch{await this.executeScript(`mobile: terminateApp`,[{appId:e,bundleId:e}])}}async performActions(e){await this.sessionRequest(`POST`,`/actions`,{actions:e})}async releaseActions(){await this.sessionRequest(`DELETE`,`/actions`,void 0,{retryAttempts:0})}async sendKeys(e){await this.sessionRequest(`POST`,`/keys`,{value:Array.from(e)})}async hideKeyboard(){await this.sessionRequest(`POST`,`/appium/device/hide_keyboard`,void 0,{retryAttempts:0})}async isKeyboardShown(e){let t;try{t=await this.sessionRequest(`GET`,`/appium/device/is_keyboard_shown`,void 0,{retryAttempts:0,...e===void 0?{}:{timeoutMs:e}})}catch(e){if(T(e))return`unsupported`;throw e}return typeof t==`boolean`?t:`unsupported`}async activeElement(e){let t=e===void 0?void 0:Date.now()+e,n;try{n=Ee(await this.sessionRequest(`GET`,`/element/active`,void 0,C(t)))}catch(e){if(T(e))return`unsupported`;if(w(e))return`none`;throw e}if(n===void 0)return`unsupported`;try{let e=await this.sessionRequest(`GET`,`/element/${encodeURIComponent(n)}/rect`,void 0,C(t));return{id:n,rect:x(e)}}catch(e){if(T(e))return`unsupported`;if(w(e))return`none`;throw e}}async back(){await this.sessionRequest(`POST`,`/back`)}async setRotation(e){await this.sessionRequest(`POST`,`/rotation`,{x:0,y:0,z:e})}async setOrientation(e){await this.sessionRequest(`POST`,`/orientation`,{orientation:e})}async source(){let t=await this.sessionRequest(`GET`,`/source`);if(typeof t!=`string`)throw new e(`COMMAND_FAILED`,`WebDriver source response was not a string`,{valueType:typeof t});return t}async screenshot(t){let n=await this.sessionRequest(`GET`,`/screenshot`);if(typeof n!=`string`)throw new e(`COMMAND_FAILED`,`WebDriver screenshot response was not base64 text`,{valueType:typeof n});await d.writeFile(t,Buffer.from(n,`base64`))}async windowRect(){return x(await this.sessionRequest(`GET`,`/window/rect`))}async executeScript(e,t=[]){return await this.sessionRequest(`POST`,`/execute/sync`,{script:e,args:t})}async sessionRequest(e,t,n,r){let i=this.requireSessionId();return await this.requestValue(e,`/session/${i}${t}`,n,r)}requireSessionId(){if(!this.sessionId)throw new e(`SESSION_NOT_FOUND`,`WebDriver session has not been created yet.`);return this.sessionId}async requestValue(e,t,n,r){return await this.transport.requestValue(e,t,n,r)}};function x(t){if(!t||typeof t!=`object`)throw new e(`COMMAND_FAILED`,`WebDriver window rect response was empty.`);let n=t,r={x:S(n,`x`),y:S(n,`y`),width:S(n,`width`),height:S(n,`height`)};if(r.x===void 0||r.y===void 0||r.width===void 0||r.height===void 0)throw new e(`COMMAND_FAILED`,`WebDriver window rect response was invalid.`,{response:n});return r}function S(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Se(e){return`alwaysMatch`in e||`firstMatch`in e?e:{alwaysMatch:e}}function Ce(t){if(!t||typeof t!=`object`)throw new e(`COMMAND_FAILED`,`WebDriver create-session response was empty.`);let n=t,r=typeof n.sessionId==`string`?n.sessionId:typeof n.session_id==`string`?n.session_id:void 0;if(!r)throw new e(`COMMAND_FAILED`,`WebDriver create-session response missed sessionId.`,{response:n});return{sessionId:r,capabilities:n.capabilities&&typeof n.capabilities==`object`?n.capabilities:{}}}const we=new Set([405,501]),Te=new Set([`unknown command`,`unknown method`]);function Ee(e){if(!e||typeof e!=`object`)return;let t=e,n=t[`element-6066-11e4-a52e-4f735466cecf`]??t.ELEMENT;return typeof n==`string`&&n.length>0?n:void 0}function C(e){return e===void 0?{retryAttempts:0}:{retryAttempts:0,timeoutMs:Math.max(0,e-Date.now())}}function w(t){return t instanceof e?E(t).toLowerCase()===`no such element`:!1}function T(t){if(!(t instanceof e))return!1;let n=t.details?.status;return typeof n==`number`&&we.has(n)?!0:Te.has(E(t).toLowerCase())}function E(e){let t=e.details?.response,n=t&&typeof t==`object`?t.value:void 0,r=n&&typeof n==`object`?n.error:void 0;return typeof r==`string`?r:``}function De(e,t){return{type:`pointer`,id:e,parameters:{pointerType:`touch`},actions:t}}function Oe(t){let n;try{n=l(t)}catch(t){throw new e(`COMMAND_FAILED`,`Failed to parse WebDriver page source XML: ${t instanceof Error?t.message:String(t)}`,void 0,t)}let r=[];for(let e of n)ke(r,e);return r}function ke(e,t,n,r=0){let i=Object.keys(t.attributes).length===0?n:Ae(e,t,n,r),a=i===n?r:r+1;for(let n of t.children)ke(e,n,i,a)}function Ae(e,t,n,r){let i=e.length;return e.push(je(i,t.name,t.attributes,n,r)),i}function je(e,t,n,r,i){let a=Me(n),o=k(n.enabled,!0),s=k(n.displayed??n.visible,!0);return{index:e,type:t,role:Ne(t,n),label:D(n,[`content-desc`,`label`,`text`,`name`]),value:O(n.value),identifier:D(n,[`resource-id`,`id`,`accessibility-id`,`name`]),rect:a,enabled:o,selected:k(n.selected),focused:k(n.focused),visibleToUser:s,hittable:s&&o&&a!==void 0&&a.width>0&&a.height>0,depth:i,parentIndex:r}}function Me(e){let t=c(e.bounds??null);if(t)return t;let n=A(e.x),r=A(e.y),i=A(e.width),a=A(e.height);if(!(n===void 0||r===void 0||i===void 0||a===void 0))return{x:n,y:r,width:i,height:a}}function D(e,t){for(let n of t){let t=O(e[n]);if(t!==void 0)return t}}function O(e){return e||void 0}function k(e,t=!1){return e===void 0?t:e===`true`||e===`1`}function A(e){if(e===void 0||e===``)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function Ne(e,t){return O(t.class)??O(e.replace(/^XCUIElementType/,``).toLowerCase())}function Pe(e){let t=Oe(e).flatMap(e=>Fe(e)&&Ie(e.rect)?[e.rect]:[]).sort((e,t)=>t.width*t.height-e.width*e.height)[0];return t?{x:t.x,y:t.y,width:t.width,height:t.height}:void 0}function Fe(e){let t=e.type?.toLowerCase()??``;return e.visibleToUser!==!1&&(t.includes(`scrollview`)||t.includes(`listview`)||t.includes(`recyclerview`))}function Ie(e){return!!e&&e.width>=50&&e.height>=50}async function Le(t,n,r){let i=[];for(let e of n===`android`?[`rotation`,`orientation`]:[`orientation`,`rotation`])try{await He(t,e,r);return}catch(t){if(!Be(t))throw t;i.push({transport:e,error:t instanceof Error?t.message:String(t)})}throw new e(`COMMAND_FAILED`,`Could not set device orientation to ${r} on the hosted WebDriver session.`,{hint:`The provider driver rejected both orientation endpoints. Set the orientation as a session capability instead, for example connect --provider-device-orientation portrait.`,rotation:r,attempts:i})}const Re=new Set([`unknown command`,`unknown method`]),ze=new Set([404,405]);function Be(t){if(!(t instanceof e)||t.code===`SESSION_NOT_FOUND`)return!1;let n=Ve(t.details?.response);if(n)return Re.has(n);let r=t.details?.status;return typeof r==`number`&&ze.has(r)}function Ve(e){if(!e||typeof e!=`object`)return``;let t=e.value;if(!t||typeof t!=`object`)return``;let n=t.error;return typeof n==`string`?n:``}async function He(e,t,n){if(t===`rotation`){await e.setRotation(o(n));return}await e.setOrientation(s(n))}const j=1500;function Ue(e){return new Promise(t=>setTimeout(t,e))}function M(t,n,r){return new e(`COMMAND_FAILED`,`fill tapped (${t}, ${n}) but ${r}`,{reason:`text_entry_focus_not_observed`,x:t,y:n,hint:`The tap most likely missed the field. Re-check the target with snapshot -i and fill the element it reports, rather than retrying the same coordinates.`})}function We(t,n){return new e(`COMMAND_FAILED`,`fill tapped (${t}, ${n}) but this driver reports neither the focused element nor keyboard state, so the text was not sent`,{reason:`text_entry_focus_unobservable`,x:t,y:n,hint:`This provider cannot confirm a field took focus. Use press <target> followed by type <text> to enter it anyway, accepting that nothing witnesses which field receives the keys.`})}function Ge(e,t,n){return t>=e.x&&t<=e.x+e.width&&n>=e.y&&n<=e.y+e.height}function Ke(e){return new qe(e.client,e.backend,e.capabilities)}var qe=class{client;backend;capabilities;constructor(e,t,n){this.client=e,this.backend=t,this.capabilities=n}async open(e,t){if(t?.url){await this.client.executeScript(`mobile: deepLink`,[{url:t.url,package:e}]);return}let n=t?.appBundleId??e;n&&await this.client.activateApp(n)}async openDevice(){await this.client.executeScript(`mobile: activateApp`,[{}])}async close(e){e&&await this.client.terminateApp(e)}async tap(e,t){return this.requireSupport(`tap`),await this.pointerGesture(`tap`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x:e,y:t}}async doubleTap(e,t){return this.requireSupport(`doubleTap`),await this.pointerGesture(`doubleTap`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pointerUp`,button:0},{type:`pause`,duration:80},{type:`pointerDown`,button:0},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x:e,y:t}}async swipe(e,t,n,r,i=400){return this.requireSupport(`swipe`),await this.pointerGesture(`swipe`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pointerMove`,duration:i,x:n,y:r},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x1:e,y1:t,x2:n,y2:r,durationMs:i}}async longPress(e,t,n=600){return this.requireSupport(`longPress`),await this.pointerGesture(`longPress`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pause`,duration:n},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x:e,y:t,durationMs:n}}async focus(e,t){return await this.tap(e,t)}async type(e){this.requireSupport(`type`),await this.client.sendKeys(e)}async fill(e,t,n,r){this.requireSupport(`fill`);let i=await this.readTextEntryState();await this.tap(e,t);let a=await this.awaitTextEntryReadiness(i,e,t);return await this.type(n),{backend:`webdriver`,x:e,y:t,text:n,textEntryReadiness:a}}async scroll(e,t){this.requireSupport(`scroll`);let n=t?.durationMs??350;await this.client.hideKeyboard().catch(()=>void 0);let r=await this.scrollGestureFrame(),a=i({direction:e,amount:t?.amount,pixels:t?.pixels,referenceWidth:r.width,referenceHeight:r.height}),o={...a,x1:a.x1+r.x,y1:a.y1+r.y,x2:a.x2+r.x,y2:a.y2+r.y};return await this.swipe(o.x1,o.y1,o.x2,o.y2,n),{backend:`webdriver`,...o,distance:a.pixels,durationMs:n}}async gestureViewport(){return await this.scrollGestureFrame()}async performGesture(e){return this.requireSupport(Ye(e)),await this.client.performActions(e.pointers.map(e=>De(`gesture-pointer-${e.pointerId}`,Je(e.samples)))),await this.client.releaseActions().catch(()=>void 0),{backend:`webdriver-w3c-actions`}}async screenshot(e,t){this.requireSupport(`screenshot`),await this.client.screenshot(e)}async snapshot(e){return this.requireSupport(`snapshot`),{backend:this.backend,nodes:Oe(await this.client.source())}}async back(e){this.requireSupport(`back`),await this.client.back()}async home(){this.requireSupport(`home`),await this.client.executeScript(`mobile: pressButton`,[{name:`home`}])}async setOrientation(e){this.requireSupport(`orientation`),await Le(this.client,this.backend,e)}async appSwitcher(){this.requireSupport(`appSwitcher`),await this.client.executeScript(`mobile: pressButton`,[{name:`appSwitch`}])}async tvRemote(e,t){this.unsupported(`tvRemote`)}async readClipboard(){this.requireSupport(`clipboard.read`);let e=await this.client.executeScript(`mobile: getClipboard`,[{}]);return typeof e==`string`?e:``}async writeClipboard(e){this.requireSupport(`clipboard.write`),await this.client.executeScript(`mobile: setClipboard`,[{content:e}])}async setSetting(e,t,n,r){this.unsupported(`settings`)}async awaitTextEntryReadiness(e,t,n){let r=e.keyboard,i=Date.now()+2e3,a=e.focusedElementId,o=await this.pollWithinBudget(i,async e=>{let r=await this.client.activeElement(e);return r===`unsupported`?`abandon`:r===`none`?`retry`:r.id!==a||Ge(r.rect,t,n)?`satisfied`:`retry`});if(o===`satisfied`)return`focused-element`;if(o===`expired`)throw M(t,n,`nothing there took text-entry focus, so the text was not sent`);if(r===`unsupported`)throw We(t,n);if(r)throw M(t,n,`the keyboard was already up and this driver cannot report which field holds focus, so the text was not sent`);if(await this.pollWithinBudget(i,async e=>await this.client.isKeyboardShown(e)===!0?`satisfied`:`retry`)===`satisfied`)return`keyboard-shown`;throw M(t,n,`no keyboard appeared, so the text was not sent`)}async readTextEntryState(){let[e,t]=await Promise.all([this.client.isKeyboardShown(j),this.client.activeElement(j)]);return{keyboard:e,focusedElementId:t===`none`||t===`unsupported`?void 0:t.id}}async pollWithinBudget(e,t){let n=!1,r;for(;;){let i=e-Date.now();if(i<=0)break;try{let e=await t(Math.min(j,i));if(n=!0,e!==`retry`)return e}catch(e){r=e}let a=e-Date.now();if(a<=0)break;await Ue(Math.min(100,a))}if(!n&&r!==void 0)throw r;return`expired`}async pointerGesture(e,t){await this.client.performActions([De(e,t)]),await this.client.releaseActions().catch(()=>void 0)}async scrollGestureFrame(){return await this.client.source().then(e=>Pe(e)).catch(()=>void 0)||await this.client.windowRect()}requireSupport(e){h(this.capabilities,e)||this.unsupported(e)}unsupported(t){throw new e(`UNSUPPORTED_OPERATION`,g(this.capabilities,t),{provider:this.capabilities.provider,platform:this.capabilities.platform,operation:t})}};function Je(t){let n=t[0];if(!n)throw new e(`INVALID_ARGS`,`WebDriver gesture pointer requires samples`);let r=[{type:`pointerMove`,duration:0,x:n.point.x,y:n.point.y},{type:`pointerDown`,button:0}];for(let e=1;e<t.length;e+=1){let n=t[e-1],i=t[e];r.push({type:`pointerMove`,duration:i.offsetMs-n.offsetMs,x:i.point.x,y:i.point.y})}return r.push({type:`pointerUp`,button:0}),r}function Ye(e){if(e.topology===`single`)return`swipe`;switch(e.intent){case`pan`:case`transform`:return`transformGesture`;case`pinch`:return`pinch`;case`rotate`:return`rotateGesture`}}var Xe=class{sessionsByLeaseId=new Map;ownedDeviceIds=new Set;releasedProviderSessionIdsByLeaseId=new Map;options;constructor(e){this.options=e}ownsDevice(e){return this.ownedDeviceIds.has(e.id)}findSessionForDevice(e){return[...this.sessionsByLeaseId.values()].find(t=>t.device.id===e.id)}findSessionForLease(e){return this.sessionsByLeaseId.get(e)}getInteractor(e){return this.findSessionForDevice(e)?.interactor}heartbeat(e){if(e.leaseProvider===this.options.provider&&this.sessionsByLeaseId.has(e.leaseId))return{provider:this.options.provider}}async allocate(e,t){if(e.leaseProvider!==this.options.provider)return;if(this.sessionsByLeaseId.has(e.leaseId))return this.heartbeat(e);let n=await this.prepareSession(e,t),r=new xe({clientVersion:this.options.clientVersion,endpoint:n.endpoint,auth:n.auth,headers:n.headers,requestPolicy:this.options.requestPolicy}),i=await this.createSessionWithPreparedCleanup(r,n),a=this.deviceForLease(e,n),o=n.providerSessionId??i.sessionId,s=ne({provider:this.options.provider,platform:n.platform,overrides:this.options.capabilityOverrides});return this.sessionsByLeaseId.set(e.leaseId,Object.freeze({lease:e,device:a,client:r,prepared:n,capabilities:s,webDriverSessionId:i.sessionId,providerSessionId:o,interactor:Ke({client:r,backend:ae(n.platform),capabilities:s})})),this.ownedDeviceIds.add(a.id),{provider:this.options.provider,deviceId:a.id,sessionId:i.sessionId,providerSessionId:o,capabilities:s,...n.providerData}}async release(e){if(e.leaseProvider!==this.options.provider)return;let t=this.sessionsByLeaseId.get(e.leaseId);if(!t)return;this.sessionsByLeaseId.delete(e.leaseId),this.releasedProviderSessionIdsByLeaseId.set(e.leaseId,t.providerSessionId);let n=await this.closeSession(t),r=await this.safeListArtifacts(t);return{provider:this.options.provider,providerSessionId:t.providerSessionId,...n.cleanup,...n.warnings.length>0?{warnings:n.warnings}:{},...r?{cloudArtifacts:r}:{}}}async listCloudArtifacts(e){if(e.provider!==this.options.provider)return;let t=e.leaseId?this.sessionsByLeaseId.get(e.leaseId):void 0;if(t)return await this.safeListArtifacts(t);let n=e.providerSessionId??(e.leaseId?this.releasedProviderSessionIdsByLeaseId.get(e.leaseId):void 0);if(!(!n||!this.options.listArtifacts))return await this.options.listArtifacts({provider:this.options.provider,providerSessionId:n})}async shutdown(){await Promise.allSettled([...this.sessionsByLeaseId.values()].map(async e=>await this.closeSession(e))),this.sessionsByLeaseId.clear(),this.ownedDeviceIds.clear()}async createSessionWithPreparedCleanup(e,t){try{return await e.createSession(t.webdriverCapabilities)}catch(e){throw await Ze(t,e),e}}async prepareSession(e,t){let n=this.baseSessionForLease(e);return this.options.prepareSession?await this.options.prepareSession({lease:e,req:t,base:n}):n}baseSessionForLease(e){let t=typeof this.options.webdriverCapabilities==`function`?this.options.webdriverCapabilities(e):this.options.webdriverCapabilities??{};return{provider:this.options.provider,endpoint:this.options.endpoint,platform:this.options.platform,deviceName:this.options.deviceName,auth:this.options.auth,headers:this.options.headers,webdriverCapabilities:N(this.options.platform,this.options.deviceName,t)}}deviceForLease(e,t){return{...r(t.platform),...t.platform===`ios`?{appleOs:`ios`}:{},id:t.deviceId??this.options.deviceId?.(e)??`${this.options.provider}:${t.platform}:${e.leaseId}`,name:t.deviceName,kind:`device`,target:`mobile`,booted:!0}}async closeSession(e){let t=[],n;try{await e.client.deleteSession()}catch(e){t.push({code:`WEBDRIVER_SESSION_DELETE_FAILED`,message:P(e)})}try{n=await e.prepared.cleanup?.()}catch(e){t.push({code:`PROVIDER_CLEANUP_FAILED`,message:P(e)})}return{cleanup:n,warnings:t}}async safeListArtifacts(e){let t=e.prepared.listArtifacts??this.options.listArtifacts;if(t)try{return await t({provider:this.options.provider,lease:e.lease,device:e.device,webDriverSessionId:e.webDriverSessionId,providerSessionId:e.providerSessionId})}catch(t){return ue({provider:this.options.provider,providerSessionId:e.providerSessionId,error:t})}}};function N(e,t,n={}){return{platformName:e===`ios`?`iOS`:`Android`,"appium:deviceName":t,...n}}function P(e){return e instanceof Error?e.message:String(e)}async function Ze(t,n){try{await t.cleanup?.()}catch(t){n instanceof e&&(n.details={...n.details,cleanupError:P(t)})}}function F(e){return new Qe(e)}var Qe=class{provider;owner;leaseLifecycle;cloudArtifacts;deviceInventoryProvider;capabilities;platformRuntimeModule;sessions;deployment;constructor(e){this.provider=e.provider,this.owner=t(e.provider,e.platform),this.capabilities=ne({provider:e.provider,platform:e.platform,overrides:e.capabilityOverrides}),this.sessions=new Xe(e),this.deployment=se({provider:e.provider,uploadApp:e.uploadApp,findSessionForDevice:e=>this.sessions.findSessionForDevice(e)}),this.platformRuntimeModule=Object.freeze({owner:this.owner,loadRuntime:async e=>await this.loadRuntime(e)}),this.leaseLifecycle={allocate:async(e,t)=>await this.sessions.allocate(e,t),heartbeat:async e=>this.sessions.heartbeat(e),release:async e=>await this.sessions.release(e)},this.cloudArtifacts={listCloudArtifacts:async e=>await this.sessions.listCloudArtifacts(e)},this.deviceInventoryProvider=async e=>{if(e.leaseProvider!==this.provider)return null;if(!e.leaseId)return[];let t=this.sessions.findSessionForLease(e.leaseId);return t?[t.device]:[]}}async loadRuntime(e){let{createWebDriverPlatformRuntimeOwner:t}=await import(`./platform-runtime2.js`);return t({host:e,owner:this.owner,ownsDevice:e=>this.ownsDevice(e),isSessionActive:e=>this.sessions.findSessionForDevice(e)!==void 0,deployment:this.deployment,getInteractor:e=>this.getInteractor(e)})}ownsDevice(e){return this.sessions.ownsDevice(e)}getInteractor(e){return this.sessions.getInteractor(e)}async installApp(e,t,n,r){return await this.deployment.installApp(e,t,n,r)}async installInstallablePath(e,t,n){return await this.deployment.installInstallablePath(e,t,n)}async shutdown(){await this.sessions.shutdown()}};async function I(e,t,n){if(t)return v({provider:e,providerSessionId:t,artifacts:(await Promise.all([n.listArtifacts(t,`FILE`),n.listArtifacts(t,`LOG`)])).flat().flatMap(n=>et(e,t,n)),pendingMessage:`AWS Device Farm artifacts are not ready yet.`})}function $e(e){if(!e||typeof e!=`object`)return[];let t=e.artifacts;return Array.isArray(t)?t:[]}function et(e,t,n){let r=n.url;return typeof r!=`string`||r.length===0?[]:[{provider:e,providerSessionId:t,kind:tt(n.type),name:n.name??n.type??`AWS Device Farm artifact`,url:r,providerArtifactId:n.arn,extension:n.extension,availability:`ready`,metadata:{awsType:n.type,...n.metadata?{awsMetadata:n.metadata}:{}}}]}function tt(e){switch(e){case`VIDEO`:return`video`;case`APPIUM_SERVER_OUTPUT`:return`appium-log`;case`DEVICE_LOG`:return`device-log`;case`MESSAGE_LOG`:case`UNKNOWN`:return`automation-log`;default:return`raw`}}const L={browserStack:`browserstack`,awsDeviceFarm:`aws-device-farm`},nt=new Set(Object.values(L));function rt(e){return e!==void 0&&nt.has(e)}L.awsDeviceFarm;const it={install:{support:`unsupported`,note:`Pass appArn when creating the remote access session; local artifact upload/install is not implemented.`},portReverse:{support:`unsupported`,note:`AWS Device Farm remote access does not expose agent-device port reverse.`},artifacts:{support:`supported`,note:`AWS Device Farm remote access exposes provider-hosted video, Appium logs, and device logs after session completion.`}};function R(e){let t=z(e);return{createRemoteAccessSession:async e=>B(await t(`create-remote-access-session`,[`--project-arn`,e.projectArn,`--device-arn`,e.deviceArn,`--name`,e.name,...e.appArn?[`--app-arn`,e.appArn]:[],...e.interactionMode?[`--interaction-mode`,e.interactionMode]:[],...e.configuration?[`--configuration`,JSON.stringify(e.configuration)]:[]])),getRemoteAccessSession:async e=>B(await t(`get-remote-access-session`,[`--arn`,e])),stopRemoteAccessSession:async e=>B(await t(`stop-remote-access-session`,[`--arn`,e])),listArtifacts:async(e,n)=>$e(await t(`list-artifacts`,[`--arn`,e,`--type`,n]))}}function at(t){return async({lease:n,base:r})=>{let i=await ct((await t.client.createRemoteAccessSession({projectArn:t.projectArn,deviceArn:t.deviceArn,appArn:t.appArn,name:de(t.sessionName,n)??`agent-device-${n.leaseId}`,interactionMode:t.interactionMode,configuration:t.configuration})).arn,t),a=ot(i);if(!a)throw new e(`COMMAND_FAILED`,`AWS Device Farm did not expose a WebDriver endpoint.`,{sessionArn:i.arn,status:i.status});let o=i.device?.name??t.deviceName,s=typeof t.webdriverCapabilities==`function`?t.webdriverCapabilities(n):t.webdriverCapabilities??{};return{...r,endpoint:a,platform:t.platform,deviceName:o,webdriverCapabilities:N(t.platform,o,s),cleanup:async()=>(await t.client.stopRemoteAccessSession(i.arn),{awsDeviceFarmSessionArn:i.arn}),providerSessionId:i.arn,providerData:{awsDeviceFarmSessionArn:i.arn}}}}function ot(e){let t=e.endpoints&&typeof e.endpoints==`object`?Object.values(e.endpoints):[],n=[e.remoteDriverEndpoint,e.endpoint,...t,e.remoteDebugUrl,e.remoteRecordAppUrl].filter(e=>typeof e==`string`&&e.length>0).find(e=>!/^wss?:\/\//i.test(e));return n?st(n):void 0}function st(e){return/^https?:\/\//i.test(e)?e:`http://${e}`}async function ct(t,n){let r=n.startupTimeoutMs??12e4,i=n.pollIntervalMs??5e3,a=Date.now(),o=await n.client.getRemoteAccessSession(t);for(;Date.now()-a<r;){if(o.status===`RUNNING`)return o;if(o.status===`ERRORED`||o.status===`STOPPED`||o.status===`COMPLETED`)throw new e(`COMMAND_FAILED`,`AWS Device Farm remote access session did not start.`,{sessionArn:t,status:o.status,result:o.result});await f(i),o=await n.client.getRemoteAccessSession(t)}throw new e(`COMMAND_FAILED`,`Timed out waiting for AWS Device Farm remote access.`,{sessionArn:t,status:o.status,result:o.result,timeoutMs:r})}async function lt(t,n,r){let i=await t(n,r);try{return JSON.parse(i.stdout)}catch(t){throw new e(`COMMAND_FAILED`,`AWS Device Farm returned invalid JSON.`,void 0,t)}}function z(e){let t=e.region?[`--region`,e.region]:[],n=e.awsCommand??`aws`;return async(r,i)=>await lt(e.runHostCommand,n,[`devicefarm`,r,...t,...i,`--output`,`json`])}function B(t){if(!t||typeof t!=`object`)throw new e(`COMMAND_FAILED`,`AWS Device Farm response was not an object.`,{response:t});let n=t.remoteAccessSession;if(!n||typeof n!=`object`)throw new e(`COMMAND_FAILED`,`AWS Device Farm response missed remoteAccessSession.`,{response:t});return n}const V=[{field:`providerDeviceOrientation`,capability:`deviceOrientation`,flag:`--provider-device-orientation`,type:`enum`,enumValues:a},{field:`providerGeoLocation`,capability:`geoLocation`,flag:`--provider-geo-location`,type:`string`},{field:`providerTimezone`,capability:`timezone`,flag:`--provider-timezone`,type:`string`},{field:`providerLanguage`,capability:`language`,flag:`--provider-language`,type:`string`},{field:`providerLocale`,capability:`locale`,flag:`--provider-locale`,type:`string`},{field:`providerNetworkProfile`,capability:`networkProfile`,flag:`--provider-network-profile`,type:`string`},{field:`providerCustomNetwork`,capability:`customNetwork`,flag:`--provider-custom-network`,type:`string`},{field:`providerNoResignApp`,capability:`resignApp`,flag:`--provider-no-resign-app`,type:`negated-boolean`,platform:`ios`}];function ut(e,t){gt(e);let n={};for(let r of V){let i=e[r.field];i===void 0||i===!1||i===``||(ht(r,t),n[r.capability]=r.type===`negated-boolean`?!1:i)}return n}function dt(e){return V.filter(t=>{let n=e?.[t.field];return n!==void 0&&n!==!1&&n!==``}).map(e=>e.flag)}function H(t,n){let r=dt(t);if(r.length===0)return;let i=r.length!==1;throw new e(`INVALID_ARGS`,`${r.join(`, `)} ${i?`are`:`is`} only supported by BrowserStack, not ${n}.`,{hint:`Drop ${i?`those flags`:`the flag`} or use the browserstack provider.`,provider:n,flags:r})}function ft(e){let t={};for(let n of V){let r=e?.[n.field];if(n.type===`negated-boolean`){r===!0&&(t.providerNoResignApp=!0);continue}typeof r!=`string`||r.length===0||pt(t,n,r)}return t}function pt(e,t,n){if(t.field===`providerDeviceOrientation`){e.providerDeviceOrientation=mt(t,n);return}t.field!==`providerNoResignApp`&&(e[t.field]=n)}function mt(t,n){let r=a.find(e=>e===n);if(r)return r;throw new e(`INVALID_ARGS`,`Invalid ${t.flag} value: ${n}.`,{hint:`Use ${a.join(`|`)}.`,flag:t.flag,capability:t.capability})}function ht(t,n){if(!(!t.platform||t.platform===n))throw new e(`INVALID_ARGS`,`${t.flag} applies to ${t.platform} sessions only, but the session platform is ${n}.`,{hint:`Drop ${t.flag} or connect with --platform ${t.platform}.`,flag:t.flag,capability:t.capability,platform:n})}function gt(t){if(!(!t.providerNetworkProfile||!t.providerCustomNetwork))throw new e(`INVALID_ARGS`,`BrowserStack accepts either a named network profile or a custom network shape, not both.`,{hint:`Pass only one of --provider-network-profile or --provider-custom-network.`,networkProfile:t.providerNetworkProfile,customNetwork:t.providerCustomNetwork})}L.browserStack;const _t={install:{support:`partial`,note:`Local app artifacts are uploaded to BrowserStack App Automate, then installed with Appium.`},portReverse:{support:`unsupported`,note:`Use BrowserStack Local for network tunneling; agent-device port reverse is not available.`},artifacts:{support:`supported`,note:`BrowserStack session details expose provider-hosted video, Appium logs, device logs, and dashboard links.`}};async function U(e,t,n){if(t)return v({provider:e,providerSessionId:t,artifacts:St(e,t,await xt(t,n)),pendingMessage:`BrowserStack artifacts are not ready yet.`})}async function W(t,n,r){r?.throwIfAborted();let i=await d.readFile(t),a=new FormData;a.set(`file`,new Blob([i]),u.basename(t));let o=await fetch(n.endpoint??`https://api-cloud.browserstack.com/app-automate/upload`,{method:`POST`,headers:{...y(n.clientVersion),Authorization:b(n)},body:a,signal:r}),s=await o.json(),c=Ct(s);if(!o.ok||!c)throw new e(`COMMAND_FAILED`,`BrowserStack app upload failed.`,{status:o.status,response:s});return c}function vt(e){return async({appPath:t,options:n,signal:r})=>({appReference:await W(t,e,r),bundleId:n?.appIdentifierHint,packageName:n?.packageNameHint,launchTarget:n?.appIdentifierHint??n?.packageNameHint})}function yt(e){let{"bstack:options":t,...n}=e.configured??{};return{device:e.deviceName,os_version:e.osVersion,...e.app?{app:e.app}:{},...n,"bstack:options":{...e.projectName?{projectName:e.projectName}:{},buildName:e.buildName,sessionName:e.sessionName,...e.deviceFeatures??{},...bt(t)}}}function bt(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}async function xt(t,n){let r=new URL(`${pe(String(n.endpoint??`https://api-cloud.browserstack.com/app-automate/sessions`))}/${t}.json`),i=await fetch(r,{headers:{...y(n.clientVersion),Authorization:b(n)}}),a=await i.json();if(!i.ok||!a||typeof a!=`object`)throw new e(`COMMAND_FAILED`,`BrowserStack session details lookup failed.`,{status:i.status,response:a});let o=a.automation_session??a;return o&&typeof o==`object`?o:{}}function St(e,t,n){return[G(e,t,n,`video_url`,`video`,`Session video`),G(e,t,n,`appium_logs_url`,`appium-log`,`Appium logs`),G(e,t,n,`device_logs_url`,`device-log`,`Device logs`),G(e,t,n,`browser_url`,`provider-session`,`BrowserStack dashboard`),G(e,t,n,`public_url`,`provider-session`,`Public session link`)].filter(e=>e!==void 0)}function G(e,t,n,r,i,a){let o=n[r];if(!(typeof o!=`string`||o.length===0))return{provider:e,providerSessionId:t,kind:i,name:a,url:o,availability:`ready`}}function Ct(e){if(!e||typeof e!=`object`)return;let t=e.app_url;return typeof t==`string`?t:void 0}function K(e){return/^arn:[^:]+:devicefarm:([^:]+):/.exec(e)?.[1]}async function wt(t,n){let r=z({runHostCommand:n,region:t.region}),[i,a,o]=await Promise.all([r(`get-project`,[`--arn`,t.projectArn]),r(`get-device`,[`--arn`,t.deviceArn]),t.appArn?r(`get-upload`,[`--arn`,t.appArn]):void 0]),s=q(i,`project`),c=q(a,`device`),l=Et(c.platform);if(l!==t.platform)throw new e(`INVALID_ARGS`,`AWS Device Farm device "${J(c.name)??t.deviceArn}" is ${l}, not ${t.platform}.`);let u=t.appArn?Tt(q(o,`upload`),t):{status:`missing`,message:`No app upload is attached; AWS Device Farm does not support install after allocation. Reconnect with --aws-app-arn <arn>.`};return{provider:`aws-device-farm`,service:`AWS Device Farm`,verificationMessage:t.appArn?`Credentials, project, device, and app upload verified.`:`Credentials, project, and device verified.`,project:{name:J(s.name),reference:t.projectArn},device:{status:`verified`,name:J(c.name)??t.deviceArn,reference:t.deviceArn,platform:l,osVersion:J(c.os),availability:J(c.availability)},app:u}}function Tt(t,n){let r=J(t.status);if(r!==`SUCCEEDED`)throw new e(`COMMAND_FAILED`,`AWS Device Farm app upload is not ready (${r??`unknown status`}).`,{status:r,hint:`Wait for the upload to succeed or reconnect with a different --aws-app-arn.`});let i=n.platform===`android`?`ANDROID_APP`:`IOS_APP`,a=J(t.type);if(a!==i)throw new e(`INVALID_ARGS`,`AWS Device Farm app upload type is ${a??`unknown`}, expected ${i}.`);return{status:`verified`,name:J(t.name),reference:n.appArn}}function q(t,n){if(!t||typeof t!=`object`)throw new e(`COMMAND_FAILED`,`AWS Device Farm ${n} response was not an object.`);let r=t[n];if(!r||typeof r!=`object`||Array.isArray(r))throw new e(`COMMAND_FAILED`,`AWS Device Farm response missed ${n}.`);return r}function Et(t){if(t===`ANDROID`)return`android`;if(t===`IOS`)return`ios`;throw new e(`UNSUPPORTED_PLATFORM`,`AWS Device Farm device platform is ${String(t)}.`)}function J(e){return typeof e==`string`&&e.length>0?e:void 0}async function Dt(t,n){let r={username:t.username,accessKey:t.accessKey},i=At(await Y(t.devicesEndpoint??`https://api-cloud.browserstack.com/app-automate/devices.json`,r,n)).find(e=>e.device===t.deviceName&&e.os.toLowerCase()===t.platform&&kt(e.osVersion,t.osVersion));if(!i)throw new e(`INVALID_ARGS`,`BrowserStack device "${t.deviceName}" with ${t.platform} ${t.osVersion} is not available.`,{hint:`Choose an exact device and OS version from the BrowserStack App Automate device list.`});let a=await Ot(t,r,n);return{provider:`browserstack`,service:`BrowserStack`,verificationMessage:a.status===`verified`?`Credentials, device, and uploaded app verified.`:`Credentials and device access verified; app availability is checked when the session is created.`,device:{status:`verified`,name:i.device,platform:t.platform,osVersion:i.osVersion},app:a}}async function Ot(e,t,n){let{app:r}=e;if(r.startsWith(`bs://`)){let i=jt(await Y(e.appsEndpoint??`https://api-cloud.browserstack.com/app-automate/recent_apps?limit=100`,t,n)).find(e=>e.reference===r);return i?{status:`verified`,...i}:{status:`configured`,reference:r,message:`App reference was not found in the 100 most recent uploads; BrowserStack validates it when creating the session.`}}return/^https?:\/\//i.test(r)?{status:`configured`,reference:r,message:`Public app URL configured; BrowserStack validates it when creating the session.`}:{status:`configured`,name:u.basename(r),reference:r,message:`Local app artifact is ready and will be uploaded when creating the session.`}}async function Y(t,n,r){try{let i=await fetch(t,{headers:{...y(r),Authorization:b(n)},signal:AbortSignal.timeout(15e3)});if(!i.ok){let t=i.status===401||i.status===403;throw new e(t?`UNAUTHORIZED`:`COMMAND_FAILED`,`BrowserStack rejected connection verification.`,{status:i.status,hint:t?`Check BROWSERSTACK_USERNAME and BROWSERSTACK_ACCESS_KEY.`:`Retry connect or check the BrowserStack service status.`})}return await i.json()}catch(t){throw t instanceof e?t:new e(`COMMAND_FAILED`,`BrowserStack connection verification failed.`,{hint:`Check network access to api-cloud.browserstack.com and retry connect.`},t)}}function kt(e,t){let n=e=>e.replace(/(?:\.0)+$/,``);return n(e)===n(t)}function At(t){if(!Array.isArray(t))throw new e(`COMMAND_FAILED`,`BrowserStack device verification response was not a list.`);return t.flatMap(e=>{let t=X(e),n=t?.os_version;return t&&typeof t.device==`string`&&typeof t.os==`string`&&(typeof n==`string`||typeof n==`number`)?[{device:t.device,os:t.os,osVersion:String(n)}]:[]})}function jt(t){let n=X(t);if(n&&Object.keys(n).length===0)return[];if(!Array.isArray(t))throw new e(`COMMAND_FAILED`,`BrowserStack app verification response was not a list.`);return t.flatMap(e=>{let t=X(e);return!t||typeof t.app_url!=`string`?[]:[{reference:t.app_url,...typeof t.app_name==`string`?{name:t.app_name}:{},...typeof t.app_version==`string`?{version:t.app_version}:{}}]})}function X(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:void 0}async function Mt(e,t){return e.provider===`browserstack`?await Dt(e,t.clientVersion):await wt(e,t.runHostCommand)}function Nt(e){return[{provider:L.browserStack,createRuntime:t=>F({clientVersion:e.clientVersion,provider:L.browserStack,platform:`android`,deviceName:`BrowserStack device`,endpoint:t.BROWSERSTACK_WEBDRIVER_ENDPOINT??`https://hub-cloud.browserstack.com/wd/hub/`,capabilityOverrides:_t,listArtifacts:async({provider:n,providerSessionId:r})=>{let i=$(t,`BROWSERSTACK_USERNAME`,`BrowserStack artifact lookup`),a=$(t,`BROWSERSTACK_ACCESS_KEY`,`BrowserStack artifact lookup`);return await U(n,r,{clientVersion:e.clientVersion,username:i,accessKey:a,endpoint:t.BROWSERSTACK_SESSION_DETAILS_ENDPOINT})},prepareSession:async({req:n,lease:r,base:i})=>{let a=It(n,`BrowserStack`),o=$(t,`BROWSERSTACK_USERNAME`,`BrowserStack`),s=$(t,`BROWSERSTACK_ACCESS_KEY`,`BrowserStack`),c=Lt(a,`BrowserStack`),l=Z(a,`device`,`BrowserStack requires --device <name>.`),u=Z(a,`providerOsVersion`,`BrowserStack requires --provider-os-version <version>.`),ee=await Pt({clientVersion:e.clientVersion,app:Z(a,`providerApp`,`BrowserStack requires --provider-app <bs://app-id-or-local-path>.`),cwd:a.cwd,username:o,accessKey:s,uploadEndpoint:t.BROWSERSTACK_APP_UPLOAD_ENDPOINT});return{...i,platform:c,deviceName:l,auth:{username:o,accessKey:s},uploadApp:vt({clientVersion:e.clientVersion,username:o,accessKey:s,endpoint:t.BROWSERSTACK_APP_UPLOAD_ENDPOINT??`https://api-cloud.browserstack.com/app-automate/upload`}),webdriverCapabilities:yt({deviceName:l,osVersion:u,app:ee,projectName:Q(a,`providerProject`),buildName:Q(a,`providerBuild`)??r.runId,sessionName:Q(a,`providerSessionName`)??r.leaseId,deviceFeatures:ut(ft(a.flags),c),configured:N(c,l)})}}}),listArtifactsFromEnv:async(t,n)=>{let r=$(n,`BROWSERSTACK_USERNAME`,`BrowserStack artifact lookup`),i=$(n,`BROWSERSTACK_ACCESS_KEY`,`BrowserStack artifact lookup`);return await U(L.browserStack,t,{clientVersion:e.clientVersion,username:r,accessKey:i,endpoint:n.BROWSERSTACK_SESSION_DETAILS_ENDPOINT})}},{provider:L.awsDeviceFarm,createRuntime:t=>F({clientVersion:e.clientVersion,provider:L.awsDeviceFarm,endpoint:`http://127.0.0.1/`,platform:`android`,deviceName:`AWS Device Farm device`,capabilityOverrides:it,listArtifacts:async({provider:n,providerSessionId:r})=>await I(n,r,R({runHostCommand:e.runHostCommand,region:t.AWS_REGION??t.AWS_DEFAULT_REGION??K(r??``)})),prepareSession:async({req:n,lease:r,base:i})=>{let a=It(n,`AWS Device Farm`);H(a.flags,L.awsDeviceFarm);let o=Lt(a,`AWS Device Farm`);return await at({client:R({runHostCommand:e.runHostCommand,region:Q(a,`awsRegion`)??t.AWS_REGION??t.AWS_DEFAULT_REGION}),projectArn:Rt(a,t,`awsProjectArn`,`AGENT_DEVICE_AWS_DEVICE_FARM_PROJECT_ARN`,`AWS_DEVICE_FARM_PROJECT_ARN`),deviceArn:Rt(a,t,`awsDeviceArn`,`AGENT_DEVICE_AWS_DEVICE_FARM_DEVICE_ARN`,`AWS_DEVICE_FARM_DEVICE_ARN`),appArn:Q(a,`awsAppArn`)??t.AGENT_DEVICE_AWS_DEVICE_FARM_APP_ARN??t.AWS_DEVICE_FARM_APP_ARN,platform:o,deviceName:Q(a,`device`)??`AWS Device Farm device`,sessionName:Q(a,`providerSessionName`)??r.leaseId,interactionMode:zt(a)})({lease:r,req:n,base:i})}}),listArtifactsFromEnv:async(t,n)=>{let r=R({runHostCommand:e.runHostCommand,region:n.AWS_REGION??n.AWS_DEFAULT_REGION??K(t)});return await I(L.awsDeviceFarm,t,r)}}]}async function Pt(t){if(Ft(t.app))return t.app;let n=u.resolve(t.cwd??process.cwd(),t.app);if(!ee.existsSync(n))throw new e(`INVALID_ARGS`,`BrowserStack --provider-app must be a bs:// app id, URL, or existing local app path.`,{providerApp:t.app});return await W(n,{clientVersion:t.clientVersion,username:t.username,accessKey:t.accessKey,endpoint:t.uploadEndpoint})}function Ft(e){return e.startsWith(`bs://`)||/^https?:\/\//.test(e)}function It(t,n){if(t)return t;throw new e(`INVALID_ARGS`,`${n} lease allocation requires provider profile flags on the request.`)}function Lt(t,n){let r=t.flags?.platform;if(r===`android`||r===`ios`)return r;throw new e(`INVALID_ARGS`,`${n} requires --platform ios|android.`)}function Z(t,n,r){let i=Q(t,n);if(i)return i;throw new e(`INVALID_ARGS`,r)}function Q(e,t){let n=e.flags?.[t];return typeof n==`string`&&n.length>0?n:void 0}function $(t,n,r){let i=t[n];if(i)return i;throw new e(`INVALID_ARGS`,`${r} requires ${n} in the environment.`)}function Rt(t,n,r,i,a){let o=Q(t,r)??n[i]??n[a];if(o)return o;throw new e(`INVALID_ARGS`,`AWS Device Farm requires --${Bt(String(r))} or ${a}.`)}function zt(e){let t=Q(e,`awsInteractionMode`);if(t===`INTERACTIVE`||t===`NO_VIDEO`||t===`VIDEO_ONLY`)return t}function Bt(e){return e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}function Vt(e){let t=Nt(e);return{providerIds:t.map(e=>e.provider),createDefaultRuntimes:(e=process.env)=>t.map(t=>t.createRuntime(e)),listArtifactsFromEnv:async(e,n)=>{if(e.providerSessionId)return await t.find(t=>t.provider===e.provider)?.listArtifactsFromEnv(e.providerSessionId,n)},verifyConnection:async t=>await Mt(t,e)}}export{rt as a,L as i,K as n,H as r,Vt as t};
|
package/dist/src/src3.js
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
import{_ as e}from"./sdk-contracts.js";import{at as t}from"./version.js";import{z as n}from"./sdk-batch-runner.js";import{_ as r,a as i}from"./sdk-device.js";import{a}from"./sdk-remote-config.js";import{i as o,r as s}from"./device.js";import{r as c}from"./entities.js";import{t as l}from"./parser.js";import u from"node:path";import d from"node:fs";import ee from"node:fs/promises";import{setTimeout as f}from"node:timers/promises";const p={support:`supported`},m={support:`unsupported`},te={lease:p,inventory:{support:`partial`,note:`Inventory exposes only the leased cloud device, not the provider catalog.`},install:{support:`partial`,note:`Requires provider-specific upload or a path visible to the remote Appium server.`},open:p,close:p,snapshot:{support:`partial`,note:`Uses Appium page source XML, not agent-device native snapshot backends.`},screenshot:p,tap:p,doubleTap:p,longPress:p,swipe:p,scroll:{support:`partial`,note:`Implemented as viewport-relative W3C pointer gestures.`},fill:p,type:p,back:p,home:{support:`partial`,note:`Uses provider/Appium mobile pressButton support where available.`},orientation:{support:`partial`,note:`Uses the WebDriver rotation/orientation endpoints; four-way rotation collapses to portrait/landscape on drivers that only accept the two-way endpoint. Rotates the current display, so an activity that does not pin its orientation may need rotating again once it is foreground.`},appSwitcher:{support:`partial`,note:`Uses provider/Appium mobile pressButton support where available.`},tvRemote:m,"clipboard.read":{support:`partial`,note:`Uses provider/Appium clipboard extension support where available.`},"clipboard.write":{support:`partial`,note:`Uses provider/Appium clipboard extension support where available.`},settings:m,pinch:m,rotateGesture:m,transformGesture:m,logs:m,record:m,artifacts:m,portReverse:m,nativeSnapshotBackend:{support:`unsupported`,note:`Cloud WebDriver cannot upload or run agent-device native runner/helper backends.`}};function h(e){return{provider:e.provider,platform:e.platform,snapshotBackend:e.platform===`ios`?`xctest`:`android`,snapshotSource:`appium-page-source`,operations:ne(te,e.overrides)}}function g(e,t){return e.operations[t].support!==`unsupported`}function _(e,t){let n=e.operations[t],r=n.note?` ${n.note}`:``;return`${e.provider} WebDriver runtime does not support ${t}.${r}`}function ne(e,t){let n={...e};for(let[r,i]of Object.entries(t??{}))n[r]=typeof i==`string`?{...e[r],support:i}:{...e[r],...i};return n}function v(e){return{provider:e.provider,providerSessionId:e.providerSessionId,status:e.artifacts.length>0?`ready`:`pending`,cloudArtifacts:e.artifacts,...e.artifacts.length>0?{}:{message:e.pendingMessage}}}function re(e){return{provider:e.provider,providerSessionId:e.providerSessionId,status:`unavailable`,cloudArtifacts:[],message:e.error instanceof Error?e.error.message:String(e.error)}}function ie(e,t){let n=e?.bundleId??t?.appIdentifierHint,r=e?.packageName??t?.packageNameHint;return{bundleId:n,packageName:r,appName:e?.appName,launchTarget:oe(e?.launchTarget,n,r)}}function ae(e){return e===`ios`?`xctest`:`android`}function oe(...e){return e.find(e=>e!==void 0)}function y(e){return{"x-agent-device-client":`agent-device-cli`,"x-agent-device-version":e}}function se(e,t){return typeof e==`function`?e(t):e}function b(e){return`Basic ${Buffer.from(`${e.username}:${e.accessKey}`).toString(`base64`)}`}function ce(e){let t=0;for(;t<e.length&&e.charCodeAt(t)===47;)t+=1;return t===0?e:e.slice(t)}function le(e){let t=e.length-1;for(;t>=0&&e.charCodeAt(t)===47;)--t;return t===e.length-1?e:e.slice(0,t+1)}function ue(e){if(e.pathname.endsWith(`/`))return e;let t=new URL(e);return t.pathname=`${t.pathname}/`,t}var de=class{endpoint;headers;requestPolicy;sessionId;constructor(e){this.endpoint=ue(new URL(e.endpoint)),this.headers={...y(e.clientVersion),...e.auth?{Authorization:b(e.auth)}:{},...e.headers},this.requestPolicy={timeoutMs:e.requestPolicy?.timeoutMs??3e4,retryAttempts:e.requestPolicy?.retryAttempts??1,retryDelayMs:e.requestPolicy?.retryDelayMs??250}}async createSession(e){let t=me(await this.requestValue(`POST`,`/session`,{capabilities:pe(e)}));return this.sessionId=t.sessionId,t}async deleteSession(){let e=this.requireSessionId();await this.requestValue(`DELETE`,`/session/${e}`),this.sessionId=void 0}async installApp(e){await this.sessionRequest(`POST`,`/appium/device/install_app`,{appPath:e})}async activateApp(e){try{await this.sessionRequest(`POST`,`/appium/device/activate_app`,{appId:e})}catch{await this.executeScript(`mobile: activateApp`,[{appId:e,bundleId:e}])}}async terminateApp(e){try{await this.sessionRequest(`POST`,`/appium/device/terminate_app`,{appId:e})}catch{await this.executeScript(`mobile: terminateApp`,[{appId:e,bundleId:e}])}}async performActions(e){await this.sessionRequest(`POST`,`/actions`,{actions:e})}async releaseActions(){await this.sessionRequest(`DELETE`,`/actions`,void 0,{retryAttempts:0})}async sendKeys(e){await this.sessionRequest(`POST`,`/keys`,{value:Array.from(e)})}async hideKeyboard(){await this.sessionRequest(`POST`,`/appium/device/hide_keyboard`,void 0,{retryAttempts:0})}async isKeyboardShown(e){let t;try{t=await this.sessionRequest(`GET`,`/appium/device/is_keyboard_shown`,void 0,{retryAttempts:0,...e===void 0?{}:{timeoutMs:e}})}catch(e){if(w(e))return`unsupported`;throw e}return typeof t==`boolean`?t:`unsupported`}async activeElement(e){let t=e===void 0?void 0:Date.now()+e,n;try{n=be(await this.sessionRequest(`GET`,`/element/active`,void 0,S(t)))}catch(e){if(w(e))return`unsupported`;if(C(e))return`none`;throw e}if(n===void 0)return`unsupported`;try{let e=await this.sessionRequest(`GET`,`/element/${encodeURIComponent(n)}/rect`,void 0,S(t));return{id:n,rect:fe(e)}}catch(e){if(w(e))return`unsupported`;if(C(e))return`none`;throw e}}async back(){await this.sessionRequest(`POST`,`/back`)}async setRotation(e){await this.sessionRequest(`POST`,`/rotation`,{x:0,y:0,z:e})}async setOrientation(e){await this.sessionRequest(`POST`,`/orientation`,{orientation:e})}async source(){let t=await this.sessionRequest(`GET`,`/source`);if(typeof t!=`string`)throw new e(`COMMAND_FAILED`,`WebDriver source response was not a string`,{valueType:typeof t});return t}async screenshot(t){let n=await this.sessionRequest(`GET`,`/screenshot`);if(typeof n!=`string`)throw new e(`COMMAND_FAILED`,`WebDriver screenshot response was not base64 text`,{valueType:typeof n});await ee.writeFile(t,Buffer.from(n,`base64`))}async windowRect(){return fe(await this.sessionRequest(`GET`,`/window/rect`))}async executeScript(e,t=[]){return await this.sessionRequest(`POST`,`/execute/sync`,{script:e,args:t})}async sessionRequest(e,t,n,r){let i=this.requireSessionId();return await this.requestValue(e,`/session/${i}${t}`,n,r)}requireSessionId(){if(!this.sessionId)throw new e(`SESSION_NOT_FOUND`,`WebDriver session has not been created yet.`);return this.sessionId}async requestValue(e,t,n,r){let i,a=r?.retryAttempts??this.requestPolicy.retryAttempts,o=r?.timeoutMs??this.requestPolicy.timeoutMs;for(let r=0;r<=a;r+=1)try{return await this.requestValueOnce(e,t,n,o)}catch(e){if(i=e,!xe(e)||r>=a)throw e;await f(this.requestPolicy.retryDelayMs)}throw i}async requestValueOnce(e,t,n,r){let i=await fetch(new URL(ce(t),this.endpoint),{method:e,headers:{Accept:`application/json`,...n===void 0?{}:{"Content-Type":`application/json`},...this.headers},body:n===void 0?void 0:JSON.stringify(n),signal:AbortSignal.timeout(r)}),a=await i.text(),o=a?ge(a):{};if(!i.ok)throw _e(i.status,o);return he(o)}};function fe(t){if(!t||typeof t!=`object`)throw new e(`COMMAND_FAILED`,`WebDriver window rect response was empty.`);let n=t,r={x:x(n,`x`),y:x(n,`y`),width:x(n,`width`),height:x(n,`height`)};if(r.x===void 0||r.y===void 0||r.width===void 0||r.height===void 0)throw new e(`COMMAND_FAILED`,`WebDriver window rect response was invalid.`,{response:n});return r}function x(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function pe(e){return`alwaysMatch`in e||`firstMatch`in e?e:{alwaysMatch:e}}function me(t){if(!t||typeof t!=`object`)throw new e(`COMMAND_FAILED`,`WebDriver create-session response was empty.`);let n=t,r=typeof n.sessionId==`string`?n.sessionId:typeof n.session_id==`string`?n.session_id:void 0;if(!r)throw new e(`COMMAND_FAILED`,`WebDriver create-session response missed sessionId.`,{response:n});return{sessionId:r,capabilities:n.capabilities&&typeof n.capabilities==`object`?n.capabilities:{}}}function he(e){if(!e||typeof e!=`object`)return e;let t=e;return`value`in t?t.value:e}function ge(t){try{return JSON.parse(t)}catch(n){throw new e(`COMMAND_FAILED`,`WebDriver response was not valid JSON.`,{text:t},n)}}function _e(t,n){let r=n&&typeof n==`object`&&`value`in n?n.value:n;return new e(`COMMAND_FAILED`,r&&typeof r==`object`&&typeof r.message==`string`?r.message:`WebDriver request failed with HTTP ${t}.`,{status:t,response:n})}const ve=new Set([405,501]),ye=new Set([`unknown command`,`unknown method`]);function be(e){if(!e||typeof e!=`object`)return;let t=e,n=t[`element-6066-11e4-a52e-4f735466cecf`]??t.ELEMENT;return typeof n==`string`&&n.length>0?n:void 0}function S(e){return e===void 0?{retryAttempts:0}:{retryAttempts:0,timeoutMs:Math.max(0,e-Date.now())}}function C(t){return t instanceof e?T(t).toLowerCase()===`no such element`:!1}function w(t){if(!(t instanceof e))return!1;let n=t.details?.status;return typeof n==`number`&&ve.has(n)?!0:ye.has(T(t).toLowerCase())}function T(e){let t=e.details?.response,n=t&&typeof t==`object`?t.value:void 0,r=n&&typeof n==`object`?n.error:void 0;return typeof r==`string`?r:``}function xe(t){if(t instanceof e){let e=t.details?.status;return typeof e==`number`&&e>=500}return t instanceof TypeError||t instanceof Error&&t.name===`TimeoutError`}function E(e,t){return{type:`pointer`,id:e,parameters:{pointerType:`touch`},actions:t}}function D(t){let n;try{n=l(t)}catch(t){throw new e(`COMMAND_FAILED`,`Failed to parse WebDriver page source XML: ${t instanceof Error?t.message:String(t)}`,void 0,t)}let r=[];for(let e of n)O(r,e);return r}function O(e,t,n,r=0){let i=Object.keys(t.attributes).length===0?n:Se(e,t,n,r),a=i===n?r:r+1;for(let n of t.children)O(e,n,i,a)}function Se(e,t,n,r){let i=e.length;return e.push(Ce(i,t.name,t.attributes,n,r)),i}function Ce(e,t,n,r,i){let a=we(n),o=j(n.enabled,!0),s=j(n.displayed??n.visible,!0);return{index:e,type:t,role:Te(t,n),label:k(n,[`content-desc`,`label`,`text`,`name`]),value:A(n.value),identifier:k(n,[`resource-id`,`id`,`accessibility-id`,`name`]),rect:a,enabled:o,selected:j(n.selected),focused:j(n.focused),visibleToUser:s,hittable:s&&o&&a!==void 0&&a.width>0&&a.height>0,depth:i,parentIndex:r}}function we(e){let t=c(e.bounds??null);if(t)return t;let n=M(e.x),r=M(e.y),i=M(e.width),a=M(e.height);if(!(n===void 0||r===void 0||i===void 0||a===void 0))return{x:n,y:r,width:i,height:a}}function k(e,t){for(let n of t){let t=A(e[n]);if(t!==void 0)return t}}function A(e){return e||void 0}function j(e,t=!1){return e===void 0?t:e===`true`||e===`1`}function M(e){if(e===void 0||e===``)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function Te(e,t){return A(t.class)??A(e.replace(/^XCUIElementType/,``).toLowerCase())}function Ee(e){let t=D(e).flatMap(e=>De(e)&&Oe(e.rect)?[e.rect]:[]).sort((e,t)=>t.width*t.height-e.width*e.height)[0];return t?{x:t.x,y:t.y,width:t.width,height:t.height}:void 0}function De(e){let t=e.type?.toLowerCase()??``;return e.visibleToUser!==!1&&(t.includes(`scrollview`)||t.includes(`listview`)||t.includes(`recyclerview`))}function Oe(e){return!!e&&e.width>=50&&e.height>=50}async function ke(t,n,r){let i=[];for(let e of n===`android`?[`rotation`,`orientation`]:[`orientation`,`rotation`])try{await Pe(t,e,r);return}catch(t){if(!Me(t))throw t;i.push({transport:e,error:t instanceof Error?t.message:String(t)})}throw new e(`COMMAND_FAILED`,`Could not set device orientation to ${r} on the hosted WebDriver session.`,{hint:`The provider driver rejected both orientation endpoints. Set the orientation as a session capability instead, for example connect --provider-device-orientation portrait.`,rotation:r,attempts:i})}const Ae=new Set([`unknown command`,`unknown method`]),je=new Set([404,405]);function Me(t){if(!(t instanceof e)||t.code===`SESSION_NOT_FOUND`)return!1;let n=Ne(t.details?.response);if(n)return Ae.has(n);let r=t.details?.status;return typeof r==`number`&&je.has(r)}function Ne(e){if(!e||typeof e!=`object`)return``;let t=e.value;if(!t||typeof t!=`object`)return``;let n=t.error;return typeof n==`string`?n:``}async function Pe(e,t,n){if(t===`rotation`){await e.setRotation(o(n));return}await e.setOrientation(s(n))}const N=1500;function Fe(e){return new Promise(t=>setTimeout(t,e))}function P(t,n,r){return new e(`COMMAND_FAILED`,`fill tapped (${t}, ${n}) but ${r}`,{reason:`text_entry_focus_not_observed`,x:t,y:n,hint:`The tap most likely missed the field. Re-check the target with snapshot -i and fill the element it reports, rather than retrying the same coordinates.`})}function Ie(t,n){return new e(`COMMAND_FAILED`,`fill tapped (${t}, ${n}) but this driver reports neither the focused element nor keyboard state, so the text was not sent`,{reason:`text_entry_focus_unobservable`,x:t,y:n,hint:`This provider cannot confirm a field took focus. Use press <target> followed by type <text> to enter it anyway, accepting that nothing witnesses which field receives the keys.`})}function Le(e,t,n){return t>=e.x&&t<=e.x+e.width&&n>=e.y&&n<=e.y+e.height}function Re(e){return new ze(e.client,e.backend,e.capabilities)}var ze=class{client;backend;capabilities;constructor(e,t,n){this.client=e,this.backend=t,this.capabilities=n}async open(e,t){if(this.requireSupport(`open`),t?.url){await this.client.executeScript(`mobile: deepLink`,[{url:t.url,package:e}]);return}let n=t?.appBundleId??e;n&&await this.client.activateApp(n)}async openDevice(){this.requireSupport(`open`),await this.client.executeScript(`mobile: activateApp`,[{}])}async close(e){this.requireSupport(`close`),e&&await this.client.terminateApp(e)}async tap(e,t){return this.requireSupport(`tap`),await this.pointerGesture(`tap`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x:e,y:t}}async doubleTap(e,t){return this.requireSupport(`doubleTap`),await this.pointerGesture(`doubleTap`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pointerUp`,button:0},{type:`pause`,duration:80},{type:`pointerDown`,button:0},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x:e,y:t}}async swipe(e,t,n,r,i=400){return this.requireSupport(`swipe`),await this.pointerGesture(`swipe`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pointerMove`,duration:i,x:n,y:r},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x1:e,y1:t,x2:n,y2:r,durationMs:i}}async longPress(e,t,n=600){return this.requireSupport(`longPress`),await this.pointerGesture(`longPress`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pause`,duration:n},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x:e,y:t,durationMs:n}}async focus(e,t){return await this.tap(e,t)}async type(e){this.requireSupport(`type`),await this.client.sendKeys(e)}async fill(e,t,n,r){this.requireSupport(`fill`);let i=await this.readTextEntryState();await this.tap(e,t);let a=await this.awaitTextEntryReadiness(i,e,t);return await this.type(n),{backend:`webdriver`,x:e,y:t,text:n,textEntryReadiness:a}}async scroll(e,n){this.requireSupport(`scroll`);let r=n?.durationMs??350;await this.client.hideKeyboard().catch(()=>void 0);let i=await this.scrollGestureFrame(),a=t({direction:e,amount:n?.amount,pixels:n?.pixels,referenceWidth:i.width,referenceHeight:i.height}),o={...a,x1:a.x1+i.x,y1:a.y1+i.y,x2:a.x2+i.x,y2:a.y2+i.y};return await this.swipe(o.x1,o.y1,o.x2,o.y2,r),{backend:`webdriver`,...o,distance:a.pixels,durationMs:r}}async gestureViewport(){return await this.scrollGestureFrame()}async performGesture(e){return this.requireSupport(Ve(e)),await this.client.performActions(e.pointers.map(e=>E(`gesture-pointer-${e.pointerId}`,Be(e.samples)))),await this.client.releaseActions().catch(()=>void 0),{backend:`webdriver-w3c-actions`}}async screenshot(e,t){this.requireSupport(`screenshot`),await this.client.screenshot(e)}async snapshot(e){return this.requireSupport(`snapshot`),{backend:this.backend,nodes:D(await this.client.source())}}async back(e){this.requireSupport(`back`),await this.client.back()}async home(){this.requireSupport(`home`),await this.client.executeScript(`mobile: pressButton`,[{name:`home`}])}async setOrientation(e){this.requireSupport(`orientation`),await ke(this.client,this.backend,e)}async appSwitcher(){this.requireSupport(`appSwitcher`),await this.client.executeScript(`mobile: pressButton`,[{name:`appSwitch`}])}async tvRemote(e,t){this.unsupported(`tvRemote`)}async readClipboard(){this.requireSupport(`clipboard.read`);let e=await this.client.executeScript(`mobile: getClipboard`,[{}]);return typeof e==`string`?e:``}async writeClipboard(e){this.requireSupport(`clipboard.write`),await this.client.executeScript(`mobile: setClipboard`,[{content:e}])}async setSetting(e,t,n,r){this.unsupported(`settings`)}async awaitTextEntryReadiness(e,t,n){let r=e.keyboard,i=Date.now()+2e3,a=e.focusedElementId,o=await this.pollWithinBudget(i,async e=>{let r=await this.client.activeElement(e);return r===`unsupported`?`abandon`:r===`none`?`retry`:r.id!==a||Le(r.rect,t,n)?`satisfied`:`retry`});if(o===`satisfied`)return`focused-element`;if(o===`expired`)throw P(t,n,`nothing there took text-entry focus, so the text was not sent`);if(r===`unsupported`)throw Ie(t,n);if(r)throw P(t,n,`the keyboard was already up and this driver cannot report which field holds focus, so the text was not sent`);if(await this.pollWithinBudget(i,async e=>await this.client.isKeyboardShown(e)===!0?`satisfied`:`retry`)===`satisfied`)return`keyboard-shown`;throw P(t,n,`no keyboard appeared, so the text was not sent`)}async readTextEntryState(){let[e,t]=await Promise.all([this.client.isKeyboardShown(N),this.client.activeElement(N)]);return{keyboard:e,focusedElementId:t===`none`||t===`unsupported`?void 0:t.id}}async pollWithinBudget(e,t){let n=!1,r;for(;;){let i=e-Date.now();if(i<=0)break;try{let e=await t(Math.min(N,i));if(n=!0,e!==`retry`)return e}catch(e){r=e}let a=e-Date.now();if(a<=0)break;await Fe(Math.min(100,a))}if(!n&&r!==void 0)throw r;return`expired`}async pointerGesture(e,t){await this.client.performActions([E(e,t)]),await this.client.releaseActions().catch(()=>void 0)}async scrollGestureFrame(){return await this.client.source().then(e=>Ee(e)).catch(()=>void 0)||await this.client.windowRect()}requireSupport(e){g(this.capabilities,e)||this.unsupported(e)}unsupported(t){throw new e(`UNSUPPORTED_OPERATION`,_(this.capabilities,t),{provider:this.capabilities.provider,platform:this.capabilities.platform,operation:t})}};function Be(t){let n=t[0];if(!n)throw new e(`INVALID_ARGS`,`WebDriver gesture pointer requires samples`);let r=[{type:`pointerMove`,duration:0,x:n.point.x,y:n.point.y},{type:`pointerDown`,button:0}];for(let e=1;e<t.length;e+=1){let n=t[e-1],i=t[e];r.push({type:`pointerMove`,duration:i.offsetMs-n.offsetMs,x:i.point.x,y:i.point.y})}return r.push({type:`pointerUp`,button:0}),r}function Ve(e){if(e.topology===`single`)return`swipe`;switch(e.intent){case`pan`:case`transform`:return`transformGesture`;case`pinch`:return`pinch`;case`rotate`:return`rotateGesture`}}function F(e){return new He(e)}function I(e,t,n={}){return{platformName:e===`ios`?`iOS`:`Android`,"appium:deviceName":t,...n}}var He=class{provider;owner;leaseLifecycle;cloudArtifacts;deviceInventoryProvider;capabilities;sessionsByLeaseId=new Map;releasedProviderSessionIdsByLeaseId=new Map;options;constructor(e){this.options=e,this.provider=e.provider,this.owner=n(e.provider,e.platform),this.capabilities=h({provider:e.provider,platform:e.platform,overrides:e.capabilityOverrides}),this.leaseLifecycle={allocate:async(e,t)=>await this.allocate(e,t),heartbeat:async e=>this.heartbeat(e),release:async e=>await this.release(e)},this.cloudArtifacts={listCloudArtifacts:async e=>await this.listCloudArtifacts(e)},this.deviceInventoryProvider=async e=>{if(e.leaseProvider!==this.provider)return null;if(!e.leaseId)return[];let t=this.sessionsByLeaseId.get(e.leaseId);return t?[t.device]:[]}}async loadRuntime(e){let{createWebDriverPlatformRuntimeOwner:t}=await import(`./platform-runtime.js`);return t({host:e,owner:this.owner,ownsDevice:e=>this.ownsDevice(e)})}ownsDevice(e){return[...this.sessionsByLeaseId.values()].some(t=>t.device.id===e.id)}getInteractor(e){return[...this.sessionsByLeaseId.values()].find(t=>t.device.id===e.id)?.interactor}async installApp(e,t,n,r){let i=this.findSessionForDevice(e);if(!i)return;let a=await this.uploadAppIfNeeded(i,e,t,n,r);return await i.client.installApp(a?.appReference??n),ie(a,r)}async installInstallablePath(e,t,n){return await this.installApp(e,``,t,n)}async shutdown(){await Promise.allSettled([...this.sessionsByLeaseId.values()].map(async e=>await this.closeSession(e))),this.sessionsByLeaseId.clear()}async allocate(e,t){if(e.leaseProvider!==this.provider)return;if(this.sessionsByLeaseId.has(e.leaseId))return this.heartbeat(e);let n=await this.prepareSession(e,t),r=new de({clientVersion:this.options.clientVersion,endpoint:n.endpoint,auth:n.auth,headers:n.headers,requestPolicy:this.options.requestPolicy}),i=await this.createSessionWithPreparedCleanup(r,n),a=this.deviceForLease(e,n),o=n.providerSessionId??i.sessionId,s=this.capabilitiesForPlatform(n.platform);return this.sessionsByLeaseId.set(e.leaseId,{lease:e,device:a,client:r,prepared:n,capabilities:s,webDriverSessionId:i.sessionId,providerSessionId:o,interactor:Re({client:r,backend:ae(n.platform),capabilities:s})}),{provider:this.provider,deviceId:a.id,sessionId:i.sessionId,providerSessionId:o,capabilities:s,...n.providerData}}async createSessionWithPreparedCleanup(e,t){try{return await e.createSession(t.webdriverCapabilities)}catch(e){throw await Ue(t,e),e}}heartbeat(e){if(e.leaseProvider===this.provider&&this.sessionsByLeaseId.has(e.leaseId))return{provider:this.provider}}async release(e){if(e.leaseProvider!==this.provider)return;let t=this.sessionsByLeaseId.get(e.leaseId);if(!t)return;this.sessionsByLeaseId.delete(e.leaseId),this.releasedProviderSessionIdsByLeaseId.set(e.leaseId,t.providerSessionId);let n=await this.closeSession(t),r=await this.safeListArtifacts(t);return{provider:this.provider,providerSessionId:t.providerSessionId,...n.cleanup,...n.warnings.length>0?{warnings:n.warnings}:{},...r?{cloudArtifacts:r}:{}}}async listCloudArtifacts(e){if(e.provider!==this.provider)return;let t=e.leaseId?this.sessionsByLeaseId.get(e.leaseId):void 0;if(t)return await this.safeListArtifacts(t);let n=e.providerSessionId??(e.leaseId?this.releasedProviderSessionIdsByLeaseId.get(e.leaseId):void 0);if(!(!n||!this.options.listArtifacts))return await this.options.listArtifacts({provider:this.provider,providerSessionId:n})}async prepareSession(e,t){let n=this.baseSessionForLease(e);return this.options.prepareSession?await this.options.prepareSession({lease:e,req:t,base:n}):n}capabilitiesForPlatform(e){return h({provider:this.provider,platform:e,overrides:this.options.capabilityOverrides})}baseSessionForLease(e){let t=typeof this.options.webdriverCapabilities==`function`?this.options.webdriverCapabilities(e):this.options.webdriverCapabilities??{};return{provider:this.provider,endpoint:this.options.endpoint,platform:this.options.platform,deviceName:this.options.deviceName,auth:this.options.auth,headers:this.options.headers,webdriverCapabilities:I(this.options.platform,this.options.deviceName,t)}}deviceForLease(e,t){return{...i(t.platform),id:t.deviceId??this.options.deviceId?.(e)??`${this.provider}:${t.platform}:${e.leaseId}`,name:t.deviceName,kind:`device`,target:`mobile`,booted:!0}}findSessionForDevice(e){return[...this.sessionsByLeaseId.values()].find(t=>t.device.id===e.id)}async uploadAppIfNeeded(t,n,i,a,o){if(!g(t.capabilities,`install`))throw new e(`UNSUPPORTED_OPERATION`,_(t.capabilities,`install`),{provider:this.provider,deviceId:n.id,platform:r(n)});let s=t.prepared.uploadApp??this.options.uploadApp;if(s)return await s({provider:this.provider,lease:t.lease,device:n,app:i,appPath:a,options:o})}async closeSession(e){let t=[],n;try{await e.client.deleteSession()}catch(e){t.push({code:`WEBDRIVER_SESSION_DELETE_FAILED`,message:L(e)})}try{n=await e.prepared.cleanup?.()}catch(e){t.push({code:`PROVIDER_CLEANUP_FAILED`,message:L(e)})}return{cleanup:n,warnings:t}}async safeListArtifacts(e){let t=e.prepared.listArtifacts??this.options.listArtifacts;if(t)try{return await t({provider:this.provider,lease:e.lease,device:e.device,webDriverSessionId:e.webDriverSessionId,providerSessionId:e.providerSessionId})}catch(t){return re({provider:this.provider,providerSessionId:e.providerSessionId,error:t})}}};function L(e){return e instanceof Error?e.message:String(e)}async function Ue(t,n){try{await t.cleanup?.()}catch(t){n instanceof e&&(n.details={...n.details,cleanupError:L(t)})}}async function R(e,t,n){if(t)return v({provider:e,providerSessionId:t,artifacts:(await Promise.all([n.listArtifacts(t,`FILE`),n.listArtifacts(t,`LOG`)])).flat().flatMap(n=>Ge(e,t,n)),pendingMessage:`AWS Device Farm artifacts are not ready yet.`})}function We(e){if(!e||typeof e!=`object`)return[];let t=e.artifacts;return Array.isArray(t)?t:[]}function Ge(e,t,n){let r=n.url;return typeof r!=`string`||r.length===0?[]:[{provider:e,providerSessionId:t,kind:Ke(n.type),name:n.name??n.type??`AWS Device Farm artifact`,url:r,providerArtifactId:n.arn,extension:n.extension,availability:`ready`,metadata:{awsType:n.type,...n.metadata?{awsMetadata:n.metadata}:{}}}]}function Ke(e){switch(e){case`VIDEO`:return`video`;case`APPIUM_SERVER_OUTPUT`:return`appium-log`;case`DEVICE_LOG`:return`device-log`;case`MESSAGE_LOG`:case`UNKNOWN`:return`automation-log`;default:return`raw`}}const z={browserStack:`browserstack`,awsDeviceFarm:`aws-device-farm`},qe=new Set(Object.values(z));function Je(e){return e!==void 0&&qe.has(e)}z.awsDeviceFarm;const Ye={install:{support:`unsupported`,note:`Pass appArn when creating the remote access session; local artifact upload/install is not implemented.`},portReverse:{support:`unsupported`,note:`AWS Device Farm remote access does not expose agent-device port reverse.`},artifacts:{support:`supported`,note:`AWS Device Farm remote access exposes provider-hosted video, Appium logs, and device logs after session completion.`}};function B(e){let t=V(e);return{createRemoteAccessSession:async e=>H(await t(`create-remote-access-session`,[`--project-arn`,e.projectArn,`--device-arn`,e.deviceArn,`--name`,e.name,...e.appArn?[`--app-arn`,e.appArn]:[],...e.interactionMode?[`--interaction-mode`,e.interactionMode]:[],...e.configuration?[`--configuration`,JSON.stringify(e.configuration)]:[]])),getRemoteAccessSession:async e=>H(await t(`get-remote-access-session`,[`--arn`,e])),stopRemoteAccessSession:async e=>H(await t(`stop-remote-access-session`,[`--arn`,e])),listArtifacts:async(e,n)=>We(await t(`list-artifacts`,[`--arn`,e,`--type`,n]))}}function Xe(t){return async({lease:n,base:r})=>{let i=await $e((await t.client.createRemoteAccessSession({projectArn:t.projectArn,deviceArn:t.deviceArn,appArn:t.appArn,name:se(t.sessionName,n)??`agent-device-${n.leaseId}`,interactionMode:t.interactionMode,configuration:t.configuration})).arn,t),a=Ze(i);if(!a)throw new e(`COMMAND_FAILED`,`AWS Device Farm did not expose a WebDriver endpoint.`,{sessionArn:i.arn,status:i.status});let o=i.device?.name??t.deviceName,s=typeof t.webdriverCapabilities==`function`?t.webdriverCapabilities(n):t.webdriverCapabilities??{};return{...r,endpoint:a,platform:t.platform,deviceName:o,webdriverCapabilities:I(t.platform,o,s),cleanup:async()=>(await t.client.stopRemoteAccessSession(i.arn),{awsDeviceFarmSessionArn:i.arn}),providerSessionId:i.arn,providerData:{awsDeviceFarmSessionArn:i.arn}}}}function Ze(e){let t=e.endpoints&&typeof e.endpoints==`object`?Object.values(e.endpoints):[],n=[e.remoteDriverEndpoint,e.endpoint,...t,e.remoteDebugUrl,e.remoteRecordAppUrl].filter(e=>typeof e==`string`&&e.length>0).find(e=>!/^wss?:\/\//i.test(e));return n?Qe(n):void 0}function Qe(e){return/^https?:\/\//i.test(e)?e:`http://${e}`}async function $e(t,n){let r=n.startupTimeoutMs??12e4,i=n.pollIntervalMs??5e3,a=Date.now(),o=await n.client.getRemoteAccessSession(t);for(;Date.now()-a<r;){if(o.status===`RUNNING`)return o;if(o.status===`ERRORED`||o.status===`STOPPED`||o.status===`COMPLETED`)throw new e(`COMMAND_FAILED`,`AWS Device Farm remote access session did not start.`,{sessionArn:t,status:o.status,result:o.result});await f(i),o=await n.client.getRemoteAccessSession(t)}throw new e(`COMMAND_FAILED`,`Timed out waiting for AWS Device Farm remote access.`,{sessionArn:t,status:o.status,result:o.result,timeoutMs:r})}async function et(t,n,r){let i=await t(n,r);try{return JSON.parse(i.stdout)}catch(t){throw new e(`COMMAND_FAILED`,`AWS Device Farm returned invalid JSON.`,void 0,t)}}function V(e){let t=e.region?[`--region`,e.region]:[],n=e.awsCommand??`aws`;return async(r,i)=>await et(e.runHostCommand,n,[`devicefarm`,r,...t,...i,`--output`,`json`])}function H(t){if(!t||typeof t!=`object`)throw new e(`COMMAND_FAILED`,`AWS Device Farm response was not an object.`,{response:t});let n=t.remoteAccessSession;if(!n||typeof n!=`object`)throw new e(`COMMAND_FAILED`,`AWS Device Farm response missed remoteAccessSession.`,{response:t});return n}const U=[{field:`providerDeviceOrientation`,capability:`deviceOrientation`,flag:`--provider-device-orientation`,type:`enum`,enumValues:a},{field:`providerGeoLocation`,capability:`geoLocation`,flag:`--provider-geo-location`,type:`string`},{field:`providerTimezone`,capability:`timezone`,flag:`--provider-timezone`,type:`string`},{field:`providerLanguage`,capability:`language`,flag:`--provider-language`,type:`string`},{field:`providerLocale`,capability:`locale`,flag:`--provider-locale`,type:`string`},{field:`providerNetworkProfile`,capability:`networkProfile`,flag:`--provider-network-profile`,type:`string`},{field:`providerCustomNetwork`,capability:`customNetwork`,flag:`--provider-custom-network`,type:`string`},{field:`providerNoResignApp`,capability:`resignApp`,flag:`--provider-no-resign-app`,type:`negated-boolean`,platform:`ios`}];function tt(e,t){st(e);let n={};for(let r of U){let i=e[r.field];i===void 0||i===!1||i===``||(ot(r,t),n[r.capability]=r.type===`negated-boolean`?!1:i)}return n}function nt(e){return U.filter(t=>{let n=e?.[t.field];return n!==void 0&&n!==!1&&n!==``}).map(e=>e.flag)}function W(t,n){let r=nt(t);if(r.length===0)return;let i=r.length!==1;throw new e(`INVALID_ARGS`,`${r.join(`, `)} ${i?`are`:`is`} only supported by BrowserStack, not ${n}.`,{hint:`Drop ${i?`those flags`:`the flag`} or use the browserstack provider.`,provider:n,flags:r})}function rt(e){let t={};for(let n of U){let r=e?.[n.field];if(n.type===`negated-boolean`){r===!0&&(t.providerNoResignApp=!0);continue}typeof r!=`string`||r.length===0||it(t,n,r)}return t}function it(e,t,n){if(t.field===`providerDeviceOrientation`){e.providerDeviceOrientation=at(t,n);return}t.field!==`providerNoResignApp`&&(e[t.field]=n)}function at(t,n){let r=a.find(e=>e===n);if(r)return r;throw new e(`INVALID_ARGS`,`Invalid ${t.flag} value: ${n}.`,{hint:`Use ${a.join(`|`)}.`,flag:t.flag,capability:t.capability})}function ot(t,n){if(!(!t.platform||t.platform===n))throw new e(`INVALID_ARGS`,`${t.flag} applies to ${t.platform} sessions only, but the session platform is ${n}.`,{hint:`Drop ${t.flag} or connect with --platform ${t.platform}.`,flag:t.flag,capability:t.capability,platform:n})}function st(t){if(!(!t.providerNetworkProfile||!t.providerCustomNetwork))throw new e(`INVALID_ARGS`,`BrowserStack accepts either a named network profile or a custom network shape, not both.`,{hint:`Pass only one of --provider-network-profile or --provider-custom-network.`,networkProfile:t.providerNetworkProfile,customNetwork:t.providerCustomNetwork})}z.browserStack;const ct={install:{support:`partial`,note:`Local app artifacts are uploaded to BrowserStack App Automate, then installed with Appium.`},portReverse:{support:`unsupported`,note:`Use BrowserStack Local for network tunneling; agent-device port reverse is not available.`},artifacts:{support:`supported`,note:`BrowserStack session details expose provider-hosted video, Appium logs, device logs, and dashboard links.`}};async function lt(e,t,n){if(t)return v({provider:e,providerSessionId:t,artifacts:ht(e,t,await mt(t,n)),pendingMessage:`BrowserStack artifacts are not ready yet.`})}async function ut(t,n){let r=await ee.readFile(t),i=new FormData;i.set(`file`,new Blob([r]),u.basename(t));let a=await fetch(n.endpoint??`https://api-cloud.browserstack.com/app-automate/upload`,{method:`POST`,headers:{...y(n.clientVersion),Authorization:b(n)},body:i}),o=await a.json(),s=gt(o);if(!a.ok||!s)throw new e(`COMMAND_FAILED`,`BrowserStack app upload failed.`,{status:a.status,response:o});return s}function dt(e){return async({appPath:t,options:n})=>({appReference:await ut(t,e),bundleId:n?.appIdentifierHint,packageName:n?.packageNameHint,launchTarget:n?.appIdentifierHint??n?.packageNameHint})}function ft(e){let{"bstack:options":t,...n}=e.configured??{};return{device:e.deviceName,os_version:e.osVersion,...e.app?{app:e.app}:{},...n,"bstack:options":{...e.projectName?{projectName:e.projectName}:{},buildName:e.buildName,sessionName:e.sessionName,...e.deviceFeatures??{},...pt(t)}}}function pt(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}async function mt(t,n){let r=new URL(`${le(String(n.endpoint??`https://api-cloud.browserstack.com/app-automate/sessions`))}/${t}.json`),i=await fetch(r,{headers:{...y(n.clientVersion),Authorization:b(n)}}),a=await i.json();if(!i.ok||!a||typeof a!=`object`)throw new e(`COMMAND_FAILED`,`BrowserStack session details lookup failed.`,{status:i.status,response:a});let o=a.automation_session??a;return o&&typeof o==`object`?o:{}}function ht(e,t,n){return[G(e,t,n,`video_url`,`video`,`Session video`),G(e,t,n,`appium_logs_url`,`appium-log`,`Appium logs`),G(e,t,n,`device_logs_url`,`device-log`,`Device logs`),G(e,t,n,`browser_url`,`provider-session`,`BrowserStack dashboard`),G(e,t,n,`public_url`,`provider-session`,`Public session link`)].filter(e=>e!==void 0)}function G(e,t,n,r,i,a){let o=n[r];if(!(typeof o!=`string`||o.length===0))return{provider:e,providerSessionId:t,kind:i,name:a,url:o,availability:`ready`}}function gt(e){if(!e||typeof e!=`object`)return;let t=e.app_url;return typeof t==`string`?t:void 0}function K(e){return/^arn:[^:]+:devicefarm:([^:]+):/.exec(e)?.[1]}async function _t(t,n){let r=V({runHostCommand:n,region:t.region}),[i,a,o]=await Promise.all([r(`get-project`,[`--arn`,t.projectArn]),r(`get-device`,[`--arn`,t.deviceArn]),t.appArn?r(`get-upload`,[`--arn`,t.appArn]):void 0]),s=q(i,`project`),c=q(a,`device`),l=yt(c.platform);if(l!==t.platform)throw new e(`INVALID_ARGS`,`AWS Device Farm device "${J(c.name)??t.deviceArn}" is ${l}, not ${t.platform}.`);let u=t.appArn?vt(q(o,`upload`),t):{status:`missing`,message:`No app upload is attached; AWS Device Farm does not support install after allocation. Reconnect with --aws-app-arn <arn>.`};return{provider:`aws-device-farm`,service:`AWS Device Farm`,verificationMessage:t.appArn?`Credentials, project, device, and app upload verified.`:`Credentials, project, and device verified.`,project:{name:J(s.name),reference:t.projectArn},device:{status:`verified`,name:J(c.name)??t.deviceArn,reference:t.deviceArn,platform:l,osVersion:J(c.os),availability:J(c.availability)},app:u}}function vt(t,n){let r=J(t.status);if(r!==`SUCCEEDED`)throw new e(`COMMAND_FAILED`,`AWS Device Farm app upload is not ready (${r??`unknown status`}).`,{status:r,hint:`Wait for the upload to succeed or reconnect with a different --aws-app-arn.`});let i=n.platform===`android`?`ANDROID_APP`:`IOS_APP`,a=J(t.type);if(a!==i)throw new e(`INVALID_ARGS`,`AWS Device Farm app upload type is ${a??`unknown`}, expected ${i}.`);return{status:`verified`,name:J(t.name),reference:n.appArn}}function q(t,n){if(!t||typeof t!=`object`)throw new e(`COMMAND_FAILED`,`AWS Device Farm ${n} response was not an object.`);let r=t[n];if(!r||typeof r!=`object`||Array.isArray(r))throw new e(`COMMAND_FAILED`,`AWS Device Farm response missed ${n}.`);return r}function yt(t){if(t===`ANDROID`)return`android`;if(t===`IOS`)return`ios`;throw new e(`UNSUPPORTED_PLATFORM`,`AWS Device Farm device platform is ${String(t)}.`)}function J(e){return typeof e==`string`&&e.length>0?e:void 0}async function bt(t,n){let r={username:t.username,accessKey:t.accessKey},i=wt(await St(t.devicesEndpoint??`https://api-cloud.browserstack.com/app-automate/devices.json`,r,n)).find(e=>e.device===t.deviceName&&e.os.toLowerCase()===t.platform&&Ct(e.osVersion,t.osVersion));if(!i)throw new e(`INVALID_ARGS`,`BrowserStack device "${t.deviceName}" with ${t.platform} ${t.osVersion} is not available.`,{hint:`Choose an exact device and OS version from the BrowserStack App Automate device list.`});let a=await xt(t,r,n);return{provider:`browserstack`,service:`BrowserStack`,verificationMessage:a.status===`verified`?`Credentials, device, and uploaded app verified.`:`Credentials and device access verified; app availability is checked when the session is created.`,device:{status:`verified`,name:i.device,platform:t.platform,osVersion:i.osVersion},app:a}}async function xt(e,t,n){let{app:r}=e;if(r.startsWith(`bs://`)){let i=Tt(await St(e.appsEndpoint??`https://api-cloud.browserstack.com/app-automate/recent_apps?limit=100`,t,n)).find(e=>e.reference===r);return i?{status:`verified`,...i}:{status:`configured`,reference:r,message:`App reference was not found in the 100 most recent uploads; BrowserStack validates it when creating the session.`}}return/^https?:\/\//i.test(r)?{status:`configured`,reference:r,message:`Public app URL configured; BrowserStack validates it when creating the session.`}:{status:`configured`,name:u.basename(r),reference:r,message:`Local app artifact is ready and will be uploaded when creating the session.`}}async function St(t,n,r){try{let i=await fetch(t,{headers:{...y(r),Authorization:b(n)},signal:AbortSignal.timeout(15e3)});if(!i.ok){let t=i.status===401||i.status===403;throw new e(t?`UNAUTHORIZED`:`COMMAND_FAILED`,`BrowserStack rejected connection verification.`,{status:i.status,hint:t?`Check BROWSERSTACK_USERNAME and BROWSERSTACK_ACCESS_KEY.`:`Retry connect or check the BrowserStack service status.`})}return await i.json()}catch(t){throw t instanceof e?t:new e(`COMMAND_FAILED`,`BrowserStack connection verification failed.`,{hint:`Check network access to api-cloud.browserstack.com and retry connect.`},t)}}function Ct(e,t){let n=e=>e.replace(/(?:\.0)+$/,``);return n(e)===n(t)}function wt(t){if(!Array.isArray(t))throw new e(`COMMAND_FAILED`,`BrowserStack device verification response was not a list.`);return t.flatMap(e=>{let t=Y(e),n=t?.os_version;return t&&typeof t.device==`string`&&typeof t.os==`string`&&(typeof n==`string`||typeof n==`number`)?[{device:t.device,os:t.os,osVersion:String(n)}]:[]})}function Tt(t){let n=Y(t);if(n&&Object.keys(n).length===0)return[];if(!Array.isArray(t))throw new e(`COMMAND_FAILED`,`BrowserStack app verification response was not a list.`);return t.flatMap(e=>{let t=Y(e);return!t||typeof t.app_url!=`string`?[]:[{reference:t.app_url,...typeof t.app_name==`string`?{name:t.app_name}:{},...typeof t.app_version==`string`?{version:t.app_version}:{}}]})}function Y(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:void 0}async function Et(e,t){return e.provider===`browserstack`?await bt(e,t.clientVersion):await _t(e,t.runHostCommand)}function Dt(e){return[{provider:z.browserStack,createRuntime:t=>F({clientVersion:e.clientVersion,provider:z.browserStack,platform:`android`,deviceName:`BrowserStack device`,endpoint:t.BROWSERSTACK_WEBDRIVER_ENDPOINT??`https://hub-cloud.browserstack.com/wd/hub/`,capabilityOverrides:ct,listArtifacts:async({provider:n,providerSessionId:r})=>{let i=Q(t,`BROWSERSTACK_USERNAME`,`BrowserStack artifact lookup`),a=Q(t,`BROWSERSTACK_ACCESS_KEY`,`BrowserStack artifact lookup`);return await lt(n,r,{clientVersion:e.clientVersion,username:i,accessKey:a,endpoint:t.BROWSERSTACK_SESSION_DETAILS_ENDPOINT})},prepareSession:async({req:n,lease:r,base:i})=>{let a=At(n,`BrowserStack`),o=Q(t,`BROWSERSTACK_USERNAME`,`BrowserStack`),s=Q(t,`BROWSERSTACK_ACCESS_KEY`,`BrowserStack`),c=jt(a,`BrowserStack`),l=X(a,`device`,`BrowserStack requires --device <name>.`),u=X(a,`providerOsVersion`,`BrowserStack requires --provider-os-version <version>.`),d=await Ot({clientVersion:e.clientVersion,app:X(a,`providerApp`,`BrowserStack requires --provider-app <bs://app-id-or-local-path>.`),cwd:a.cwd,username:o,accessKey:s,uploadEndpoint:t.BROWSERSTACK_APP_UPLOAD_ENDPOINT});return{...i,platform:c,deviceName:l,auth:{username:o,accessKey:s},uploadApp:dt({clientVersion:e.clientVersion,username:o,accessKey:s,endpoint:t.BROWSERSTACK_APP_UPLOAD_ENDPOINT??`https://api-cloud.browserstack.com/app-automate/upload`}),webdriverCapabilities:ft({deviceName:l,osVersion:u,app:d,projectName:Z(a,`providerProject`),buildName:Z(a,`providerBuild`)??r.runId,sessionName:Z(a,`providerSessionName`)??r.leaseId,deviceFeatures:tt(rt(a.flags),c),configured:I(c,l)})}}}),listArtifactsFromEnv:async(t,n)=>{let r=Q(n,`BROWSERSTACK_USERNAME`,`BrowserStack artifact lookup`),i=Q(n,`BROWSERSTACK_ACCESS_KEY`,`BrowserStack artifact lookup`);return await lt(z.browserStack,t,{clientVersion:e.clientVersion,username:r,accessKey:i,endpoint:n.BROWSERSTACK_SESSION_DETAILS_ENDPOINT})}},{provider:z.awsDeviceFarm,createRuntime:t=>F({clientVersion:e.clientVersion,provider:z.awsDeviceFarm,endpoint:`http://127.0.0.1/`,platform:`android`,deviceName:`AWS Device Farm device`,capabilityOverrides:Ye,listArtifacts:async({provider:n,providerSessionId:r})=>await R(n,r,B({runHostCommand:e.runHostCommand,region:t.AWS_REGION??t.AWS_DEFAULT_REGION??K(r??``)})),prepareSession:async({req:n,lease:r,base:i})=>{let a=At(n,`AWS Device Farm`);W(a.flags,z.awsDeviceFarm);let o=jt(a,`AWS Device Farm`);return await Xe({client:B({runHostCommand:e.runHostCommand,region:Z(a,`awsRegion`)??t.AWS_REGION??t.AWS_DEFAULT_REGION}),projectArn:$(a,t,`awsProjectArn`,`AGENT_DEVICE_AWS_DEVICE_FARM_PROJECT_ARN`,`AWS_DEVICE_FARM_PROJECT_ARN`),deviceArn:$(a,t,`awsDeviceArn`,`AGENT_DEVICE_AWS_DEVICE_FARM_DEVICE_ARN`,`AWS_DEVICE_FARM_DEVICE_ARN`),appArn:Z(a,`awsAppArn`)??t.AGENT_DEVICE_AWS_DEVICE_FARM_APP_ARN??t.AWS_DEVICE_FARM_APP_ARN,platform:o,deviceName:Z(a,`device`)??`AWS Device Farm device`,sessionName:Z(a,`providerSessionName`)??r.leaseId,interactionMode:Mt(a)})({lease:r,req:n,base:i})}}),listArtifactsFromEnv:async(t,n)=>{let r=B({runHostCommand:e.runHostCommand,region:n.AWS_REGION??n.AWS_DEFAULT_REGION??K(t)});return await R(z.awsDeviceFarm,t,r)}}]}async function Ot(t){if(kt(t.app))return t.app;let n=u.resolve(t.cwd??process.cwd(),t.app);if(!d.existsSync(n))throw new e(`INVALID_ARGS`,`BrowserStack --provider-app must be a bs:// app id, URL, or existing local app path.`,{providerApp:t.app});return await ut(n,{clientVersion:t.clientVersion,username:t.username,accessKey:t.accessKey,endpoint:t.uploadEndpoint})}function kt(e){return e.startsWith(`bs://`)||/^https?:\/\//.test(e)}function At(t,n){if(t)return t;throw new e(`INVALID_ARGS`,`${n} lease allocation requires provider profile flags on the request.`)}function jt(t,n){let r=t.flags?.platform;if(r===`android`||r===`ios`)return r;throw new e(`INVALID_ARGS`,`${n} requires --platform ios|android.`)}function X(t,n,r){let i=Z(t,n);if(i)return i;throw new e(`INVALID_ARGS`,r)}function Z(e,t){let n=e.flags?.[t];return typeof n==`string`&&n.length>0?n:void 0}function Q(t,n,r){let i=t[n];if(i)return i;throw new e(`INVALID_ARGS`,`${r} requires ${n} in the environment.`)}function $(t,n,r,i,a){let o=Z(t,r)??n[i]??n[a];if(o)return o;throw new e(`INVALID_ARGS`,`AWS Device Farm requires --${Nt(String(r))} or ${a}.`)}function Mt(e){let t=Z(e,`awsInteractionMode`);if(t===`INTERACTIVE`||t===`NO_VIDEO`||t===`VIDEO_ONLY`)return t}function Nt(e){return e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}function Pt(e){let t=Dt(e);return{providerIds:t.map(e=>e.provider),createDefaultRuntimes:(e=process.env)=>t.map(t=>t.createRuntime(e)),listArtifactsFromEnv:async(e,n)=>{if(e.providerSessionId)return await t.find(t=>t.provider===e.provider)?.listArtifactsFromEnv(e.providerSessionId,n)},verifyConnection:async t=>await Et(t,e)}}export{Je as a,z as i,K as n,W as r,Pt as t};
|
|
1
|
+
import{_ as e}from"./sdk-contracts.js";import{St as t,bt as n,dt as r,nt as i,wt as a}from"./sdk-batch-runner.js";import{d as o,o as s}from"./sdk-device.js";const c=4096;function l(e){return d(e,{seen:new WeakSet,nodes:0},0)}function u(e){return Object.freeze(Object.fromEntries(Object.entries(e).map(([e,t])=>[e,p(t)])))}function d(e,t,n){if(!te(e)||n>32||t.seen.has(e))return!1;t.seen.add(e),t.nodes+=1;let r=t.nodes<=c&&Object.values(e).every(e=>f(e,t,n+1));return t.seen.delete(e),r}function f(e,t,n){return ne(e)?!0:n>32?!1:Array.isArray(e)?ee(e,t,n):d(e,t,n)}function ee(e,t,n){if(t.seen.has(e))return!1;t.seen.add(e),t.nodes+=1;let r=t.nodes<=c&&e.every(e=>f(e,t,n+1));return t.seen.delete(e),r}function te(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ne(e){return e===null?!0:typeof e==`number`?Number.isFinite(e):typeof e==`string`||typeof e==`boolean`}function p(e){return Array.isArray(e)?Object.freeze(e.map(p)):typeof e==`object`&&e?u(e):e}function m(e){if(!S(e))return h(`Durable resource envelope must be an object`);let t=e.envelopeVersion;if(!x(t))return h(`Durable resource envelopeVersion must be a non-negative integer`);if(t!==1)return{status:`unreattachable`,reason:`descriptor-version-unsupported`,message:`Unsupported durable resource envelope version: ${t}`,version:t};if(!b(e.resourceKind))return h(`Durable resource resourceKind must be a non-empty string`);if(!b(e.sessionId))return h(`Durable resource sessionId must be a non-empty string`);let n=g(e.device);if(!n)return h(`Durable resource device identity is invalid`);let r=ae(e.owner);if(!r)return h(`Durable resource owner reference is invalid`);if(r.kind===`local-family`&&r.family!==n.family)return h(`Durable resource local owner does not match the device family`);let i=ue(e.fence);if(!i)return h(`Durable resource ownership fence is invalid`);if(!fe(e.lifecycle))return h(`Durable resource lifecycle state is invalid`);let a=de(e.descriptor);return a?e.metadata!==void 0&&!l(e.metadata)?h(`Durable resource metadata must be a JSON object`):{status:`decoded`,envelope:Object.freeze({envelopeVersion:1,resourceKind:e.resourceKind,sessionId:e.sessionId,device:n,owner:r,fence:i,lifecycle:e.lifecycle,descriptor:a,...e.metadata===void 0?{}:{metadata:u(e.metadata)}})}:h(`Durable resource descriptor is invalid`)}function re(e,t){return Object.freeze({version:e.version,body:u(e.encode(t))})}function ie(e){let t=m({envelopeVersion:1,...e});if(t.status!==`decoded`)throw TypeError(t.message);return t.envelope}function h(e){return{status:`unreattachable`,reason:`descriptor-invalid`,message:e}}function ae(e){return S(e)?e.kind===`local-family`&&o(e.family)?n(e.family):e.kind===`provider-runtime`&&b(e.provider)&&b(e.instance)?t(e.provider,e.instance):null:null}function g(e){if(!S(e))return null;let t=se(e.id),n=ce(e.family),r=_(e.kind),i=v(e.target);return!t||!n||!r||i===null||!y(e,n,r)?null:oe(e,t,n,r,i)}function oe(e,t,n,r,i){return Object.freeze({id:t,family:n,...e.appleOs===void 0?{}:{appleOs:e.appleOs},kind:r,...i===void 0?{}:{target:i},...e.iosPhysicalDeviceBackend===void 0?{}:{iosPhysicalDeviceBackend:e.iosPhysicalDeviceBackend}})}function se(e){return b(e)?e:null}function ce(e){return o(e)?e:null}function _(e){return pe(e)?e:null}function v(e){if(e!==void 0)return me(e)?e:null}function y(e,t,n){if(t===`apple`){if(!s(e.appleOs))return!1}else if(e.appleOs!==void 0||e.iosPhysicalDeviceBackend!==void 0)return!1;return le(e.iosPhysicalDeviceBackend,n)}function le(e,t){return e===void 0?!0:t===`device`?e===`coredevice`||e===`xctest`:!1}function ue(e){return!S(e)||!b(e.token)||!x(e.generation)?null:Object.freeze({token:e.token,generation:e.generation})}function de(e){return!S(e)||!x(e.version)||!l(e.body)?null:Object.freeze({version:e.version,body:u(e.body)})}function fe(e){return e===`open`||e===`completed`}function pe(e){return e===`simulator`||e===`emulator`||e===`device`}function me(e){return e===`mobile`||e===`tv`||e===`desktop`}function b(e){return typeof e==`string`&&e.trim().length>0}function x(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0}function S(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function C(e,t){if(e.resourceKind!==t.resourceKind)return{status:`unreattachable`,reason:`descriptor-invalid`,message:`Durable resource kind ${e.resourceKind} does not match ${t.resourceKind}`};if(e.descriptor.version!==t.version)return{status:`unreattachable`,reason:`descriptor-version-unsupported`,message:`Unsupported ${t.resourceKind} descriptor version: ${e.descriptor.version}`,version:e.descriptor.version};try{let n=t.decode(e.descriptor.body);return n.status===`decoded`?n:{status:`unreattachable`,reason:`descriptor-invalid`,message:n.message}}catch(e){return{status:`unreattachable`,reason:`descriptor-invalid`,message:e instanceof Error?e.message:`Descriptor codec rejected the body`}}}function w(e,t){return Object.freeze({pendingHandle:new r(e),envelope:t})}function T(e){return Object.freeze({appLogReattach:async({envelope:t})=>{let n=C(t,e.codec);return n.status===`unreattachable`?n:await e.reattach(n.descriptor,E(t))},appLogCleanup:async({envelope:t})=>{let n=C(t,e.codec);return n.status===`decoded`?await e.cleanup(n.descriptor,E(t)):{status:`cleanup-pending`,reason:`manual-recovery-required`,message:n.message}}})}function E(e){return Object.freeze({sessionId:e.sessionId,fence:e.fence})}function he(e){if(typeof e!=`object`||!e||Array.isArray(e))return{status:`invalid`,message:`App-log process marker must be an object`};let t=e;return!Number.isInteger(t.pid)||Number(t.pid)<=0?{status:`invalid`,message:`App-log process marker pid must be a positive integer`}:typeof t.startTime!=`string`||t.startTime.trim().length===0?{status:`invalid`,message:`App-log process marker startTime must be a non-empty string`}:typeof t.command!=`string`||t.command.trim().length===0?{status:`invalid`,message:`App-log process marker command must be a non-empty string`}:{status:`decoded`,marker:Object.freeze({pid:Number(t.pid),startTime:t.startTime,command:t.command})}}function ge(e){let t,n,r,i=()=>n??=e.forceCleanup();return Object.freeze({inspect:()=>e.inspect(),finish:()=>t??=e.finish(),forceCleanup:i,[Symbol.asyncDispose]:async()=>{r??=i().then(_e),await r}})}function D(e){return ge({inspect:e.inspect,finish:e.finish,forceCleanup:async()=>{let t=await e.finish();return t.status===`completed`?{status:`cleaned`}:{status:`cleanup-pending`,reason:t.reason,message:t.message}}})}function _e(t){if(!i(t))throw new e(`COMMAND_FAILED`,t.message??`Durable resource cleanup could not be confirmed`,{reason:t.reason,retriable:t.reason!==`ownership-fence-lost`,hint:t.reason===`ownership-fence-lost`?`Use the current resource owner or recovery record before retrying cleanup.`:`Keep the recovery record and retry cleanup through the exact runtime owner.`})}function ve(e,t){let n=O(e),r,i,a,o=()=>r??=t.finish(n),s=()=>i??=r?r.then(async e=>e.status===`completed`?{status:`cleaned`}:await t.forceCleanup(n),async()=>await t.forceCleanup(n)):t.forceCleanup(n);return Object.freeze({inspect:()=>n,appendGestureEvents:e=>{e.length===0||r||i||(n=O({...n,gestureEvents:[...n.gestureEvents,...e]}))},setTouchReferenceFrame:e=>{r||i||(n=O({...n,...e?{touchReferenceFrame:e}:{}}))},setRunnerSessionId:e=>{r||i||e.trim().length===0||(n=O({...n,runnerSessionId:e}))},invalidate:e=>{r||i||n.invalidatedReason||(n=O({...n,invalidatedReason:e}))},finish:o,forceCleanup:s,[Symbol.asyncDispose]:async()=>{a??=s().then(ye),await a}})}function O(e){return Object.freeze({...e,gestureEvents:Object.freeze([...e.gestureEvents])})}function ye(t){if(!i(t))throw new e(`COMMAND_FAILED`,t.message??`Screen recording cleanup could not be confirmed`,{reason:t.reason,retriable:t.reason!==`ownership-fence-lost`,hint:t.reason===`ownership-fence-lost`?`Use the current recording owner or recovery record before retrying cleanup.`:`Keep the recovery record and retry cleanup through the exact runtime owner.`})}function k(e,t,n=e.showTouches){return Object.freeze({status:`completed`,result:Object.freeze({backend:e.backend,outPath:e.outPath,...e.clientOutPath===void 0?{}:{clientOutPath:e.clientOutPath},startedAt:e.startedAt,completedAt:Date.now(),scope:e.scope,showTouches:n,recordOnlySession:e.recordOnlySession,...e.activeSessionApp===void 0?{}:{activeSessionApp:e.activeSessionApp},...t})})}function A(t,n,r){let i=j(t,n);if(i.length>0)throw new e(`INVALID_ARGS`,r(i))}function j(e,t){return Object.freeze([...t.scopes.includes(e.scope)?[]:[`--scope`],...t.fps||e.fps===void 0?[]:[`--fps`],...t.exportQuality||e.exportQuality===void 0?[]:[`--quality`],...t.hideTouches||!e.hideTouchesRequested?[]:[`--hide-touches`]])}async function M(e,t){let n=await P(e,t);if(n.status===`missing`)return{status:`missing`};if(n.status===`invalid`)return{status:`unreattachable`,reason:`ownership-fence-lost`,message:n.message};let r=await e.processes.inspect(n.marker);return r===`missing`?(t&&await e.processes.clearMarker(t),{status:`missing`}):r===`ownership-lost`?{status:`unreattachable`,reason:`ownership-fence-lost`}:{status:`unreattachable`,reason:`transport-not-reattachable`}}async function N(e,t){if(!t)return{status:`cleanup-pending`,reason:`manual-recovery-required`,message:`App-log process marker path is missing`};let n=await P(e,t);if(n.status===`missing`)return{status:`already-missing`};if(n.status===`invalid`)return{status:`cleanup-pending`,reason:`manual-recovery-required`,message:n.message};let r=await e.processes.inspect(n.marker);if(r===`ownership-lost`)return F();if(r===`missing`)return await e.processes.clearMarker(t),{status:`already-missing`};let i=await e.processes.terminate(n.marker);return i===`ownership-lost`?F():(await e.processes.clearMarker(t),{status:i===`terminated`?`cleaned`:`already-missing`})}async function P(e,t){return t?await e.processes.readMarker(t):{status:`invalid`,message:`App-log process marker path is missing`}}function F(){return{status:`cleanup-pending`,reason:`ownership-fence-lost`}}async function be(e){let t=e.initialProcess;for(;!e.stopped();){if(t){await xe(e,t),t=void 0,await Oe(e);continue}let n=await ke(e);if(n.status===`stopped`)return;n.status!==`waiting`&&(t=n.process)}}async function xe(e,t){let{process:n}=t;e.setActive(n);try{e.setState(`active`),await Se(e,t)}finally{await I(e,n)}}async function Se(e,t){let n=Ce(t.process);try{await we(e,t,n),await Ee(e,t.process,n),await De(n.outcome)}finally{n.controller.abort()}}function Ce(e){let t=new AbortController,n=!1,r=()=>{n=!0,t.abort()};return{controller:t,outcome:e.wait.then(()=>(r(),{status:`exited`}),e=>(r(),{status:`failed`,error:e})),settled:()=>n}}async function we(e,t,n){for(;!e.stopped()&&!n.settled();){if(!await Te(e,n))return;let r=await e.resolvePid();if(e.stopped())return;if(r!==t.pid){await t.process.terminate();return}}}async function Te(e,t){try{await e.sleep(500,t.controller.signal)}catch(e){if(!t.settled())throw e}return!t.settled()}async function Ee(e,t,n){e.stopped()&&!n.settled()&&await t.terminate()}async function De(e){let t=await e;if(t.status===`failed`)throw t.error}async function Oe(e){e.stopped()||(e.setState(`recovering`),await e.sleep(500))}async function ke(e){let t=await e.resolvePid();if(e.stopped())return{status:`stopped`};if(!t)return e.setState(`recovering`),await e.sleep(1e3),{status:`waiting`};let n=await e.startProcess(t);return e.setActive(n),e.stopped()?(await Ae(e,n),{status:`stopped`}):{status:`started`,process:{pid:t,process:n}}}async function Ae(e,t){try{await t.terminate(),await t.wait}finally{await I(e,t)}}async function I(e,t){try{await t[Symbol.asyncDispose]()}finally{e.setActive(void 0)}}async function je(e){let t=await e.resolvePid(e.setupSignal);e.setupSignal.throwIfAborted();let n=await e.host.outputs.openAppend(e.outputPath),r=`recovering`,i=!1,a;try{if(e.setupSignal.throwIfAborted(),t){e.setupSignal.throwIfAborted();let i=new AbortController,o=()=>i.abort(e.setupSignal.reason);e.setupSignal.addEventListener(`abort`,o,{once:!0});try{a=await e.processStart({command:e.command(t),output:n,markerPath:e.pidPath},i.signal)}finally{e.setupSignal.removeEventListener(`abort`,o)}e.setupSignal.throwIfAborted(),r=`active`}}catch(e){throw await L([async()=>await a?.terminate(),async()=>{await a?.wait},async()=>await a?.[Symbol.asyncDispose](),async()=>await n[Symbol.asyncDispose]()]),e}let o=be({initialProcess:a&&t?{pid:t,process:a}:void 0,stopped:()=>i,setActive:e=>{a=e},setState:e=>{r=e},resolvePid:async()=>await e.resolvePid(),startProcess:async t=>await e.processStart({command:e.command(t),output:n,markerPath:e.pidPath}),sleep:async(t,n)=>await e.host.clock.sleep(t,n)}).catch(()=>{r=`failed`}),s,c=async()=>s??=Me({options:e,monitor:o,active:()=>a,stop:()=>{i=!0},setState:e=>{r=e},output:n}),l=e.host.clock.now();return D({inspect:()=>({backend:e.backend,state:r,startedAt:l}),finish:c})}async function Me(e){return e.stop(),(await L([async()=>await e.active()?.terminate(),async()=>await e.monitor,async()=>await e.output[Symbol.asyncDispose]()])).length>0?(e.setState(`failed`),{status:`cleanup-pending`,reason:`transport-failed`,message:e.options.cleanupFailureMessage}):(e.setState(`ended`),{status:`completed`,result:{backend:e.options.backend,outputPath:e.options.outputPath,completedAt:e.options.host.clock.now()}})}async function L(e){let t=[];for(let n of e)try{await n()}catch(e){t.push(e)}return t}function R(e,t,n){let r=e.artifacts.resolveSession(t);return n.outputPath===r.outputPath&&(n.pidPath===void 0||n.pidPath===r.pidPath)}function z(t,n){if(!R(t,n.sessionId,n))throw new e(`INVALID_ARGS`,`App-log paths do not match the owning session`)}const B=Object.freeze({available:!0});async function Ne(e,t,n){let r=(await e.commands.run(t,n)).stdout.trim().split(/\s+/)[0]??``;return/^\d+$/.test(r)?r:``}function Pe(t,r){let i=n(r.family);return Object.freeze({owner:i,ownsDevice:e=>e.platform===r.family,inspectFacts:async e=>V(e,await t.processTransports.resolve(e),r),bind:async n=>{if(n.intent.kind===`exact-owner`&&!a(n.intent.owner,i))throw new e(`UNSUPPORTED_OPERATION`,`${r.label} app-log owner identity does not match`);if(n.device.platform!==r.family)throw new e(`UNSUPPORTED_PLATFORM`,`${r.label} app-log owner cannot bind ${n.device.platform}`);let o=await t.processTransports.resolve(n.device);return Fe(t,n.device,n.scope.signal,o,i,r)},shutdown:async()=>void 0})}function Fe(e,t,n,r,i,a){let o=T({codec:a.codec,reattach:async(t,n)=>R(e,n.sessionId,t)?await M(e,t.pidPath):{status:`unreattachable`,reason:`descriptor-invalid`,message:`${a.label} app-log descriptor paths do not match the owning session`},cleanup:async(t,n)=>R(e,n.sessionId,t)?await N(e,t.pidPath):{status:`cleanup-pending`,reason:`ownership-fence-lost`,message:`${a.label} app-log descriptor paths do not match the owning session`}}),s=Object.freeze({appLogInspect:async()=>({backend:a.backend}),appLogDoctor:async({appBundleId:r})=>await a.doctor({host:e,device:t,signal:n},r),...r.start?{appLogStart:async o=>await Ie(e,t,n,r,i,o,a)}:{},...o});return Object.freeze({device:t,owner:i,facts:V(t,r,a),operations:s,[Symbol.asyncDispose]:async()=>void 0})}function V(e,t,n){let r=t.start?B:{available:!1,reason:`owner-capability-missing`,hint:n.startUnavailableHint};return Object.freeze({device:{family:n.family,kind:e.kind,...e.target===void 0?{}:{target:e.target},providerMode:t.mode},operations:{appLogInspect:B,appLogDoctor:B,appLogStart:r,appLogReattach:B,appLogCleanup:B}})}async function Ie(t,n,r,i,a,o,s){if(!i.start)throw new e(`UNSUPPORTED_OPERATION`,s.startUnavailableHint);z(t,o);let c=t.artifacts.resolveSession(o.sessionId),l={host:t,device:n,signal:r,input:o,artifacts:c,transport:i};s.validateStart?.(l),r.throwIfAborted();let u=await s.process(l);r.throwIfAborted();let d=await je({host:t,backend:s.backend,outputPath:c.outputPath,pidPath:c.pidPath,processStart:i.start,setupSignal:r,resolvePid:u.resolvePid,command:u.command,cleanupFailureMessage:s.cleanupFailureMessage}),f=s.descriptor({artifacts:c,transport:i});return w(d,s.envelope({input:o,device:n,owner:a,descriptor:f}))}async function Le(e,t){try{return await e()}catch{if(t?.aborted)throw t.reason;return!1}}function Re(e){return e.exitCode===0}function H(e){for(let t of[/\bstatus(?:Code)?["'=: ]+([1-5]\d{2})\b/i,/\bresponse(?:\s+code)?["'=: ]+([1-5]\d{2})\b/i,/\bHTTP\/[0-9.]+\s+([1-5]\d{2})\b/i]){let n=t.exec(e);if(!n)continue;let r=Number.parseInt(n[1]??``,10);if(Number.isInteger(r))return r}return null}function U(e){return/\b\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z)?\b/.exec(e)?.[0]??/\b\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d+\b/.exec(e)?.[0]}function ze(e){let t=e.indexOf(`{`),n=e.lastIndexOf(`}`);if(t<0||n<=t)return null;try{let r=JSON.parse(e.slice(t,n+1));return r&&typeof r==`object`&&!Array.isArray(r)?r:null}catch{return null}}function W(e,t){for(let n of t){let t=e?.[n];if(typeof t==`string`&&t.trim())return t.trim()}}function Be(e,t){for(let n of t){let t=e?.[n];if(typeof t==`number`&&Number.isInteger(t))return t;if(typeof t==`string`&&/^\d{3}$/.test(t.trim()))return Number.parseInt(t,10)}return null}function Ve(e,t){let n=t?.headers??t?.requestHeaders??t?.responseHeaders;return n===void 0?/\bheaders?["'=: ]+(\{.*\})/i.exec(e)?.[1]?.trim():K(n)}function G(e,t,n){for(let r of n){if(t?.[r]!==void 0)return K(t[r]);let n=r.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),i=RegExp(`\\b${n}["'=: ]+(.+)$`,`i`).exec(e);if(i?.[1])return i[1].trim()}}function K(e){if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}function He(e,t,n){let r=Y(t,n,5),i=e.packetId??r.map(q).find(e=>typeof e==`string`&&e.length>0);i&&(e.packetId=i);let a=i?Y(t,n,12).filter(e=>q(e)===i):r;e.timestamp??=a.map(U).find(e=>typeof e==`string`&&e.length>0),e.status??=a.map(H).find(e=>typeof e==`number`)??void 0,e.durationMs??=a.map(J).find(e=>typeof e==`number`)??void 0}function q(e){return/\bpacket id (\d+)\b/i.exec(e)?.[1]??null}function J(e){let t=/\b(?:duration|elapsed request\/response time, ms)[:= ]+(\d+)\b/i.exec(e);return t?Number.parseInt(t[1]??``,10):null}function Y(e,t,n){return e.slice(Math.max(0,t-n),Math.min(e.length,t+n+1)).map(e=>e.trim()).filter(Boolean)}const Ue=RegExp(`\\b(${[`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`,`OPTIONS`].join(`|`)})\\b\\s+https?:\\/\\/`,`i`),We=/https?:\/\/[^\s"'<>\])]+/i;function Ge(e,t,n=e.limits.maxEntries){let r=[...e.entries],i=new Set(r.map(Z));for(let e of t.entries){let t=Z(e);if(!i.has(t)&&(i.add(t),r.push(e),r.length>=n))break}return Object.freeze({...e,matchedLines:r.length,entries:Object.freeze(r)})}function Ke(e,t){let n=$(t.maxEntries,25,1,200),r=t.include??`summary`,i=$(t.maxPayloadChars,2048,64,16384),a=$(t.maxScanLines,4e3,100,2e4),o=qe(t.lineNumberOffset);if(!t.exists)return Object.freeze({path:t.path,exists:!1,scannedLines:0,matchedLines:0,entries:Object.freeze([]),include:r,limits:Object.freeze({maxEntries:n,maxPayloadChars:i,maxScanLines:a})});let s=e.split(`
|
|
2
|
+
`),c=Math.max(0,s.length-a),l=s.slice(c),u=[];for(let e=l.length-1;e>=0&&u.length<n;--e){if(!l[e]?.trim())continue;let n=X(l,e,o+c+e+1,t.backend,r,i);n&&u.push(n)}return Object.freeze({path:t.path,exists:!0,scannedLines:l.length,matchedLines:u.length,entries:Object.freeze(u),include:r,limits:Object.freeze({maxEntries:n,maxPayloadChars:i,maxScanLines:a})})}function qe(e){if(e===void 0)return 0;if(!Number.isInteger(e)||e<0)throw TypeError(`Network line number offset must be a non-negative integer`);return e}function X(e,t,n,r,i,a){let o=e[t]?.trim();if(!o)return null;let s=ze(o),c=Je(o,s);if(!c)return null;let l=$e(o,n,c,a);return r===`android`&&He(l,e,t),et(l,o,s,i,a),l}function Je(e,t){let n=Ye(e,t),r=Xe(e,t);if(!r)return null;let i=Ze(e,t);return Qe(e,n.explicit,i)?{method:n.value,url:r,status:i}:null}function Ye(e,t){let n=W(t,[`method`,`httpMethod`]),r=/\bmethod["'=: ]+([A-Z]+)\b/i.exec(e)?.[1],i=Ue.exec(e)?.[1],a=n??r??i;return{value:a?.toUpperCase(),explicit:!!a}}function Xe(e,t){return W(t,[`url`,`requestUrl`])??We.exec(e)?.[0]}function Ze(e,t){return Be(t,[`status`,`statusCode`,`responseCode`])??H(e)??void 0}function Qe(e,t,n){return t||n!==void 0||/\bURL["'=: ]+https?:\/\//i.test(e)||/\bheaders?["'=: ]+/i.test(e)||/\b(?:requestBody|responseBody|payload|request|response)["'=: ]+/i.test(e)}function $e(e,t,n,r){return{...n,timestamp:U(e),packetId:q(e)??void 0,durationMs:J(e)??void 0,raw:Q(e,r),line:t}}function et(e,t,n,r,i){if(tt(r)){let r=Ve(t,n);r&&(e.headers=Q(r,i))}if(nt(r)){let r=G(t,n,[`requestBody`,`body`,`payload`,`request`]),a=G(t,n,[`responseBody`,`response`]);r&&(e.requestBody=Q(r,i)),a&&(e.responseBody=Q(a,i))}}function tt(e){return e===`headers`||e===`all`}function nt(e){return e===`body`||e===`all`}function Z(e){return`${e.timestamp??``}|${e.method??``}|${e.url}|${e.status??``}|${e.raw}`}function Q(e,t){return e.length<=t?e:`${e.slice(0,t)}...<truncated>`}function $(e,t,n,r){return e===void 0||!Number.isInteger(e)?t:Math.max(n,Math.min(r,e))}export{he as _,Pe as a,m as b,z as c,A as d,k as f,w as g,T as h,Le as i,N as l,D as m,Ke as n,Ne as o,ve as p,Re as r,R as s,Ge as t,M as u,ie as v,re as x,g as y};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{_ as e}from"./sdk-contracts.js";function t(t,n={message:e=>`Invalid value: ${e}`}){let r=new Set(t),i=n.normalize??(e=>e);return{is:e=>typeof e==`string`&&r.has(e),parse:t=>{let a=i(t??``);if(r.has(a))return a;throw new e(`INVALID_ARGS`,n.message(t??``))}}}export{t};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`).replace(/\n$/,``),writeClipboard:async t=>{
|
|
3
|
-
`)){let t=e.trim();t&&i.add(t)}}return
|
|
1
|
+
import{n as e}from"./rolldown-runtime.js";import{_ as t}from"./sdk-contracts.js";import{C as n,_ as r,d as i,h as a}from"./sdk-android-adb.js";import{t as o}from"./scoped-provider.js";import s from"node:path";import{promises as c}from"node:fs";import l from"node:os";function u(e,t){return t===`user-installed`?e.filter(e=>!e.bundleId.startsWith(`com.apple.`)):e}function d(e,n){return{openBundle:async(t,n)=>{await e(`open`,f(t,n))},openTarget:async t=>{await e(`open`,[t])},readClipboard:async()=>a(await e(`pbpaste`,[],{allowFailure:!0}),`Failed to read macOS clipboard`).stdout.replace(/\r\n/g,`
|
|
2
|
+
`).replace(/\n$/,``),writeClipboard:async t=>{a(await e(`pbcopy`,[],{allowFailure:!0,stdin:t}),`Failed to write macOS clipboard`)},readDarkMode:async()=>{let n=a(await e(`osascript`,[`-e`,`tell application "System Events" to tell appearance preferences to get dark mode`],{allowFailure:!0}),`Failed to read macOS appearance`),r=n.stdout.trim().toLowerCase();if(r===`true`)return!0;if(r===`false`)return!1;throw new t(`COMMAND_FAILED`,`Unable to determine current macOS appearance from osascript output: ${n.stdout.trim()}`)},setDarkMode:async t=>{a(await e(`osascript`,[`-e`,`tell application "System Events" to tell appearance preferences to set dark mode to ${t?`true`:`false`}`],{allowFailure:!0}),`Failed to set macOS appearance`)},listApps:async t=>await p(e,n,t)}}function f(e,t){let n=[`-b`,e];return t&&n.push(t),n}async function p(e,t,n){let r=[`/Applications`,`/System/Applications`,s.join(l.homedir(),`Applications`)],i=new Set;for(let t of r){if(!(await c.stat(t).catch(()=>null))?.isDirectory())continue;let n=await e(`find`,[t,`-maxdepth`,`4`,`-type`,`d`,`-name`,`*.app`],{allowFailure:!0});if(n.exitCode===0)for(let e of n.stdout.split(`
|
|
3
|
+
`)){let t=e.trim();t&&i.add(t)}}return u((await Promise.all(Array.from(i).map(async e=>{let n=await m(e,t).catch(()=>({})),r=n.bundleId;return r?{bundleId:r,name:n.appName??s.basename(e,`.app`)}:null}))).filter(e=>e!==null).sort((e,t)=>e.name.localeCompare(t.name)),n)}async function m(e,t){for(let n of[s.join(e,`Contents`,`Info.plist`),s.join(e,`Info.plist`)]){let e=await t(n),r=h(e,`CFBundleIdentifier`),i=h(e,`CFBundleDisplayName`),a=h(e,`CFBundleName`);if(r||i||a)return{bundleId:r,appName:i??a}}return{}}function h(e,t){let n=e?.[t];return typeof n==`string`&&n.trim()?n.trim():void 0}var g=e({createLocalAppleToolProvider:()=>y,hasScopedAppleToolProvider:()=>S,readApplePlistJson:()=>T,resolveAppleToolProvider:()=>b,runAppleToolCommand:()=>C,runXcrun:()=>w,withAppleToolProvider:()=>x});const _={runCommand:r,simctl:{run:async(e,t)=>await r(`xcrun`,[`simctl`,...e],t)},devicectl:{run:async(e,t)=>await r(`xcrun`,[`devicectl`,...e],t)},plist:{readJson:async(e,t)=>await k(r,e,t)},macosHost:d(r,async e=>await k(r,e)),whichCommand:n},v=o(_,E);function y(e={}){let t={..._,...e},n=e.plist??{readJson:async(e,n)=>await k(t.runCommand,e,n)};return{...t,simctl:e.simctl??{run:async(e,n)=>await t.runCommand(`xcrun`,[`simctl`,...e],n)},devicectl:e.devicectl??{run:async(e,n)=>await t.runCommand(`xcrun`,[`devicectl`,...e],n)},plist:n,macosHost:e.macosHost??d(t.runCommand,async e=>await n.readJson(e))}}function b(e){return v.resolve(e)}async function x(e,t){return await v.run(e,t)}function S(){return v.hasScope()}async function C(e,t,n){return await b().runCommand(e,t,n)}async function w(e,t){let n=b(),[r,...i]=e;return r===`simctl`?await(n.simctl?.run(i,t)??n.runCommand(`xcrun`,e,t)):r===`devicectl`?await(n.devicectl?.run(i,t)??n.runCommand(`xcrun`,e,t)):await C(`xcrun`,e,t)}async function T(e,t){return await b().plist?.readJson(e,t)??null}function E(e){return y({...e,runCommand:D(e.runCommand),...e.simctl?{simctl:{run:O(e.simctl.run)}}:{},...e.devicectl?{devicectl:{run:O(e.devicectl.run)}}:{},...e.macosHelper?{macosHelper:{run:O(e.macosHelper.run)}}:{}})}function D(e){return async(t,n,r)=>i(await e(t,n,r))}function O(e){return async(t,n)=>i(await e(t,n))}async function k(e,t,n){try{let r=await e(`plutil`,[`-convert`,`json`,`-o`,`-`,t],{allowFailure:!0,signal:n});return r.exitCode!==0||!r.stdout.trim()?null:JSON.parse(r.stdout)}catch{return n?.throwIfAborted(),null}}export{w as a,C as i,T as n,g as o,b as r,u as s,S as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{n as e}from"./rolldown-runtime.js";import{C as t,_ as n}from"./sdk-android-adb.js";import{t as r}from"./scoped-provider.js";import i from"node:path";import{constants as a}from"node:fs";import o from"node:os";import{access as s}from"node:fs/promises";var c=e({createLocalVegaToolProvider:()=>d,resolveVegaToolProvider:()=>f,withVegaToolProvider:()=>p});const l={run:async(e,t)=>await n(await h()??`vega`,e,t),isAvailable:async()=>!!await h()},u=r(d());function d(e=l){return{isAvailable:async()=>await e.isAvailable(),version:async t=>await e.run([`--version`],t),listDevices:async t=>await e.run([`device`,`list`],t),checkConnected:async(t,n)=>await e.run([`device`,`is-connected`,`--device`,t],n),launchApp:async(t,n,r)=>await e.run([`device`,`launch-app`,`--device`,t,`--appName`,n],r),terminateApp:async(t,n,r)=>await e.run([`device`,`terminate-app`,`--device`,t,`--appName`,n],r),pressRemote:async(t,n,r,i)=>await e.run([`device`,`run-cmd`,`--device`,t,`--command`,[`inputd-cli`,`button_press`,n,...r===void 0?[]:[`--holdDuration`,String(r)]].join(` `)],i)}}function f(e){return u.resolve(e)}async function p(e,t){return await u.run(e,t)}let m;async function h(){if(m)return m;if(await t(`vega`))return m=`vega`,m;let e=i.join(o.homedir(),`vega`,`bin`,`vega`);try{await s(e,a.X_OK),m=e}catch{return}return m}export{c as n,f as t};
|
package/dist/src/update-check.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{y as e}from"./sdk-android-adb.js";import t from"node:path";import n from"node:fs";import{fileURLToPath as r}from"node:url";const i=`agent-device`,a=`--agent-device-run-update-check`;function o(e){if(!c(e))return;let n=Date.now(),r=t.join(e.stateDir,`update-check.json`),a=d(r);l(a,e.currentVersion)&&(process.stderr.write(`Update available: ${i} ${e.currentVersion} -> ${a.latestVersion}. Run \`npm install -g ${i}@latest\` to upgrade the CLI.\n`),f(r,{...a,prompted:!0})),u(a,n)&&m(r,e.currentVersion)}async function s(e){let t=Date.now(),n=d(e.cachePath);try{let r=await h()??void 0;if(!r||_(r,e.currentVersion)<=0){f(e.cachePath,{checkedAt:new Date(t).toISOString()});return}f(e.cachePath,{checkedAt:new Date(t).toISOString(),latestVersion:r,prompted:n.latestVersion===r?n.prompted===!0:!1})}catch{f(e.cachePath,{...n,checkedAt:new Date(t).toISOString()})}}function c(e){return!e.command||e.command===`help`||e.command===`test`||e.flags.help||e.flags.version||e.flags.json||process.env.CI?.trim()||process.env.NODE_ENV===`test`||process.env.AGENT_DEVICE_NO_UPDATE_NOTIFIER?.trim()?!1:!!process.stderr.isTTY}function l(e,t){return!e.latestVersion||_(e.latestVersion,t)<=0?!1:e.prompted!==!0}function u(e,t){let n=g(e.checkedAt);return n===void 0||t-n>=12096e5}function d(e){try{let t=JSON.parse(n.readFileSync(e,`utf8`));return{checkedAt:typeof t.checkedAt==`string`?t.checkedAt:void 0,latestVersion:typeof t.latestVersion==`string`?t.latestVersion:void 0,prompted:t.prompted===!0}}catch{return{}}}function f(e,r){try{n.mkdirSync(t.dirname(e),{recursive:!0}),n.writeFileSync(e,`${JSON.stringify(r,null,2)}\n`,`utf8`)}catch{}}function p(){let e=r(import.meta.url),i=t.extname(e)||`.js`,a=[t.join(t.dirname(e),`update-check-entry${i}`),t.join(t.dirname(e),`internal`,`update-check-entry${i}`)].find(e=>n.existsSync(e));if(!a)throw Error(`Update check entrypoint not found. Rebuild the package to include the update-check worker entry.`);return a}function m(t,n){let r=p(),i=r.endsWith(`.ts`)?[`--experimental-strip-types`]:[];e(process.execPath,[...i,r,a,t,n])}async function h(){let e=await fetch(`https://registry.npmjs.org/${i}/latest`,{signal:AbortSignal.timeout(3500),headers:{accept:`application/json`}});if(!e.ok)return;let t=await e.json();return typeof t.version==`string`&&t.version.trim().length>0?t.version.trim():void 0}function g(e){if(!e)return;let t=Date.parse(e);return Number.isNaN(t)?void 0:t}function _(e,t){return e.localeCompare(t,void 0,{numeric:!0})}function v(e){if(e[0]!==a)return null;let t=e[1]?.trim(),n=e[2]?.trim();return!t||!n?null:{cachePath:t,currentVersion:n}}export{v as n,s as r,o as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=new Set([`healthy`,`recovered`,`sparse`]),t=new Set([`tree`,`queries`,`private-ax`]),n=new Set([`ax-rejected`,`sparse-tree`,`budget`,`no-nodes`,`capture-failed`,`deferred`,`requested-backend`]);function r(r){if(!r||typeof r!=`object`)return;let a=r;if(!(typeof a.state!=`string`||!e.has(a.state))&&!(typeof a.backend!=`string`||!t.has(a.backend)))return{state:a.state,backend:a.backend,reason:typeof a.reason==`string`?a.reason:void 0,reasonCode:typeof a.reasonCode==`string`&&n.has(a.reasonCode)?a.reasonCode:void 0,customActions:i(a.customActions),effectiveDepth:typeof a.effectiveDepth==`number`?a.effectiveDepth:void 0,collapsedLeafIndexes:Array.isArray(a.collapsedLeafIndexes)?a.collapsedLeafIndexes.filter(e=>typeof e==`number`):void 0}}function i(e){if(!e||typeof e!=`object`)return;let t=e;if(!(typeof t.read!=`number`||typeof t.candidates!=`number`))return{read:t.read,candidates:t.candidates,truncated:typeof t.truncated==`number`?t.truncated:0,blocked:t.blocked===!0}}function a(e){return e?.state===`sparse`}function o(e){return e?.backend===`private-ax`?`private-ax`:void 0}export{o as n,r,a as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e}from"./rolldown-runtime.js";import{_ as t}from"./sdk-contracts.js";import"./sdk-batch-runner.js";import{o as n}from"./cancel.js";import{AsyncLocalStorage as r}from"node:async_hooks";import i from"node:fs";var a=e({listDeviceInventory:()=>l,listLocalDeviceInventory:()=>d,readDeviceInventory:()=>u,shouldPropagateDeviceInventoryProbeError:()=>m,withDeviceInventoryContext:()=>c});const o=`device_inventory_context_unavailable`,s=new r;async function c(e,t){return await s.run(e,t)}async function l(e){return await f(`providerFirst`,e)}async function u(e){let t=p(),n=await t.providerFirst.discoverWithSource(e,t.requestScope);return{devices:n.devices.map(e=>({...e})),source:n.source}}async function d(e){return await f(`localOnly`,e)}async function f(e,t){let n=p();return(await n[e].discover(t,n.requestScope)).map(e=>({...e}))}function p(){let e=s.getStore();if(!e)throw new t(`COMMAND_FAILED`,`Device inventory gateway is unavailable outside request execution`,{reason:o});return e}function m(e){return n(e)||e instanceof t&&e.code===`COMMAND_FAILED`&&e.details?.reason===o?!0:e instanceof Error&&e.name===`AbortError`}function h(e){return v(e,i.constants.O_RDONLY,!1)}function g(e){return v(e,i.constants.O_WRONLY|i.constants.O_APPEND,!0)}function _(e){let t=v(e,i.constants.O_RDWR,!0);try{return i.ftruncateSync(t,0),t}catch(e){throw i.closeSync(t),e}}function v(e,t,n){for(let r=0;r<2;r+=1){let r=y(e,t,n);if(r.status!==`retry`)return r.status===`missing`?void 0:r.descriptor}throw Error(`Final file could not be opened without an identity race: ${e}`)}function y(e,t,n){let r=w(e);if(!r&&!n)return{status:`missing`};let a=b(e,t,r===void 0,n);if(typeof a!=`number`)return a;try{return S(e,a,r),{status:`opened`,descriptor:a}}catch(e){throw i.closeSync(a),e}}function b(e,t,n,r){try{return i.openSync(e,t|E()|(n?i.constants.O_CREAT|i.constants.O_EXCL:0),384)}catch(e){let t=e.code,i=x(t,n,r);if(i)return i;throw e}}function x(e,t,n){if(e===`EEXIST`)return t?{status:`retry`}:void 0;if(e===`ENOENT`&&!t)return{status:n?`retry`:`missing`}}function S(e,t,n){let r=i.fstatSync(t),a=w(e);if(!r.isFile()||!a||!T(r,a)||n&&!T(n,r))throw C(e)}function C(e){return Error(`Final file identity changed while it was opened: ${e}`)}function w(e){try{let t=i.lstatSync(e);if(!t.isFile())throw Error(`Final path must be a regular file: ${e}`);return t}catch(e){if(e.code===`ENOENT`)return;throw e}}function T(e,t){return e.dev===t.dev&&e.ino===t.ino}function E(){let e=i.constants.O_NOFOLLOW;return Number.isInteger(e)&&e>0?e:0}export{l as a,m as c,a as i,c as l,h as n,d as o,_ as r,u as s,g as t};
|
package/dist/src/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{_ as e}from"./sdk-contracts.js";import{An as t,Cn as n,En as r,Fn as i,Ht as a,On as o,kn as s,rr as c,wn as l,zn as u}from"./sdk-batch-runner.js";import d from"node:path";import f from"node:fs";import{fileURLToPath as ee}from"node:url";const p={min:.01,max:1},m={flagKey:`screenshotMaxSize`,cliToken:`--max-size`,envVar:`AGENT_DEVICE_SCREENSHOT_MAX_SIZE`,publicOptionKey:`maxSize`,migration:{screenshot:`screenshot --max-size was removed; use --scale <0.01-1> (or AGENT_DEVICE_SCREENSHOT_SCALE) to downscale proportionally`,record:`record --max-size was removed; recordings capture at native resolution`}};function te(e,t){return t&&Object.hasOwn(t,m.flagKey)?m.migration[e]:void 0}function ne(t,n){if(Object.hasOwn(n,m.publicOptionKey)||Object.hasOwn(n,m.flagKey))throw new e(`INVALID_ARGS`,m.migration[t])}const re=[`out`,`overlayRefs`,`screenshotPixelDensity`,`screenshotFullscreen`,`screenshotScale`,`screenshotNoStabilize`,`screenshotNormalizeStatusBar`],ie=[`screenshotPixelDensity`,`screenshotFullscreen`,`screenshotScale`,`screenshotNoStabilize`,`screenshotNormalizeStatusBar`],ae=[{key:`screenshotPixelDensity`,names:[`--pixel-density`],type:`int`,min:1,usageLabel:`--pixel-density <n>`,usageDescription:`Screenshot: output PNG pixel density in pixels per logical point (currently supported on iOS simulators)`},{key:`screenshotFullscreen`,names:[`--fullscreen`,`--full`,`-f`],type:`boolean`,usageLabel:`--fullscreen, --full, -f`,usageDescription:`Screenshot: on web capture the full page; on macOS app sessions capture the full desktop instead of the app window`},{key:`screenshotScale`,names:[`--scale`],type:`number`,min:p.min,max:p.max,usageLabel:`--scale <0.01-1>`,usageDescription:`Screenshot: resize both dimensions by this factor (or use AGENT_DEVICE_SCREENSHOT_SCALE)`},{key:`screenshotNoStabilize`,names:[`--no-stabilize`],type:`boolean`,usageLabel:`--no-stabilize`,usageDescription:`Screenshot: skip Android demo-mode/status-bar stabilization and settle delay for low-latency capture loops`},{key:`screenshotNormalizeStatusBar`,names:[`--normalize-status-bar`],type:`boolean`,usageLabel:`--normalize-status-bar`,usageDescription:`Screenshot: on iOS simulators temporarily normalize status-bar chrome for deterministic screenshot diffs`}],oe=[{tokens:[`--fullscreen`,`--full`,`-f`],key:`screenshotFullscreen`},{tokens:[`--no-stabilize`],key:`screenshotNoStabilize`},{tokens:[`--normalize-status-bar`],key:`screenshotNormalizeStatusBar`}],se=[{token:`--pixel-density`,key:`screenshotPixelDensity`,label:`screenshot --pixel-density`}],ce=[{token:`--scale`,key:`screenshotScale`,label:`screenshot --scale`,min:p.min,max:p.max}];function le(e){return he({overlayRefs:e?.overlayRefs,pixelDensity:e?.screenshotPixelDensity,fullscreen:e?.screenshotFullscreen,scale:e?.screenshotScale,stabilize:e?.screenshotNoStabilize?!1:void 0,normalizeStatusBar:e?.screenshotNormalizeStatusBar})}function ue(e={}){return he({overlayRefs:e.overlayRefs,screenshotPixelDensity:e.screenshotPixelDensity??e.pixelDensity,screenshotFullscreen:e.screenshotFullscreen??e.fullscreen,screenshotScale:e.screenshotScale,screenshotNoStabilize:e.screenshotNoStabilize??(e.stabilize===!1?!0:void 0),screenshotNormalizeStatusBar:e.screenshotNormalizeStatusBar??e.normalizeStatusBar})}function de(e={}){return ue({...e,screenshotScale:e.screenshotScale??e.scale})}function fe(t){let{min:n,max:r}=p;if(t.scale!==void 0&&(!Number.isFinite(t.scale)||t.scale<n||t.scale>r))throw new e(`INVALID_ARGS`,`screenshot scale must be between ${n} and ${r}`)}function pe(e,t){typeof t?.screenshotPixelDensity==`number`&&e.push(`--pixel-density`,String(t.screenshotPixelDensity)),t?.screenshotFullscreen&&e.push(`--fullscreen`),typeof t?.screenshotScale==`number`&&e.push(`--scale`,String(t.screenshotScale)),t?.screenshotNoStabilize&&e.push(`--no-stabilize`),t?.screenshotNormalizeStatusBar&&e.push(`--normalize-status-bar`)}function me(t){let{args:n,flags:r,index:i}=t,a=n[i];if(a===m.cliToken)throw new e(`INVALID_ARGS`,m.migration.screenshot);return ge(a,r,i)??_e({args:n,index:i,flags:r,token:a})??ve({args:n,index:i,flags:r,token:a})??{handled:!1}}function he(e){return Object.fromEntries(Object.entries(e).filter(e=>e[1]!==void 0))}function ge(e,t,n){let r=oe.find(t=>t.tokens.some(t=>t===e));if(r)return t[r.key]=!0,{handled:!0,nextIndex:n}}function _e(t){let n=se.find(e=>e.token===t.token);if(!n)return;let r=Number(t.args[t.index+1]);if(!Number.isInteger(r)||r<1)throw new e(`INVALID_ARGS`,`${n.label} requires a positive integer`);return t.flags[n.key]=r,{handled:!0,nextIndex:t.index+1}}function ve(t){let n=ce.find(e=>e.token===t.token);if(!n)return;let r=Number(t.args[t.index+1]);if(!Number.isFinite(r)||r<n.min||r>n.max)throw new e(`INVALID_ARGS`,`${n.label} requires a number from ${n.min} to ${n.max}`);return t.flags[n.key]=r,{handled:!0,nextIndex:t.index+1}}function ye(e){let t=Se(e.quality);return{...e.analysis?{analysis:e.analysis}:{},...e.androidSnapshot?{androidSnapshot:e.androidSnapshot}:{},...e.freshness?{freshness:e.freshness}:{},...t?{quality:t}:{},...e.warnings?{warnings:e.warnings}:{}}}function be(e){return{...e.androidSnapshot?{androidSnapshot:e.androidSnapshot}:{},...e.quality?{snapshotQuality:e.quality}:{},...e.warnings&&e.warnings.length>0?{warnings:e.warnings}:{}}}function xe(e){let t=Ce(e.androidSnapshot),n=Array.isArray(e.warnings)?e.warnings.filter(e=>typeof e==`string`):void 0,r=Se(e.snapshotQuality);return be({...t?{androidSnapshot:t}:{},...r?{quality:r}:{},...n?{warnings:n}:{}})}function Se(e){if(!e||typeof e!=`object`)return;let t=e;return typeof t.state==`string`&&typeof t.backend==`string`?t:void 0}function Ce(e){return typeof e==`object`&&e?e:void 0}const h=1500;function we(e,t){e&&(e.snapshotDiagnostics??={samples:[]}).samples.push({...t,durationMs:Math.max(0,Math.round(t.durationMs))})}function Te(e){let t=e?.snapshotDiagnostics?.samples;if(!(!t||t.length===0))return Ee(t)}function Ee(e){if(e.length===0)return;let t=e.slice(1),n=t.length>=3?g(t):void 0,r=t.filter(e=>e.durationMs>=h).length,i=n!==void 0&&n.p95Ms>=h&&r>=2;return{stats:g(e),...i&&n?{warning:je(n)}:{}}}function De(e){let t=e.filter(e=>e!==void 0),n=t.flatMap(e=>Le(e.stats));if(n.length===0)return;let r=g(n),i=t.filter(e=>e.warning);return{stats:r,...i.length>0?{warning:Me({warnedCount:i.length,totalCount:t.length,worst:i.reduce((e,t)=>Math.max(e,t.stats.p95Ms),0),platform:r.platform})}:{}}}function Oe(e){if(!c(e))return;let t=Ne(e.stats);if(!t)return;let n=typeof e.warning==`string`?e.warning:void 0;return{stats:t,...n?{warning:n}:{}}}function g(e){let t=e.map(e=>e.durationMs).sort((e,t)=>e-t);return{count:t.length,p50Ms:_(t,50),p95Ms:_(t,95),maxMs:t[t.length-1]??0,slowThresholdMs:h,...ke(e),...Ae(e)}}function _(e,t){if(e.length===0)return 0;let n=Math.max(0,Math.ceil(t/100*e.length)-1);return e[Math.min(n,e.length-1)]??0}function ke(e){let t=e.map(e=>e.platform).filter(e=>!!e);return new Set(t).size===1?{platform:t[0]}:{}}function Ae(e){let t={};for(let n of e)n.backend&&(t[n.backend]=(t[n.backend]??0)+1);return Object.keys(t).length>0?{backends:t}:{}}function je(e){return`Warning: ${e.platform?`${e.platform} `:``}snapshots are slow in this run: p95 ${e.p95Ms}ms over ${e.count} captures. Possible causes: device load, app or dev server stuck, helper fallback, or stale daemon.`}function Me(e){return`Warning: ${e.platform?`${e.platform} `:``}snapshots were slow in ${e.warnedCount} of ${e.totalCount} runs (worst run p95 ${e.worst}ms). Possible causes: device load, app or dev server stuck, helper fallback, or stale daemon.`}function Ne(e){if(!c(e))return;let t=Pe(e);if(t)return{...t,...Ie(e)}}function Pe(e){let t={count:e.count,p50Ms:e.p50Ms,p95Ms:e.p95Ms,maxMs:e.maxMs,slowThresholdMs:e.slowThresholdMs};if(!Object.values(t).some(e=>typeof e!=`number`))return t}function Fe(e){let t=Object.entries(e).filter(e=>typeof e[1]==`number`);return t.length>0?Object.fromEntries(t):void 0}function Ie(e){let t=typeof e.platform==`string`?e.platform:void 0,n=c(e.backends)?Fe(e.backends):void 0;return{...t?{platform:t}:{},...n?{backends:n}:{}}}function Le(e){if(!e||e.count<=0)return[];let t=e.platform;return e.count===1?[{durationMs:e.maxMs,platform:t}]:e.count===2?[{durationMs:e.p50Ms,platform:t},{durationMs:e.maxMs,platform:t}]:[...Array.from({length:e.count-3},()=>({durationMs:e.p50Ms,platform:t})),{durationMs:e.p50Ms,platform:t},{durationMs:e.p95Ms,platform:t},{durationMs:e.maxMs,platform:t}]}const Re=1e4,ze=2e3,Be=[`get`,`accept`,`dismiss`,`wait`],Ve=[`in-app`,`system`],He=[`primary`,`secondary`,`middle`];function Ue(e){return e?.clickButton??`primary`}function We(t){return t.button===`primary`?null:t.commandLabel===`click`?t.platform!==`macos`&&t.platform!==`linux`?new e(`UNSUPPORTED_OPERATION`,`click --button ${t.button} is supported only on macOS and Linux`):t.platform===`macos`&&t.button===`middle`?new e(`UNSUPPORTED_OPERATION`,`click --button middle is not supported by the macOS runner yet`):typeof t.count==`number`||typeof t.intervalMs==`number`||typeof t.holdMs==`number`||typeof t.jitterPx==`number`||t.doubleTap===!0?new e(`INVALID_ARGS`,`click --button ${t.button} does not support repeat or gesture modifier flags`):null:new e(`INVALID_ARGS`,`--button is supported only for click`)}function Ge(e){return e===`primary`?{}:{button:e}}function v(t,n={message:e=>`Invalid value: ${e}`}){let r=new Set(t),i=n.normalize??(e=>e);return{is:e=>typeof e==`string`&&r.has(e),parse:t=>{let a=i(t??``);if(r.has(a))return a;throw new e(`INVALID_ARGS`,n.message(t??``))}}}const Ke=[`up`,`down`,`left`,`right`,`top`,`bottom`],y=[`up`,`down`,`left`,`right`],b=[`left`,`right`,`left-edge`,`right-edge`],qe=[`one-way`,`ping-pong`],Je=1e4,Ye=6e4,Xe=v(y,{message:e=>`Unknown direction: ${e}`});function Ze(e){let t=e.direction,n=t===`up`||t===`down`?e.referenceHeight:e.referenceWidth,r=T(e.amount),i=e.pixels===void 0?Math.round(n*r):E(e.pixels),a=Math.max(1,Math.round(n*.05)),o=Math.max(1,n-a*2),s=Math.max(1,Math.min(i,o)),c=Math.round(s/2),l=Math.round(e.referenceWidth/2),u=Math.round(e.referenceHeight/2),d=(n,r,i,a)=>({direction:t,x1:n,y1:r,x2:i,y2:a,referenceWidth:e.referenceWidth,referenceHeight:e.referenceHeight,amount:e.amount,pixels:s});switch(t){case`up`:return d(l,u-c,l,u+c);case`down`:return d(l,u+c,l,u-c);case`left`:return d(l-c,u,l+c,u);case`right`:return d(l+c,u,l-c,u)}}function Qe(e){T(e.amount),e.pixels!==void 0&&E(e.pixels)}function $e(e,t){if(e===`left`||e===`right`){let n=x(e,t);return{preset:e,x1:n.x1,y1:n.y1,x2:n.x2,y2:n.y2,referenceWidth:n.referenceWidth,referenceHeight:n.referenceHeight}}let[n,r]=e===`left-edge`?[99,15]:[1,85],i=C(S(t,n,50),t,8),a=C(S(t,r,50),t,8);return{preset:e,x1:i.x,y1:i.y,x2:a.x,y2:a.y,referenceWidth:t.referenceWidth,referenceHeight:t.referenceHeight}}function et(e,t){switch(e){case`up`:return{x:0,y:-t};case`down`:return{x:0,y:t};case`left`:return{x:-t,y:0};case`right`:return{x:t,y:0}}}function x(e,t){let n=e===`left`||e===`up`,r=n?85:15,i=n?15:85,a=e===`up`||e===`down`,o=C(S(t,a?50:r,a?r:50),t,8),s=C(S(t,a?50:i,a?i:50),t,8);return{direction:e,x1:o.x,y1:o.y,x2:s.x,y2:s.y,referenceWidth:t.referenceWidth,referenceHeight:t.referenceHeight}}function tt(e){let t=rt(e);if(t)return{referenceWidth:t.width,referenceHeight:t.height}}function S(e,t,n){let r=Math.trunc(e.referenceWidth*t/100),i=Math.trunc(e.referenceHeight*n/100);return{x:Number.isFinite(r)?r:0,y:Number.isFinite(i)?i:0}}function C(e,t,n){return{x:D(e.x,n,t.referenceWidth),y:D(e.y,n,t.referenceHeight)}}function nt(e){return Xe.parse(e)}function rt(e){let t=e.filter(e=>o(e)&&w(e.rect)).map(e=>e.rect).sort((e,t)=>(t?.width??0)*(t?.height??0)-(e?.width??0)*(e?.height??0))[0];if(t)return t;let n=e.map(e=>e.rect).filter(w);if(n.length===0)return;let r=Math.max(...n.map(e=>e.x+e.width)),i=Math.max(...n.map(e=>e.y+e.height));if(!(r<=0||i<=0))return{x:0,y:0,width:r,height:i}}function w(e){return!!e&&e.width>0&&e.height>0}function T(t){if(t===void 0)return .6;if(!Number.isFinite(t)||t<=0)throw new e(`INVALID_ARGS`,`scroll amount must be a positive number`);return t}function E(t){if(!Number.isFinite(t)||t<=0)throw new e(`INVALID_ARGS`,`scroll pixels must be a positive integer`);return Math.max(1,Math.round(t))}function D(e,t,n){let r=Math.round(t);if(!Number.isFinite(r))return 0;let i=Math.max(r,Math.round(n-t));return!Number.isFinite(i)||!Number.isFinite(e)?r:Math.min(i,Math.max(r,Math.round(e)))}const O=1e4,k=[`pan`,`fling`,`swipe`,`pinch`,`rotate`,`transform`,`drag`];function A(t){let n=M(t),r=I(n,`kind`,k);if(r===`pan`)return{kind:r,origin:N(n,`origin`),delta:N(n,`delta`),pointerCount:a(n,`pointerCount`,{min:1,max:2}),durationMs:j(n)};if(r===`drag`)return it(n);if(n.pointerCount!==void 0)throw new e(`INVALID_ARGS`,`pointerCount is supported only for gesture pan`);if(r===`fling`){if(n.durationMs!==void 0)throw new e(`INVALID_ARGS`,`gesture fling does not accept durationMs; use gesture pan for timed movement`);return{kind:r,direction:I(n,`direction`,y),origin:N(n,`origin`),distance:a(n,`distance`,{min:0})}}if(r===`swipe`){if(n.durationMs!==void 0)throw new e(`INVALID_ARGS`,`gesture swipe does not accept durationMs; use gesture pan for timed movement`);return{kind:r,preset:I(n,`preset`,b)}}if(r===`pinch`)return{kind:r,scale:F(n,`scale`),origin:P(n,`origin`)};if(r===`rotate`){if(n.velocity!==void 0)throw new e(`INVALID_ARGS`,`gesture rotate does not accept velocity; rotation pacing derives from degrees`);return{kind:r,degrees:F(n,`degrees`),origin:P(n,`origin`)}}return{kind:r,origin:N(n,`origin`),delta:N(n,`delta`),scale:F(n,`scale`),degrees:F(n,`degrees`),durationMs:j(n)}}function it(t){let n=a(t,`sourceHoldMs`,{min:1,max:1e4}),r=a(t,`moveMs`,{min:16,max:1e4}),i=a(t,`destinationHoldMs`,{min:0,max:1e4});if((n??800)+(r??500)+(i??0)>1e4)throw new e(`INVALID_ARGS`,`gesture drag total duration must be at most ${O}`);return{kind:`drag`,source:at(t,`source`),destination:at(t,`destination`),sourceHoldMs:n,moveMs:r,destinationHoldMs:i}}function j(t){let n=a(t,`durationMs`);if(n!==void 0){if(n<16||n>1e4)throw new e(`INVALID_ARGS`,`Expected durationMs to be an integer between 16 and ${O}.`);return n}}function M(t){if(!t||typeof t!=`object`||Array.isArray(t))throw new e(`INVALID_ARGS`,`gesture requires structured object input`);return t}function N(e,t){let n=M(e[t]);return{x:F(n,`x`),y:F(n,`y`)}}function P(e,t){return e[t]===void 0?void 0:N(e,t)}function F(t,n){let r=t[n];if(typeof r!=`number`||!Number.isFinite(r))throw new e(`INVALID_ARGS`,`Expected ${n} to be a finite number.`);return r}function at(t,n){let r=t[n];if(typeof r!=`string`||r.trim().length===0)throw new e(`INVALID_ARGS`,`Expected ${n} to be a non-empty string.`);return r.trim()}function I(t,n,r){let i=t[n];if(typeof i!=`string`||!r.includes(i))throw new e(`INVALID_ARGS`,`Expected ${n} to be one of: ${r.join(`, `)}.`);return i}const ot={swipe:{max:4,usage:`swipe accepts 4 arguments: x1 y1 x2 y2`,retired:{positional:`durationMs`,migrate:st}},"gesture pan":{max:5,usage:`gesture pan accepts at most 5 arguments: x y dx dy [durationMs]`},"gesture fling":{max:4,usage:`gesture fling accepts at most 4 arguments: direction x y [distance]`,retired:{positional:`durationMs`,migrate:(e,t)=>`use "${t}", or gesture pan for timed movement.`}},"gesture swipe":{max:1,usage:`gesture swipe accepts 1 argument: preset`,retired:{positional:`durationMs`,migrate:(e,t)=>`use "${t}", or gesture pan for timed movement.`}},"gesture pinch":{max:3,usage:`gesture pinch accepts at most 3 arguments: scale [x] [y]`},"gesture rotate":{max:3,usage:`gesture rotate accepts at most 3 arguments: degrees [x] [y]`,retired:{positional:`velocity`,migrate:(e,t)=>`use "${t}"; rotation pacing derives from degrees.`}},"gesture transform":{max:7,usage:`gesture transform accepts at most 7 arguments: x y dx dy scale degrees [durationMs]`},"gesture drag":{max:5,usage:`gesture drag accepts at most 5 arguments: source destination [sourceHoldMs] [moveMs] [destinationHoldMs]`}};function st(e,t){let[n,r,i,a,o]=e,s=ct(n,i),c=ct(r,a);return s===void 0||c===void 0?`use "gesture pan x1 y1 dx dy durationMs" for the same timed drag, or "${t}" for a default-duration swipe.`:`use "gesture pan ${n} ${r} ${s} ${c} ${o}" for the same timed drag, or "${t}" for a default-duration swipe.`}function ct(e,t){let n=Number(t)-Number(e);return Number.isFinite(n)?n:void 0}function L(e,t){let n=ot[e];if(t.length<=n.max)return;let r=n.retired;if(!r||t.length!==n.max+1||!lt(t[n.max]))return{usage:n.usage};let i=`${e} ${t.slice(0,n.max).join(` `)}`;return{usage:n.usage,migration:`The trailing ${r.positional} positional was removed: ${r.migrate(t,i)}`}}function lt(e){return e===void 0||e.trim().length===0?!1:e.startsWith("${")||Number.isFinite(Number(e))}function ut(t){if(!(!t||typeof t!=`object`||Array.isArray(t))&&t.durationMs!==void 0)throw new e(`INVALID_ARGS`,`swipe does not accept durationMs; use gesture pan for timed movement`)}function dt(e,t){let n=t?`${e.usage} (${t})`:e.usage;return e.migration?`${n}. ${e.migration}`:`${n}.`}function R(t,n){let r=L(t,n);if(r)throw new e(`INVALID_ARGS`,dt(r))}function ft(e,t,n){let r=pt(e,t);return r?dt(r,n):void 0}function pt(e,t){if(e===`swipe`)return L(`swipe`,t);if(e!==`gesture`)return;let n=`gesture ${t[0]}`;if(Object.hasOwn(ot,n))return L(n,t.slice(1))}function mt(e){return{origin:{x:Number(e[0]),y:Number(e[1])},delta:{x:Number(e[2]),y:Number(e[3])}}}function ht(e,t){let n=e[0],r=e.slice(1);switch(n){case`pan`:{R(`gesture pan`,r);let{origin:e,delta:i}=mt(r);return A({kind:n,origin:e,delta:i,pointerCount:t,durationMs:z(r[4])})}case`fling`:return R(`gesture fling`,r),A({kind:n,direction:r[0],origin:{x:Number(r[1]),y:Number(r[2])},distance:z(r[3])});case`swipe`:return R(`gesture swipe`,r),A({kind:n,preset:r[0]});case`pinch`:return R(`gesture pinch`,r),A({kind:n,scale:Number(r[0]),origin:St(r[1],r[2])});case`rotate`:return R(`gesture rotate`,r),A({kind:n,degrees:Number(r[0]),origin:St(r[1],r[2])});case`transform`:{R(`gesture transform`,r);let{origin:e,delta:t}=mt(r);return A({kind:n,origin:e,delta:t,scale:Number(r[4]),degrees:Number(r[5]),durationMs:z(r[6])})}case`drag`:return R(`gesture drag`,r),A({kind:n,source:r[0],destination:r[1],sourceHoldMs:z(r[2]),moveMs:z(r[3]),destinationHoldMs:z(r[4])});default:return A({kind:n})}}function gt(e){if(e[0]!==`drag`)return;let t=ht(e);return t.kind===`drag`?t:void 0}function _t(e){switch(e.kind){case`pan`:return B([e.kind,e.origin.x,e.origin.y,e.delta.x,e.delta.y,e.durationMs]);case`fling`:return B([e.kind,e.direction,e.origin.x,e.origin.y,e.distance]);case`swipe`:return[e.kind,e.preset];case`pinch`:return B([e.kind,e.scale,e.origin?.x,e.origin?.y]);case`rotate`:return e.origin?B([e.kind,e.degrees,e.origin.x,e.origin.y]):[e.kind,String(e.degrees)];case`transform`:return B([e.kind,e.origin.x,e.origin.y,e.delta.x,e.delta.y,e.scale,e.degrees,e.durationMs]);case`drag`:return[e.kind,e.source,e.destination,String(e.sourceHoldMs??800),String(e.moveMs??500),String(e.destinationHoldMs??0)]}}function vt(e,t={}){return R(`swipe`,e),{from:{x:Number(e[0]),y:Number(e[1])},to:{x:Number(e[2]),y:Number(e[3])},...t.count===void 0?{}:{count:t.count},...t.pauseMs===void 0?{}:{pauseMs:t.pauseMs},...t.pattern===void 0?{}:{pattern:t.pattern}}}function yt(t){switch(t.kind){case`pan`:return{gesture:{intent:`pan`,origin:t.origin,delta:t.delta,pointerCount:t.pointerCount,durationMs:t.durationMs}};case`fling`:return{gesture:{intent:`fling`,direction:t.direction,origin:t.origin,distance:t.distance}};case`swipe`:return{gesture:{intent:`fling`,preset:t.preset}};case`pinch`:return{gesture:{intent:`pinch`,origin:t.origin,scale:t.scale}};case`rotate`:return{gesture:{intent:`rotate`,origin:t.origin,degrees:t.degrees}};case`transform`:return{gesture:{intent:`transform`,origin:t.origin,delta:t.delta,scale:t.scale,degrees:t.degrees,durationMs:t.durationMs}};case`drag`:throw new e(`INVALID_ARGS`,`gesture drag targets must be resolved before coordinate normalization`)}}function bt(e){return e.kind===`drag`?{intent:`drag`,source:e.source,destination:e.destination,sourceHoldMs:e.sourceHoldMs,moveMs:e.moveMs,destinationHoldMs:e.destinationHoldMs}:yt(e).gesture}function xt(e){return{gesture:{intent:`fling`,from:e.from,to:e.to}}}function z(e){return e===void 0?void 0:Number(e)}function St(t,n){if(t===void 0!=(n===void 0))throw new e(`INVALID_ARGS`,`gesture origin requires both x and y coordinates`);return t===void 0?void 0:{x:Number(t),y:Number(n)}}function B(e){return e.filter(e=>e!==void 0).map(String)}const V={pinchAxisDegrees:-90,samplingProfile:`default`},Ct={ios:V,macos:V,android:{pinchAxisDegrees:0,samplingProfile:`android`},harmonyos:V,vega:V,linux:V,web:V};function wt(e,t,n){let r=It(t),i=Gt(n);switch(e.intent){case`fling`:return Ot(e,r);case`pan`:return kt(e,r,i);case`pinch`:return U({intent:`pinch`,origin:e.origin??Ht(r),delta:{x:0,y:0},scale:Bt(e.scale,`gesture pinch scale`),rotationDegrees:0,durationMs:300},r,i);case`rotate`:{let t=K(e.degrees,`gesture rotate degrees`);return U({intent:`rotate`,origin:e.origin??Ht(r),delta:{x:0,y:0},scale:1,rotationDegrees:t,durationMs:zt(t)},r,i)}case`transform`:{let t=K(e.degrees,`gesture transform degrees`);return U({intent:`transform`,origin:e.origin,delta:e.delta,scale:Bt(e.scale,`gesture transform scale`),rotationDegrees:t,durationMs:W(e.durationMs,zt(t),`gesture transform durationMs`)},r,i)}}}function Tt(e){let[{samples:t}]=e.pointers,n=t[0],r=t.at(-1);return{start:n.point,end:r.point}}function Et(t,n){let r=It(n),i=Lt(t.sourceHoldMs,800,`gesture drag sourceHoldMs`),a=W(t.moveMs,500,`gesture drag moveMs`),o=Rt(t.destinationHoldMs,0,`gesture drag destinationHoldMs`);if(i+a+o>1e4)throw new e(`INVALID_ARGS`,`gesture drag total duration must be at most ${O}`);return Dt(H(`pan`,t.from,t.to,a,r,`timed-pan`),i,o)}function Dt(e,t,n){let r=e.pointers[0],[i,a]=r.samples,o=t+e.durationMs+n,s=[{offsetMs:0,point:i.point},{...i,offsetMs:i.offsetMs+t},{...a,offsetMs:a.offsetMs+t},...n>0?[{offsetMs:o,point:a.point}]:[]];return{...e,durationMs:o,pointers:[{...r,samples:s}]}}function Ot(e,t){if(`preset`in e){let{from:n,to:r}=Wt(e.preset,t);return H(`fling`,n,r,100,t,`endpoint-hold`)}if(`from`in e)return H(`fling`,e.from,e.to,100,t,`endpoint-hold`);let n=G(e.origin,`gesture fling origin`),r=Vt(e.distance??180,`gesture fling distance`);return H(`fling`,n,q(n,et(e.direction,r)),100,t,`endpoint-hold`)}function kt(t,n,r){let i=W(t.durationMs,500,`gesture pan durationMs`);if((t.pointerCount??1)===1){let e=G(t.origin,`gesture pan origin`);return H(`pan`,e,q(e,G(t.delta,`gesture pan delta`)),i,n,t.executionProfile??`timed-pan`)}if(t.pointerCount!==2)throw new e(`INVALID_ARGS`,`gesture pan pointerCount must be 1 or 2`);return U({intent:`pan`,origin:t.origin,delta:t.delta,scale:1,rotationDegrees:0,durationMs:i},n,r)}function H(e,t,n,r,i,a){let o=G(t,`gesture ${e} start`),s=G(n,`gesture ${e} end`),c=[{offsetMs:0,point:o},{offsetMs:r,point:s}];return Pt(c,i,{intent:e,pointerId:0}),{topology:`single`,intent:e,executionProfile:a,durationMs:r,viewport:i,pointers:[{pointerId:0,samples:c}]}}function U(e,t,n){let r=G(e.origin,`gesture ${e.intent} origin`),i=q(r,G(e.delta,`gesture ${e.intent} delta`)),a=Math.min(t.width,t.height)*Mt(e.intent),o=e.scale>1?a/e.scale:a,s=o*e.scale;if(Math.min(o,s)<48)throw Ft({intent:e.intent,viewport:t,initialSpan:o,finalSpan:s,minimumReliableSpan:48});let c=o/2,l=Nt(e.durationMs,n.samplingProfile),u=(a,o)=>{let s=l.map(t=>({offsetMs:t,point:At({...e,start:r,end:i,initialRadius:c,offsetMs:t,side:o,profile:n})}));return Pt(s,t,{intent:e.intent,pointerId:a}),{pointerId:a,samples:s}};return{topology:`two`,intent:e.intent,durationMs:e.durationMs,viewport:t,pointers:[u(0,1),u(1,-1)]}}function At(e){let t=e.offsetMs/e.durationMs,n=Ut(e.start,e.end,t),r=e.initialRadius*(1+(e.scale-1)*t),i=Kt(jt(e.intent,e.profile)+e.rotationDegrees*t);return{x:n.x+Math.cos(i)*r*e.side,y:n.y+Math.sin(i)*r*e.side}}function jt(e,t){return e===`pinch`?t.pinchAxisDegrees:-90}function Mt(e){return e===`pinch`?.4:.25}function Nt(t,n){if(!Number.isFinite(t)||t<=0)throw new e(`INVALID_ARGS`,`gesture sample duration must be a positive finite number`);let r=t/16,i=Math.max(3,n===`android`?Math.round(r):Math.floor(r));return Array.from({length:i+1},(e,n)=>Math.round(t*n/i))}function Pt(t,n,r){let i=n.x+n.width-1,a=n.y+n.height-1;for(let o of t){let{x:t,y:s}=o.point;if(!Number.isFinite(t)||!Number.isFinite(s))throw new e(`INVALID_ARGS`,`Gesture motion produces non-finite pointer coordinates`,{...r,reason:`GESTURE_TRAJECTORY_NON_FINITE`,hint:`Reduce the requested rotation, translation, or scale.`});if(t<n.x+1||t>i||s<n.y+1||s>a)throw Ft({...r,viewport:n,sample:o})}}function Ft(t){return new e(`INVALID_ARGS`,`Gesture trajectory does not fit inside the viewport`,{...t,reason:`GESTURE_TRAJECTORY_OUT_OF_BOUNDS`,hint:`Move the gesture away from the edge or reduce its translation, scale, or rotation.`})}function It(t){let n={x:K(t.x,`gesture viewport x`),y:K(t.y,`gesture viewport y`),width:K(t.width,`gesture viewport width`),height:K(t.height,`gesture viewport height`)};if(n.width<=0||n.height<=0)throw new e(`INVALID_ARGS`,`gesture viewport width and height must be positive`);return n}function W(t,n,r){let i=t??n;if(!Number.isInteger(i)||i<16||i>1e4)throw new e(`INVALID_ARGS`,`${r} must be an integer between 16 and ${O}`);return i}function Lt(t,n,r){let i=t??n;if(!Number.isInteger(i)||i<1||i>1e4)throw new e(`INVALID_ARGS`,`${r} must be an integer between 1 and ${O}`);return i}function Rt(t,n,r){let i=t??n;if(!Number.isInteger(i)||i<0||i>1e4)throw new e(`INVALID_ARGS`,`${r} must be an integer between 0 and ${O}`);return i}function zt(e){let t=Math.ceil(Math.abs(e)/3)*16;return Math.min(Math.max(300,t),2400)}function G(e,t){return{x:K(e.x,`${t} x`),y:K(e.y,`${t} y`)}}function K(t,n){if(!Number.isFinite(t))throw new e(`INVALID_ARGS`,`${n} must be a finite number`);return t}function Bt(t,n){let r=K(t,n);if(r<=0)throw new e(`INVALID_ARGS`,`${n} must be greater than 0`);return r}function Vt(t,n){let r=K(t,n);if(r<=0)throw new e(`INVALID_ARGS`,`${n} must be a positive number`);return r}function Ht(e){return{x:e.x+e.width/2,y:e.y+e.height/2}}function q(e,t){return{x:e.x+t.x,y:e.y+t.y}}function Ut(e,t,n){return{x:e.x+(t.x-e.x)*n,y:e.y+(t.y-e.y)*n}}function Wt(e,t){let n=$e(e,{referenceWidth:t.width,referenceHeight:t.height});return{from:{x:t.x+n.x1,y:t.y+n.y1},to:{x:t.x+n.x2,y:t.y+n.y2}}}function Gt(e){return e===void 0?V:Ct[e]}function Kt(e){return e*Math.PI/180}const qt={occlusion:{kind:`runtime`,via:`src/snapshot/snapshot-occlusion.ts#isSnapshotNodeInteractionBlocked`},parentOwnedTouchPoint:{kind:`runtime`,via:`src/core/interaction-touch-point.ts#resolveInteractionTouchPoint`},offscreen:{kind:`runtime`,via:`src/commands/interaction/runtime/resolution.ts#throwIfOffscreenInteractionTarget`},nonHittable:{kind:`runtime`,via:`src/core/interaction-targeting.ts#resolveActionableTouchResolution`},responseConstruction:{kind:`runtime`,via:`src/daemon/handlers/interaction-touch-response.ts#buildInteractionResponseData`},responseIdentity:{kind:`runtime`,via:`src/daemon/handlers/interaction-touch-targets.ts#interactionResultExtra`},verifyEvidence:{kind:`runtime`,via:`src/commands/interaction/runtime/interactions.ts#pressCommand`,appliesTo:[`press`,`click`,`fill`]},settleObservation:{kind:`runtime`,via:`src/commands/interaction/runtime/settle.ts#settleAfterInteraction`}};({...qt}),{...qt};const Jt=`tapped via non-hittable coordinate fallback`,Yt=[`xctest-element`,`synthesized-first-responder`,`synthesized-first-responder-replacement`,`xctest-application-fallback`],Xt=[`focused-element`,`keyboard-shown`],Zt=1e4;function Qt(t,n=`scroll accepts either a relative amount or --pixels, not both`){if(t.amount!==void 0&&t.pixels!==void 0)throw new e(`INVALID_ARGS`,n)}function $t(t,n={}){if(t===void 0)return;let r=n.field??`scroll durationMs`,i=n.max??1e4,a=n.invalidMessage??`${r} must be a non-negative integer`;if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new e(`INVALID_ARGS`,a);if(t>i)throw new e(`INVALID_ARGS`,`${r} must be a non-negative integer at most ${i}`);return t}function en(e){return typeof e?.durationMs==`number`?e.durationMs:void 0}const tn={android:`longpress`,apple:`exact`,vega:`exact`},J={up:{aliases:[],androidKeyevent:`KEYCODE_DPAD_UP`,appleRemoteButton:`up`,vegaKey:`KEY_UP`},down:{aliases:[],androidKeyevent:`KEYCODE_DPAD_DOWN`,appleRemoteButton:`down`,vegaKey:`KEY_DOWN`},left:{aliases:[],androidKeyevent:`KEYCODE_DPAD_LEFT`,appleRemoteButton:`left`,vegaKey:`KEY_LEFT`},right:{aliases:[],androidKeyevent:`KEYCODE_DPAD_RIGHT`,appleRemoteButton:`right`,vegaKey:`KEY_RIGHT`},select:{aliases:[`ok`,`center`,`enter`],androidKeyevent:`KEYCODE_DPAD_CENTER`,appleRemoteButton:`select`,vegaKey:`KEY_ENTER`},menu:{aliases:[],androidKeyevent:`KEYCODE_MENU`,appleRemoteButton:`menu`,vegaKey:`KEY_MENU`},home:{aliases:[],androidKeyevent:`KEYCODE_HOME`,appleRemoteButton:`home`,vegaKey:`KEY_HOMEPAGE`},back:{aliases:[],androidKeyevent:`KEYCODE_BACK`,appleRemoteButton:`menu`,vegaKey:`KEY_BACK`}},Y=Object.keys(J),nn=`<${Y.join(`|`)}>`;function rn(t){let n=t?.toLowerCase();if(an(n))return n;let r=n?un.get(n):void 0;if(r)return r;throw new e(`INVALID_ARGS`,`tv-remote button must be one of: ${Y.join(`, `)}.`)}function an(e){return typeof e==`string`&&Y.includes(e)}function on(e){return J[e].appleRemoteButton}function sn(e){return J[e].androidKeyevent}function cn(e){return J[e].vegaKey}function ln(e){return tn[e]}const un=new Map(Y.flatMap(e=>J[e].aliases.map(t=>[t,e]))),dn={captureStalled:`wait_capture_stalled`,deadlineExceeded:`wait_deadline_exceeded`,targetAbsent:`wait_target_absent`,stableTimeout:`wait_stable_timeout`,landmarkIdentityMismatch:`wait_landmark_identity_mismatch`},fn=[`camera`,`microphone`,`photos`,`contacts`,`contacts-limited`,`notifications`,`calendar`,`location`,`location-always`,`media-library`,`motion`,`reminders`,`siri`],pn=`<wifi|airplane|location> <on|off>`,mn=`location set <lat> <lon>`,hn=`animations <on|off>`,X=`appearance <light|dark|toggle>`,gn=`faceid <match|nonmatch|enroll|unenroll>`,_n=`touchid <match|nonmatch|enroll|unenroll>`,vn=`fingerprint <match|nonmatch>`,yn=`clear-app-state [app-id]`,bn=`permission <grant|deny|reset> <camera|microphone|photos|contacts|contacts-limited|notifications|calendar|location|location-always|media-library|motion|reminders|siri> [full|limited]`,Z=`permission <grant|reset> <accessibility|screen-recording|input-monitoring>`,xn=`macOS supports only settings ${X} and settings ${Z}. wifi|airplane|location|animations remain unsupported on macOS.`,Sn=[`settings ${pn}`,`settings ${mn}`,`settings ${hn}`,`settings ${X}`,`settings ${gn}`,`settings ${_n}`,`settings ${vn}`,`settings ${yn}`,`settings ${bn}`,`settings ${Z}`].join(` | `),Cn=`settings requires ${pn}, ${mn}, ${hn}, ${X}, ${gn}, ${_n}, ${vn}, ${yn}, ${bn}, or ${Z}`;function wn(e){let t=e.trim().toLowerCase();return t===`appearance`||t===`permission`}function Tn(e){return`Unsupported macOS setting: ${e}. ${xn}`}function En(t){let n=t.trim().toLowerCase();if(n===`grant`)return`grant`;if(n===`deny`)return`deny`;if(n===`reset`)return`reset`;throw new e(`INVALID_ARGS`,`Invalid permission action: ${t}. Use grant|deny|reset.`)}function Dn(t){let n=t?.trim().toLowerCase();if(n===`camera`||n===`microphone`||n===`photos`||n===`contacts`||n===`contacts-limited`||n===`notifications`||n===`calendar`||n===`location`||n===`location-always`||n===`media-library`||n===`motion`||n===`reminders`||n===`siri`)return n;throw new e(`INVALID_ARGS`,`permission setting requires a target: ${fn.join(`|`)}`)}function On(t,n){if(t===void 0||t.trim()===``)throw new e(`INVALID_ARGS`,`settings location set requires ${n}`);return Q(Number(t),n)}function kn(e){return{latitude:Q(e?.latitude,`latitude`),longitude:Q(e?.longitude,`longitude`)}}function Q(t,n){let r=n===`latitude`?-90:-180,i=n===`latitude`?90:180;if(typeof t!=`number`||!Number.isFinite(t)||t<r||t>i)throw new e(`INVALID_ARGS`,`${n} must be a number from ${r} to ${i}`);return t}function An(e){let t=new Map;for(let[n,r]of e.entries())t.set(r.index,n);let n=[],r=[];for(let[i,a]of e.entries()){let e=Math.max(0,a.depth??0);for(;r.length>0&&e<=r[r.length-1].depth;)r.pop();let o=i,s=typeof a.parentIndex==`number`?t.get(a.parentIndex):void 0,c=typeof s==`number`&&s<o?s:r[r.length-1]?.index;n.push({...a,index:o,depth:e,parentIndex:c}),r.push({depth:e,index:o})}return n}function $(e){return e.label?.trim()||e.value?.trim()||e.identifier?.trim()||``}function jn(e){let t=e.trim().toLowerCase();return t?/^(vertical|horizontal)\s+scroll\s+bar(?:,?\s*\d+\s+pages?)?$/.test(t):!1}function Mn(e,t){if(!(e?.trim().toLowerCase()??``).includes(`vertical scroll bar`))return null;let n=Nn(t);return n===null?null:n<=1?{above:!1,below:!0}:n>=99?{above:!0,below:!1}:{above:!0,below:!0}}function Nn(e){if(!e)return null;let t=/^(\d{1,3})%$/.exec(e.trim());if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?Math.max(0,Math.min(100,n)):null}function Pn(e){if(e.length===0)return{nodes:e,hiddenCount:0,summaryLines:[]};let{byIndex:t,visibleNodeIndexes:n,offscreenNodes:r,hintedContainers:i}=In(e),a=n.size===0?e:e.filter(e=>n.has(e.index));return{nodes:a.map(e=>Hn(e,i.directionsByContainer)),hiddenCount:n.size===0?0:e.length-a.length,summaryLines:Un(r.filter(e=>!i.coveredNodeIndexes.has(e.index)&&Kn(e)),e,t)}}function Fn(e){if(e.length===0)return new Map;let{hintedContainers:t}=In(e);return Vn(t.directionsByContainer)}function In(e){let t=u(e),n=new Set,r=[];for(let i of e){if(l(i,e,t)){Jn(i,n,t);continue}r.push(i)}return{byIndex:t,visibleNodeIndexes:n,offscreenNodes:r,hintedContainers:Bn(e,r,n,t)}}function Ln(e,t){return e.hittable&&r(e.rect,t)}function Rn(e,n,a=u(n)){if(!e.rect)return null;let o=s(e,n,a);if(o&&!i(e.rect,o)){let t=zn(e.rect,o);if(t)return t}let c=t(n,e.rect);if(c&&!r(e.rect,c)){let t=zn(e.rect,c);if(t)return t}return null}function zn(e,t){let n=e.x+e.width/2,r=e.y+e.height/2,i=[{direction:`down`,amount:r-(t.y+t.height)},{direction:`up`,amount:t.y-r},{direction:`right`,amount:n-(t.x+t.width)},{direction:`left`,amount:t.x-n}],a=null;for(let e of i)e.amount>0&&(!a||e.amount>a.amount)&&(a=e);return a?.direction??null}function Bn(e,t,n,r){let i=new Map,a=new Map,o=new Set;for(let e of t){if(!e.rect)continue;let t=Yn(e,n,r);if(!t?.rect)continue;let s=Gn(e.rect,t.rect);if(!s)continue;let c=i.get(t.index)??new Set;c.add(s),i.set(t.index,c);let l=a.get(t.index)??new Set;l.add(s),a.set(t.index,l),o.add(e.index)}return Xn(e,n,r,i,a),{directionsByContainer:i,coveredNodeIndexes:o}}function Vn(e){let t=new Map;for(let[n,r]of e){let e={};r.has(`above`)&&(e.hiddenContentAbove=!0),r.has(`below`)&&(e.hiddenContentBelow=!0),(e.hiddenContentAbove||e.hiddenContentBelow)&&t.set(n,e)}return t}function Hn(e,t){let n=t.get(e.index);if(!n||n.size===0)return e;let r=e.hiddenContentAbove===!0||n.has(`above`)?!0:void 0,i=e.hiddenContentBelow===!0||n.has(`below`)?!0:void 0;return{...e,hiddenContentAbove:r,hiddenContentBelow:i}}function Un(e,t,n){let r=new Map;for(let i of e){let e=Wn(i,t,n);if(!e)continue;let a=r.get(e)??[];a.push(i),r.set(e,a)}return[`above`,`below`].flatMap(e=>{let t=r.get(e);if(!t||t.length===0)return[];let n=qn(t).slice(0,3).map(e=>`"${e}"`),i=t.length===1?`interactive item`:`interactive items`,a=n.length>0?`: ${n.join(`, `)}`:``;return[`[off-screen ${e}] ${t.length} ${i}${a}`]})}function Wn(e,t,n){if(!e.rect)return null;let r=s(e,t,n);return r?Gn(e.rect,r):null}function Gn(e,t){return e.y+e.height<=t.y?`above`:e.y>=t.y+t.height?`below`:null}function Kn(e){if(e.hittable===!0)return!0;let t=(e.type??``).toLowerCase();return t.includes(`button`)||t.includes(`link`)||t.includes(`textfield`)||t.includes(`edittext`)||t.includes(`searchfield`)||t.includes(`checkbox`)||t.includes(`radio`)||t.includes(`switch`)||t.includes(`menuitem`)||!!$(e)}function qn(e){let t=new Set,n=[];for(let r of e){let e=$(r);!e||t.has(e)||(t.add(e),n.push(e))}return n}function Jn(e,t,n){let r=e,i=new Set;for(;r&&!i.has(r.index);)i.add(r.index),t.add(r.index),r=typeof r.parentIndex==`number`?n.get(r.parentIndex):void 0}function Yn(e,t,r){return n(e,r,e=>t.has(e.index))}function Xn(e,t,n,r,i){for(let a of e){let e=Zn(a);if(!e||e.size===0)continue;let o=Yn(a,t,n);if(!o)continue;let s=r.get(o.index)??new Set,c=i.get(o.index);for(let t of e)c&&c.size>0&&!c.has(t)||s.add(t);r.set(o.index,s)}}function Zn(e){let t=Mn(e.label,e.value);if(!t)return null;let n=new Set;return t.above&&n.add(`above`),t.below&&n.add(`below`),n.size>0?n:null}function Qn(e){return e}function $n(e,t){let n=Math.max(e.x,t.x),r=Math.max(e.y,t.y),i=Math.min(e.x+e.width,t.x+t.width),a=Math.min(e.y+e.height,t.y+t.height);return i<=n||a<=r?0:(i-n)*(a-r)}function er(e=tr()){try{let t=JSON.parse(f.readFileSync(d.join(e,`package.json`),`utf8`));return typeof t.version==`string`?t.version:`0.0.0`}catch{return`0.0.0`}}function tr(){let e=d.dirname(ee(import.meta.url)),t=e;for(let e=0;e<6;e+=1){let e=d.join(t,`package.json`);if(f.existsSync(e))return t;t=d.dirname(t)}return e}export{qe as $,Qt as A,pe as At,Tt as B,nn as C,xe as Ct,cn as D,re as Dt,on as E,ie as Et,Yt as F,le as Ft,_t as G,ft as H,Et as I,ne as It,vt as J,bt as K,wt as L,fe as Lt,$t as M,te as Mt,Xt as N,ue as Nt,ln as O,p as Ot,Jt as P,de as Pt,Ke as Q,Ut as R,Y as S,be as St,sn as T,m as Tt,gt as U,ut as V,ht as W,A as X,k as Y,y as Z,Tn as _,De as _t,Pn as a,Ze as at,Dn as b,Te as bt,Ln as c,v as ct,$ as d,We as dt,Je as et,An as f,Ue as ft,Sn as g,Re as gt,Cn as h,ze as ht,Qn as i,x as it,en as j,me as jt,Zt as k,ae as kt,Mn as l,He as lt,kn as m,Be as mt,er as n,Ye as nt,Rn as o,tt as ot,On as p,Ve as pt,xt as q,$n as r,Qe as rt,Fn as s,nt as st,tr as t,b as tt,jn as u,Ge as ut,wn as v,Oe as vt,rn as w,ye as wt,dn as x,Ee as xt,En as y,we as yt,Nt as z};
|
|
1
|
+
import e from"node:path";import t from"node:fs";import{fileURLToPath as n}from"node:url";function r(n=i()){try{let r=JSON.parse(t.readFileSync(e.join(n,`package.json`),`utf8`));return typeof r.version==`string`?r.version:`0.0.0`}catch{return`0.0.0`}}function i(){let r=e.dirname(n(import.meta.url)),i=r;for(let n=0;n<6;n+=1){let n=e.join(i,`package.json`);if(t.existsSync(n))return i;i=e.dirname(i)}return r}export{r as n,i as t};
|
package/dist/src/video.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{_ as e}from"./sdk-contracts.js";import{
|
|
1
|
+
import{_ as e}from"./sdk-contracts.js";import{_ as t}from"./sdk-android-adb.js";import{t as n}from"./timeouts.js";import{c as r}from"./host-process.js";import{t as i}from"./process-lock.js";import a from"node:path";import{createHash as o}from"node:crypto";import s from"node:fs";import c from"node:os";function l(e=process.env){let t=f(),n=a.join(t,`home`),r=a.join(t,`module-cache`);return s.mkdirSync(n,{recursive:!0}),s.mkdirSync(r,{recursive:!0}),{...e,HOME:n,CLANG_MODULE_CACHE_PATH:r}}async function u(e){let t=s.statSync(e.sourcePath),n=s.readFileSync(e.sourcePath),r=g(e.cacheName??a.basename(e.sourcePath,a.extname(e.sourcePath))),i=v([`2`,process.platform,process.arch,a.resolve(e.sourcePath),t.size,n]),o=a.join(f(),`bin`,`${r}-${i}`);return await p({sourcePath:e.sourcePath,executablePath:o,timeoutMs:e.timeoutMs}),o}async function d(e){let t=g(e.cacheName),n=v([`2`,process.platform,process.arch,e.source]),r=a.join(f(),`sources`,`${t}-${n}.swift`),i=a.join(f(),`bin`,`${t}-${n}`);return await p({sourcePath:r,executablePath:i,sourceText:e.source,timeoutMs:e.timeoutMs}),i}function f(){let e=process.env.AGENT_DEVICE_SWIFT_CACHE_DIR?.trim();return e?a.resolve(e):a.join(c.tmpdir(),`agent-device-swift-cache`)}async function p(e){if(h(e.executablePath))return;let n=a.dirname(e.executablePath);s.mkdirSync(n,{recursive:!0});let r=await m(`${e.executablePath}.lock`,e.executablePath,e.timeoutMs??12e4);if(!r)return;let i=s.mkdtempSync(a.join(n,`.${a.basename(e.executablePath)}.${process.pid}.`)),o=a.join(i,a.basename(e.executablePath));try{if(h(e.executablePath))return;e.sourceText!==void 0&&!s.existsSync(e.sourcePath)&&(s.mkdirSync(a.dirname(e.sourcePath),{recursive:!0}),s.writeFileSync(e.sourcePath,e.sourceText)),await t(`xcrun`,[`swiftc`,e.sourcePath,`-o`,o],{timeoutMs:e.timeoutMs??12e4,env:l()}),s.renameSync(o,e.executablePath)}finally{s.rmSync(i,{recursive:!0,force:!0}),await r()}}async function m(t,n,a){if(h(n))return null;try{return await i({lockDirPath:t,owner:{pid:process.pid,startTime:r(process.pid),acquiredAtMs:Date.now()},timeoutMs:a,pollMs:25,ownerGraceMs:a,description:`Swift cache lock: ${t} (${a}ms)`})}catch(n){throw n instanceof e&&n.message.startsWith(`Timed out waiting for Swift cache lock:`)?new e(`COMMAND_FAILED`,n.message,{...n.details,lockDir:t,timeoutMs:a,hint:`Another agent-device process may still be compiling this Swift helper. Retry shortly; if no agent-device process is active, remove "${t}" and retry.`}):n}}function h(e){try{return s.accessSync(e,s.constants.X_OK),s.statSync(e).isFile()}catch{return!1}}function g(e){return _(e.replaceAll(/[^A-Za-z0-9._-]/g,`-`))||`swift-helper`}function _(e){let t=0,n=e.length;for(;t<n&&e[t]===`-`;)t+=1;for(;n>t&&e[n-1]===`-`;)--n;return e.slice(t,n)}function v(e){let t=o(`sha256`);for(let n of e)t.update(Buffer.isBuffer(n)?n:String(n)),t.update(`\0`);return t.digest(`hex`).slice(0,16)}const y={block:161,blockGroup:160,cluster:524531317,codecId:134,documentType:17026,ebml:440786851,segment:408125543,simpleBlock:163,trackEntry:174,trackNumber:215,tracks:374648427,trackType:131};function b(e){let t=x(e);if(!t)return!1;let{bytes:n,fileSize:r}=t,i=M(n,0,n.length,r);if(!i||i.id!==y.ebml||!i.complete||i.unknownSize||!S(n,i))return!1;let a=M(n,i.nextOffset,n.length,r);return!a||a.id!==y.segment||!I(a,r)?!1:C(n,a,r)}function x(e){try{let t=s.openSync(e,`r`);try{let e=s.fstatSync(t).size;if(e<=0)return;let n=Buffer.alloc(Math.min(e,1048576));return s.readSync(t,n,0,n.length,0)===n.length?{bytes:n,fileSize:e}:void 0}finally{s.closeSync(t)}}catch{return}}function S(e,t){let n=j(e,t)?.find(e=>e.id===y.documentType);return n!==void 0&&e.toString(`ascii`,n.dataStart,n.dataEnd)===`webm`}function C(e,t,n){let r=new Set,i=new Set;for(let a=t.dataStart;a<t.dataEnd;){let o=M(e,a,t.dataEnd,n);if(!o||!I(o,n))return!1;if(o.id===y.tracks&&w(e,o,r),o.id===y.cluster&&E(e,o,n,i),L(r,i))return!0;if(!o.complete||o.unknownSize)return!1;a=o.nextOffset}return!1}function w(e,t,n){let r=j(e,t);if(r){for(let t of r)if(t.id===y.trackEntry){let r=T(e,t);r!==void 0&&n.add(r)}}}function T(e,t){let n=j(e,t),r=A(e,n,y.trackNumber),i=A(e,n,y.trackType),a=n?.find(e=>e.id===y.codecId),o=a?e.toString(`ascii`,a.dataStart,a.dataEnd):void 0;return i===1&&o?.startsWith(`V_`)?r:void 0}function E(e,t,n,r){for(let i=t.dataStart;i<t.dataEnd;){let a=M(e,i,t.dataEnd,n);if(!a||!I(a,n)||(a.id===y.simpleBlock&&O(e,a,r),a.id===y.blockGroup&&D(e,a,r),!a.complete||a.unknownSize))return;i=a.nextOffset}}function D(e,t,n){let r=j(e,t)?.find(e=>e.id===y.block);r&&O(e,r,n)}function O(e,t,n){if(!t.complete||t.unknownSize)return;let r=P(e,t.dataStart);!r||r.unknown||t.dataEnd-t.dataStart<r.length+4||n.add(r.value)}function k(e,t){let n=t.dataEnd-t.dataStart;if(n<1||n>6)return;let r=0;for(let n=t.dataStart;n<t.dataEnd;n+=1)r=r*256+e[n];return Number.isSafeInteger(r)?r:void 0}function A(e,t,n){let r=t?.find(e=>e.id===n);return r?k(e,r):void 0}function j(e,t){if(!t.complete||t.unknownSize)return;let n=[];for(let r=t.dataStart;r<t.dataEnd;){let i=M(e,r,t.dataEnd,e.length);if(!i||!i.complete||i.unknownSize)return;n.push(i),r=i.nextOffset}return n}function M(e,t,n,r){let i=N(e,t);if(!i)return;let a=P(e,t+i.length);if(!a)return;let o=t+i.length+a.length;if(o>n)return;let s=a.unknown?r:o+a.value;if(!(!Number.isSafeInteger(s)||s<o))return{id:i.value,dataStart:o,dataEnd:Math.min(s,n),nextOffset:s,complete:s<=n,unknownSize:a.unknown}}function N(e,t){let n=F(e,t,4);if(!n)return;let r=0;for(let i=0;i<n;i+=1)r=r*256+e[t+i];return{length:n,value:r}}function P(e,t){let n=F(e,t,8);if(!n)return;let r=e[t],i=128>>n-1;if((r&i-1)==i-1&&e.subarray(t+1,t+n).every(e=>e===255))return{length:n,value:0,unknown:!0};let a=r&i-1;for(let r=1;r<n;r+=1)a=a*256+e[t+r];return Number.isSafeInteger(a)?{length:n,value:a,unknown:!1}:void 0}function F(e,t,n){let r=e[t];if(r===void 0||r===0)return;let i=128,a=1;for(;(r&i)===0;)i>>=1,a+=1;return a<=n&&t+a<=e.length?a:void 0}function I(e,t){return e.unknownSize||e.nextOffset<=t}function L(e,t){for(let n of e)if(t.has(n))return!0;return!1}let R;async function z(e,t={}){let r=t.pollMs??150,i=t.attempts??12,a,o=0;for(let t=0;t<i;t+=1){let t=0;try{t=s.statSync(e).size}catch{t=0}if(t>0&&t===a){if(o+=1,o>=2)return}else o=0;a=t,await n(r)}}async function B(e){let n=G(e);if(!n)return!1;if(n===`webm`)return!0;try{let n=await t(await V(),[e],{allowFailure:!0,timeoutMs:1e4,env:l()});return n.exitCode===0?!0:W(n.stderr,n.stdout)}catch(e){if(H(e))return!0;throw e}}async function V(){R??=d({source:`import Foundation
|
|
2
2
|
import AVFoundation
|
|
3
3
|
|
|
4
4
|
let url = URL(fileURLWithPath: CommandLine.arguments[1])
|
package/dist/src/web.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{_ as e}from"./sdk-contracts.js";import{
|
|
1
|
+
import{_ as e}from"./sdk-contracts.js";import{F as t}from"./sdk-android-adb.js";import{n}from"./provider.js";import{t as r}from"./unsupported-interactor.js";function i(){let i=()=>n();return{...r(`web`),open:(e,t)=>i().open(t?.url??e,{url:t?.url}),openDevice:()=>i().open(`about:blank`),close:e=>i().close(e),tap:(e,t)=>i().click(e,t),focus:(e,t)=>i().click(e,t),type:(e,t)=>i().typeText(e,{delayMs:t}),fill:(e,t,n,r)=>i().fill(e,t,n,{delayMs:r}),scroll:(e,t)=>i().scroll(e,t),screenshot:(e,t)=>i().screenshot(e,t),setViewport:(e,t)=>i().setViewport(e,t),snapshot:async e=>{let n=await t(`snapshot_capture`,async()=>await i().snapshot(e),{backend:`web`});return{nodes:n.nodes,truncated:n.truncated??!1,backend:`web`}},setOrientation:async()=>{throw new e(`UNSUPPORTED_OPERATION`,`orientation is not supported on web`)}}}export{i as createWebInteractor};
|