agent-device 0.21.34 → 0.21.35
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.34.apk → agent-device-android-ime-helper-0.21.35.apk} +0 -0
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.35.apk.sha256 +1 -0
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.34.manifest.json → agent-device-android-ime-helper-0.21.35.manifest.json} +4 -4
- package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.34.apk → agent-device-android-snapshot-helper-0.21.35.apk} +0 -0
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.35.apk.sha256 +1 -0
- package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.34.manifest.json → agent-device-android-snapshot-helper-0.21.35.manifest.json} +7 -7
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Keyboard.swift +27 -18
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextInputProbe.swift +26 -7
- package/dist/src/agent-browser-provider.js +1 -1
- package/dist/src/agent-device-client.js +1 -1
- package/dist/src/ai-sdk.d.ts +1 -1
- package/dist/src/alert.js +1 -1
- package/dist/src/android-adb.d.ts +1 -1
- package/dist/src/app-backend.js +1 -1
- package/dist/src/app-launch.js +1 -1
- package/dist/src/app-lifecycle.js +1 -1
- package/dist/src/app-log-reconnect.js +1 -1
- package/dist/src/app-log-runtime2.js +2 -2
- package/dist/src/app-log-session-resource.js +1 -1
- package/dist/src/app-resolution.js +2 -2
- package/dist/src/app-state-runtime.d.ts +1 -1
- package/dist/src/apple-runner-platform.js +1 -1
- package/dist/src/application-lifecycle-interaction.js +1 -1
- package/dist/src/artifact-download.js +1 -1
- package/dist/src/back-mode.js +1 -1
- package/dist/src/cli-config.js +1 -1
- package/dist/src/cli-help.js +3 -2
- package/dist/src/cli.js +2 -2
- package/dist/src/client-types.d.ts +17 -4
- package/dist/src/cloud-artifacts.d.ts +2 -2
- package/dist/src/command-metadata.js +41 -41
- package/dist/src/command-schema.js +3 -1
- package/dist/src/command-tools.js +1 -1
- package/dist/src/composed-inventory-gateways.js +1 -1
- package/dist/src/composite-resource-admission.js +1 -1
- package/dist/src/connection-runtime.js +1 -1
- package/dist/src/connection.js +5 -5
- package/dist/src/contract.d.ts +2 -1
- package/dist/src/contracts.d.ts +1 -1
- package/dist/src/daemon-client-lease-beat.js +1 -1
- package/dist/src/daemon-client.js +2 -2
- package/dist/src/daemon-command-registry.js +1 -1
- package/dist/src/daemon-composition.js +1 -1
- package/dist/src/daemon-policy-file.js +1 -1
- package/dist/src/debug-symbols-facade.js +1 -1
- package/dist/src/destination-tunnel-dialer.js +27 -0
- package/dist/src/device-claim-recovery.js +1 -1
- package/dist/src/device-claims.js +1 -1
- package/dist/src/device-input-state.d.ts +1 -1
- package/dist/src/device-readiness-runtime.js +1 -1
- package/dist/src/device-selection-resolver.js +1 -1
- package/dist/src/device.js +1 -1
- package/dist/src/discovery.js +1 -1
- package/dist/src/doctor-facade.js +1 -1
- package/dist/src/durable-resource.js +1 -1
- package/dist/src/explicit-session-resolution.js +1 -1
- package/dist/src/find.js +1 -1
- package/dist/src/generic.js +1 -1
- package/dist/src/gesture-admission.js +1 -1
- package/dist/src/gesture-plan-types.d.ts +1 -1
- package/dist/src/gesture-runtime.js +1 -1
- package/dist/src/human-control.js +1 -1
- package/dist/src/index.d.ts +1 -1
- package/dist/src/instance-client.js +1 -1
- package/dist/src/interaction.js +1 -1
- package/dist/src/interaction2.js +1 -1
- package/dist/src/interactor.js +5 -5
- package/dist/src/interactor4.js +1 -1
- package/dist/src/interactors.js +1 -1
- package/dist/src/internal/bin.js +1 -1
- package/dist/src/inventory2.js +1 -1
- package/dist/src/ios-client.js +4 -4
- package/dist/src/launch-confirmation.js +1 -1
- package/dist/src/lease-context.js +1 -1
- package/dist/src/lease-registry-scope.js +1 -1
- package/dist/src/lease.js +1 -1
- package/dist/src/leased-recording-retention.js +1 -1
- package/dist/src/legacy.js +1 -1
- package/dist/src/limrun.d.ts +6 -1
- package/dist/src/local-interactor-operation-set.js +1 -1
- package/dist/src/log-stream.js +2 -28
- package/dist/src/mechanics.js +1 -1
- package/dist/src/metro.d.ts +1 -1
- package/dist/src/network-har.js +2 -0
- package/dist/src/open-target-resolution.js +1 -1
- package/dist/src/perf-facade.js +1 -1
- package/dist/src/perf-target.js +1 -1
- package/dist/src/platform-runtime-daemon-services.js +1 -1
- package/dist/src/platform-runtime-open-target.js +1 -1
- package/dist/src/platform-runtime-operation-host.js +3 -3
- package/dist/src/platform-runtime-runtime-hints.js +1 -1
- package/dist/src/platform-runtime-unavailable.js +1 -1
- package/dist/src/platform-runtime.js +1 -1
- package/dist/src/platform-runtime2.js +1 -1
- package/dist/src/plugin-inventory.js +1 -1
- package/dist/src/provider-device-runtime.d.ts +1 -1
- package/dist/src/provider-plugin.d.ts +1 -1
- package/dist/src/proxy.js +2 -2
- package/dist/src/react-native.js +1 -1
- package/dist/src/record-runtime-response.js +1 -1
- package/dist/src/record-runtime.js +1 -1
- package/dist/src/record-trace.js +1 -1
- package/dist/src/registry.js +1 -1
- package/dist/src/replay-maestro-backend.js +3 -3
- package/dist/src/replay-script-selection.js +1 -1
- package/dist/src/replay.d.ts +1 -1
- package/dist/src/request-runtime-binding.js +1 -1
- package/dist/src/result-serialization.js +2 -1
- package/dist/src/runner-client.js +1 -1
- package/dist/src/runner-dev-tools-security.js +1 -1
- package/dist/src/runner-device-readiness.js +1 -1
- package/dist/src/runner-retention.js +1 -1
- package/dist/src/runner-selector-query.js +1 -1
- package/dist/src/runner-startup-transport.js +1 -1
- package/dist/src/runner.js +1 -1
- package/dist/src/runtime-admission.js +1 -1
- package/dist/src/runtime-deployment.js +1 -1
- package/dist/src/runtime-session.js +1 -1
- package/dist/src/runtime.js +2 -2
- package/dist/src/runtime3.js +4 -4
- package/dist/src/runtime4.js +1 -1
- package/dist/src/runtime5.js +1 -1
- package/dist/src/runtime6.js +1 -1
- package/dist/src/runtime7.js +1 -1
- package/dist/src/runtime8.js +1 -1
- package/dist/src/runtime9.js +1 -1
- package/dist/src/screen-recording-resource-recovery.js +1 -1
- package/dist/src/screen-recording-session-resource.js +1 -1
- package/dist/src/screen-recording-transport.js +1 -1
- package/dist/src/screenshot-density.js +1 -1
- package/dist/src/screenshot-runtime.js +1 -1
- package/dist/src/sdk-batch-runner.js +2 -2
- package/dist/src/sdk-batch.js +2 -2
- package/dist/src/sdk-contracts.d.ts +4 -1
- package/dist/src/sdk-device.js +1 -1
- package/dist/src/sdk-finders.d.ts +1 -1
- package/dist/src/sdk-remote-config.d.ts +8 -1
- package/dist/src/sdk-remote-config.js +1 -1
- package/dist/src/sdk-selectors.d.ts +1 -1
- package/dist/src/selector-runtime.js +1 -1
- package/dist/src/server-startup.js +1 -1
- package/dist/src/server.js +1 -1
- package/dist/src/session-artifact-paths.js +1 -1
- package/dist/src/session-device-resolution.js +1 -1
- package/dist/src/session-open.js +1 -1
- package/dist/src/session-runtime.js +1 -1
- package/dist/src/session-selector.js +1 -1
- package/dist/src/session-store.js +1 -1
- package/dist/src/session2.js +4 -4
- package/dist/src/settle-observation-capture.js +1 -1
- package/dist/src/simctl.js +1 -1
- package/dist/src/simulator-boot.js +1 -1
- package/dist/src/snapshot-diagnostics.js +1 -1
- package/dist/src/snapshot-runtime-binding.js +1 -1
- package/dist/src/snapshot-runtime-capture-input.js +1 -1
- package/dist/src/snapshot-runtime.js +1 -1
- package/dist/src/snapshot.js +1 -1
- package/dist/src/src.js +1 -1
- package/dist/src/src3.js +4 -4
- package/dist/src/src4.js +1 -1
- package/dist/src/src9.js +1 -1
- package/dist/src/store.js +1 -1
- package/dist/src/telephony-runtime.js +1 -1
- package/dist/src/touch-runtime2.js +1 -1
- package/dist/src/transport.js +2 -2
- package/dist/src/tv-remote-runtime.js +1 -1
- package/dist/src/tv-remote.js +1 -1
- package/dist/src/type-text-runtime.js +1 -1
- package/package.json +1 -1
- package/server.json +2 -2
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.34.apk.sha256 +0 -1
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.34.apk.sha256 +0 -1
- package/dist/src/session-capture-binding.js +0 -1
- package/dist/src/session-teardown.js +0 -1
package/dist/src/runtime9.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{r as e}from"./rolldown-runtime.js";import{J as t,R as n}from"./sdk-contracts.js";import{A as r,dt as i,j as a}from"./tv-remote.js";import{l as o}from"./sdk-device.js";import{Si as s,vn as c}from"./sdk-batch.js";import{a as l}from"./sdk-remote-config.js";import{a as u,i as ee,o as d,r as te,s as ne,t as re}from"./runtime-deployment.js";import f from"node:fs";import p from"node:path";import ie,{readFile as m,stat as h}from"node:fs/promises";import{setTimeout as g}from"node:timers/promises";function _(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 v(e){return{provider:e.provider,providerSessionId:e.providerSessionId,status:`unavailable`,cloudArtifacts:[],message:e.error instanceof Error?e.error.message:String(e.error)}}function ae(e,t,n,r,i,a){let o=n[r],s=typeof o==`string`?o.trim():``;if(s.length!==0)return{provider:e,providerSessionId:t,kind:i,name:a,url:s,availability:`ready`}}function y(e){return{"x-agent-device-client":`agent-device-cli`,"x-agent-device-version":e}}async function b(e,r){try{await r()}catch(r){e instanceof n&&(e.details={...e.details,cleanupError:t(r)})}}function x(e){return`Basic ${Buffer.from(`${e.username}:${e.accessKey}`).toString(`base64`)}`}function oe(e){let t=0;for(;t<e.length&&e.charCodeAt(t)===47;)t+=1;return t===0?e:e.slice(t)}function se(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 ce(e,t){let n=new URL(e);return n.pathname=`${se(n.pathname)}/${t}`,n}function le(e){if(e.pathname.endsWith(`/`))return e;let t=new URL(e);return t.pathname=`${t.pathname}/`,t}async function ue(e,t,r){if(!(await h(e).catch(()=>void 0))?.isFile())throw new n(`INVALID_ARGS`,`${r.service} can only upload a regular app file: ${e}`,{provider:r.provider,appPath:e,hint:`Use an existing .ipa, .apk, or .aab file, or a .zip of the iOS simulator .app bundle.`});let i=new FormData;return i.set(t,new Blob([await m(e)]),p.basename(e)),i}async function de(e,t,r){let i=await fetch(t.endpoint,{method:`POST`,headers:{...y(t.clientVersion),Authorization:x(t.auth)},body:e,signal:r}),a=await C(i),o=t.readAppReference(a)?.trim();if(!i.ok||!o)throw new n(`COMMAND_FAILED`,`${t.service} app upload failed.`,{status:i.status,response:a});return o}function fe(e){return async({appPath:t,options:n,signal:r})=>({appReference:await e(t,r),bundleId:n?.appIdentifierHint,packageName:n?.packageNameHint,launchTarget:n?.appIdentifierHint??n?.packageNameHint})}async function pe(e){let{app:t}=e,r=e.parseReference(t);if(r!==void 0)return r;if(/^https?:\/\//i.test(t))return t;let i=p.isAbsolute(t)?t:p.resolve(me(e),t);if(!f.existsSync(i))throw new n(`INVALID_ARGS`,`${e.service} --provider-app must be ${e.referenceLabel}, URL, or existing local app path.`,{providerApp:t});return await e.uploadFile(i,e.signal)}function me(e){if(e.cwd!==void 0)return e.cwd;throw new n(`INVALID_ARGS`,`${e.service} --provider-app ${e.app} is a relative path and the request names no working directory; pass an absolute path.`,{providerApp:e.app,reason:`provider_app_cwd_missing`})}const S=15e3;async function he(e,t){let{service:r,unauthorizedHint:i,networkHint:a}=t.hints,o=`Retry connect or check the ${r} service status.`;try{let a=await fetch(e,{headers:{...y(t.clientVersion),...t.auth?{Authorization:x(t.auth)}:{}},signal:AbortSignal.timeout(S)});if(!a.ok){let e=a.status===401||a.status===403;throw new n(e?`UNAUTHORIZED`:`COMMAND_FAILED`,`${r} rejected connection verification.`,{status:a.status,hint:e?i:o})}let s=await C(a);if(s===void 0)throw new n(`COMMAND_FAILED`,`${r} connection verification answer was not JSON.`,{status:a.status,hint:o});return s}catch(e){throw e instanceof n?e:new n(`COMMAND_FAILED`,`${r} connection verification failed.`,{hint:a},e)}}async function ge(e,t){let r,i;try{r=await fetch(e,{headers:{...y(t.clientVersion),Authorization:x(t.auth)},signal:AbortSignal.timeout(S)}),i=await C(r)}catch(e){throw new n(`COMMAND_FAILED`,`${t.service} session details lookup failed.`,{hint:`Check network access to the ${t.service} API, then retry.`},e)}let a=i&&typeof i==`object`&&!Array.isArray(i)?i:void 0;if(!r.ok||!a)throw new n(`COMMAND_FAILED`,`${t.service} session details lookup failed.`,{status:r.status,response:i});return a}async function C(e){let t=await e.text();if(t.length!==0)try{return JSON.parse(t)}catch{return}}function _e(e,t){let n=e=>e.replace(/(?:\.0)+$/,``);return n(e)===n(t)}function ve(e,t){let r=l.find(e=>e===t);if(r)return r;throw new n(`INVALID_ARGS`,`Invalid ${e.flag} value: ${t}.`,{hint:`Use ${l.join(`|`)}.`,flag:e.flag,capability:e.capability})}function w(e,t){if(e)return e;throw new n(`INVALID_ARGS`,`${t} lease allocation requires provider profile flags on the request.`)}function T(e,t){let r=e.flags?.platform;if(r===`android`||r===`ios`)return r;throw new n(`INVALID_ARGS`,`${t} requires --platform ios|android.`)}function E(e,t,r){let i=D(e,t);if(i)return i;throw new n(`INVALID_ARGS`,r)}function D(e,t){let n=e.flags?.[t];return typeof n==`string`&&n.length>0?n:void 0}function O(e,t,r){let i=e[t];if(i?.trim())return i;throw new n(`INVALID_ARGS`,`${r} requires ${t} in the environment.`)}function k(e,t){if(e.platform===`android`||e.platform===`ios`)return e.platform;throw new n(`INVALID_ARGS`,`connect ${t} requires --platform ios|android.`)}function A(e,t,r){if(e?.trim())return e;throw new n(`INVALID_ARGS`,`connect ${t} requires ${r}.`)}function j(e,t,r){let i=p.resolve(t,e);if(f.statSync(i,{throwIfNoEntry:!1})?.isFile())return i;throw new n(`INVALID_ARGS`,`${r} app file not found: ${i}`)}const M=`webdriver_request_timeout`;function N(e){return e instanceof n&&e.details?.reason===M}function P(e){return{dispatched:e}}const F=`webdriver_connect_refused`,I=`webdriver_request_interrupted`,ye=new Set([`ECONNREFUSED`,`ENOTFOUND`,`EAI_AGAIN`,`EHOSTUNREACH`,`ENETUNREACH`,`UND_ERR_CONNECT_TIMEOUT`]);function be(e){return e instanceof n&&e.details?.reason===F}const xe=new Set([`GET`,`HEAD`]),Se=Object.freeze({});var Ce=class{endpoint;headers;requestPolicy;constructor(e){this.endpoint=le(new URL(e.endpoint)),this.headers={...y(e.clientVersion),...e.auth?{Authorization:x(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.request(e,t,n,r)).value}async request(e,t,n,r){let i=r?.idempotent??xe.has(e);return await this.requestWithRetries(e,t,n,{retryAttempts:r?.retryAttempts??(i?this.requestPolicy.retryAttempts:0),timeoutMs:r?.timeoutMs??this.requestPolicy.timeoutMs,signal:r?.signal})}async requestWithRetries(e,t,n,r){let i;for(let a=0;a<=r.retryAttempts;a+=1)try{return await this.requestOnce(e,t,n,r.timeoutMs,r.signal)}catch(e){if(i=e,!Te(e,a,r.retryAttempts,r.signal))throw e;await g(this.requestPolicy.retryDelayMs,void 0,{signal:r.signal})}throw i}async requestOnce(e,t,n,r,i){let{ok:a,status:o,text:s}=await this.fetchWebDriver(e,t,n,r,i),c=s?De(s):{};if(a)return{status:o,value:Ee(c)};let l=Oe(o,c);throw U(l)&&H(z,{method:e,path:t,status:o,code:V(c)??null}),l}async fetchWebDriver(e,t,n,r,i){let a=new URL(oe(t),this.endpoint),o=n===void 0&&e===`POST`?Se:n,s=AbortSignal.timeout(r),c=i?AbortSignal.any([i,s]):s,l={method:e,path:t,timeoutMs:r,timeoutSignal:s,requestSignal:i},u;try{u=await fetch(a,{method:e,headers:{Accept:`application/json`,...o===void 0?{}:{"Content-Type":`application/json`},...this.headers},body:o===void 0?void 0:JSON.stringify(o),signal:c})}catch(e){throw L(e,l,`request`)}try{return{ok:u.ok,status:u.status,text:await u.text()}}catch(e){throw L(e,l,`response`)}}};function L(e,t,n){let{method:r,path:i,timeoutMs:a,timeoutSignal:o,requestSignal:s}=t;return s?.aborted?e:o.aborted?Me(r,i,a,e):n===`request`&&we(e)?Ne(r,i,e):n===`response`||e instanceof TypeError?Pe(r,i,e):e}function we(e){let t=R(e,0);return t.length>0&&t.every(e=>ye.has(e))}function R(e,t){if(t>4||!e||typeof e!=`object`)return[];let{code:n,cause:r}=e,i=e instanceof AggregateError?e.errors:[];return[...typeof n==`string`?[n]:[],...R(r,t+1),...i.flatMap(e=>R(e,t+1))]}function Te(e,t,n,r){return!r?.aborted&&Fe(e)&&t<n}function Ee(e){if(!e||typeof e!=`object`)return e;let t=e;return`value`in t?t.value:e}function De(e){try{return JSON.parse(e)}catch(t){throw new n(`COMMAND_FAILED`,`WebDriver response was not valid JSON.`,{text:e},t)}}function Oe(e,t){let r=t&&typeof t==`object`&&`value`in t?t.value:t,i=r&&typeof r==`object`&&typeof r.message==`string`?r.message:`WebDriver request failed with HTTP ${e}.`;return je(e,t)?new n(`COMMAND_FAILED`,i,{...B(),status:e,response:t}):new n(`COMMAND_FAILED`,i,{status:e,response:t,...e>=500?P(`unknown`):{}})}const z=`webdriver_route_unsupported`;function B(){return{reason:z,...P(`no`)}}const ke=new Set([`unknown command`,`unknown method`]),Ae=new Set([404,405,501]);function je(e,t){let n=V(t);return n===void 0?Ae.has(e):ke.has(n.toLowerCase())}function V(e){let t=e&&typeof e==`object`&&`value`in e?e.value:void 0,n=t&&typeof t==`object`?t.error:void 0;return typeof n==`string`?n:void 0}function H(e,t){import(`./diagnostics.js`).then(e=>e.t).then(({emitDiagnostic:n})=>n({level:`debug`,phase:e,data:t})).catch(()=>void 0)}function U(e){return e instanceof n&&e.details?.reason===z}function Me(e,t,r,i){return new n(`COMMAND_FAILED`,`WebDriver ${e} ${t} timed out after ${r}ms.`,{reason:M,method:e,path:t,timeoutMs:r,...P(`unknown`)},i instanceof Error?i:void 0)}function Ne(e,t,r){return new n(`COMMAND_FAILED`,`WebDriver ${e} ${t} could not reach the driver.`,{reason:F,method:e,path:t,...P(`no`)},r instanceof Error?r:void 0)}function Pe(e,t,r){return new n(`COMMAND_FAILED`,`WebDriver ${e} ${t} lost its connection to the driver.`,{reason:I,method:e,path:t,...P(`unknown`)},r instanceof Error?r:void 0)}function Fe(e){if(N(e)||be(e)||e instanceof n&&e.details?.reason===I)return!0;if(e instanceof n){let t=e.details?.status;return typeof t==`number`&&t>=500}return!1}var Ie=class{transport;sessionCreateTimeoutMs;sessionId;constructor(e){this.transport=new Ce(e),this.sessionCreateTimeoutMs=e.requestPolicy?.sessionCreateTimeoutMs??18e4}async createSession(e,t){let n=Re(await this.requestValue(`POST`,`/session`,{capabilities:Le(e)},{timeoutMs:Be(this.sessionCreateTimeoutMs,t?.deadline)}));return this.sessionId=n.sessionId,n}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){await this.appRouteWithSibling(`/appium/device/activate_app`,`mobile: activateApp`,e)}async terminateApp(e){await this.appRouteWithSibling(`/appium/device/terminate_app`,`mobile: terminateApp`,e)}async appRouteWithSibling(e,t,n){try{await this.sessionRequest(`POST`,e,{appId:n})}catch(r){if(!U(r))throw r;let{status:i}=await this.transport.request(`POST`,`/session/${this.requireSessionId()}/execute/sync`,{script:t,args:[{appId:n,bundleId:n}]});H(`webdriver_route_fallback`,{from:e,to:t,status:i})}}async performActions(e){await this.sessionRequest(`POST`,`/actions`,{actions:e})}async releaseActions(){await this.sessionRequest(`DELETE`,`/actions`)}async sendKeys(e){await this.sessionRequest(`POST`,`/keys`,{value:Array.from(e)})}async clearElement(e){await this.sessionRequest(`POST`,`/element/${encodeURIComponent(e)}/clear`)}async sendElementKeys(e,t){await this.sessionRequest(`POST`,`/element/${encodeURIComponent(e)}/value`,{text:t,value:Array.from(t)})}async hideKeyboard(){await this.sessionRequest(`POST`,`/appium/device/hide_keyboard`)}async isKeyboardShown(e,t){let n;try{n=await this.sessionRequest(`GET`,`/appium/device/is_keyboard_shown`,void 0,{retryAttempts:0,...e===void 0?{}:{timeoutMs:e},...t===void 0?{}:{signal:t}})}catch(e){if(U(e))return`unsupported`;throw e}return typeof n==`boolean`?n:`unsupported`}async activeElementReference(e){let t=e===void 0?void 0:Date.now()+e;try{let e=ze(await this.sessionRequest(`GET`,`/element/active`,void 0,K(t)));return e===void 0?`unsupported`:{id:e}}catch(e){if(U(e))return`unsupported`;if(J(e))return`none`;throw e}}async activeElement(e){let t=e===void 0?void 0:Date.now()+e,n=await this.activeElementReference(K(t).timeoutMs);if(typeof n==`string`)return n;let r=n.id;try{return{id:r,rect:W(await this.sessionRequest(`GET`,`/element/${encodeURIComponent(r)}/rect`,void 0,K(t)))}}catch(e){if(U(e))return`unsupported`;if(J(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(e){let t=await this.sessionRequest(`GET`,`/source`,void 0,e);if(typeof t!=`string`)throw new n(`COMMAND_FAILED`,`WebDriver source response was not a string`,{valueType:typeof t});return t}async screenshot(e){let t=await this.sessionRequest(`GET`,`/screenshot`);if(typeof t!=`string`)throw new n(`COMMAND_FAILED`,`WebDriver screenshot response was not base64 text`,{valueType:typeof t});await ie.writeFile(e,Buffer.from(t,`base64`))}async windowRect(e){return W(await this.sessionRequest(`GET`,`/window/rect`,void 0,e))}async executeScript(e,t=[]){return await this.sessionRequest(`POST`,`/execute/sync`,{script:e,args:t})}async executeReadScript(e,t=[]){return await this.sessionRequest(`POST`,`/execute/sync`,{script:e,args:t},{idempotent:!0})}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 n(`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 W(e){if(!e||typeof e!=`object`)throw new n(`COMMAND_FAILED`,`WebDriver window rect response was empty.`);let t=e,r={x:G(t,`x`),y:G(t,`y`),width:G(t,`width`),height:G(t,`height`)};if(r.x===void 0||r.y===void 0||r.width===void 0||r.height===void 0)throw new n(`COMMAND_FAILED`,`WebDriver window rect response was invalid.`,{response:t});return r}function G(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Le(e){return`alwaysMatch`in e||`firstMatch`in e?e:{alwaysMatch:e}}function Re(e){if(!e||typeof e!=`object`)throw new n(`COMMAND_FAILED`,`WebDriver create-session response was empty.`);let t=e,r=typeof t.sessionId==`string`?t.sessionId:typeof t.session_id==`string`?t.session_id:void 0;if(!r)throw new n(`COMMAND_FAILED`,`WebDriver create-session response missed sessionId.`,{response:t});return{sessionId:r,capabilities:t.capabilities&&typeof t.capabilities==`object`?t.capabilities:{}}}function ze(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 K(e){return e===void 0?{retryAttempts:0}:{retryAttempts:0,timeoutMs:q(e)}}function Be(e,t){return t===void 0?e:Math.min(e,q(t))}function q(e){return Math.max(0,e-Date.now())}function J(e){return e instanceof n&&Ve(e).toLowerCase()===`no such element`}function Ve(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 Y(e,t){return{type:`pointer`,id:e,parameters:{pointerType:`touch`},actions:t}}async function He(e){let{parseWebDriverSourceFacts:t}=await import(`./webdriver-source.js`);return X(t(e,`android`).nodes)}async function Ue(e){let{parseWebDriverSourceFacts:t}=await import(`./webdriver-source.js`);return X(t(e).nodes)}function X(e){let t=e.flatMap(e=>We(e)&&Ge(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 We(e){let t=e.type?.toLowerCase()??``;return e.visibleToUser!==!1&&(t.includes(`scrollview`)||t.includes(`listview`)||t.includes(`recyclerview`))}function Ge(e){return!!e&&e.width>=50&&e.height>=50}async function Ke(e,t,r){let i=[];for(let n of t===`android`?[`rotation`,`orientation`]:[`orientation`,`rotation`])try{await qe(e,n,r);return}catch(e){if(!U(e))throw e;i.push({transport:n,error:e instanceof Error?e.message:String(e)})}throw new n(`COMMAND_FAILED`,`Could not set device orientation to ${r} on the hosted WebDriver session.`,{...B(),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})}async function qe(e,t,n){if(t===`rotation`){await e.setRotation(a(n));return}await e.setOrientation(r(n))}const Z=1500;function Je(e){return new Promise(t=>setTimeout(t,e))}function Ye(e,t,r){return new n(`COMMAND_FAILED`,`fill tapped (${e}, ${t}) but ${r}`,{reason:`text_entry_focus_not_observed`,x:e,y:t,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 Q(){return new n(`UNSUPPORTED_OPERATION`,`fill requires a focused element reference to clear and replace the field`,{reason:`text_entry_clear_target_unavailable`})}function Xe(e,t,n){return t>=e.x&&t<=e.x+e.width&&n>=e.y&&n<=e.y+e.height}function Ze(e){return new $(e.client,e.backend,e.capabilities,e.targetId)}var $=class{client;backend;capabilities;targetId;constructor(e,t,n,r){this.client=e,this.backend=t,this.capabilities=n,this.targetId=r}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.client.activeElementReference(Z);if(i===`unsupported`)throw Q();let a=i===`none`?void 0:i.id;await this.tap(e,t);let o=await this.awaitTextEntryReadiness(a,e,t);return await this.client.clearElement(o),n.length>0&&await this.client.sendElementKeys(o,n),{backend:`webdriver`,x:e,y:t,text:n,textEntryReadiness:`focused-element`}}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($e(e)),await this.client.performActions(e.pointers.map(e=>Y(`gesture-pointer-${e.pointerId}`,Qe(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`),await this.captureSource(e?.signal)}async captureSource(e){let t=this.backend===`android`?await this.readAndroidSnapshotViewport(e):void 0,n=await this.readSource(e);e?.throwIfAborted();let r=await this.readSnapshotKeyboardVisibility(e);if(this.backend===`xctest`){let{acquireWebDriverIosSnapshot:e}=await import(`./webdriver-ios-snapshot.js`);return e(n,this.targetId,r)}let{parseWebDriverAndroidSnapshotNodes:i}=await import(`./webdriver-android-source.js`),{acquireProviderKeyboard:a}=await import(`./tap-keyboard-occlusion.js`).then(e=>e.i),o=i(n),s=t===void 0?void 0:await this.readAndroidSnapshotViewport(e),c=t!==void 0&&s!==void 0&&t.width===s.width&&t.height===s.height?t:void 0;return{backend:`android`,producer:`appium-source`,...a({nodes:o,viewport:null,visibility:r}),...c===void 0?{}:{viewport:c}}}async readAndroidSnapshotViewport(e){try{let t=await this.client.windowRect({timeoutMs:500,retryAttempts:0,...e===void 0?{}:{signal:e}});return s(t)}catch{e?.throwIfAborted();return}}async readSnapshotKeyboardVisibility(e){try{let t=await this.client.isKeyboardShown(500,e);return e?.throwIfAborted(),t}catch{return e?.throwIfAborted(),`failed`}}async readSource(e){try{return await this.client.source(e===void 0?{}:{signal:e})}catch(e){throw N(e)?et(e):e}}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 volumeUp(){await this.pressVolumeKey(`volumeUp`,`volumeup`)}async volumeDown(){await this.pressVolumeKey(`volumeDown`,`volumedown`)}async pressVolumeKey(e,t){if(this.backend===`android`){await this.pressAndroidHardwareKey(e);return}this.requireSupport(e),await this.client.executeScript(`mobile: pressButton`,[{name:t}])}async power(){await this.pressAndroidHardwareKey(`power`)}async pressAndroidHardwareKey(e){this.requireSupport(e);let{HARDWARE_BUTTON_NAME_LABELS:t}=await import(`./tv-remote.js`).then(e=>e.f),{toAndroidTvRemoteKeyevent:n}=await import(`./tv-remote.js`).then(e=>e.d),r=Number(n(t[e]));await this.client.executeScript(`mobile: pressKey`,[{keycode:r}])}async mute(){await this.pressAndroidHardwareKey(`mute`)}async sleep(){await this.pressAndroidHardwareKey(`sleep`)}async wake(){await this.pressAndroidHardwareKey(`wake`)}async mediaPlayPause(){await this.pressAndroidHardwareKey(`mediaPlayPause`)}async mediaNext(){await this.pressAndroidHardwareKey(`mediaNext`)}async mediaPrevious(){await this.pressAndroidHardwareKey(`mediaPrevious`)}async mediaRewind(){await this.pressAndroidHardwareKey(`mediaRewind`)}async mediaFastForward(){await this.pressAndroidHardwareKey(`mediaFastForward`)}async tvRemote(e,t){this.unsupported(`tvRemote`)}async keyboardStatus(){return this.requireSupport(`keyboard`),{kind:`ime-probe`,visible:await this.keyboardVisible()}}async keyboardDismiss(){this.requireSupport(`keyboard`);let e=await this.keyboardVisibility();if(e===!1)return this.dismissResult({wasVisible:e,visible:!1,dismissed:!1});await this.client.hideKeyboard();let t=await this.keyboardVisibilityAfterMutation();return this.dismissResult({...e===void 0?{}:{wasVisible:e},...t===void 0?{}:{visible:t,dismissed:e===!0&&!t}})}dismissResult(e){return this.backend===`android`?{kind:`ime-probe`,...e}:{kind:`mechanism`,mechanism:`appium-hide-keyboard`,...e}}async keyboardEnter(){if(this.requireSupport(`keyboard`),this.backend===`android`)return await this.client.executeScript(`mobile: pressKey`,[{keycode:66}]),{kind:`android-acknowledged`};let e=await this.keyboardVisibility();await this.client.sendKeys(`
|
|
1
|
+
import{r as e}from"./rolldown-runtime.js";import{J as t,R as n}from"./sdk-contracts.js";import{A as r,dt as i,j as a}from"./tv-remote.js";import{u as o}from"./sdk-device.js";import{Si as s,bn as c}from"./sdk-batch.js";import{a as l}from"./sdk-remote-config.js";import{a as u,i as ee,o as d,r as te,s as ne,t as re}from"./runtime-deployment.js";import f from"node:fs";import p from"node:path";import ie,{readFile as m,stat as h}from"node:fs/promises";import{setTimeout as g}from"node:timers/promises";function _(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 v(e){return{provider:e.provider,providerSessionId:e.providerSessionId,status:`unavailable`,cloudArtifacts:[],message:e.error instanceof Error?e.error.message:String(e.error)}}function ae(e,t,n,r,i,a){let o=n[r],s=typeof o==`string`?o.trim():``;if(s.length!==0)return{provider:e,providerSessionId:t,kind:i,name:a,url:s,availability:`ready`}}function y(e){return{"x-agent-device-client":`agent-device-cli`,"x-agent-device-version":e}}async function b(e,r){try{await r()}catch(r){e instanceof n&&(e.details={...e.details,cleanupError:t(r)})}}function x(e){return`Basic ${Buffer.from(`${e.username}:${e.accessKey}`).toString(`base64`)}`}function oe(e){let t=0;for(;t<e.length&&e.charCodeAt(t)===47;)t+=1;return t===0?e:e.slice(t)}function se(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 ce(e,t){let n=new URL(e);return n.pathname=`${se(n.pathname)}/${t}`,n}function le(e){if(e.pathname.endsWith(`/`))return e;let t=new URL(e);return t.pathname=`${t.pathname}/`,t}async function ue(e,t,r){if(!(await h(e).catch(()=>void 0))?.isFile())throw new n(`INVALID_ARGS`,`${r.service} can only upload a regular app file: ${e}`,{provider:r.provider,appPath:e,hint:`Use an existing .ipa, .apk, or .aab file, or a .zip of the iOS simulator .app bundle.`});let i=new FormData;return i.set(t,new Blob([await m(e)]),p.basename(e)),i}async function de(e,t,r){let i=await fetch(t.endpoint,{method:`POST`,headers:{...y(t.clientVersion),Authorization:x(t.auth)},body:e,signal:r}),a=await C(i),o=t.readAppReference(a)?.trim();if(!i.ok||!o)throw new n(`COMMAND_FAILED`,`${t.service} app upload failed.`,{status:i.status,response:a});return o}function fe(e){return async({appPath:t,options:n,signal:r})=>({appReference:await e(t,r),bundleId:n?.appIdentifierHint,packageName:n?.packageNameHint,launchTarget:n?.appIdentifierHint??n?.packageNameHint})}async function pe(e){let{app:t}=e,r=e.parseReference(t);if(r!==void 0)return r;if(/^https?:\/\//i.test(t))return t;let i=p.isAbsolute(t)?t:p.resolve(me(e),t);if(!f.existsSync(i))throw new n(`INVALID_ARGS`,`${e.service} --provider-app must be ${e.referenceLabel}, URL, or existing local app path.`,{providerApp:t});return await e.uploadFile(i,e.signal)}function me(e){if(e.cwd!==void 0)return e.cwd;throw new n(`INVALID_ARGS`,`${e.service} --provider-app ${e.app} is a relative path and the request names no working directory; pass an absolute path.`,{providerApp:e.app,reason:`provider_app_cwd_missing`})}const S=15e3;async function he(e,t){let{service:r,unauthorizedHint:i,networkHint:a}=t.hints,o=`Retry connect or check the ${r} service status.`;try{let a=await fetch(e,{headers:{...y(t.clientVersion),...t.auth?{Authorization:x(t.auth)}:{}},signal:AbortSignal.timeout(S)});if(!a.ok){let e=a.status===401||a.status===403;throw new n(e?`UNAUTHORIZED`:`COMMAND_FAILED`,`${r} rejected connection verification.`,{status:a.status,hint:e?i:o})}let s=await C(a);if(s===void 0)throw new n(`COMMAND_FAILED`,`${r} connection verification answer was not JSON.`,{status:a.status,hint:o});return s}catch(e){throw e instanceof n?e:new n(`COMMAND_FAILED`,`${r} connection verification failed.`,{hint:a},e)}}async function ge(e,t){let r,i;try{r=await fetch(e,{headers:{...y(t.clientVersion),Authorization:x(t.auth)},signal:AbortSignal.timeout(S)}),i=await C(r)}catch(e){throw new n(`COMMAND_FAILED`,`${t.service} session details lookup failed.`,{hint:`Check network access to the ${t.service} API, then retry.`},e)}let a=i&&typeof i==`object`&&!Array.isArray(i)?i:void 0;if(!r.ok||!a)throw new n(`COMMAND_FAILED`,`${t.service} session details lookup failed.`,{status:r.status,response:i});return a}async function C(e){let t=await e.text();if(t.length!==0)try{return JSON.parse(t)}catch{return}}function _e(e,t){let n=e=>e.replace(/(?:\.0)+$/,``);return n(e)===n(t)}function ve(e,t){let r=l.find(e=>e===t);if(r)return r;throw new n(`INVALID_ARGS`,`Invalid ${e.flag} value: ${t}.`,{hint:`Use ${l.join(`|`)}.`,flag:e.flag,capability:e.capability})}function w(e,t){if(e)return e;throw new n(`INVALID_ARGS`,`${t} lease allocation requires provider profile flags on the request.`)}function T(e,t){let r=e.flags?.platform;if(r===`android`||r===`ios`)return r;throw new n(`INVALID_ARGS`,`${t} requires --platform ios|android.`)}function E(e,t,r){let i=D(e,t);if(i)return i;throw new n(`INVALID_ARGS`,r)}function D(e,t){let n=e.flags?.[t];return typeof n==`string`&&n.length>0?n:void 0}function O(e,t,r){let i=e[t];if(i?.trim())return i;throw new n(`INVALID_ARGS`,`${r} requires ${t} in the environment.`)}function k(e,t){if(e.platform===`android`||e.platform===`ios`)return e.platform;throw new n(`INVALID_ARGS`,`connect ${t} requires --platform ios|android.`)}function A(e,t,r){if(e?.trim())return e;throw new n(`INVALID_ARGS`,`connect ${t} requires ${r}.`)}function j(e,t,r){let i=p.resolve(t,e);if(f.statSync(i,{throwIfNoEntry:!1})?.isFile())return i;throw new n(`INVALID_ARGS`,`${r} app file not found: ${i}`)}const M=`webdriver_request_timeout`;function N(e){return e instanceof n&&e.details?.reason===M}function P(e){return{dispatched:e}}const F=`webdriver_connect_refused`,I=`webdriver_request_interrupted`,ye=new Set([`ECONNREFUSED`,`ENOTFOUND`,`EAI_AGAIN`,`EHOSTUNREACH`,`ENETUNREACH`,`UND_ERR_CONNECT_TIMEOUT`]);function be(e){return e instanceof n&&e.details?.reason===F}const xe=new Set([`GET`,`HEAD`]),Se=Object.freeze({});var Ce=class{endpoint;headers;requestPolicy;constructor(e){this.endpoint=le(new URL(e.endpoint)),this.headers={...y(e.clientVersion),...e.auth?{Authorization:x(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.request(e,t,n,r)).value}async request(e,t,n,r){let i=r?.idempotent??xe.has(e);return await this.requestWithRetries(e,t,n,{retryAttempts:r?.retryAttempts??(i?this.requestPolicy.retryAttempts:0),timeoutMs:r?.timeoutMs??this.requestPolicy.timeoutMs,signal:r?.signal})}async requestWithRetries(e,t,n,r){let i;for(let a=0;a<=r.retryAttempts;a+=1)try{return await this.requestOnce(e,t,n,r.timeoutMs,r.signal)}catch(e){if(i=e,!Te(e,a,r.retryAttempts,r.signal))throw e;await g(this.requestPolicy.retryDelayMs,void 0,{signal:r.signal})}throw i}async requestOnce(e,t,n,r,i){let{ok:a,status:o,text:s}=await this.fetchWebDriver(e,t,n,r,i),c=s?De(s):{};if(a)return{status:o,value:Ee(c)};let l=Oe(o,c);throw U(l)&&H(z,{method:e,path:t,status:o,code:V(c)??null}),l}async fetchWebDriver(e,t,n,r,i){let a=new URL(oe(t),this.endpoint),o=n===void 0&&e===`POST`?Se:n,s=AbortSignal.timeout(r),c=i?AbortSignal.any([i,s]):s,l={method:e,path:t,timeoutMs:r,timeoutSignal:s,requestSignal:i},u;try{u=await fetch(a,{method:e,headers:{Accept:`application/json`,...o===void 0?{}:{"Content-Type":`application/json`},...this.headers},body:o===void 0?void 0:JSON.stringify(o),signal:c})}catch(e){throw L(e,l,`request`)}try{return{ok:u.ok,status:u.status,text:await u.text()}}catch(e){throw L(e,l,`response`)}}};function L(e,t,n){let{method:r,path:i,timeoutMs:a,timeoutSignal:o,requestSignal:s}=t;return s?.aborted?e:o.aborted?Me(r,i,a,e):n===`request`&&we(e)?Ne(r,i,e):n===`response`||e instanceof TypeError?Pe(r,i,e):e}function we(e){let t=R(e,0);return t.length>0&&t.every(e=>ye.has(e))}function R(e,t){if(t>4||!e||typeof e!=`object`)return[];let{code:n,cause:r}=e,i=e instanceof AggregateError?e.errors:[];return[...typeof n==`string`?[n]:[],...R(r,t+1),...i.flatMap(e=>R(e,t+1))]}function Te(e,t,n,r){return!r?.aborted&&Fe(e)&&t<n}function Ee(e){if(!e||typeof e!=`object`)return e;let t=e;return`value`in t?t.value:e}function De(e){try{return JSON.parse(e)}catch(t){throw new n(`COMMAND_FAILED`,`WebDriver response was not valid JSON.`,{text:e},t)}}function Oe(e,t){let r=t&&typeof t==`object`&&`value`in t?t.value:t,i=r&&typeof r==`object`&&typeof r.message==`string`?r.message:`WebDriver request failed with HTTP ${e}.`;return je(e,t)?new n(`COMMAND_FAILED`,i,{...B(),status:e,response:t}):new n(`COMMAND_FAILED`,i,{status:e,response:t,...e>=500?P(`unknown`):{}})}const z=`webdriver_route_unsupported`;function B(){return{reason:z,...P(`no`)}}const ke=new Set([`unknown command`,`unknown method`]),Ae=new Set([404,405,501]);function je(e,t){let n=V(t);return n===void 0?Ae.has(e):ke.has(n.toLowerCase())}function V(e){let t=e&&typeof e==`object`&&`value`in e?e.value:void 0,n=t&&typeof t==`object`?t.error:void 0;return typeof n==`string`?n:void 0}function H(e,t){import(`./diagnostics.js`).then(e=>e.t).then(({emitDiagnostic:n})=>n({level:`debug`,phase:e,data:t})).catch(()=>void 0)}function U(e){return e instanceof n&&e.details?.reason===z}function Me(e,t,r,i){return new n(`COMMAND_FAILED`,`WebDriver ${e} ${t} timed out after ${r}ms.`,{reason:M,method:e,path:t,timeoutMs:r,...P(`unknown`)},i instanceof Error?i:void 0)}function Ne(e,t,r){return new n(`COMMAND_FAILED`,`WebDriver ${e} ${t} could not reach the driver.`,{reason:F,method:e,path:t,...P(`no`)},r instanceof Error?r:void 0)}function Pe(e,t,r){return new n(`COMMAND_FAILED`,`WebDriver ${e} ${t} lost its connection to the driver.`,{reason:I,method:e,path:t,...P(`unknown`)},r instanceof Error?r:void 0)}function Fe(e){if(N(e)||be(e)||e instanceof n&&e.details?.reason===I)return!0;if(e instanceof n){let t=e.details?.status;return typeof t==`number`&&t>=500}return!1}var Ie=class{transport;sessionCreateTimeoutMs;sessionId;constructor(e){this.transport=new Ce(e),this.sessionCreateTimeoutMs=e.requestPolicy?.sessionCreateTimeoutMs??18e4}async createSession(e,t){let n=Re(await this.requestValue(`POST`,`/session`,{capabilities:Le(e)},{timeoutMs:Be(this.sessionCreateTimeoutMs,t?.deadline)}));return this.sessionId=n.sessionId,n}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){await this.appRouteWithSibling(`/appium/device/activate_app`,`mobile: activateApp`,e)}async terminateApp(e){await this.appRouteWithSibling(`/appium/device/terminate_app`,`mobile: terminateApp`,e)}async appRouteWithSibling(e,t,n){try{await this.sessionRequest(`POST`,e,{appId:n})}catch(r){if(!U(r))throw r;let{status:i}=await this.transport.request(`POST`,`/session/${this.requireSessionId()}/execute/sync`,{script:t,args:[{appId:n,bundleId:n}]});H(`webdriver_route_fallback`,{from:e,to:t,status:i})}}async performActions(e){await this.sessionRequest(`POST`,`/actions`,{actions:e})}async releaseActions(){await this.sessionRequest(`DELETE`,`/actions`)}async sendKeys(e){await this.sessionRequest(`POST`,`/keys`,{value:Array.from(e)})}async clearElement(e){await this.sessionRequest(`POST`,`/element/${encodeURIComponent(e)}/clear`)}async sendElementKeys(e,t){await this.sessionRequest(`POST`,`/element/${encodeURIComponent(e)}/value`,{text:t,value:Array.from(t)})}async hideKeyboard(){await this.sessionRequest(`POST`,`/appium/device/hide_keyboard`)}async isKeyboardShown(e,t){let n;try{n=await this.sessionRequest(`GET`,`/appium/device/is_keyboard_shown`,void 0,{retryAttempts:0,...e===void 0?{}:{timeoutMs:e},...t===void 0?{}:{signal:t}})}catch(e){if(U(e))return`unsupported`;throw e}return typeof n==`boolean`?n:`unsupported`}async activeElementReference(e){let t=e===void 0?void 0:Date.now()+e;try{let e=ze(await this.sessionRequest(`GET`,`/element/active`,void 0,K(t)));return e===void 0?`unsupported`:{id:e}}catch(e){if(U(e))return`unsupported`;if(J(e))return`none`;throw e}}async activeElement(e){let t=e===void 0?void 0:Date.now()+e,n=await this.activeElementReference(K(t).timeoutMs);if(typeof n==`string`)return n;let r=n.id;try{return{id:r,rect:W(await this.sessionRequest(`GET`,`/element/${encodeURIComponent(r)}/rect`,void 0,K(t)))}}catch(e){if(U(e))return`unsupported`;if(J(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(e){let t=await this.sessionRequest(`GET`,`/source`,void 0,e);if(typeof t!=`string`)throw new n(`COMMAND_FAILED`,`WebDriver source response was not a string`,{valueType:typeof t});return t}async screenshot(e){let t=await this.sessionRequest(`GET`,`/screenshot`);if(typeof t!=`string`)throw new n(`COMMAND_FAILED`,`WebDriver screenshot response was not base64 text`,{valueType:typeof t});await ie.writeFile(e,Buffer.from(t,`base64`))}async windowRect(e){return W(await this.sessionRequest(`GET`,`/window/rect`,void 0,e))}async executeScript(e,t=[]){return await this.sessionRequest(`POST`,`/execute/sync`,{script:e,args:t})}async executeReadScript(e,t=[]){return await this.sessionRequest(`POST`,`/execute/sync`,{script:e,args:t},{idempotent:!0})}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 n(`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 W(e){if(!e||typeof e!=`object`)throw new n(`COMMAND_FAILED`,`WebDriver window rect response was empty.`);let t=e,r={x:G(t,`x`),y:G(t,`y`),width:G(t,`width`),height:G(t,`height`)};if(r.x===void 0||r.y===void 0||r.width===void 0||r.height===void 0)throw new n(`COMMAND_FAILED`,`WebDriver window rect response was invalid.`,{response:t});return r}function G(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Le(e){return`alwaysMatch`in e||`firstMatch`in e?e:{alwaysMatch:e}}function Re(e){if(!e||typeof e!=`object`)throw new n(`COMMAND_FAILED`,`WebDriver create-session response was empty.`);let t=e,r=typeof t.sessionId==`string`?t.sessionId:typeof t.session_id==`string`?t.session_id:void 0;if(!r)throw new n(`COMMAND_FAILED`,`WebDriver create-session response missed sessionId.`,{response:t});return{sessionId:r,capabilities:t.capabilities&&typeof t.capabilities==`object`?t.capabilities:{}}}function ze(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 K(e){return e===void 0?{retryAttempts:0}:{retryAttempts:0,timeoutMs:q(e)}}function Be(e,t){return t===void 0?e:Math.min(e,q(t))}function q(e){return Math.max(0,e-Date.now())}function J(e){return e instanceof n&&Ve(e).toLowerCase()===`no such element`}function Ve(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 Y(e,t){return{type:`pointer`,id:e,parameters:{pointerType:`touch`},actions:t}}async function He(e){let{parseWebDriverSourceFacts:t}=await import(`./webdriver-source.js`);return X(t(e,`android`).nodes)}async function Ue(e){let{parseWebDriverSourceFacts:t}=await import(`./webdriver-source.js`);return X(t(e).nodes)}function X(e){let t=e.flatMap(e=>We(e)&&Ge(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 We(e){let t=e.type?.toLowerCase()??``;return e.visibleToUser!==!1&&(t.includes(`scrollview`)||t.includes(`listview`)||t.includes(`recyclerview`))}function Ge(e){return!!e&&e.width>=50&&e.height>=50}async function Ke(e,t,r){let i=[];for(let n of t===`android`?[`rotation`,`orientation`]:[`orientation`,`rotation`])try{await qe(e,n,r);return}catch(e){if(!U(e))throw e;i.push({transport:n,error:e instanceof Error?e.message:String(e)})}throw new n(`COMMAND_FAILED`,`Could not set device orientation to ${r} on the hosted WebDriver session.`,{...B(),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})}async function qe(e,t,n){if(t===`rotation`){await e.setRotation(a(n));return}await e.setOrientation(r(n))}const Z=1500;function Je(e){return new Promise(t=>setTimeout(t,e))}function Ye(e,t,r){return new n(`COMMAND_FAILED`,`fill tapped (${e}, ${t}) but ${r}`,{reason:`text_entry_focus_not_observed`,x:e,y:t,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 Q(){return new n(`UNSUPPORTED_OPERATION`,`fill requires a focused element reference to clear and replace the field`,{reason:`text_entry_clear_target_unavailable`})}function Xe(e,t,n){return t>=e.x&&t<=e.x+e.width&&n>=e.y&&n<=e.y+e.height}function Ze(e){return new $(e.client,e.backend,e.capabilities,e.targetId)}var $=class{client;backend;capabilities;targetId;constructor(e,t,n,r){this.client=e,this.backend=t,this.capabilities=n,this.targetId=r}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.client.activeElementReference(Z);if(i===`unsupported`)throw Q();let a=i===`none`?void 0:i.id;await this.tap(e,t);let o=await this.awaitTextEntryReadiness(a,e,t);return await this.client.clearElement(o),n.length>0&&await this.client.sendElementKeys(o,n),{backend:`webdriver`,x:e,y:t,text:n,textEntryReadiness:`focused-element`}}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($e(e)),await this.client.performActions(e.pointers.map(e=>Y(`gesture-pointer-${e.pointerId}`,Qe(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`),await this.captureSource(e?.signal)}async captureSource(e){let t=this.backend===`android`?await this.readAndroidSnapshotViewport(e):void 0,n=await this.readSource(e);e?.throwIfAborted();let r=await this.readSnapshotKeyboardVisibility(e);if(this.backend===`xctest`){let{acquireWebDriverIosSnapshot:e}=await import(`./webdriver-ios-snapshot.js`);return e(n,this.targetId,r)}let{parseWebDriverAndroidSnapshotNodes:i}=await import(`./webdriver-android-source.js`),{acquireProviderKeyboard:a}=await import(`./tap-keyboard-occlusion.js`).then(e=>e.i),o=i(n),s=t===void 0?void 0:await this.readAndroidSnapshotViewport(e),c=t!==void 0&&s!==void 0&&t.width===s.width&&t.height===s.height?t:void 0;return{backend:`android`,producer:`appium-source`,...a({nodes:o,viewport:null,visibility:r}),...c===void 0?{}:{viewport:c}}}async readAndroidSnapshotViewport(e){try{let t=await this.client.windowRect({timeoutMs:500,retryAttempts:0,...e===void 0?{}:{signal:e}});return s(t)}catch{e?.throwIfAborted();return}}async readSnapshotKeyboardVisibility(e){try{let t=await this.client.isKeyboardShown(500,e);return e?.throwIfAborted(),t}catch{return e?.throwIfAborted(),`failed`}}async readSource(e){try{return await this.client.source(e===void 0?{}:{signal:e})}catch(e){throw N(e)?et(e):e}}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 volumeUp(){await this.pressVolumeKey(`volumeUp`,`volumeup`)}async volumeDown(){await this.pressVolumeKey(`volumeDown`,`volumedown`)}async pressVolumeKey(e,t){if(this.backend===`android`){await this.pressAndroidHardwareKey(e);return}this.requireSupport(e),await this.client.executeScript(`mobile: pressButton`,[{name:t}])}async power(){await this.pressAndroidHardwareKey(`power`)}async pressAndroidHardwareKey(e){this.requireSupport(e);let{HARDWARE_BUTTON_NAME_LABELS:t}=await import(`./tv-remote.js`).then(e=>e.f),{toAndroidTvRemoteKeyevent:n}=await import(`./tv-remote.js`).then(e=>e.d),r=Number(n(t[e]));await this.client.executeScript(`mobile: pressKey`,[{keycode:r}])}async mute(){await this.pressAndroidHardwareKey(`mute`)}async sleep(){await this.pressAndroidHardwareKey(`sleep`)}async wake(){await this.pressAndroidHardwareKey(`wake`)}async mediaPlayPause(){await this.pressAndroidHardwareKey(`mediaPlayPause`)}async mediaNext(){await this.pressAndroidHardwareKey(`mediaNext`)}async mediaPrevious(){await this.pressAndroidHardwareKey(`mediaPrevious`)}async mediaRewind(){await this.pressAndroidHardwareKey(`mediaRewind`)}async mediaFastForward(){await this.pressAndroidHardwareKey(`mediaFastForward`)}async tvRemote(e,t){this.unsupported(`tvRemote`)}async keyboardStatus(){return this.requireSupport(`keyboard`),{kind:`ime-probe`,visible:await this.keyboardVisible()}}async keyboardDismiss(){this.requireSupport(`keyboard`);let e=await this.keyboardVisibility();if(e===!1)return this.dismissResult({wasVisible:e,visible:!1,dismissed:!1});await this.client.hideKeyboard();let t=await this.keyboardVisibilityAfterMutation();return this.dismissResult({...e===void 0?{}:{wasVisible:e},...t===void 0?{}:{visible:t,dismissed:e===!0&&!t}})}dismissResult(e){return this.backend===`android`?{kind:`ime-probe`,...e}:{kind:`mechanism`,mechanism:`appium-hide-keyboard`,...e}}async keyboardEnter(){if(this.requireSupport(`keyboard`),this.backend===`android`)return await this.client.executeScript(`mobile: pressKey`,[{keycode:66}]),{kind:`android-acknowledged`};let e=await this.keyboardVisibility();await this.client.sendKeys(`
|
|
2
2
|
`);let t=await this.keyboardVisibilityAfterMutation();return{kind:`visibility-echo`,...e===void 0?{}:{wasVisible:e},...t===void 0?{}:{visible:t}}}async keyboardVisibilityAfterMutation(){try{return await this.keyboardVisibility()}catch{return}}async keyboardVisibility(){let e=await this.client.isKeyboardShown(Z);return e===`unsupported`?void 0:e}async keyboardVisible(){let e=await this.keyboardVisibility();if(e===void 0)throw new n(`UNSUPPORTED_OPERATION`,`This driver does not implement the keyboard visibility route.`,{provider:this.capabilities.provider,platform:this.capabilities.platform,operation:`keyboard`});return e}async readClipboard(){this.requireSupport(`clipboard.read`);let e=await this.client.executeReadScript(`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=Date.now()+2e3,i,a=await this.pollWithinBudget(r,async r=>{let a=await this.client.activeElement(r);return a===`unsupported`?`abandon`:a===`none`||a.id===e&&!Xe(a.rect,t,n)?`retry`:(i=a.id,`satisfied`)});if(i!==void 0)return i;throw a===`abandon`?Q():Ye(t,n,`nothing there took text-entry focus, so the text was not sent`)}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(Z,i));if(n=!0,e!==`retry`)return e}catch(e){r=e}let a=e-Date.now();if(a<=0)break;await Je(Math.min(100,a))}if(!n&&r!==void 0)throw r;return`expired`}async pointerGesture(e,t){await this.client.performActions([Y(e,t)]),await this.client.releaseActions().catch(()=>void 0)}async scrollGestureFrame(){return await this.client.source().then(e=>this.backend===`xctest`?Ue(e):He(e)).catch(()=>void 0)||await this.client.windowRect()}requireSupport(e){u(this.capabilities,e)||this.unsupported(e)}unsupported(e){throw new n(`UNSUPPORTED_OPERATION`,ne(this.capabilities,e),{provider:this.capabilities.provider,platform:this.capabilities.platform,operation:e})}};function Qe(e){let t=e[0];if(!t)throw new n(`INVALID_ARGS`,`WebDriver gesture pointer requires samples`);let r=[{type:`pointerMove`,duration:0,x:t.point.x,y:t.point.y},{type:`pointerDown`,button:0}];for(let t=1;t<e.length;t+=1){let n=e[t-1],i=e[t];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 $e(e){if(e.topology===`single`)return`swipe`;switch(e.intent){case`pan`:case`transform`:return`transformGesture`;case`pinch`:return`pinch`;case`rotate`:return`rotateGesture`;case`tap`:return`tapGesture`}}function et(e){return new n(`COMMAND_FAILED`,`The cloud driver did not finish reading the screen in its budget.`,{...e.details,hint:`A screen that never goes idle (looping video, live ticker, continuous animation) gives the driver no moment to read the UI tree. This read has the transport's own budget and does not grow with --timeout; take a screenshot, or drive the screen from refs an earlier snapshot already captured.`},e)}var tt=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;let{rejectRefusedProviderProfileFields:n}=await import(`./provider-profile-fields.js`).then(e=>e.t);if(n(t?.flags,this.options.profileFields),this.sessionsByLeaseId.has(e.leaseId))return this.heartbeat(e);let r=await this.prepareSession(e,t),i=new Ie({clientVersion:this.options.clientVersion,endpoint:r.endpoint,auth:r.auth,headers:r.headers,requestPolicy:this.options.requestPolicy}),a=await this.createSessionWithPreparedCleanup(i,r,e,t),o=this.deviceForLease(e,r),s=r.providerSessionId??a.sessionId,c=d({provider:this.options.provider,platform:r.platform,overrides:this.options.capabilityOverrides});return this.sessionsByLeaseId.set(e.leaseId,Object.freeze({lease:e,device:o,client:i,prepared:r,capabilities:c,webDriverSessionId:a.sessionId,providerSessionId:s,interactor:Ze({client:i,backend:te(r.platform),capabilities:c,targetId:o.id})})),this.ownedDeviceIds.add(o.id),{provider:this.options.provider,deviceId:o.id,sessionId:a.sessionId,providerSessionId:s,capabilities:c,...r.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=this.sessionsByLeaseId.get(e.leaseId??``);return t?await this.listActiveCloudArtifacts(t,e.providerSessionId):await this.listReleasedCloudArtifacts(e)}async listActiveCloudArtifacts(e,t){if(!(t&&t!==e.providerSessionId))return await this.safeListArtifacts(e)}async listReleasedCloudArtifacts(e){let t=this.releasedProviderSessionIdsByLeaseId.get(e.leaseId??``);if(!(!t||!this.options.listArtifacts)&&!(e.providerSessionId&&e.providerSessionId!==t))return await this.options.listArtifacts({provider:this.options.provider,providerSessionId:t})}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,n,r){try{return await e.createSession(t.webdriverCapabilities,{deadline:r?.deadline})}catch(e){let r=N(e)?nt(e,this.options.provider,n,t):e;throw await b(r,()=>t.cleanup?.()),r}}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:ee(this.options.platform,this.options.deviceName,t)}}deviceForLease(e,t){return{...o(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 n=[],r;try{await e.client.deleteSession()}catch(e){n.push({code:`WEBDRIVER_SESSION_DELETE_FAILED`,message:t(e)})}try{r=await e.prepared.cleanup?.()}catch(e){n.push({code:`PROVIDER_CLEANUP_FAILED`,message:t(e)})}return{cleanup:r,warnings:n}}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 v({provider:this.options.provider,providerSessionId:e.providerSessionId,error:t})}}};function nt(e,t,r,i){let a=e.details?.timeoutMs;return new n(`COMMAND_FAILED`,`${t} did not create the WebDriver session within ${String(a)}ms.`,{reason:`provider_session_create_timeout`,provider:t,leaseId:r.leaseId,runId:r.runId,timeoutMs:a,...i.providerSessionId?{providerSessionId:i.providerSessionId}:{},hint:`${t} may still finish creating the session after agent-device stopped waiting, and that session would keep billing until the provider reaps it. Before retrying, check ${t} for a running session created for lease ${r.leaseId} (run ${r.runId}) and stop it.`},e)}var rt=e({createCloudWebDriverRuntime:()=>it});function it(e){return new at(e)}var at=class{provider;owner;leaseLifecycle;cloudArtifacts;deviceInventoryProvider;capabilities;platformRuntimeModule;sessions;deployment;constructor(e){this.provider=e.provider,this.owner=c(e.provider,e.platform),this.capabilities=d({provider:e.provider,platform:e.platform,overrides:e.capabilityOverrides}),this.sessions=new tt(e),this.deployment=re({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-runtime.js`);return t({host:e,owner:this.owner,ownsDevice:e=>this.ownsDevice(e),isSessionActive:e=>this.sessions.findSessionForDevice(e)!==void 0,deployment:this.deployment,capabilities:this.capabilities,snapshotAvailable:this.capabilities.operations.snapshot.support!==`unsupported`,screenshotAvailable:this.capabilities.operations.screenshot.support!==`unsupported`,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()}};export{pe as _,ge as a,_ as b,D as c,k as d,O as f,T as g,w as h,fe as i,b as l,ve as m,ue as n,he as o,E as p,ce as r,de as s,rt as t,A as u,j as v,ae as x,_e as y};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{j as e,yn as t}from"./sdk-batch.js";import{a as n}from"./screen-recording-session-resource.js";async function r(e){let t;try{return t=await e.gateway.bind({device:i(e.envelope),intent:{kind:`exact-owner`,owner:e.envelope.owner,fence:e.envelope.fence},scope:e.scope}),e.scope.signal.throwIfAborted(),e.create(t)}catch(e){throw t&&await t[Symbol.asyncDispose](),e}}function i(e){return{platform:e.device.family,id:e.device.id,name:e.device.id,kind:e.device.kind,...e.device.target===void 0?{}:{target:e.device.target},...e.device.appleOs===void 0?{}:{appleOs:e.device.appleOs},...e.device.iosPhysicalDeviceBackend===void 0?{}:{iosPhysicalDeviceBackend:e.device.iosPhysicalDeviceBackend}}}function a(e){return n.recoverOne({sessionsDir:e.sessionsDir,scope:e.scope,perRecordDeadlineMs:e.perRecordDeadlineMs,onDiagnostic:e.onDiagnostic,acquireControl:async(t,n)=>await o(e.gateway,t,n)},e.resourcePath)}async function o(n,i,a){return await r({gateway:n,envelope:i,scope:a,create:n=>s({runtime:t(n,e),dispose:async()=>await n[Symbol.asyncDispose]()})})}function s(e){return Object.freeze({reattach:async t=>await e.runtime.operations.screenRecordingReattach({envelope:t}),cleanup:async t=>await e.runtime.operations.screenRecordingCleanup({envelope:t}),[Symbol.asyncDispose]:e.dispose})}export{a as n,r,s as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{J as e,R as t}from"./sdk-contracts.js";import{_t as n,ut as r}from"./sdk-io.js";import"./diagnostics.js";import{G as i,H as a,U as o}from"./sdk-device.js";import{Gt as s,Jt as c,Ut as l,Wt as u,qt as d,yn as f}from"./sdk-batch.js";import{m as p}from"./observability.js";import{i as m}from"./verified-file.js";import"./file.js";import{r as ee}from"./session-paths.js";import{n as te,r as h,t as g}from"./durable-resource.js";import{n as ne}from"./screen-recording-runtime.js";import re from"node:crypto";import _ from"node:fs";import v from"node:path";function y(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function b(e){return e.replaceAll(`-`,`_`)}async function ie(e,t,n){let r={kind:`pending`};try{t.binding.assertAdoptable();let i=C(S(e,t),`active`);e.store.write(n,i),r={kind:`persisted`},t.throwIfCanceled();let a=t.pendingHandle.transfer();r={kind:`transferred`,handle:a},t.binding.adopt({handle:a,envelope:i})}catch(i){throw await ae(e,t,n,r,i),i}}async function ae(e,t,n,r,i){let a=t.binding.canPersist(),o=r.kind!==`pending`||a&&ce(e,t,n),s=oe(e,t,n,await se(t,r));t.reportUndurableCleanup(t.device,!o&&s.cleanupError===void 0||s.confirmed?{confirmed:!0}:{confirmed:!1,reason:s.cleanupError instanceof Error?s.cleanupError.message:`The durable cleanup transition could not be confirmed`}),s.cleanupError!==void 0&&fe(e,t,i,s.cleanupError)}function oe(e,t,r,i){try{return{confirmed:de(e,r,t.fence,i),cleanupError:i}}catch(r){return n({level:`error`,phase:`${b(e.resourceKind)}_pending_adoption_transition_failed`,data:{session:t.binding.address,transitionError:r instanceof Error?r.message:String(r)}}),{confirmed:!1,cleanupError:i??r}}}async function se(e,t){try{t.kind===`transferred`?await t.handle[Symbol.asyncDispose]():await e.pendingHandle[Symbol.asyncDispose]();return}catch(e){return e}}function ce(e,t,r){try{return e.store.write(r,le(e,t)),!0}catch(i){try{return e.store.write(r,x(e,t,{version:0,body:{reason:`runtime-contract-invalid`}})),!0}catch(r){return n({level:`error`,phase:`${b(e.resourceKind)}_runtime_contract_tombstone_failed`,data:{session:t.binding.address,descriptorError:i instanceof Error?i.message:String(i),persistenceError:r instanceof Error?r.message:String(r)}}),!1}}}function le(e,t){try{return C(S(e,t),`active`)}catch{return x(e,t,t.envelope.descriptor)}}function x(e,t,n){return te({resourceKind:e.resourceKind,sessionId:t.binding.address,device:a(t.device),owner:t.owner,fence:t.fence,lifecycle:`open`,descriptor:n,metadata:{phase:`runtime-contract-invalid`,runtimeContractInvalid:!0}})}function S(e,n){let r=h(n.envelope);if(r.status===`decoded`&&ue(r.envelope,n,e.resourceKind))return r.envelope;throw new t(`COMMAND_FAILED`,`${y(e.displayName)} runtime returned an incoherent durable envelope`,{reason:`runtime-contract-invalid`,hint:`Retain the runtime diagnostics and report the selected device and owner.`})}function ue(e,t,n){return e.resourceKind===n&&e.sessionId===t.binding.address&&i(e.device,a(t.device))&&f(e.owner)===f(t.owner)&&e.fence.token===t.fence.token&&e.fence.generation===t.fence.generation&&e.lifecycle===`open`}function de(e,t,n,r){let i=e.store.read(t);return i.status!==`decoded`||i.envelope.fence.token!==n.token||i.envelope.fence.generation!==n.generation?!1:(e.store.write(t,{...i.envelope,lifecycle:r===void 0?`completed`:`open`,metadata:{...i.envelope.metadata??{},phase:r===void 0?`completed`:`cleanup-pending`,cleanupStatus:r===void 0?`cleaned`:`cleanup-pending`}}),!0)}function fe(e,t,r,i){n({level:`error`,phase:`${b(e.resourceKind)}_pending_adoption_cleanup_failed`,data:{session:t.binding.address,primaryError:r instanceof Error?r.message:String(r),cleanupError:i instanceof Error?i.message:String(i)}})}function C(e,t){return Object.freeze({...e,lifecycle:`open`,metadata:{...e.metadata??{},phase:t}})}async function w(e){e.scope.signal.throwIfAborted();let t=new AbortController,n={...e.scope,signal:AbortSignal.any([e.scope.signal,t.signal])},r=()=>{},i=new Promise((e,t)=>{r=t}),a=()=>{},o=new Promise((t,n)=>{let r=()=>{try{e.scope.signal.throwIfAborted()}catch(e){n(e)}};if(e.scope.signal.aborted){r();return}e.scope.signal.addEventListener(`abort`,r,{once:!0}),a=()=>e.scope.signal.removeEventListener(`abort`,r)}),s=setTimeout(()=>{let n=new E(e.displayName,e.deadlineMs);t.abort(n),r(n)},e.deadlineMs);s.unref?.();let c=me(e,n),l,u=c.then(e=>(l??={kind:`acquisition`},e),e=>{throw l??={kind:`acquisition-error`},e}),d=i.catch(e=>{throw l??={kind:`deadline`,error:e},e}),f=o.catch(e=>{throw l??={kind:`cancellation`,error:e},e});try{return await Promise.race([u,d,f])}finally{if(clearTimeout(s),a(),l?.kind===`deadline`||l?.kind===`cancellation`){let t=l.error;c.then(n=>pe(e,n,t),()=>{}).catch(()=>{})}else c.catch(()=>{})}}async function pe(e,t,n){try{t.reattached.status===`active`&&await T(e,t.reattached.handle,`late_handle_cleanup_failed`,n)}finally{await T(e,t.control,`late_control_cleanup_failed`,n)}}async function me(e,t){let n,r;try{return n=await e.acquireControl(e.envelope,t),t.signal.throwIfAborted(),r=await n.reattach(e.envelope),t.signal.throwIfAborted(),{control:n,reattached:r}}catch(t){try{r?.status===`active`&&await T(e,r.handle,`late_handle_cleanup_failed`,t)}finally{n&&await T(e,n,`late_control_cleanup_failed`,t)}throw t}}async function T(e,t,n,r){try{await t[Symbol.asyncDispose]()}catch(t){e.onLateCleanupFailure(n,t,r)}}var E=class extends Error{deadlineMs;constructor(e,t){super(`${y(e)} recovery exceeded its ${t}ms deadline`),this.name=`DurableCaptureRecoveryDeadlineError`,this.deadlineMs=t}};const D=new Map;async function O(e){return await ge(e.resourcePath,async()=>{let t=e.store.read(e.resourcePath);if(t.status!==`decoded`)throw k(e.store,t.status===`missing`?`${e.store.displayName} resource record is missing`:`${e.store.displayName} resource record is unreattachable: ${t.message}`);if(!he(t.envelope.fence,e.expected))throw k(e.store,`${e.store.displayName} resource ownership fence was lost`);let n=t.envelope;return await e.run({get envelope(){return n},transition(t,r={}){return n=Object.freeze({...n,lifecycle:t,...r.descriptor===void 0?{}:{descriptor:r.descriptor},...r.metadata===void 0?{}:{metadata:r.metadata}}),e.store.write(e.resourcePath,n),n}})})}function he(e,t){return e.token===t.token&&e.generation===t.generation}async function ge(e,t){let n=D.get(e)??Promise.resolve(),r,i=new Promise(e=>{r=e}),a=n.catch(()=>{}).then(()=>i);D.set(e,a),await n.catch(()=>{});try{return await t()}finally{r(),D.get(e)===a&&D.delete(e)}}function k(e,n){return new t(`COMMAND_FAILED`,n,{reason:`ownership-fence-lost`,retriable:!1,hint:`Use the current ${e.displayName.toLowerCase()} resource owner or retain the recovery record for manual recovery.`})}async function _e(e,n,r){let i=n.binding.read();if(!i)throw new t(`INVALID_ARGS`,e.messages.noActive);try{let t=await A(e,{handle:i.handle,fence:i.envelope.fence,resourcePath:r,intent:n.intent});return n.binding.clear(i),t}catch(t){let a=e.store.read(r);throw a.status===`decoded`&&a.envelope.lifecycle===`completed`&&n.binding.clear(i),t}}async function A(e,t){return await O({store:e.store,resourcePath:t.resourcePath,expected:t.fence,run:async n=>{R(n);let r=be(n),i;try{i=await t.handle.finish(r)}catch(r){throw await j(e,n,t,r,t.intent),r}if(i.status===`completed`)return L(e,n,i),i.result;L(e,n,i);let a=I(e,i);throw await j(e,n,t,a,t.intent),a}})}async function j(e,t,n,r,i){if(i===`capture`&&e.failedFinishPolicy===`preserve-retry-material`){ye(e,n,r);return}let a;try{a=await n.handle.forceCleanup()}catch(i){M(e,n,r,i,ve(t,i));return}try{P(t,a)}catch(t){M(e,n,r,a.status===`cleanup-pending`?a.message??a.reason:`cleanup returned ${a.status}`,t);return}g(a)||M(e,n,r,a.message)}function ve(t,n){try{P(t,{status:`cleanup-pending`,reason:`cleanup-unconfirmed`,message:e(n)});return}catch(e){return e}}function ye(t,r,i){n({level:`error`,phase:`${b(t.resourceKind)}_finish_evidence_preserved`,data:{resourcePath:r.resourcePath,finishError:e(i),failedFinishPolicy:t.failedFinishPolicy}})}function M(t,r,i,a,o){n({level:`error`,phase:`${b(t.resourceKind)}_finish_cleanup_failed`,data:{resourcePath:r.resourcePath,finishError:e(i),cleanupError:a===void 0?`cleanup could not be confirmed`:e(a),...o===void 0?{}:{transitionError:e(o)}}})}async function N(e,t){let n=t.binding.read();n&&(F(e,await O({store:e.store,resourcePath:t.resourcePath,expected:n.envelope.fence,run:async e=>{R(e);let t=await n.handle.forceCleanup();return P(e,t),t}})),t.binding.clear(n))}function P(e,t){e.transition(g(t)?`completed`:`open`,{metadata:{...e.envelope.metadata??{},phase:g(t)?`completed`:`cleanup-pending`,cleanupStatus:t.status,...t.status===`cleanup-pending`?{cleanupPendingReason:t.reason,...t.message?{cleanupPendingMessage:t.message}:{}}:{}}})}function F(e,t){if(!g(t))throw I(e,t)}function I(e,n){return new t(`COMMAND_FAILED`,n.message??`${y(e.displayName)} cleanup could not be confirmed`,{reason:n.reason,retriable:n.reason!==`ownership-fence-lost`,hint:e.messages.cleanupPendingHint})}function L(e,t,n){if(n.status===`completed`){t.transition(`completed`,{metadata:{...t.envelope.metadata??{},...e.completionMetadata(n.result),phase:`completed`}});return}P(t,n)}function be(e){return Object.freeze({learned:e.envelope.metadata,record:t=>{e.transition(`open`,{metadata:{...e.envelope.metadata??{},...t}})}})}function R(e){e.transition(`open`,{metadata:{...e.envelope.metadata??{},phase:`completing`}})}async function xe(e){let t=e.definition.store.list(e.sessionsDir),n=[];for(let r of t)n.push(await z(e,r));return{scanned:t.length,recovered:n.filter(e=>e===`recovered`).length,retained:n.filter(e=>e===`retained`).length}}async function z(e,t){let n=Se(e,t);if(n.status!==`recoverable`)return n.status;try{return await Ce(e,t,n.envelope,e.perRecordDeadlineMs??5e3)?`recovered`:`retained`}catch(n){return H(e,n instanceof E?`timed_out`:`failed`,t,{error:n instanceof Error?n.message:String(n),...n instanceof E?{deadlineMs:n.deadlineMs}:{}}),`retained`}}function Se(e,t){let n=e.definition.store.read(t);if(n.status===`unreattachable`)return H(e,`record_unreattachable`,t,{reason:n.reason,message:n.message,version:n.version}),{status:`retained`};if(n.status===`missing`||n.envelope.lifecycle===`completed`)return{status:`ignored`};let r=e.definition.store.resolvePath(e.resolveSessionDir(n.envelope.sessionId));return v.resolve(t)===v.resolve(r)?{status:`recoverable`,envelope:n.envelope}:(H(e,`session_path_mismatch`,t,{envelopeSessionId:n.envelope.sessionId,canonicalPath:r}),{status:`retained`})}async function Ce(e,t,n,r){return await we(e,t,n,await w({displayName:e.definition.displayName,envelope:n,scope:e.scope,deadlineMs:r,acquireControl:e.acquireControl,onLateCleanupFailure:(n,r,i)=>H(e,n,t,{error:r instanceof Error?r.message:String(r),primaryError:i instanceof Error?i.message:String(i)})}))}async function we(e,t,n,r){try{switch(r.reattached.status){case`active`:{let i=r.reattached.handle,a=await O({store:e.definition.store,resourcePath:t,expected:n.fence,run:async e=>{Te(e);let t=await i.forceCleanup();return P(e,t),t}});return g(a)}case`completed`:return await B(e,t,n,{...e.definition.completionMetadata(r.reattached.result)}),!0;case`missing`:return await B(e,t,n,{recoveryStatus:`already-missing`}),!0;case`unreattachable`:{if(!V(r.reattached.reason))return H(e,`retained`,t,{reason:r.reattached.reason,message:r.reattached.message}),!1;let i=await r.control.cleanup(n);return await O({store:e.definition.store,resourcePath:t,expected:n.fence,run:async e=>P(e,i)}),g(i)}}}finally{await r.control[Symbol.asyncDispose]()}}async function B(e,t,n,r){await O({store:e.definition.store,resourcePath:t,expected:n.fence,run:async e=>{e.transition(`completed`,{metadata:{...e.envelope.metadata??{},phase:`completed`,...r}})}})}function Te(e){e.transition(`open`,{metadata:{...e.envelope.metadata??{},phase:`completing`}})}function V(e){switch(e){case`descriptor-invalid`:case`descriptor-version-unsupported`:case`ownership-fence-lost`:return!1;case`owner-unavailable`:case`transport-not-reattachable`:return!0}}function H(e,t,r,i){let a={phase:`${b(e.definition.resourceKind)}_recovery_${t}`,resourcePath:r,data:i};e.onDiagnostic?e.onDiagnostic(a):n({level:`warn`,phase:a.phase,data:{resourcePath:r,...i}})}async function Ee(n,r){let i=n.store.read(r.resourcePath);if(i.status!==`decoded`||i.envelope.lifecycle!==`open`)throw De(n,i.status);let a=i.envelope,o=await w({displayName:n.displayName,envelope:a,scope:r.scope,deadlineMs:r.deadlineMs??5e3,acquireControl:r.acquireControl,onLateCleanupFailure:(t,i,a)=>r.scope.diagnostics.emit({level:`error`,phase:`${b(n.resourceKind)}_recovery_${t}`,data:{resourcePath:r.resourcePath,error:e(i),primaryError:e(a)}})});try{switch(o.reattached.status){case`active`:return await A(n,{handle:o.reattached.handle,fence:a.fence,resourcePath:r.resourcePath,intent:`capture`});case`completed`:{let e=o.reattached.result;return await O({store:n.store,resourcePath:r.resourcePath,expected:a.fence,run:async t=>{L(n,t,{status:`completed`,result:e,alreadyCompleted:!0})}}),e}case`missing`:throw new t(`COMMAND_FAILED`,`${y(n.displayName)} is missing`,{reason:`resource-missing`,hint:n.messages.cleanupPendingHint});case`unreattachable`:if(V(o.reattached.reason)){let e=await o.control.cleanup(a);await O({store:n.store,resourcePath:r.resourcePath,expected:a.fence,run:async t=>P(t,e)}),F(n,e)}throw new t(`COMMAND_FAILED`,o.reattached.message??`${y(n.displayName)} cannot be reattached`,{reason:o.reattached.reason,hint:n.messages.cleanupPendingHint})}}finally{await o.control[Symbol.asyncDispose]()}}function De(e,n){return new t(`INVALID_ARGS`,n===`missing`?e.messages.noActive:`${y(e.displayName)} recovery record is not open`)}function U(e){ke(e.fileName);let t=t=>v.join(t,e.fileName);return Object.freeze({resourceKind:e.resourceKind,displayName:e.displayName,resolvePath:t,read(t){let n,r;try{if(n=m(t),n===void 0)return{status:`missing`};r=JSON.parse(_.readFileSync(n,`utf8`))}catch(t){return K(t)?{status:`missing`}:G(Ae(t,e.displayName))}finally{n!==void 0&&_.closeSync(n)}return Oe(h(r),e.resourceKind)},write(e,t){let n=v.dirname(e);_.mkdirSync(n,{recursive:!0}),r({destination:e,contents:`${JSON.stringify(t)}\n`})},list(e){let n;try{n=_.readdirSync(e,{withFileTypes:!0})}catch{return[]}return n.filter(e=>e.isDirectory()).map(n=>t(v.join(e,n.name))).filter(W).sort()}})}function Oe(e,t){return e.status===`decoded`?e.envelope.resourceKind===t?{status:`decoded`,envelope:e.envelope}:G(`Expected ${t} resource record, received ${e.envelope.resourceKind}`):e}function ke(e){if(e.length===0||v.basename(e)!==e)throw TypeError(`Durable capture resource fileName must be one file name`)}function W(e){try{return _.lstatSync(e),!0}catch(e){return!K(e)}}function G(e){return{status:`unreattachable`,reason:`descriptor-invalid`,message:e}}function K(e){return typeof e==`object`&&!!e&&`code`in e&&e.code===`ENOENT`}function Ae(e,t){return e instanceof Error?e.message:`${t} resource record is invalid`}function je(e,t){t.admissionLedger.assertStartAllowed(t.device),Me(e,t.resourcePath,t.device);let n=e.store.read(t.resourcePath);return Object.freeze({token:re.randomUUID(),generation:n.status===`decoded`?n.envelope.fence.generation+1:1})}function Me(e,n,r){let i=o(a(r));for(let r of e.store.list(v.dirname(v.dirname(n)))){let a=e.store.read(r);if(a.status===`unreattachable`)throw new t(`COMMAND_FAILED`,`${y(q(e.displayName))} ${e.displayName} recovery record is unreattachable: ${a.message}`,{reason:a.reason,retriable:!1,hint:`Retain the corrupt or future-version ${e.displayName} manifest for manual recovery; no replacement capture is safe.`});if(a.status===`decoded`&&a.envelope.lifecycle!==`completed`&&(r===n||o(a.envelope.device)===i))throw new t(`COMMAND_FAILED`,`${y(q(e.displayName))} ${e.displayName} resource for this device has not reached a confirmed terminal state`,{reason:`cleanup-unconfirmed`,hint:`Retry exact-owner cleanup using the existing ${e.displayName} manifest before starting a replacement.`})}}function q(e){return/^[aeiou]/i.test(e)?`an`:`a`}function J(e){let t=(t,n)=>e.store.resolvePath(t.resolveSessionDir(n)),n=t=>({definition:e,resolveSessionDir:e=>v.join(t.sessionsDir,ee(e)),...t});return Object.freeze({store:e.store,resourcePath:t,createNextFence(t){return je(e,t)},adoptStarted(t){return ie(e,{...t,reportUndurableCleanup:(e,n)=>{n.confirmed?t.admissionLedger.clearUndurableCleanup(e):t.admissionLedger.blockUndurableCleanup(e,n.reason)}},e.store.resolvePath(t.binding.sessionDir))},finishLive(t){return _e(e,t,e.store.resolvePath(t.binding.sessionDir))},finishRecovered(t){return Ee(e,t)},forceCleanupLive(t){return N(e,{...t,resourcePath:e.store.resolvePath(t.binding.sessionDir)})},recoverAll(e){return xe(n(e))},recoverOne(e,t){return z(n(e),t)}})}const Y=U({resourceKind:`app-log`,fileName:`app-log.resource.json`,displayName:`App-log`}),Ne=J({resourceKind:`app-log`,displayName:`app-log`,store:Y,completionMetadata:e=>({backend:e.backend,outputPath:e.outputPath,completedAt:e.completedAt}),failedFinishPolicy:`dispose-on-failed-finish`,messages:{noActive:`no app log stream active`,cleanupPendingHint:`Keep app-log.resource.json and retry cleanup through its exact runtime owner.`}}),X=J({resourceKind:`audio-probe`,displayName:`audio probe`,store:U({resourceKind:`audio-probe`,fileName:`audio-probe.resource.json`,displayName:`Audio probe`}),completionMetadata:e=>({backend:e.backend??`unknown`,source:e.source,durationMs:e.durationMs,elapsedMs:e.elapsedMs,bucketMs:e.bucketMs,sampleCount:e.sampleCount,heard:e.heard}),failedFinishPolicy:`dispose-on-failed-finish`,messages:{noActive:`no active audio probe`,cleanupPendingHint:`Keep audio-probe.resource.json and retry stop through its exact runtime owner.`}});function Pe(e){return X.adoptStarted(e)}function Fe(e){return X.finishLive(e)}function Ie(e){if(e.area===`frames`)return Object.freeze({kind:`frames`,request:e,use:l});if(e.area===`memory`)return e.action===`snapshot`?Object.freeze({kind:`memory-snapshot`,request:e,use:s}):Object.freeze({kind:`memory-sample`,request:e,use:u});if(e.area===`trace`)return e.action===`start`?Object.freeze({kind:`capture-start`,request:e,use:d}):Object.freeze({kind:`capture-stop`,request:e});switch(e.action){case`start`:return Object.freeze({kind:`capture-start`,request:e,use:d});case`stop`:return Object.freeze({kind:`capture-stop`,request:e});case`report`:return Object.freeze({kind:`profile-report`,request:e,use:c})}}function Le(e){let n=e.positionals??[],r=n[0]?.toLowerCase();if(r===`frames`){let i=n[1]?.toLowerCase();if(i!==void 0&&i!==`sample`||n.length>2||e.kind!==void 0)throw new t(`INVALID_ARGS`,`perf action must be frames, memory sample|snapshot, cpu profile start|stop|report, or trace start|stop`);return Object.freeze({area:r,action:`sample`})}if(r===`memory`)return Re(n,e);if(r===`cpu`)return ze(n,e.outPath);if(r===`trace`)return Be(n,e.outPath);throw new t(`INVALID_ARGS`,`perf requires frames, memory, cpu, or trace`)}function Re(e,n){let r=(e[1]??`sample`).toLowerCase();if(r!==`sample`&&r!==`snapshot`)throw new t(`INVALID_ARGS`,`perf memory requires sample or snapshot`);if(n.kind!==void 0&&r!==`snapshot`)throw new t(`INVALID_ARGS`,`--kind is only supported with perf memory snapshot`);if(r===`sample`&&e.length>2)throw new t(`INVALID_ARGS`,`perf memory sample does not accept additional positionals`);if(r===`snapshot`&&e.length>3)throw new t(`INVALID_ARGS`,`perf memory snapshot accepts at most one positional kind`);let i=n.kind??e[2];if(i!==void 0&&!p(i))throw new t(`INVALID_ARGS`,`perf memory snapshot --kind must be android-hprof or memgraph`);return Object.freeze({area:`memory`,action:r,...i===void 0?{}:{kind:i},...n.outPath===void 0?{}:{outPath:n.outPath}})}function ze(e,n){if(e[1]?.toLowerCase()!==`profile`)throw new t(`INVALID_ARGS`,`perf cpu requires profile`);let r=e[2]?.toLowerCase();if(r!==`start`&&r!==`stop`&&r!==`report`)throw new t(`INVALID_ARGS`,`perf cpu profile action must be start, stop, or report`);let i=e[3]?.toLowerCase();if(i!==`xctrace`&&i!==`simpleperf`)throw new t(`INVALID_ARGS`,`perf cpu profile requires --kind xctrace or simpleperf`);let a=n??e[5];return Object.freeze({area:`cpu`,subject:`profile`,action:r,kind:i,...e[4]?{template:e[4]}:{},...a?{outPath:a}:{},...e[6]?{tracePath:e[6]}:{}})}function Be(e,n){let r=e[1]?.toLowerCase();if(r!==`start`&&r!==`stop`)throw new t(`INVALID_ARGS`,`perf trace action must be start or stop`);let i=e[2]?.toLowerCase();if(i!==`xctrace`&&i!==`perfetto`)throw new t(`INVALID_ARGS`,`perf trace requires --kind xctrace or perfetto`);let a=n??e[4];return Object.freeze({area:`trace`,action:r,kind:i,...e[3]?{template:e[3]}:{},...a?{outPath:a}:{}})}const Z=J({resourceKind:`perf-capture`,displayName:`perf capture`,store:U({resourceKind:`perf-capture`,fileName:`perf-capture.resource.json`,displayName:`Perf capture`}),completionMetadata:e=>({kind:typeof e.kind==`string`?e.kind:`unknown`,mode:typeof e.mode==`string`?e.mode:`unknown`,...typeof e.outPath==`string`?{outPath:e.outPath}:{}}),failedFinishPolicy:`preserve-retry-material`,messages:{noActive:`no active native perf capture`,cleanupPendingHint:`Keep perf-capture.resource.json and retry stop through its exact runtime owner.`}});function Ve(e){return Z.adoptStarted(e)}function He(e){return Z.finishLive(e)}const Q=J({resourceKind:`screen-recording`,displayName:`screen recording`,store:U({resourceKind:ne,fileName:`screen-recording.resource.json`,displayName:`screen recording`}),completionMetadata:Ge,failedFinishPolicy:`preserve-retry-material`,messages:{noActive:`no active recording`,cleanupPendingHint:`Keep screen-recording.resource.json and retry stop through its exact runtime owner.`}});function Ue(e){return Q.adoptStarted(e)}function We(e){return Q.finishLive(e)}const $=`completion`;function Ge(e){return{[$]:{backend:e.backend,outPath:e.outPath,startedAt:e.startedAt,completedAt:e.completedAt,...e.capturedDurationMs===void 0?{}:{capturedDurationMs:e.capturedDurationMs},...e.stopObservation===void 0?{}:{stopObservation:qe(e.stopObservation)},...e.nativePathDisposition===void 0?{}:{nativePathDisposition:e.nativePathDisposition},scope:e.scope,showTouches:e.showTouches,recordOnlySession:e.recordOnlySession,...e.clientOutPath===void 0?{}:{clientOutPath:e.clientOutPath},...e.telemetryPath===void 0?{}:{telemetryPath:e.telemetryPath},...e.warning===void 0?{}:{warning:e.warning},...e.overlayWarning===void 0?{}:{overlayWarning:e.overlayWarning},...e.activeSessionApp===void 0?{}:{activeSessionApp:Ke(e.activeSessionApp)},...e.chunks===void 0?{}:{chunks:e.chunks.map(Je)}}}}function Ke(e){return{bundleId:e.bundleId,...e.name===void 0?{}:{name:e.name}}}function qe(e){return e.recorder===`confirmed`?{recorder:e.recorder}:{recorder:e.recorder,why:e.why}}function Je(e){return{index:e.index,path:e.path,...e.clientOutPath===void 0?{}:{clientOutPath:e.clientOutPath}}}function Ye(e){return Q.finishRecovered(e)}export{Q as a,Z as c,Pe as d,X as f,Y as h,Ye as i,Le as l,Ne as m,Ue as n,Ve as o,Fe as p,We as r,He as s,$ as t,Ie as u};
|
|
1
|
+
import{J as e,R as t}from"./sdk-contracts.js";import{_t as n,ut as r}from"./sdk-io.js";import"./diagnostics.js";import{G as i,W as a,q as o}from"./sdk-device.js";import{xn as s}from"./sdk-batch.js";import{i as c}from"./verified-file.js";import"./file.js";import{r as l}from"./session-paths.js";import{n as u,r as d,t as f}from"./durable-resource.js";import{n as p}from"./screen-recording-runtime.js";import ee from"node:crypto";import m from"node:fs";import h from"node:path";function g(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function _(e){return e.replaceAll(`-`,`_`)}async function te(e,t,n){let r={kind:`pending`};try{t.binding.assertAdoptable();let i=b(y(e,t),`active`);e.store.write(n,i),r={kind:`persisted`},t.throwIfCanceled();let a=t.pendingHandle.transfer();r={kind:`transferred`,handle:a},t.binding.adopt({handle:a,envelope:i})}catch(i){throw await ne(e,t,n,r,i),i}}async function ne(e,t,n,r,i){let a=t.binding.canPersist(),o=r.kind!==`pending`||a&&ae(e,t,n),s=re(e,t,n,await ie(t,r));t.reportUndurableCleanup(t.device,!o&&s.cleanupError===void 0||s.confirmed?{confirmed:!0}:{confirmed:!1,reason:s.cleanupError instanceof Error?s.cleanupError.message:`The durable cleanup transition could not be confirmed`}),s.cleanupError!==void 0&&le(e,t,i,s.cleanupError)}function re(e,t,r,i){try{return{confirmed:ce(e,r,t.fence,i),cleanupError:i}}catch(r){return n({level:`error`,phase:`${_(e.resourceKind)}_pending_adoption_transition_failed`,data:{session:t.binding.address,transitionError:r instanceof Error?r.message:String(r)}}),{confirmed:!1,cleanupError:i??r}}}async function ie(e,t){try{t.kind===`transferred`?await t.handle[Symbol.asyncDispose]():await e.pendingHandle[Symbol.asyncDispose]();return}catch(e){return e}}function ae(e,t,r){try{return e.store.write(r,oe(e,t)),!0}catch(i){try{return e.store.write(r,v(e,t,{version:0,body:{reason:`runtime-contract-invalid`}})),!0}catch(r){return n({level:`error`,phase:`${_(e.resourceKind)}_runtime_contract_tombstone_failed`,data:{session:t.binding.address,descriptorError:i instanceof Error?i.message:String(i),persistenceError:r instanceof Error?r.message:String(r)}}),!1}}}function oe(e,t){try{return b(y(e,t),`active`)}catch{return v(e,t,t.envelope.descriptor)}}function v(e,t,n){return u({resourceKind:e.resourceKind,sessionId:t.binding.address,device:a(t.device),owner:t.owner,fence:t.fence,lifecycle:`open`,descriptor:n,metadata:{phase:`runtime-contract-invalid`,runtimeContractInvalid:!0}})}function y(e,n){let r=d(n.envelope);if(r.status===`decoded`&&se(r.envelope,n,e.resourceKind))return r.envelope;throw new t(`COMMAND_FAILED`,`${g(e.displayName)} runtime returned an incoherent durable envelope`,{reason:`runtime-contract-invalid`,hint:`Retain the runtime diagnostics and report the selected device and owner.`})}function se(e,t,n){return e.resourceKind===n&&e.sessionId===t.binding.address&&o(e.device,a(t.device))&&s(e.owner)===s(t.owner)&&e.fence.token===t.fence.token&&e.fence.generation===t.fence.generation&&e.lifecycle===`open`}function ce(e,t,n,r){let i=e.store.read(t);return i.status!==`decoded`||i.envelope.fence.token!==n.token||i.envelope.fence.generation!==n.generation?!1:(e.store.write(t,{...i.envelope,lifecycle:r===void 0?`completed`:`open`,metadata:{...i.envelope.metadata??{},phase:r===void 0?`completed`:`cleanup-pending`,cleanupStatus:r===void 0?`cleaned`:`cleanup-pending`}}),!0)}function le(e,t,r,i){n({level:`error`,phase:`${_(e.resourceKind)}_pending_adoption_cleanup_failed`,data:{session:t.binding.address,primaryError:r instanceof Error?r.message:String(r),cleanupError:i instanceof Error?i.message:String(i)}})}function b(e,t){return Object.freeze({...e,lifecycle:`open`,metadata:{...e.metadata??{},phase:t}})}async function x(e){e.scope.signal.throwIfAborted();let t=new AbortController,n={...e.scope,signal:AbortSignal.any([e.scope.signal,t.signal])},r=()=>{},i=new Promise((e,t)=>{r=t}),a=()=>{},o=new Promise((t,n)=>{let r=()=>{try{e.scope.signal.throwIfAborted()}catch(e){n(e)}};if(e.scope.signal.aborted){r();return}e.scope.signal.addEventListener(`abort`,r,{once:!0}),a=()=>e.scope.signal.removeEventListener(`abort`,r)}),s=setTimeout(()=>{let n=new C(e.displayName,e.deadlineMs);t.abort(n),r(n)},e.deadlineMs);s.unref?.();let c=de(e,n),l,u=c.then(e=>(l??={kind:`acquisition`},e),e=>{throw l??={kind:`acquisition-error`},e}),d=i.catch(e=>{throw l??={kind:`deadline`,error:e},e}),f=o.catch(e=>{throw l??={kind:`cancellation`,error:e},e});try{return await Promise.race([u,d,f])}finally{if(clearTimeout(s),a(),l?.kind===`deadline`||l?.kind===`cancellation`){let t=l.error;c.then(n=>ue(e,n,t),()=>{}).catch(()=>{})}else c.catch(()=>{})}}async function ue(e,t,n){try{t.reattached.status===`active`&&await S(e,t.reattached.handle,`late_handle_cleanup_failed`,n)}finally{await S(e,t.control,`late_control_cleanup_failed`,n)}}async function de(e,t){let n,r;try{return n=await e.acquireControl(e.envelope,t),t.signal.throwIfAborted(),r=await n.reattach(e.envelope),t.signal.throwIfAborted(),{control:n,reattached:r}}catch(t){try{r?.status===`active`&&await S(e,r.handle,`late_handle_cleanup_failed`,t)}finally{n&&await S(e,n,`late_control_cleanup_failed`,t)}throw t}}async function S(e,t,n,r){try{await t[Symbol.asyncDispose]()}catch(t){e.onLateCleanupFailure(n,t,r)}}var C=class extends Error{deadlineMs;constructor(e,t){super(`${g(e)} recovery exceeded its ${t}ms deadline`),this.name=`DurableCaptureRecoveryDeadlineError`,this.deadlineMs=t}};const w=new Map;async function T(e){return await D(e.resourcePath,async()=>{let t=e.store.read(e.resourcePath);if(t.status!==`decoded`)throw O(e.store,t.status===`missing`?`${e.store.displayName} resource record is missing`:`${e.store.displayName} resource record is unreattachable: ${t.message}`);if(!E(t.envelope.fence,e.expected))throw O(e.store,`${e.store.displayName} resource ownership fence was lost`);let n=t.envelope;return await e.run({get envelope(){return n},transition(t,r={}){return n=Object.freeze({...n,lifecycle:t,...r.descriptor===void 0?{}:{descriptor:r.descriptor},...r.metadata===void 0?{}:{metadata:r.metadata}}),e.store.write(e.resourcePath,n),n}})})}function E(e,t){return e.token===t.token&&e.generation===t.generation}async function D(e,t){let n=w.get(e)??Promise.resolve(),r,i=new Promise(e=>{r=e}),a=n.catch(()=>{}).then(()=>i);w.set(e,a),await n.catch(()=>{});try{return await t()}finally{r(),w.get(e)===a&&w.delete(e)}}function O(e,n){return new t(`COMMAND_FAILED`,n,{reason:`ownership-fence-lost`,retriable:!1,hint:`Use the current ${e.displayName.toLowerCase()} resource owner or retain the recovery record for manual recovery.`})}async function fe(e,n,r){let i=n.binding.read();if(!i)throw new t(`INVALID_ARGS`,e.messages.noActive);try{let t=await k(e,{handle:i.handle,fence:i.envelope.fence,resourcePath:r,intent:n.intent});return n.binding.clear(i),t}catch(t){let a=e.store.read(r);throw a.status===`decoded`&&a.envelope.lifecycle===`completed`&&n.binding.clear(i),t}}async function k(e,t){return await T({store:e.store,resourcePath:t.resourcePath,expected:t.fence,run:async n=>{L(n);let r=I(n),i;try{i=await t.handle.finish(r)}catch(r){throw await A(e,n,t,r,t.intent),r}if(i.status===`completed`)return F(e,n,i),i.result;F(e,n,i);let a=P(e,i);throw await A(e,n,t,a,t.intent),a}})}async function A(e,t,n,r,i){if(i===`capture`&&e.failedFinishPolicy===`preserve-retry-material`){me(e,n,r);return}let a;try{a=await n.handle.forceCleanup()}catch(i){j(e,n,r,i,pe(t,i));return}try{M(t,a)}catch(t){j(e,n,r,a.status===`cleanup-pending`?a.message??a.reason:`cleanup returned ${a.status}`,t);return}f(a)||j(e,n,r,a.message)}function pe(t,n){try{M(t,{status:`cleanup-pending`,reason:`cleanup-unconfirmed`,message:e(n)});return}catch(e){return e}}function me(t,r,i){n({level:`error`,phase:`${_(t.resourceKind)}_finish_evidence_preserved`,data:{resourcePath:r.resourcePath,finishError:e(i),failedFinishPolicy:t.failedFinishPolicy}})}function j(t,r,i,a,o){n({level:`error`,phase:`${_(t.resourceKind)}_finish_cleanup_failed`,data:{resourcePath:r.resourcePath,finishError:e(i),cleanupError:a===void 0?`cleanup could not be confirmed`:e(a),...o===void 0?{}:{transitionError:e(o)}}})}async function he(e,t){let n=t.binding.read();n&&(N(e,await T({store:e.store,resourcePath:t.resourcePath,expected:n.envelope.fence,run:async e=>{L(e);let t=await n.handle.forceCleanup();return M(e,t),t}})),t.binding.clear(n))}function M(e,t){e.transition(f(t)?`completed`:`open`,{metadata:{...e.envelope.metadata??{},phase:f(t)?`completed`:`cleanup-pending`,cleanupStatus:t.status,...t.status===`cleanup-pending`?{cleanupPendingReason:t.reason,...t.message?{cleanupPendingMessage:t.message}:{}}:{}}})}function N(e,t){if(!f(t))throw P(e,t)}function P(e,n){return new t(`COMMAND_FAILED`,n.message??`${g(e.displayName)} cleanup could not be confirmed`,{reason:n.reason,retriable:n.reason!==`ownership-fence-lost`,hint:e.messages.cleanupPendingHint})}function F(e,t,n){if(n.status===`completed`){t.transition(`completed`,{metadata:{...t.envelope.metadata??{},...e.completionMetadata(n.result),phase:`completed`}});return}M(t,n)}function I(e){return Object.freeze({learned:e.envelope.metadata,record:t=>{e.transition(`open`,{metadata:{...e.envelope.metadata??{},...t}})}})}function L(e){e.transition(`open`,{metadata:{...e.envelope.metadata??{},phase:`completing`}})}async function R(e){let t=e.definition.store.list(e.sessionsDir),n=[];for(let r of t)n.push(await z(e,r));return{scanned:t.length,recovered:n.filter(e=>e===`recovered`).length,retained:n.filter(e=>e===`retained`).length}}async function z(e,t){let n=ge(e,t);if(n.status!==`recoverable`)return n.status;try{return await _e(e,t,n.envelope,e.perRecordDeadlineMs??5e3)?`recovered`:`retained`}catch(n){return U(e,n instanceof C?`timed_out`:`failed`,t,{error:n instanceof Error?n.message:String(n),...n instanceof C?{deadlineMs:n.deadlineMs}:{}}),`retained`}}function ge(e,t){let n=e.definition.store.read(t);if(n.status===`unreattachable`)return U(e,`record_unreattachable`,t,{reason:n.reason,message:n.message,version:n.version}),{status:`retained`};if(n.status===`missing`||n.envelope.lifecycle===`completed`)return{status:`ignored`};let r=e.definition.store.resolvePath(e.resolveSessionDir(n.envelope.sessionId));return h.resolve(t)===h.resolve(r)?{status:`recoverable`,envelope:n.envelope}:(U(e,`session_path_mismatch`,t,{envelopeSessionId:n.envelope.sessionId,canonicalPath:r}),{status:`retained`})}async function _e(e,t,n,r){return await ve(e,t,n,await x({displayName:e.definition.displayName,envelope:n,scope:e.scope,deadlineMs:r,acquireControl:e.acquireControl,onLateCleanupFailure:(n,r,i)=>U(e,n,t,{error:r instanceof Error?r.message:String(r),primaryError:i instanceof Error?i.message:String(i)})}))}async function ve(e,t,n,r){try{switch(r.reattached.status){case`active`:{let i=r.reattached.handle,a=await T({store:e.definition.store,resourcePath:t,expected:n.fence,run:async e=>{V(e);let t=await i.forceCleanup();return M(e,t),t}});return f(a)}case`completed`:return await B(e,t,n,{...e.definition.completionMetadata(r.reattached.result)}),!0;case`missing`:return await B(e,t,n,{recoveryStatus:`already-missing`}),!0;case`unreattachable`:{if(!H(r.reattached.reason))return U(e,`retained`,t,{reason:r.reattached.reason,message:r.reattached.message}),!1;let i=await r.control.cleanup(n);return await T({store:e.definition.store,resourcePath:t,expected:n.fence,run:async e=>M(e,i)}),f(i)}}}finally{await r.control[Symbol.asyncDispose]()}}async function B(e,t,n,r){await T({store:e.definition.store,resourcePath:t,expected:n.fence,run:async e=>{e.transition(`completed`,{metadata:{...e.envelope.metadata??{},phase:`completed`,...r}})}})}function V(e){e.transition(`open`,{metadata:{...e.envelope.metadata??{},phase:`completing`}})}function H(e){switch(e){case`descriptor-invalid`:case`descriptor-version-unsupported`:case`ownership-fence-lost`:return!1;case`owner-unavailable`:case`transport-not-reattachable`:return!0}}function U(e,t,r,i){let a={phase:`${_(e.definition.resourceKind)}_recovery_${t}`,resourcePath:r,data:i};e.onDiagnostic?e.onDiagnostic(a):n({level:`warn`,phase:a.phase,data:{resourcePath:r,...i}})}async function ye(n,r){let i=n.store.read(r.resourcePath);if(i.status!==`decoded`||i.envelope.lifecycle!==`open`)throw be(n,i.status);let a=i.envelope,o=await x({displayName:n.displayName,envelope:a,scope:r.scope,deadlineMs:r.deadlineMs??5e3,acquireControl:r.acquireControl,onLateCleanupFailure:(t,i,a)=>r.scope.diagnostics.emit({level:`error`,phase:`${_(n.resourceKind)}_recovery_${t}`,data:{resourcePath:r.resourcePath,error:e(i),primaryError:e(a)}})});try{switch(o.reattached.status){case`active`:return await k(n,{handle:o.reattached.handle,fence:a.fence,resourcePath:r.resourcePath,intent:`capture`});case`completed`:{let e=o.reattached.result;return await T({store:n.store,resourcePath:r.resourcePath,expected:a.fence,run:async t=>{F(n,t,{status:`completed`,result:e,alreadyCompleted:!0})}}),e}case`missing`:throw new t(`COMMAND_FAILED`,`${g(n.displayName)} is missing`,{reason:`resource-missing`,hint:n.messages.cleanupPendingHint});case`unreattachable`:if(H(o.reattached.reason)){let e=await o.control.cleanup(a);await T({store:n.store,resourcePath:r.resourcePath,expected:a.fence,run:async t=>M(t,e)}),N(n,e)}throw new t(`COMMAND_FAILED`,o.reattached.message??`${g(n.displayName)} cannot be reattached`,{reason:o.reattached.reason,hint:n.messages.cleanupPendingHint})}}finally{await o.control[Symbol.asyncDispose]()}}function be(e,n){return new t(`INVALID_ARGS`,n===`missing`?e.messages.noActive:`${g(e.displayName)} recovery record is not open`)}function W(e){Se(e.fileName);let t=t=>h.join(t,e.fileName);return Object.freeze({resourceKind:e.resourceKind,displayName:e.displayName,resolvePath:t,read(t){let n,r;try{if(n=c(t),n===void 0)return{status:`missing`};r=JSON.parse(m.readFileSync(n,`utf8`))}catch(t){return K(t)?{status:`missing`}:G(we(t,e.displayName))}finally{n!==void 0&&m.closeSync(n)}return xe(d(r),e.resourceKind)},write(e,t){let n=h.dirname(e);m.mkdirSync(n,{recursive:!0}),r({destination:e,contents:`${JSON.stringify(t)}\n`})},list(e){let n;try{n=m.readdirSync(e,{withFileTypes:!0})}catch{return[]}return n.filter(e=>e.isDirectory()).map(n=>t(h.join(e,n.name))).filter(Ce).sort()}})}function xe(e,t){return e.status===`decoded`?e.envelope.resourceKind===t?{status:`decoded`,envelope:e.envelope}:G(`Expected ${t} resource record, received ${e.envelope.resourceKind}`):e}function Se(e){if(e.length===0||h.basename(e)!==e)throw TypeError(`Durable capture resource fileName must be one file name`)}function Ce(e){try{return m.lstatSync(e),!0}catch(e){return!K(e)}}function G(e){return{status:`unreattachable`,reason:`descriptor-invalid`,message:e}}function K(e){return typeof e==`object`&&!!e&&`code`in e&&e.code===`ENOENT`}function we(e,t){return e instanceof Error?e.message:`${t} resource record is invalid`}function Te(e,t){t.admissionLedger.assertStartAllowed(t.device),Ee(e,t.resourcePath,t.device);let n=e.store.read(t.resourcePath);return Object.freeze({token:ee.randomUUID(),generation:n.status===`decoded`?n.envelope.fence.generation+1:1})}function Ee(e,n,r){let o=i(a(r));for(let r of e.store.list(h.dirname(h.dirname(n)))){let a=e.store.read(r);if(a.status===`unreattachable`)throw new t(`COMMAND_FAILED`,`${g(q(e.displayName))} ${e.displayName} recovery record is unreattachable: ${a.message}`,{reason:a.reason,retriable:!1,hint:`Retain the corrupt or future-version ${e.displayName} manifest for manual recovery; no replacement capture is safe.`});if(a.status===`decoded`&&a.envelope.lifecycle!==`completed`&&(r===n||i(a.envelope.device)===o))throw new t(`COMMAND_FAILED`,`${g(q(e.displayName))} ${e.displayName} resource for this device has not reached a confirmed terminal state`,{reason:`cleanup-unconfirmed`,hint:`Retry exact-owner cleanup using the existing ${e.displayName} manifest before starting a replacement.`})}}function q(e){return/^[aeiou]/i.test(e)?`an`:`a`}function J(e){let t=(t,n)=>e.store.resolvePath(t.resolveSessionDir(n)),n=t=>({definition:e,resolveSessionDir:e=>h.join(t.sessionsDir,l(e)),...t});return Object.freeze({store:e.store,resourcePath:t,createNextFence(t){return Te(e,t)},adoptStarted(t){return te(e,{...t,reportUndurableCleanup:(e,n)=>{n.confirmed?t.admissionLedger.clearUndurableCleanup(e):t.admissionLedger.blockUndurableCleanup(e,n.reason)}},e.store.resolvePath(t.binding.sessionDir))},finishLive(t){return fe(e,t,e.store.resolvePath(t.binding.sessionDir))},finishRecovered(t){return ye(e,t)},forceCleanupLive(t){return he(e,{...t,resourcePath:e.store.resolvePath(t.binding.sessionDir)})},recoverAll(e){return R(n(e))},recoverOne(e,t){return z(n(e),t)}})}const Y=W({resourceKind:`app-log`,fileName:`app-log.resource.json`,displayName:`App-log`}),De=J({resourceKind:`app-log`,displayName:`app-log`,store:Y,completionMetadata:e=>({backend:e.backend,outputPath:e.outputPath,completedAt:e.completedAt}),failedFinishPolicy:`dispose-on-failed-finish`,messages:{noActive:`no app log stream active`,cleanupPendingHint:`Keep app-log.resource.json and retry cleanup through its exact runtime owner.`}}),X=J({resourceKind:`audio-probe`,displayName:`audio probe`,store:W({resourceKind:`audio-probe`,fileName:`audio-probe.resource.json`,displayName:`Audio probe`}),completionMetadata:e=>({backend:e.backend??`unknown`,source:e.source,durationMs:e.durationMs,elapsedMs:e.elapsedMs,bucketMs:e.bucketMs,sampleCount:e.sampleCount,heard:e.heard}),failedFinishPolicy:`dispose-on-failed-finish`,messages:{noActive:`no active audio probe`,cleanupPendingHint:`Keep audio-probe.resource.json and retry stop through its exact runtime owner.`}});function Oe(e){return X.adoptStarted(e)}function ke(e){return X.finishLive(e)}const Z=J({resourceKind:`perf-capture`,displayName:`perf capture`,store:W({resourceKind:`perf-capture`,fileName:`perf-capture.resource.json`,displayName:`Perf capture`}),completionMetadata:e=>({kind:typeof e.kind==`string`?e.kind:`unknown`,mode:typeof e.mode==`string`?e.mode:`unknown`,...typeof e.outPath==`string`?{outPath:e.outPath}:{}}),failedFinishPolicy:`preserve-retry-material`,messages:{noActive:`no active native perf capture`,cleanupPendingHint:`Keep perf-capture.resource.json and retry stop through its exact runtime owner.`}});function Ae(e){return Z.adoptStarted(e)}function je(e){return Z.finishLive(e)}const Q=J({resourceKind:`screen-recording`,displayName:`screen recording`,store:W({resourceKind:p,fileName:`screen-recording.resource.json`,displayName:`screen recording`}),completionMetadata:Pe,failedFinishPolicy:`preserve-retry-material`,messages:{noActive:`no active recording`,cleanupPendingHint:`Keep screen-recording.resource.json and retry stop through its exact runtime owner.`}});function Me(e){return Q.adoptStarted(e)}function Ne(e){return Q.finishLive(e)}const $=`completion`;function Pe(e){return{[$]:{backend:e.backend,outPath:e.outPath,startedAt:e.startedAt,completedAt:e.completedAt,...e.capturedDurationMs===void 0?{}:{capturedDurationMs:e.capturedDurationMs},...e.stopObservation===void 0?{}:{stopObservation:Ie(e.stopObservation)},...e.nativePathDisposition===void 0?{}:{nativePathDisposition:e.nativePathDisposition},scope:e.scope,showTouches:e.showTouches,recordOnlySession:e.recordOnlySession,...e.clientOutPath===void 0?{}:{clientOutPath:e.clientOutPath},...e.telemetryPath===void 0?{}:{telemetryPath:e.telemetryPath},...e.warning===void 0?{}:{warning:e.warning},...e.overlayWarning===void 0?{}:{overlayWarning:e.overlayWarning},...e.activeSessionApp===void 0?{}:{activeSessionApp:Fe(e.activeSessionApp)},...e.chunks===void 0?{}:{chunks:e.chunks.map(Le)}}}}function Fe(e){return{bundleId:e.bundleId,...e.name===void 0?{}:{name:e.name}}}function Ie(e){return e.recorder===`confirmed`?{recorder:e.recorder}:{recorder:e.recorder,why:e.why}}function Le(e){return{index:e.index,path:e.path,...e.clientOutPath===void 0?{}:{clientOutPath:e.clientOutPath}}}function Re(e){return Q.finishRecovered(e)}export{Q as a,Z as c,ke as d,De as f,Re as i,Oe as l,Me as n,Ae as o,Y as p,Ne as r,je as s,$ as t,X as u};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{W as e}from"./sdk-device.js";import{i as t,n}from"./durable-resource.js";import{n as r}from"./screen-recording-runtime.js";import{n as i}from"./async-lifecycle.js";import{n as a,t as o}from"./screen-recording-completion.js";import{t as s}from"./screen-recording-options.js";function c(e){return Object.freeze({resourceKind:r,version:1,encode:e=>({...e}),decode:t=>t.backend===e&&typeof t.outputPath==`string`?{status:`decoded`,descriptor:Object.freeze({backend:e,outputPath:t.outputPath})}:{status:`invalid`,message:`Invalid ${e} screen-recording descriptor`}})}function l(e){return{status:`unreattachable`,reason:`transport-not-reattachable`,message:e}}function u(e){return{status:`cleanup-pending`,reason:`manual-recovery-required`,message:e}}async function d(l){let{host:u,device:d,owner:m,input:h,signal:g,transport:_}=l;s(h,l.support,l.unsupported),g.throwIfAborted(),await u.screenRecording.outputs.prepare(h.outputPath);let v=f(_),y=!1;try{await _.start(g),y=!0,g.throwIfAborted()}catch(e){throw y&&await v().catch(()=>{}),g.throwIfAborted(),e}let b=a(p(_.backend,h),{finish:async e=>{let t=await v();_.collect&&await _.collect(t,e.outPath);let n=await u.screenRecording.finalize.complete({outputPath:e.outPath,showTouches:!1,gestureEvents:e.gestureEvents,...e.exportQuality===void 0?{}:{exportQuality:e.exportQuality},targetLabel:_.targetLabel});return o(e,n,{stopObservation:{recorder:`confirmed`},showTouches:!1})},forceCleanup:async()=>{try{return await v(),{status:`cleaned`}}catch(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:`${_.backend} recording cleanup failed`}}}});return Object.freeze({pendingHandle:new i(b),envelope:n({resourceKind:r,sessionId:h.sessionId,device:e(d),owner:m,fence:h.fence,lifecycle:`open`,descriptor:t(c(_.backend),{backend:_.backend,outputPath:h.outputPath})})})}function f(e){let t;return()=>t??=e.stop().catch(e=>{throw t=void 0,e})}function p(e,t){return Object.freeze({backend:e,outPath:t.outputPath,...t.clientOutputPath===void 0?{}:{clientOutPath:t.clientOutputPath},startedAt:Date.now(),scope:t.scope,showTouches:!1,recordOnlySession:t.recordOnlySession,...t.activeSessionApp===void 0?{}:{activeSessionApp:t.activeSessionApp},...t.exportQuality===void 0?{}:{exportQuality:t.exportQuality},gestureEvents:[]})}export{u as n,l as r,d as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{R as e}from"./sdk-contracts.js";import{
|
|
1
|
+
import{R as e}from"./sdk-contracts.js";import{w as t}from"./sdk-device.js";import{t as n}from"./png-size.js";function r(t,n){if(!(n===void 0||s(t)))throw new e(`UNSUPPORTED_OPERATION`,`--pixel-density is currently supported only on iOS-family simulators`)}function i(e,t,n){let r=o(n);if(t!==r)return{width:Math.max(1,Math.round(e.width/t*r)),height:Math.max(1,Math.round(e.height/t*r))}}async function a(e){let t=s(e.device),r;try{r=await n(e.path)}catch(e){if(t)throw e;return{}}let i={width:r.width,height:r.height};if(!t||e.scale!==void 0&&e.scale!==1)return i;let a=o(e.requestedPixelDensity);return{...i,logicalWidth:Math.round(r.width/a),logicalHeight:Math.round(r.height/a),pixelDensity:a}}function o(e){return e??1}function s(e){return t(e)&&e.kind===`simulator`}export{i as n,a as r,r as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as e}from"./rolldown-runtime.js";import{R as t,S as n,s as r}from"./sdk-contracts.js";import{At as i,Dt as a,Ot as o,xt as s}from"./tv-remote.js";import{C as c,F as l,R as u}from"./sdk-device.js";import{Ci as d,Nn as f,Qt as p,Xr as m,ai as h,bi as g,gi as _,mi as v,ni as y,ri as b,xi as x}from"./sdk-batch.js";import{t as ee}from"./session-paths.js";import{t as S}from"./snapshot-state.js";import{n as C}from"./snapshot-runtime-capture-input.js";import{i as te,t as ne}from"./selector-pipeline-policy.js";import{i as re,o as ie,r as ae}from"./png-worker-client.js";import{f as w,i as T,n as E}from"./runtime-session.js";import{t as oe}from"./command-policy.js";import{a as se,i as ce,n as le,t as ue}from"./session-runtime-admission.js";import{t as de}from"./react-native-overlay2.js";import{t as fe}from"./png-size.js";import{r as pe,t as me}from"./screenshot-density.js";import{a as D,o as O,s as k,t as he}from"./screenshot-overlay-draw.js";import{promises as A}from"node:fs";import j from"node:os";import M from"node:path";const N=s.pendingPixelIdentityEvidence,P=[{target:`ios-simulator`,status:`accepted`},{target:`android-emulator`,status:`accepted`},{target:`android-device`,status:`rejected`,rejectionReason:N},{target:`macos-app-window`,status:`rejected`,rejectionReason:N},{target:`ios-physical`,status:`accepted`},{target:`ios-physical-xctest`,status:`rejected`,rejectionReason:N},{target:`ipados-physical`,status:`rejected`,rejectionReason:N},{target:`macos-helper`,status:`rejected`,rejectionReason:N},{target:`web`,status:`rejected`,rejectionReason:N},{target:`linux`,status:`rejected`,rejectionReason:N},{target:`tvos`,status:`rejected`,rejectionReason:N},{target:`harmonyos`,status:`rejected`,rejectionReason:N},{target:`vega`,status:`rejected`,rejectionReason:N}];function F(e,t){switch(e.platform){case`apple`:return I(e,t);case`android`:return e.kind===`device`?`android-device`:`android-emulator`;case`harmonyos`:return`harmonyos`;case`vega`:return`vega`;case`linux`:return`linux`;case`web`:return`web`}}function I(e,t){let n=u(e);switch(n){case`ios`:return e.kind===`device`?e.iosPhysicalDeviceBackend===`xctest`?`ios-physical-xctest`:`ios-physical`:`ios-simulator`;case`ipados`:return e.kind===`device`?`ipados-physical`:`ios-simulator`;case`tvos`:return`tvos`;case`macos`:return L(t);case`watchos`:case`visionos`:throw R(n)}}function L(e){return(e??`app`)===`app`?`macos-app-window`:`macos-helper`}function R(e,n){return new t(`UNSUPPORTED_OPERATION`,`screenshot --crop-on is not accepted on ${e} targets`,{reason:s.targetNotAccepted,...n?{rejectionReason:n}:{}})}function ge(e){if(e.overlayRefs||e.fullscreen)throw new t(`INVALID_ARGS`,`--crop-on cannot be combined with --overlay-refs or --fullscreen: both move the captured frame away from the snapshot viewport the crop is measured against`,{reason:s.frameMismatch});try{f(e.cropOn)}catch{throw new t(`INVALID_ARGS`,`screenshot --crop-on requires a valid selector expression`,{reason:s.selectorInvalid})}let n=F(e.device,e.surface),r=P.find(e=>e.target===n);if(!r||r.status===`rejected`)throw R(n,r?.status===`rejected`?r.rejectionReason:void 0)}function _e(e,t){if(F(e,void 0)===`ios-physical`&&t.iosPhysicalCaptureBackend!==`coredevice`)throw R(`ios-physical-non-coredevice-capture`,N)}async function ve(e,n){if(!ye(n))throw new t(`INVALID_ARGS`,`Screenshot crop box must be positive integer pixel offsets`);let r=await ae(await A.readFile(e),n,`screenshot`);r!==null&&await A.writeFile(e,r)}function ye(e){return Number.isInteger(e.x)&&e.x>=0&&Number.isInteger(e.y)&&e.y>=0&&Number.isInteger(e.width)&&e.width>0&&Number.isInteger(e.height)&&e.height>0}function be(e){switch(e){case`android`:return`device-pixels`;case`xctest`:case`macos-helper`:return`viewport-points`;default:throw new t(`UNSUPPORTED_OPERATION`,`screenshot --crop-on does not accept snapshot backend "${e??`unknown`}"`,{reason:s.targetNotAccepted})}}function z(e,t,n,r,i){if(e===`device-pixels`||t===null)return we(n);let a=r/t.width,o=i/t.height;return{x:Math.round((n.x-t.x)*a),y:Math.round((n.y-t.y)*o),width:Math.round(n.width*a),height:Math.round(n.height*o)}}function xe(e,t,n){return v(e,{x:0,y:0,width:t,height:n})??null}function B(e){let t=null;for(let n of e)!m(n)||!_(n.rect)||(!t||g(n.rect)>g(t))&&(t=n.rect);return t||Se(e.filter(e=>_(e.rect)&&!Ce(e)))}function Se(e){let t=1/0,n=1/0,r=-1/0,i=-1/0;for(let a of e)_(a.rect)&&(t=Math.min(t,a.rect.x),n=Math.min(n,a.rect.y),r=Math.max(r,a.rect.x+a.rect.width),i=Math.max(i,a.rect.y+a.rect.height));return!Number.isFinite(t)||!Number.isFinite(n)||r<=t||i<=n?null:{x:t,y:n,width:r-t,height:i-n}}function Ce(e){return b(e.type??``)===`image`&&!y(e.label)}function we(e){return{x:Math.round(e.x),y:Math.round(e.y),width:Math.round(e.width),height:Math.round(e.height)}}const Te=`${s.partialIntersection}: the selector frame extends past the captured image; the crop was clipped to the image frame`;function Ee(e){return e?.partialIntersection?[Te]:[]}async function De(e){let{device:n,session:r,surface:i,cropOn:a,screenshotPath:o,logPath:c,dispatchContext:l}=e,u={snapshotInteractiveOnly:!1},d=await T({device:n,session:r,flags:u,logPath:c,snapshotScope:void 0,captureData:async()=>await e.captureSnapshot({options:{appBundleId:l.appBundleId,interactiveOnly:!1,includeRects:!0,surface:i},execution:C(l)})}),f=S(d,u);if(f.snapshotQuality?.state===`sparse`)throw new t(`COMMAND_FAILED`,`the snapshot taken for --crop-on was sparse and cannot be read as the screen`,{reason:s.captureUnreadable});let p=await Oe(f.nodes,a,f.truncated,n),m=await fe(o),h=z(be(f.backend),B(f.nodes),p.rect,m.width,m.height),g=xe(h,m.width,m.height);if(g===null)throw new t(`COMMAND_FAILED`,`the frame resolved by --crop-on occupies no pixel of the capture`,{reason:s.emptyIntersection});let _=g.x!==h.x||g.y!==h.y||g.width<h.width||g.height<h.height;return await ve(o,g),{partialIntersection:_}}async function Oe(e,n,r,i){let a=await te(ne.cropTarget,e,n,{platform:l(i)});if(a.kind===`ambiguous`)throw new t(`COMMAND_FAILED`,`--crop-on matched ${a.matchedNodes.length} nodes and must resolve to one`,{reason:s.targetAmbiguous,candidates:a.matchedNodes.map(e=>e.label??e.ref),matches:a.matchedNodes.length});if(a.kind===`none`)throw r?new t(`COMMAND_FAILED`,`the snapshot taken for --crop-on was truncated, so a missing match is not proven`,{reason:s.captureIncomplete}):new t(`COMMAND_FAILED`,`--crop-on matched no node: ${n}`,{reason:s.targetNotFound,hint:`find ${n} list`});return a.node}const ke=[`scroll`,`list`,`recyclerview`,`edittext`,`textfield`];function Ae(e,t,n){if(e.backend!==`android`||!n.hittable||!O(n.rect)||m(n))return!1;let r=b(n.type??``);return!(ke.some(e=>r.includes(e))||t&&k(n.rect)>k(t)*.25)}function je(e,t,n,r){return!e.rect||e.hittable!==!0||n(e)||r(e)?null:Me(e,t,r)}function Me(e,t,n){let r=e.rect,i=Ne(e,t,n);if(!i)return null;let a=i.y-r.y,o=r.y+r.height-(i.y+i.height);if(a<0||o<0||Math.abs(o-a)<16)return null;let s=Math.min(a,o),c=Math.round(i.y-s),l=Math.round(i.height+s*2);return l<=0||l>=r.height?null:{x:r.x,y:c,width:r.width,height:l}}function Ne(e,t,n){let r=e.rect,i=new Map(t.map(e=>[e.index,e])),a=t.filter(t=>t.ref!==e.ref&&Fe(t,e,i)&&Pe(t,n)&&O(t.rect)&&x(r,t.rect)).map(e=>e.rect);return a.length<2?null:d(a)}function Pe(e,t){let n=b(e.type??``);return n.includes(`text`)||n.includes(`image`)&&t(e)}function Fe(e,t,n){let r=e;for(;r.parentIndex!==void 0;){let e=n.get(r.parentIndex);if(!e)return!1;if(e.ref===t.ref)return!0;r=e}return!1}const Ie=[`button`,`link`,`menu`,`tab`,`textfield`,`searchfield`,`securetextfield`,`checkbox`,`radio`,`switch`,`cell`];async function V(e){let t=await A.readFile(e.screenshotPath),n=await re(t,`screenshot`),r=Le(e.snapshot,n.width,n.height,{maxRefs:e.maxRefs});for(let e of r)he(n,e);return await A.writeFile(e.screenshotPath,await ie(n)),r}function Le(e,t,r,i={}){let a=B(e.nodes),o=new Map;for(let n of e.nodes){if(!Be(e,a,n))continue;let i=Ve(e.nodes,n);if(!i?.ref||!i.rect||!O(i.rect))continue;let s=He(n,i,e.nodes),c=Ue(n,i,s),l=H(e,a,ze(e,i,e.nodes),t,r);if(!O(l))continue;let u=o.get(i.ref);(!u||c>u.score)&&o.set(i.ref,{ref:i.ref,label:s,rect:i.rect,overlayRect:l,score:c})}return Re(e,a,o,t,r),We([...o.values()]).sort(et).slice(0,i.maxRefs??24).sort(J).map(e=>({ref:e.ref,label:e.label,rect:e.rect,overlayRect:e.overlayRect,center:n(e.overlayRect)}))}function Re(e,t,n,r,i){let a=de(e.nodes).primaryAction;if(!a?.ref||!a.rect||!O(a.rect))return;let o=H(e,t,a.rect,r,i);if(!O(o))return;let s={ref:a.ref,label:a.label,rect:a.rect,overlayRect:o,score:100},c=n.get(a.ref);n.set(a.ref,c?{...c,score:Math.max(c.score,s.score)}:s)}function ze(e,t,n){return e.backend===`android`?je(t,n,U,e=>!!q(e))??t.rect:t.rect}function Be(e,t,n){let r=[n.label,n.value].some(G)||K(n.identifier);return Ae(e,t,n)?!0:U(n)?r:r&&Ge(n)}function Ve(e,t){return[W(t)?t:null,h(e,t,W),t.hittable?t:null,h(e,t,e=>e.hittable===!0)].find(Ke)??null}function He(e,t,n){let r=q(e);return e.ref!==t.ref&&r?r:qe(t,n)||q(t)}function Ue(e,t,n){let r=0;return e.ref===t.ref&&(r+=4),t.hittable&&(r+=3),U(t)&&(r+=3),U(e)&&(r+=2),n&&(r+=2),K(t.identifier)&&(r+=1),y(t.value)&&(r+=1),r}function We(e){let t=[];for(let n of e.sort((e,t)=>k(e.overlayRect)-k(t.overlayRect))){let e=t.findIndex(e=>e.label!==void 0&&e.label===n.label&&(x(e.overlayRect,n.overlayRect)||x(n.overlayRect,e.overlayRect)));if(e===-1){t.push(n);continue}k(n.overlayRect)<k(t[e].overlayRect)&&(t[e]=n)}return t}function H(e,t,n,r,i){return $e(z(e.backend===`android`?`device-pixels`:`viewport-points`,t,n,r,i),r,i)}function U(e){let t=[e.type,e.role,e.subrole].map(e=>b(e??``)).join(` `);return Ie.some(e=>t.includes(e))}function W(e){return U(e)&&!m(e)}function Ge(e){let t=b(e.type??``);return t.includes(`statictext`)||t.includes(`image`)||t.includes(`text`)||t.includes(`other`)}function Ke(e){return!!(e?.rect&&O(e.rect)&&!m(e))}function G(e){return y(e)?!Xe(e):!1}function K(e){return typeof e!=`string`||!G(e)?!1:!Ze(e)}function q(e){let t=[e.label,e.value].find(G);if(t)return t.trim();if(K(e.identifier))return e.identifier.trim()}function qe(e,t){let n=null;for(let r of t){if(r.ref===e.ref||!Je(r,e,t))continue;let i=q(r);if(!i)continue;let a=Ye(r);(!n||a>n.score)&&(n={label:i,score:a})}return n?.label}function Je(e,t,n){let r=e;for(;r.parentIndex!==void 0;){let e=n[r.parentIndex];if(!e)return!1;if(e.ref===t.ref)return!0;r=e}return!1}function Ye(e){let t=0;return b(e.type??``).includes(`text`)&&(t+=2),G(e.label)&&(t+=2),G(e.value)&&(t+=1),t}function Xe(e){let t=e?.trim().toLowerCase();return t===`toolbar`||t===`window`||t===`application`||t?.startsWith(`vertical scroll bar`)===!0}function Ze(e){return/^[a-z0-9_.]+:id\/[a-z0-9_.-]+$/i.test(e.trim())}function Qe(e,t){return Number.parseInt(e.replace(/^\D+/,``),10)-Number.parseInt(t.replace(/^\D+/,``),10)}function $e(e,t,n){let r=D(e.x,0,Math.max(0,t-1)),i=D(e.y,0,Math.max(0,n-1)),a=Math.max(1,t-r),o=Math.max(1,n-i);return{x:r,y:i,width:D(e.width,1,a),height:D(e.height,1,o)}}function J(e,t){let n=e.overlayRect.y-t.overlayRect.y;if(n!==0)return n;let r=e.overlayRect.x-t.overlayRect.x;return r===0?Qe(e.ref,t.ref):r}function et(e,t){return t.score===e.score?J(e,t):t.score-e.score}async function Y(e){let t=p({overlayRefs:e.overlayRefs,cropOn:e.cropOn!==void 0}),n=await ue({device:e.device,plan:t,inspectFacts:e.inspectFacts});return n.admitted?{ok:!0,runtime:await tt(e.bindDevice,n)}:{ok:!1,response:rt(t.kind,n.operation,n.fact)}}async function tt(e,t){let n=le(e),{device:r,plan:i}=se(t);switch(i.kind){case`capture`:{let e=await n(r,i.use);return Object.freeze({captureScreenshot:X(e)})}case`capture-with-overlay-refs`:case`capture-with-crop-on`:{let e=await n(r,i.use);return Object.freeze({captureScreenshot:X(e),captureSnapshot:nt(e)})}}}function X(e){return async t=>await e.operations.captureScreenshot(t)}function nt(e){return async t=>await e.operations.captureSnapshot(t)}function rt(e,t,n){return t===`captureScreenshot`?ce(`screenshot`,n):e===`capture-with-crop-on`?r(`UNSUPPORTED_OPERATION`,`--crop-on crops the capture to a selector frame using a snapshot taken on the same screen, which this target cannot capture.`,{reason:n.available?void 0:n.reason},{hint:(n.available?void 0:n.hint)??`Re-run screenshot without --crop-on.`}):r(`UNSUPPORTED_OPERATION`,`--overlay-refs annotates a capture with the refs of a snapshot taken on the same screen, which this target cannot capture.`,{reason:n.available?void 0:n.reason},{hint:(n.available?void 0:n.hint)??`Re-run screenshot without --overlay-refs.`})}var Z=e({captureScreenshotArtifact:()=>Q,resolveScreenshotGenericExecution:()=>it,screenshotExecutionFromContext:()=>$});async function it(e){let{req:n,session:r}=e,i=a(`screenshot`,n.flags);if(i)throw new t(`INVALID_ARGS`,i);me(r.device,n.flags?.screenshotPixelDensity);let o=lt(n,e.hostCwd),s=typeof n.flags?.screenshotCropOn==`string`&&n.flags.screenshotCropOn.length>0?n.flags.screenshotCropOn:void 0;s!==void 0&&ge({device:r.device,surface:r.surface,cropOn:s,overlayRefs:n.flags?.overlayRefs===!0,fullscreen:n.flags?.screenshotFullscreen===!0});let c=await Y({device:r.device,overlayRefs:n.flags?.overlayRefs===!0,cropOn:s,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});if(!c.ok)return c;let l=c.runtime,u={warnings:[]},{createCommandSurface:d}=e;return{ok:!0,recorded:o.recorded,execute:async e=>await at({createCommandSurface:d,session:e.session,sessionName:e.sessionName,logPath:e.logPath,dispatchContext:e.dispatchContext,flags:e.request.flags,outPath:o.outPath,runtime:l,cropOn:s,cropRun:u})}}async function Q(e){let{session:t,sessionName:n,outPath:r,dispatchContext:a}=e;return await(await e.createCommandSurface({backend:ut(e),artifacts:dt(),sessions:E(n,t),policy:oe()})).capture.screenshot({session:n,requestId:a.requestId,appBundleId:t.appBundleId,...i(a),surface:t.surface,...r?{out:{kind:`path`,path:r}}:{}})}function $(e){return C(e)}async function at(e){let{session:t,runtime:n,flags:r}=e,i=ot({cropOn:e.cropOn,captureSnapshot:n.captureSnapshot,cropRun:e.cropRun,logPath:e.logPath}),a=await Q({createCommandSurface:e.createCommandSurface,session:t,sessionName:e.sessionName,outPath:e.outPath,dispatchContext:e.dispatchContext,captureScreenshot:n.captureScreenshot,...i?{crop:i}:{}}),o=[...a.warnings??[],...i?.run?.warnings??[]];return{...a,...o.length>0?{warnings:o}:{},...await st({session:t,cropOn:e.cropOn,captureSnapshot:n.captureSnapshot,screenshotPath:a.path,logPath:e.logPath,dispatchContext:e.dispatchContext}),...await pe({device:t.device,path:a.path,requestedPixelDensity:r?.screenshotPixelDensity,scale:r?.screenshotScale})}}function ot(e){let{cropOn:t,captureSnapshot:n,cropRun:r}=e;if(t!==void 0&&n!==void 0&&r!==void 0)return{cropOn:t,captureSnapshot:n,run:r,logPath:e.logPath}}async function st(e){let{session:t,cropOn:n,captureSnapshot:r}=e;return n!==void 0||r===void 0?{}:{overlayRefs:await ct({session:t,logPath:e.logPath,screenshotPath:e.screenshotPath,dispatchContext:e.dispatchContext,captureSnapshot:r})}}async function ct(e){let{session:t,dispatchContext:n}=e,r={snapshotInteractiveOnly:!0},i=await T({device:t.device,session:t,flags:r,logPath:e.logPath,snapshotScope:void 0,captureData:async()=>await e.captureSnapshot({options:{appBundleId:t.appBundleId,interactiveOnly:!0,surface:t.surface},execution:$(n)})}),a=S(i,r);return w(t,a),await V({screenshotPath:e.screenshotPath,snapshot:a})}function lt(e,t){let n=e.positionals??[],r=e.flags??{},i=n=>n===void 0?void 0:ee(n,e.meta?.cwd??t),a=i(n[0]),o=i(r.out);return{outPath:a??o,recorded:{positionals:a?[a,...n.slice(1)]:n,flags:o?{...r,out:o}:r}}}function ut(e){let{session:t,dispatchContext:n,captureScreenshot:r,crop:a}=e;return{platform:l(t.device),captureScreenshot:async(e,s,l)=>{let u=i({...n,...o(l)}),d=await r({outPath:s,options:{appBundleId:n.appBundleId,pixelDensity:u.pixelDensity,fullscreen:u.fullscreen,normalizeStatusBar:u.normalizeStatusBar,stabilize:u.stabilize,surface:l?.surface,skipIosSimulatorBootCheck:n.skipIosSimulatorBootCheck??(c(t.device)&&t.device.kind===`simulator`),captureBackend:n.screenshotCaptureBackend},execution:$(n)});if(a){_e(t.device,d);let e=await De({device:t.device,session:t,surface:t.surface,cropOn:a.cropOn,screenshotPath:s,logPath:a.logPath,dispatchContext:n,captureSnapshot:a.captureSnapshot});a.run.warnings.push(...Ee(e))}return d.displayRotation?{displayRotation:d.displayRotation}:void 0}}}function dt(){return{resolveInput:async()=>{throw new t(`UNSUPPORTED_OPERATION`,`screenshot does not resolve input artifacts`)},reserveOutput:async e=>{let t,n;return e?.kind===`path`?n=e.path:(t=await A.mkdtemp(M.join(j.tmpdir(),`agent-device-screenshot-`)),n=M.join(t,`screenshot.png`)),await A.mkdir(M.dirname(n),{recursive:!0}),{path:n,visibility:`client-visible`,publish:async()=>void 0,...t?{cleanup:async()=>{await A.rm(t,{recursive:!0,force:!0})}}:{}}},createTempFile:async e=>{let t=await A.mkdtemp(M.join(j.tmpdir(),`${e.prefix}-`));return{path:M.join(t,`file${e.ext}`),visibility:`internal`,cleanup:async()=>{await A.rm(t,{recursive:!0,force:!0})}}}}}export{V as a,Y as i,$ as n,Z as r,Q as t};
|
|
1
|
+
import{r as e}from"./rolldown-runtime.js";import{R as t,S as n,s as r}from"./sdk-contracts.js";import{At as i,Dt as a,Ot as o,xt as s}from"./tv-remote.js";import{B as c,L as l,w as u}from"./sdk-device.js";import{Ci as d,Nn as f,Xr as p,ai as m,bi as h,en as g,gi as _,mi as v,ni as y,ri as b,xi as x}from"./sdk-batch.js";import{t as ee}from"./session-paths.js";import{t as S}from"./snapshot-state.js";import{n as C}from"./snapshot-runtime-capture-input.js";import{i as te,t as ne}from"./selector-pipeline-policy.js";import{i as re,o as ie,r as ae}from"./png-worker-client.js";import{f as w,i as T,n as E}from"./runtime-session.js";import{t as oe}from"./command-policy.js";import{a as se,i as ce,n as le,t as ue}from"./session-runtime-admission.js";import{t as de}from"./react-native-overlay2.js";import{t as fe}from"./png-size.js";import{r as pe,t as me}from"./screenshot-density.js";import{a as D,o as O,s as k,t as he}from"./screenshot-overlay-draw.js";import{promises as A}from"node:fs";import j from"node:os";import M from"node:path";const N=s.pendingPixelIdentityEvidence,P=[{target:`ios-simulator`,status:`accepted`},{target:`android-emulator`,status:`accepted`},{target:`android-device`,status:`rejected`,rejectionReason:N},{target:`macos-app-window`,status:`rejected`,rejectionReason:N},{target:`ios-physical`,status:`accepted`},{target:`ios-physical-xctest`,status:`rejected`,rejectionReason:N},{target:`ipados-physical`,status:`rejected`,rejectionReason:N},{target:`macos-helper`,status:`rejected`,rejectionReason:N},{target:`web`,status:`rejected`,rejectionReason:N},{target:`linux`,status:`rejected`,rejectionReason:N},{target:`tvos`,status:`rejected`,rejectionReason:N},{target:`harmonyos`,status:`rejected`,rejectionReason:N},{target:`vega`,status:`rejected`,rejectionReason:N}];function F(e,t){switch(e.platform){case`apple`:return I(e,t);case`android`:return e.kind===`device`?`android-device`:`android-emulator`;case`harmonyos`:return`harmonyos`;case`vega`:return`vega`;case`linux`:return`linux`;case`web`:return`web`}}function I(e,t){let n=c(e);switch(n){case`ios`:return e.kind===`device`?e.iosPhysicalDeviceBackend===`xctest`?`ios-physical-xctest`:`ios-physical`:`ios-simulator`;case`ipados`:return e.kind===`device`?`ipados-physical`:`ios-simulator`;case`tvos`:return`tvos`;case`macos`:return L(t);case`watchos`:case`visionos`:throw R(n)}}function L(e){return(e??`app`)===`app`?`macos-app-window`:`macos-helper`}function R(e,n){return new t(`UNSUPPORTED_OPERATION`,`screenshot --crop-on is not accepted on ${e} targets`,{reason:s.targetNotAccepted,...n?{rejectionReason:n}:{}})}function ge(e){if(e.overlayRefs||e.fullscreen)throw new t(`INVALID_ARGS`,`--crop-on cannot be combined with --overlay-refs or --fullscreen: both move the captured frame away from the snapshot viewport the crop is measured against`,{reason:s.frameMismatch});try{f(e.cropOn)}catch{throw new t(`INVALID_ARGS`,`screenshot --crop-on requires a valid selector expression`,{reason:s.selectorInvalid})}let n=F(e.device,e.surface),r=P.find(e=>e.target===n);if(!r||r.status===`rejected`)throw R(n,r?.status===`rejected`?r.rejectionReason:void 0)}function _e(e,t){if(F(e,void 0)===`ios-physical`&&t.iosPhysicalCaptureBackend!==`coredevice`)throw R(`ios-physical-non-coredevice-capture`,N)}async function ve(e,n){if(!ye(n))throw new t(`INVALID_ARGS`,`Screenshot crop box must be positive integer pixel offsets`);let r=await ae(await A.readFile(e),n,`screenshot`);r!==null&&await A.writeFile(e,r)}function ye(e){return Number.isInteger(e.x)&&e.x>=0&&Number.isInteger(e.y)&&e.y>=0&&Number.isInteger(e.width)&&e.width>0&&Number.isInteger(e.height)&&e.height>0}function be(e){switch(e){case`android`:return`device-pixels`;case`xctest`:case`macos-helper`:return`viewport-points`;default:throw new t(`UNSUPPORTED_OPERATION`,`screenshot --crop-on does not accept snapshot backend "${e??`unknown`}"`,{reason:s.targetNotAccepted})}}function z(e,t,n,r,i){if(e===`device-pixels`||t===null)return we(n);let a=r/t.width,o=i/t.height;return{x:Math.round((n.x-t.x)*a),y:Math.round((n.y-t.y)*o),width:Math.round(n.width*a),height:Math.round(n.height*o)}}function xe(e,t,n){return v(e,{x:0,y:0,width:t,height:n})??null}function B(e){let t=null;for(let n of e)!p(n)||!_(n.rect)||(!t||h(n.rect)>h(t))&&(t=n.rect);return t||Se(e.filter(e=>_(e.rect)&&!Ce(e)))}function Se(e){let t=1/0,n=1/0,r=-1/0,i=-1/0;for(let a of e)_(a.rect)&&(t=Math.min(t,a.rect.x),n=Math.min(n,a.rect.y),r=Math.max(r,a.rect.x+a.rect.width),i=Math.max(i,a.rect.y+a.rect.height));return!Number.isFinite(t)||!Number.isFinite(n)||r<=t||i<=n?null:{x:t,y:n,width:r-t,height:i-n}}function Ce(e){return b(e.type??``)===`image`&&!y(e.label)}function we(e){return{x:Math.round(e.x),y:Math.round(e.y),width:Math.round(e.width),height:Math.round(e.height)}}const Te=`${s.partialIntersection}: the selector frame extends past the captured image; the crop was clipped to the image frame`;function Ee(e){return e?.partialIntersection?[Te]:[]}async function De(e){let{device:n,session:r,surface:i,cropOn:a,screenshotPath:o,logPath:c,dispatchContext:l}=e,u={snapshotInteractiveOnly:!1},d=await T({device:n,session:r,flags:u,logPath:c,snapshotScope:void 0,captureData:async()=>await e.captureSnapshot({options:{appBundleId:l.appBundleId,interactiveOnly:!1,includeRects:!0,surface:i},execution:C(l)})}),f=S(d,u);if(f.snapshotQuality?.state===`sparse`)throw new t(`COMMAND_FAILED`,`the snapshot taken for --crop-on was sparse and cannot be read as the screen`,{reason:s.captureUnreadable});let p=await Oe(f.nodes,a,f.truncated,n),m=await fe(o),h=z(be(f.backend),B(f.nodes),p.rect,m.width,m.height),g=xe(h,m.width,m.height);if(g===null)throw new t(`COMMAND_FAILED`,`the frame resolved by --crop-on occupies no pixel of the capture`,{reason:s.emptyIntersection});let _=g.x!==h.x||g.y!==h.y||g.width<h.width||g.height<h.height;return await ve(o,g),{partialIntersection:_}}async function Oe(e,n,r,i){let a=await te(ne.cropTarget,e,n,{platform:l(i)});if(a.kind===`ambiguous`)throw new t(`COMMAND_FAILED`,`--crop-on matched ${a.matchedNodes.length} nodes and must resolve to one`,{reason:s.targetAmbiguous,candidates:a.matchedNodes.map(e=>e.label??e.ref),matches:a.matchedNodes.length});if(a.kind===`none`)throw r?new t(`COMMAND_FAILED`,`the snapshot taken for --crop-on was truncated, so a missing match is not proven`,{reason:s.captureIncomplete}):new t(`COMMAND_FAILED`,`--crop-on matched no node: ${n}`,{reason:s.targetNotFound,hint:`find ${n} list`});return a.node}const ke=[`scroll`,`list`,`recyclerview`,`edittext`,`textfield`];function Ae(e,t,n){if(e.backend!==`android`||!n.hittable||!O(n.rect)||p(n))return!1;let r=b(n.type??``);return!(ke.some(e=>r.includes(e))||t&&k(n.rect)>k(t)*.25)}function je(e,t,n,r){return!e.rect||e.hittable!==!0||n(e)||r(e)?null:Me(e,t,r)}function Me(e,t,n){let r=e.rect,i=Ne(e,t,n);if(!i)return null;let a=i.y-r.y,o=r.y+r.height-(i.y+i.height);if(a<0||o<0||Math.abs(o-a)<16)return null;let s=Math.min(a,o),c=Math.round(i.y-s),l=Math.round(i.height+s*2);return l<=0||l>=r.height?null:{x:r.x,y:c,width:r.width,height:l}}function Ne(e,t,n){let r=e.rect,i=new Map(t.map(e=>[e.index,e])),a=t.filter(t=>t.ref!==e.ref&&Fe(t,e,i)&&Pe(t,n)&&O(t.rect)&&x(r,t.rect)).map(e=>e.rect);return a.length<2?null:d(a)}function Pe(e,t){let n=b(e.type??``);return n.includes(`text`)||n.includes(`image`)&&t(e)}function Fe(e,t,n){let r=e;for(;r.parentIndex!==void 0;){let e=n.get(r.parentIndex);if(!e)return!1;if(e.ref===t.ref)return!0;r=e}return!1}const Ie=[`button`,`link`,`menu`,`tab`,`textfield`,`searchfield`,`securetextfield`,`checkbox`,`radio`,`switch`,`cell`];async function V(e){let t=await A.readFile(e.screenshotPath),n=await re(t,`screenshot`),r=Le(e.snapshot,n.width,n.height,{maxRefs:e.maxRefs});for(let e of r)he(n,e);return await A.writeFile(e.screenshotPath,await ie(n)),r}function Le(e,t,r,i={}){let a=B(e.nodes),o=new Map;for(let n of e.nodes){if(!Be(e,a,n))continue;let i=Ve(e.nodes,n);if(!i?.ref||!i.rect||!O(i.rect))continue;let s=He(n,i,e.nodes),c=Ue(n,i,s),l=H(e,a,ze(e,i,e.nodes),t,r);if(!O(l))continue;let u=o.get(i.ref);(!u||c>u.score)&&o.set(i.ref,{ref:i.ref,label:s,rect:i.rect,overlayRect:l,score:c})}return Re(e,a,o,t,r),We([...o.values()]).sort(et).slice(0,i.maxRefs??24).sort(J).map(e=>({ref:e.ref,label:e.label,rect:e.rect,overlayRect:e.overlayRect,center:n(e.overlayRect)}))}function Re(e,t,n,r,i){let a=de(e.nodes).primaryAction;if(!a?.ref||!a.rect||!O(a.rect))return;let o=H(e,t,a.rect,r,i);if(!O(o))return;let s={ref:a.ref,label:a.label,rect:a.rect,overlayRect:o,score:100},c=n.get(a.ref);n.set(a.ref,c?{...c,score:Math.max(c.score,s.score)}:s)}function ze(e,t,n){return e.backend===`android`?je(t,n,U,e=>!!q(e))??t.rect:t.rect}function Be(e,t,n){let r=[n.label,n.value].some(G)||K(n.identifier);return Ae(e,t,n)?!0:U(n)?r:r&&Ge(n)}function Ve(e,t){return[W(t)?t:null,m(e,t,W),t.hittable?t:null,m(e,t,e=>e.hittable===!0)].find(Ke)??null}function He(e,t,n){let r=q(e);return e.ref!==t.ref&&r?r:qe(t,n)||q(t)}function Ue(e,t,n){let r=0;return e.ref===t.ref&&(r+=4),t.hittable&&(r+=3),U(t)&&(r+=3),U(e)&&(r+=2),n&&(r+=2),K(t.identifier)&&(r+=1),y(t.value)&&(r+=1),r}function We(e){let t=[];for(let n of e.sort((e,t)=>k(e.overlayRect)-k(t.overlayRect))){let e=t.findIndex(e=>e.label!==void 0&&e.label===n.label&&(x(e.overlayRect,n.overlayRect)||x(n.overlayRect,e.overlayRect)));if(e===-1){t.push(n);continue}k(n.overlayRect)<k(t[e].overlayRect)&&(t[e]=n)}return t}function H(e,t,n,r,i){return $e(z(e.backend===`android`?`device-pixels`:`viewport-points`,t,n,r,i),r,i)}function U(e){let t=[e.type,e.role,e.subrole].map(e=>b(e??``)).join(` `);return Ie.some(e=>t.includes(e))}function W(e){return U(e)&&!p(e)}function Ge(e){let t=b(e.type??``);return t.includes(`statictext`)||t.includes(`image`)||t.includes(`text`)||t.includes(`other`)}function Ke(e){return!!(e?.rect&&O(e.rect)&&!p(e))}function G(e){return y(e)?!Xe(e):!1}function K(e){return typeof e!=`string`||!G(e)?!1:!Ze(e)}function q(e){let t=[e.label,e.value].find(G);if(t)return t.trim();if(K(e.identifier))return e.identifier.trim()}function qe(e,t){let n=null;for(let r of t){if(r.ref===e.ref||!Je(r,e,t))continue;let i=q(r);if(!i)continue;let a=Ye(r);(!n||a>n.score)&&(n={label:i,score:a})}return n?.label}function Je(e,t,n){let r=e;for(;r.parentIndex!==void 0;){let e=n[r.parentIndex];if(!e)return!1;if(e.ref===t.ref)return!0;r=e}return!1}function Ye(e){let t=0;return b(e.type??``).includes(`text`)&&(t+=2),G(e.label)&&(t+=2),G(e.value)&&(t+=1),t}function Xe(e){let t=e?.trim().toLowerCase();return t===`toolbar`||t===`window`||t===`application`||t?.startsWith(`vertical scroll bar`)===!0}function Ze(e){return/^[a-z0-9_.]+:id\/[a-z0-9_.-]+$/i.test(e.trim())}function Qe(e,t){return Number.parseInt(e.replace(/^\D+/,``),10)-Number.parseInt(t.replace(/^\D+/,``),10)}function $e(e,t,n){let r=D(e.x,0,Math.max(0,t-1)),i=D(e.y,0,Math.max(0,n-1)),a=Math.max(1,t-r),o=Math.max(1,n-i);return{x:r,y:i,width:D(e.width,1,a),height:D(e.height,1,o)}}function J(e,t){let n=e.overlayRect.y-t.overlayRect.y;if(n!==0)return n;let r=e.overlayRect.x-t.overlayRect.x;return r===0?Qe(e.ref,t.ref):r}function et(e,t){return t.score===e.score?J(e,t):t.score-e.score}async function Y(e){let t=g({overlayRefs:e.overlayRefs,cropOn:e.cropOn!==void 0}),n=await ue({device:e.device,plan:t,inspectFacts:e.inspectFacts});return n.admitted?{ok:!0,runtime:await tt(e.bindDevice,n)}:{ok:!1,response:rt(t.kind,n.operation,n.fact)}}async function tt(e,t){let n=le(e),{device:r,plan:i}=se(t);switch(i.kind){case`capture`:{let e=await n(r,i.use);return Object.freeze({captureScreenshot:X(e)})}case`capture-with-overlay-refs`:case`capture-with-crop-on`:{let e=await n(r,i.use);return Object.freeze({captureScreenshot:X(e),captureSnapshot:nt(e)})}}}function X(e){return async t=>await e.operations.captureScreenshot(t)}function nt(e){return async t=>await e.operations.captureSnapshot(t)}function rt(e,t,n){return t===`captureScreenshot`?ce(`screenshot`,n):e===`capture-with-crop-on`?r(`UNSUPPORTED_OPERATION`,`--crop-on crops the capture to a selector frame using a snapshot taken on the same screen, which this target cannot capture.`,{reason:n.available?void 0:n.reason},{hint:(n.available?void 0:n.hint)??`Re-run screenshot without --crop-on.`}):r(`UNSUPPORTED_OPERATION`,`--overlay-refs annotates a capture with the refs of a snapshot taken on the same screen, which this target cannot capture.`,{reason:n.available?void 0:n.reason},{hint:(n.available?void 0:n.hint)??`Re-run screenshot without --overlay-refs.`})}var Z=e({captureScreenshotArtifact:()=>Q,resolveScreenshotGenericExecution:()=>it,screenshotExecutionFromContext:()=>$});async function it(e){let{req:n,session:r}=e,i=a(`screenshot`,n.flags);if(i)throw new t(`INVALID_ARGS`,i);me(r.device,n.flags?.screenshotPixelDensity);let o=lt(n,e.hostCwd),s=typeof n.flags?.screenshotCropOn==`string`&&n.flags.screenshotCropOn.length>0?n.flags.screenshotCropOn:void 0;s!==void 0&&ge({device:r.device,surface:r.surface,cropOn:s,overlayRefs:n.flags?.overlayRefs===!0,fullscreen:n.flags?.screenshotFullscreen===!0});let c=await Y({device:r.device,overlayRefs:n.flags?.overlayRefs===!0,cropOn:s,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});if(!c.ok)return c;let l=c.runtime,u={warnings:[]},{createCommandSurface:d}=e;return{ok:!0,recorded:o.recorded,execute:async e=>await at({createCommandSurface:d,session:e.session,sessionName:e.sessionName,logPath:e.logPath,dispatchContext:e.dispatchContext,flags:e.request.flags,outPath:o.outPath,runtime:l,cropOn:s,cropRun:u})}}async function Q(e){let{session:t,sessionName:n,outPath:r,dispatchContext:a}=e;return await(await e.createCommandSurface({backend:ut(e),artifacts:dt(),sessions:E(n,t),policy:oe()})).capture.screenshot({session:n,requestId:a.requestId,appBundleId:t.appBundleId,...i(a),surface:t.surface,...r?{out:{kind:`path`,path:r}}:{}})}function $(e){return C(e)}async function at(e){let{session:t,runtime:n,flags:r}=e,i=ot({cropOn:e.cropOn,captureSnapshot:n.captureSnapshot,cropRun:e.cropRun,logPath:e.logPath}),a=await Q({createCommandSurface:e.createCommandSurface,session:t,sessionName:e.sessionName,outPath:e.outPath,dispatchContext:e.dispatchContext,captureScreenshot:n.captureScreenshot,...i?{crop:i}:{}}),o=[...a.warnings??[],...i?.run?.warnings??[]];return{...a,...o.length>0?{warnings:o}:{},...await st({session:t,cropOn:e.cropOn,captureSnapshot:n.captureSnapshot,screenshotPath:a.path,logPath:e.logPath,dispatchContext:e.dispatchContext}),...await pe({device:t.device,path:a.path,requestedPixelDensity:r?.screenshotPixelDensity,scale:r?.screenshotScale})}}function ot(e){let{cropOn:t,captureSnapshot:n,cropRun:r}=e;if(t!==void 0&&n!==void 0&&r!==void 0)return{cropOn:t,captureSnapshot:n,run:r,logPath:e.logPath}}async function st(e){let{session:t,cropOn:n,captureSnapshot:r}=e;return n!==void 0||r===void 0?{}:{overlayRefs:await ct({session:t,logPath:e.logPath,screenshotPath:e.screenshotPath,dispatchContext:e.dispatchContext,captureSnapshot:r})}}async function ct(e){let{session:t,dispatchContext:n}=e,r={snapshotInteractiveOnly:!0},i=await T({device:t.device,session:t,flags:r,logPath:e.logPath,snapshotScope:void 0,captureData:async()=>await e.captureSnapshot({options:{appBundleId:t.appBundleId,interactiveOnly:!0,surface:t.surface},execution:$(n)})}),a=S(i,r);return w(t,a),await V({screenshotPath:e.screenshotPath,snapshot:a})}function lt(e,t){let n=e.positionals??[],r=e.flags??{},i=n=>n===void 0?void 0:ee(n,e.meta?.cwd??t),a=i(n[0]),o=i(r.out);return{outPath:a??o,recorded:{positionals:a?[a,...n.slice(1)]:n,flags:o?{...r,out:o}:r}}}function ut(e){let{session:t,dispatchContext:n,captureScreenshot:r,crop:a}=e;return{platform:l(t.device),captureScreenshot:async(e,s,c)=>{let l=i({...n,...o(c)}),d=await r({outPath:s,options:{appBundleId:n.appBundleId,pixelDensity:l.pixelDensity,fullscreen:l.fullscreen,normalizeStatusBar:l.normalizeStatusBar,stabilize:l.stabilize,surface:c?.surface,skipIosSimulatorBootCheck:n.skipIosSimulatorBootCheck??(u(t.device)&&t.device.kind===`simulator`),captureBackend:n.screenshotCaptureBackend},execution:$(n)});if(a){_e(t.device,d);let e=await De({device:t.device,session:t,surface:t.surface,cropOn:a.cropOn,screenshotPath:s,logPath:a.logPath,dispatchContext:n,captureSnapshot:a.captureSnapshot});a.run.warnings.push(...Ee(e))}return d.displayRotation?{displayRotation:d.displayRotation}:void 0}}}function dt(){return{resolveInput:async()=>{throw new t(`UNSUPPORTED_OPERATION`,`screenshot does not resolve input artifacts`)},reserveOutput:async e=>{let t,n;return e?.kind===`path`?n=e.path:(t=await A.mkdtemp(M.join(j.tmpdir(),`agent-device-screenshot-`)),n=M.join(t,`screenshot.png`)),await A.mkdir(M.dirname(n),{recursive:!0}),{path:n,visibility:`client-visible`,publish:async()=>void 0,...t?{cleanup:async()=>{await A.rm(t,{recursive:!0,force:!0})}}:{}}},createTempFile:async e=>{let t=await A.mkdtemp(M.join(j.tmpdir(),`${e.prefix}-`));return{path:M.join(t,`file${e.ext}`),visibility:`internal`,cleanup:async()=>{await A.rm(t,{recursive:!0,force:!0})}}}}}export{V as a,Y as i,$ as n,Z as r,Q as t};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{R as e,V as t,c as n,f as r,o as i}from"./sdk-contracts.js";import{S as a,a as o,n as s,o as c,r as l}from"./sdk-batch.js";function u(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function d(t,n,r,i){let a=r(t[n]);if(a===void 0)throw new e(`COMMAND_FAILED`,i,{response:t});return a}function f(e,t,n){return n(e[t])}function
|
|
2
|
-
`).map(e=>e.trim()).filter(e=>e.length>0)}function F(t,n,r={}){let i=t[n];if(i===void 0)return;if(!Number.isInteger(i))throw new e(`INVALID_ARGS`,`Expected ${n} to be an integer.`);let a=i;if(r.min!==void 0&&a<r.min)throw new e(`INVALID_ARGS`,`Expected ${n} to be at least ${r.min}.`);if(r.max!==void 0&&a>r.max)throw new e(`INVALID_ARGS`,`Expected ${n} to be at most ${r.max}.`);return a}function I(t,n,r={}){let i=t[n];if(i!==void 0){if(typeof i!=`number`||!Number.isFinite(i))throw new e(`INVALID_ARGS`,`Expected ${n} to be a finite number.`);if(r.min!==void 0&&i<r.min)throw new e(`INVALID_ARGS`,`Expected ${n} to be at least ${r.min}.`);if(r.max!==void 0&&i>r.max)throw new e(`INVALID_ARGS`,`Expected ${n} to be at most ${r.max}.`);return i}}const L=`android_shell_text_unsupported`;function R(e){return Number.isInteger(e)&&e>=1&&e<=1e3}function z(t,n){if(t>n)throw new e(`INVALID_ARGS`,`batch has ${t} steps; max allowed is ${n}.`)}const B=`Each batch step is {"command":"<name>","input":{...}}, where input is that command's own structured input object, keyed by field name. There is no positional step form: args, argv, positionals, and flags are not step fields.`;function
|
|
1
|
+
import{R as e,V as t,c as n,f as r,o as i}from"./sdk-contracts.js";import{S as a,a as o,n as s,o as c,r as l}from"./sdk-batch.js";function u(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function d(t,n,r,i){let a=r(t[n]);if(a===void 0)throw new e(`COMMAND_FAILED`,i,{response:t});return a}function f(e,t,n){return n(e[t])}function p(e,t,n){let r=e[t];return r===null?null:n(r)}function ee(e,t){return d(e,t,T,`Daemon response is missing "${t}".`)}function te(e,t){return f(e,t,T)}function ne(e,t){return p(e,t,T)}function m(e,t){return d(e,t,E,`Daemon response is missing numeric "${t}".`)}function h(e,t){return d(e,t,D,`Daemon response has invalid "${t}".`)}function g(e,t){return d(e,t,O,`Daemon response has invalid "${t}".`)}function _(e,t){return f(e,t,k)??`mobile`}function v(e){if(!j(e))return;let t=w(e,`x`),n=w(e,`y`),r=w(e,`width`),i=w(e,`height`);if(t!==void 0&&n!==void 0&&r!==void 0&&i!==void 0)return{x:t,y:n,width:r,height:i}}function y(e){if(e!==void 0)return j(e)?e.kind===`absent`?{kind:`absent`}:e.kind===`unmeasurable`?typeof e.reason==`string`&&e.reason.trim().length>0?{kind:`unmeasurable`,reason:e.reason}:{kind:`unmeasurable`,reason:`unreported-reason`}:e.kind===`tree-rejected`?b(e):e.kind===`visibility-only`?typeof e.visible==`boolean`?{kind:`visibility-only`,visible:e.visible}:{kind:`unmeasurable`,reason:`invalid-visibility-probe`}:e.kind===`derived`&&e.derivation!==`docked-tree`?{kind:`unmeasurable`,reason:`unrecognized-derivation`}:e.kind===`visible`||e.kind===`derived`?x(e.frame,e.kind):{kind:`unmeasurable`,reason:`unrecognized-kind`}:{kind:`unmeasurable`,reason:`malformed-fact`}}function b(e){return e.derivation===`docked-tree`?e.visible!==void 0&&typeof e.visible!=`boolean`?{kind:`unmeasurable`,reason:`invalid-visibility-probe`}:{kind:`tree-rejected`,derivation:`docked-tree`,...typeof e.visible==`boolean`?{visible:e.visible}:{}}:{kind:`unmeasurable`,reason:`unrecognized-derivation`}}function x(e,t){let n=v(e);return n!==void 0&&[n.x,n.y,n.width,n.height].every(Number.isFinite)&&n.width>0&&n.height>0?t===`derived`?{kind:`derived`,derivation:`docked-tree`,frame:n}:{kind:`visible`,frame:n}:{kind:`unmeasurable`,reason:`invalid-${t}-frame`}}const S={presented:`presented`,absent:`absent`,unknown:`unknown`},C=`presentedSurface`;function re(e){if(!Object.hasOwn(e,C))return;let t=e[C];return typeof t==`string`&&Object.hasOwn(S,t)?S[t]:`unknown`}function ie(e){if(!j(e))return;let t=w(e,`x`),n=w(e,`y`);if(t!==void 0&&n!==void 0)return{x:t,y:n}}function w(e,t){let n=e[t];return typeof n==`number`?n:void 0}function T(e){return typeof e==`string`&&e.length>0?e:void 0}function E(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function D(e){return e===`apple`?`ios`:e===`ios`||e===`macos`||e===`android`||e===`harmonyos`||e===`vega`||e===`linux`||e===`web`?e:void 0}function O(e){return e===`simulator`||e===`emulator`||e===`device`?e:void 0}function k(e){return e===`tv`||e===`mobile`||e===`desktop`?e:void 0}function A(t){if(!j(t))throw new e(`COMMAND_FAILED`,`Daemon returned an unexpected response shape.`,{value:t});return t}function j(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function M(e){return j(e)?e:void 0}function N(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function P(e){return e.split(`
|
|
2
|
+
`).map(e=>e.trim()).filter(e=>e.length>0)}function F(t,n,r={}){let i=t[n];if(i===void 0)return;if(!Number.isInteger(i))throw new e(`INVALID_ARGS`,`Expected ${n} to be an integer.`);let a=i;if(r.min!==void 0&&a<r.min)throw new e(`INVALID_ARGS`,`Expected ${n} to be at least ${r.min}.`);if(r.max!==void 0&&a>r.max)throw new e(`INVALID_ARGS`,`Expected ${n} to be at most ${r.max}.`);return a}function I(t,n,r={}){let i=t[n];if(i!==void 0){if(typeof i!=`number`||!Number.isFinite(i))throw new e(`INVALID_ARGS`,`Expected ${n} to be a finite number.`);if(r.min!==void 0&&i<r.min)throw new e(`INVALID_ARGS`,`Expected ${n} to be at least ${r.min}.`);if(r.max!==void 0&&i>r.max)throw new e(`INVALID_ARGS`,`Expected ${n} to be at most ${r.max}.`);return i}}const L=`android_shell_text_unsupported`;function R(e){return Number.isInteger(e)&&e>=1&&e<=1e3}function z(t,n){if(t>n)throw new e(`INVALID_ARGS`,`batch has ${t} steps; max allowed is ${n}.`)}const B=`Each batch step is {"command":"<name>","input":{...}}, where input is that command's own structured input object, keyed by field name. There is no positional step form: args, argv, positionals, and flags are not step fields.`;function ae(t,n,r=B){if(!u(t))throw new e(`INVALID_ARGS`,`Invalid batch step ${n}.`,{hint:r});return t}function V(t,n,r=B){let i=t.input;if(!u(i))throw new e(`INVALID_ARGS`,`Batch step ${n} input must be an object.`,{hint:r});return i}function H(t,n){if(t!==void 0)try{return i.parse(t)}catch(t){throw new e(`INVALID_ARGS`,`Batch step ${n} runtime is invalid: ${t instanceof Error?t.message:String(t)}`)}}function U(e){let t=e.trim();if(!t||/\s/.test(t))return!1;let n=/^([A-Za-z][A-Za-z0-9+.-]*):(.+)$/.exec(t);if(!n)return!1;let r=n[1]?.toLowerCase(),i=n[2]??``;return r===`http`||r===`https`||r===`ws`||r===`wss`||r===`ftp`||r===`ftps`?i.startsWith(`//`):!0}function W(e){let t=e.trim().split(`:`)[0]?.toLowerCase();return t===`http`||t===`https`}const G=`com.apple.mobilesafari`;function K(e,t){let n=e?.trim();if(n)return n;if(W(t))return G}const q=new Set(s);async function J(e,n,r){let i=Q(e.flags),a=i?.batchOnError??`stop`;if(a!==`stop`)return $(`INVALID_ARGS`,`Unsupported batch on-error mode: ${a}.`);let o=i?.batchMaxSteps??100;if(!R(o))return $(`INVALID_ARGS`,`Invalid batch max-steps: ${String(i?.batchMaxSteps)}`);try{let t=Y(i?.batchSteps,o),a=Date.now(),s=[];for(let[i,a]of t.entries()){let o=await Z(e,n,a,r,{stepNumber:i+1,totalSteps:t.length,remainingSteps:t.slice(i+1).map(e=>({command:e.command,positionals:e.positionals,flags:e.flags,...e.input===void 0?{}:{input:e.input}}))});if(!o.ok)return oe(o,a,{executedSteps:t.slice(0,i),total:t.length,partialResults:s});s.push(o.result)}return{ok:!0,data:{total:t.length,executed:t.length,totalDurationMs:Date.now()-a,results:s}}}catch(e){let n=t(e);return $(n.code,n.message,n.details)}}function oe(e,t,n){let{error:r}=e;return{ok:!1,error:{code:r.code,message:`Batch failed at step ${e.step} (${t.command}): ${r.message}`,hint:r.hint,diagnosticId:r.diagnosticId,logPath:r.logPath,...r.retriable===void 0?{}:{retriable:r.retriable},...r.supportedOn===void 0?{}:{supportedOn:r.supportedOn},details:{...r.details??{},...n.executedSteps.some(se)&&(r.details?.reason!==`bounded_composite_resource_unsupported`||r.details.dispatched!==`no`)?{dispatched:`unknown`}:{},step:e.step,command:t.command,positionals:t.positionals,executed:n.executedSteps.length,total:n.total,partialResults:n.partialResults}}}}function se(e){return a(e)!==`observes-app`}function Y(t,n){if(!Array.isArray(t)||t.length===0)throw new e(`INVALID_ARGS`,`batch requires a non-empty batchSteps array.`);z(t.length,n);let r=[];for(let n=0;n<t.length;n+=1){let i=t[n];if(!j(i))throw new e(`INVALID_ARGS`,`Invalid batch step at index ${n}.`);let a=Object.keys(i).filter(e=>!q.has(e));if(a.length>0){let t=a.map(e=>`"${e}"`).join(`, `);throw new e(`INVALID_ARGS`,`Batch step ${n+1} has unknown field(s): ${t}. Allowed fields: command, positionals, input, flags, runtime.`)}let s=c(i.command);if(!s)throw new e(`INVALID_ARGS`,`Batch step ${n+1} requires command.`);if(o(s,n+1),i.positionals!==void 0&&!Array.isArray(i.positionals))throw new e(`INVALID_ARGS`,`Batch step ${n+1} positionals must be an array.`);let l=i.positionals??[];if(l.some(e=>typeof e!=`string`))throw new e(`INVALID_ARGS`,`Batch step ${n+1} positionals must contain only strings.`);if(i.flags!==void 0&&!j(i.flags))throw new e(`INVALID_ARGS`,`Batch step ${n+1} flags must be an object.`);if(ce(i.flags,n+1),i.input!==void 0&&!j(i.input))throw new e(`INVALID_ARGS`,`Batch step ${n+1} input must be an object.`);r.push({command:s,positionals:l,input:i.input,flags:i.flags??{},runtime:H(i.runtime,n+1)})}return r}function ce(t,n){if(t?.textStdin===!0)throw new e(`INVALID_ARGS`,`Batch step ${n}: fill textStdin is not supported because batch steps have no stdin of their own.`,{reason:`fill_text_stdin_in_batch`})}function le(e,t){let{batchSteps:n,batchOnError:r,batchMaxSteps:i,...a}=t??{};return X(Q(e),a)}function X(e,t){let n=Q(e)??{},r=t;for(let e of l)r[e]===void 0&&n[e]!==void 0&&(r[e]=n[e]);return t}function ue(e,t){return n(e)?t?e:`digest`:e}function de(e,t){let n=e?.responseLevel,r=ue(n,t);return r===n?e:{...e,responseLevel:r}}async function Z(e,t,n,i,a){let{stepNumber:o,totalSteps:s}=a,c=o===s,l=Date.now(),u=le(e.flags,n.flags);u.session===void 0&&r(e)&&(u.session=t);let d=await i({token:e.token,session:t,command:n.command,positionals:n.positionals,input:n.input,flags:u,runtime:n.runtime===void 0?e.runtime:n.runtime,meta:de(e.meta,c)},a),f=Date.now()-l;return d.ok?{ok:!0,step:o,result:{step:o,command:n.command,ok:!0,data:d.data??{},durationMs:f}}:{ok:!1,step:o,error:d.error}}function Q(e){return e}function $(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{details:n}:{}}}}export{y as A,ne as C,m as D,g as E,N as M,u as N,h as O,_ as S,re as T,M as _,U as a,ie as b,B as c,H as d,V as f,I as g,F as h,G as i,P as j,ee as k,z as l,L as m,J as n,W as o,ae as p,Y as r,K as s,X as t,R as u,A as v,te as w,v as x,j as y};
|