agent-device 0.17.7 → 0.17.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -0
- package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.17.7.apk → agent-device-android-multitouch-helper-0.17.9.apk} +0 -0
- package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.17.9.apk.sha256 +1 -0
- package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.17.7.manifest.json → agent-device-android-multitouch-helper-0.17.9.manifest.json} +4 -4
- package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.17.7.apk → agent-device-android-snapshot-helper-0.17.9.apk} +0 -0
- package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.17.9.apk.sha256 +1 -0
- package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.17.7.manifest.json → agent-device-android-snapshot-helper-0.17.9.manifest.json} +6 -6
- package/dist/src/1404.js +1 -0
- package/dist/src/2133.js +1 -1
- package/dist/src/2577.js +1 -0
- package/dist/src/2948.js +30 -1
- package/dist/src/4428.js +1 -1
- package/dist/src/587.js +1 -1
- package/dist/src/7394.js +5 -5
- package/dist/src/8184.js +1 -1
- package/dist/src/8358.js +4 -0
- package/dist/src/9581.js +13 -2
- package/dist/src/9722.js +36 -36
- package/dist/src/9836.js +1 -1
- package/dist/src/9919.js +5 -5
- package/dist/src/android.js +3 -3
- package/dist/src/apple.js +1 -1
- package/dist/src/apps.js +1 -1
- package/dist/src/cli-help.js +25 -7
- package/dist/src/cli-output.js +1 -4
- package/dist/src/cli.js +28 -18
- package/dist/src/command-surface.js +1 -1
- package/dist/src/find.js +1 -1
- package/dist/src/generic.js +5 -5
- package/dist/src/index.d.ts +12 -0
- package/dist/src/input-actions.js +1 -1
- package/dist/src/input-actions~1.js +1 -1
- package/dist/src/interaction.js +1 -1
- package/dist/src/internal/bin.js +1 -1
- package/dist/src/react-native.js +1 -1
- package/dist/src/record-trace-recording.js +1 -1
- package/dist/src/selector-runtime.js +1 -1
- package/dist/src/selectors.js +1 -1
- package/dist/src/server.js +1 -1
- package/dist/src/session.js +7 -7
- package/dist/src/snapshot.js +1 -1
- package/dist/src/web.js +1 -1
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +92 -4
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandJournal.swift +1 -1
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +130 -0
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +4 -2
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScrollGesture.swift +18 -0
- package/package.json +3 -3
- package/server.json +2 -2
- package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.17.7.apk.sha256 +0 -1
- package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.17.7.apk.sha256 +0 -1
- package/dist/src/2892.js +0 -4
- package/dist/src/368.js +0 -1
- package/dist/src/6311.js +0 -27
- package/dist/src/7244.js +0 -1
- package/dist/src/9873.js +0 -1
package/dist/src/4428.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import e from"node:fs";import{parseAllDocuments as t,stringify as n}from"yaml";import{AppError as r}from"./733.js";import{recordingQualityInputToExportQuality as i,readScreenshotScriptFlag as o,MAESTRO_COMPAT_TRACKER_URL as s,MAESTRO_NEW_ISSUE_URL as l}from"./
|
|
1
|
+
import e from"node:fs";import{parseAllDocuments as t,stringify as n}from"yaml";import{AppError as r}from"./733.js";import{recordingQualityInputToExportQuality as i,readScreenshotScriptFlag as o,MAESTRO_COMPAT_TRACKER_URL as s,MAESTRO_NEW_ISSUE_URL as l}from"./2948.js";import{formatScriptStringLiteral as a,parseReplayOpenFlags as u,formatPortableActionLine as f,parseReplaySeriesFlags as c,parseReplayRuntimeFlags as p,isClickLikeCommand as h}from"./2577.js";let d=/^[A-Z_][A-Z0-9_]*$/,m=/(\\\$\{)|\$\{([A-Za-z_][A-Za-z0-9_.]*)(?::-((?:[^}\\]|\\.)*))?\}/g,g="AD_VAR_";function A(e){return e.startsWith("AD_")}function v(e){return new r("INVALID_ARGS",`The AD_* namespace is reserved for built-in variables. Rename ${e} to avoid the AD_ prefix.`)}function y(e){let t={};if(e.builtins)for(let[n,r]of Object.entries(e.builtins))t[n]=r;for(let n of[e.fileEnv,e.shellEnv,e.cliEnv])if(n)for(let[e,r]of Object.entries(n)){if(A(e))throw v(e);t[e]=r}return{values:t}}function w(e,t){Object.assign(e.values,t)}function b(e){let t={};for(let[n,r]of Object.entries(e)){if("string"!=typeof r||!n.startsWith(g))continue;let e=n.slice(g.length);0!==e.length&&d.test(e)&&(A(e)||(t[e]=r))}return t}function I(e){let t={};for(let n of e){let e=n.indexOf("=");if(e<=0)throw new r("INVALID_ARGS",`Invalid -e entry "${n}": expected KEY=VALUE.`);let i=n.slice(0,e);if(!d.test(i))throw new r("INVALID_ARGS",`Invalid -e key "${i}": keys must be uppercase letters, digits, and underscores (e.g. APP_ID).`);if(A(i))throw v(i);t[i]=n.slice(e+1)}return t}function $(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e):[]}function S(e){if(e&&"object"==typeof e&&!Array.isArray(e)){let t={};for(let[n,r]of Object.entries(e))"string"==typeof r&&(t[n]=r);return t}return process.env}function _(e,t,n){return e.replace(m,(e,i,o,s)=>{if(i)return"${";if(!o)return e;if(Object.prototype.hasOwnProperty.call(t.values,o))return String(t.values[o]);if(void 0!==s)return s.replace(/\\(.)/g,"$1");throw new r("INVALID_ARGS",`Unresolved variable \${${o}} at ${n.file}:${n.line}.`)})}function N(e,t,n){return{...e,positionals:(e.positionals??[]).map(e=>_(e,t,n)),flags:R(e.flags,t,n)??{},runtime:R(e.runtime,t,n),replayControl:function(e,t,n){if(!e)return e;if(e.kind==="maestroRunFlowWhen"){return{...e,selector:_(e.selector,t,n)}}return e}(e.replayControl,t,n)}}function R(e,t,n){return e?function e(t,n,r){return"string"==typeof t?_(t,n,r):Array.isArray(t)?t.map(t=>e(t,n,r)):t&&"object"==typeof t?Object.fromEntries(Object.entries(t).map(([t,i])=>[t,e(i,n,r)])):t}(e,t,n):e}let D=new Set(["ios","android","macos","linux"]),M=new Set(["mobile","tv","desktop"]);function x(e){let t=[],n=[],s=e.split(/\r?\n/),l=!1;for(let[e,a]of s.entries()){let s=a.trim();if(0===s.length||s.startsWith("#"))continue;if(L(s)){if(l)throw new r("INVALID_ARGS",`env directives must precede all actions (line ${e+1}).`);continue}let f=function(e){let t=e.trim();if(0===t.length||t.startsWith("#"))return null;let[n,...s]=function(e){let t=[],n=0;for(;n<e.length&&!((n=function(e,t){let n=t;for(;n<e.length&&/\s/.test(e.charAt(n));)n+=1;return n}(e,n))>=e.length);){let i='"'===e[n]?function(e,t){let n=!1,i=t+1;for(;i<e.length;i+=1){let t=e.charAt(i);if('"'===t&&!n)break;if(n){n=!1;continue}n="\\"===t}if(i>=e.length)throw new r("INVALID_ARGS",`Invalid replay script line: ${e}`);return{value:JSON.parse(e.slice(t,i+1)),nextCursor:i+1}}(e,n):function(e,t){let n=t;for(;n<e.length&&!/\s/.test(e.charAt(n));)n+=1;return{value:e.slice(t,n),nextCursor:n}}(e,n);t.push(i.value),n=i.nextCursor}return t}(t);if(void 0===n||"context"===n)return null;let l={ts:Date.now(),command:n,positionals:[],flags:{}};if("snapshot"===n){l.positionals=[];for(let e=0;e<s.length;e+=1){let t=s[e];if("-i"===t){l.flags.snapshotInteractiveOnly=!0;continue}if("-c"!==t){if("--raw"===t){l.flags.snapshotRaw=!0;continue}if("--force-full"===t){l.flags.snapshotForceFull=!0;continue}if(("-d"===t||"--depth"===t)&&e+1<s.length){let t=Number(s[e+1]);Number.isFinite(t)&&t>=0&&(l.flags.snapshotDepth=Math.floor(t)),e+=1;continue}if(("-s"===t||"--scope"===t)&&e+1<s.length){l.flags.snapshotScope=s[e+1],e+=1;continue}if("--backend"===t&&e+1<s.length){e+=1;continue}}}return l}if("open"===n){let e=u(s);return l.positionals=e.positionals,Object.assign(l.flags,e.flags),l.runtime=e.runtime,l}if("runtime"===n){let e=p(s);return l.positionals=e.positionals,Object.assign(l.flags,e.flags),l}if(h(n)){let e=c(n,s);Object.assign(l.flags,e.flags);let t=e.positionals[0];if(void 0===t)return l;if(t.startsWith("@"))return l.positionals=[t],e.positionals[1]&&(l.result={refLabel:e.positionals[1]}),l;let r=e.positionals[0],i=e.positionals[1];return V(r)&&V(i)&&e.positionals.length>=2?l.positionals=[r,i]:l.positionals=[e.positionals.join(" ")],l}if("fill"===n){let e=c(n,s);if(Object.assign(l.flags,e.flags),!(e.positionals.length>=2))return l.positionals=e.positionals,l;let[t,r,...i]=e.positionals;return t.startsWith("@")?(i.length>0?(l.positionals=[t,i.join(" ")],l.result={refLabel:r}):l.positionals=[t,r],l):(l.positionals=[t,[r,...i].join(" ")],l)}if("get"===n){let e=s[0],t=s[1];return void 0===e||void 0===t?l.positionals=s:t.startsWith("@")?(l.positionals=[e,t],s[2]&&(l.result={refLabel:s[2]})):l.positionals=[e,s.slice(1).join(" ")],l}if("swipe"===n||"type"===n){let e=c(n,s);return Object.assign(l.flags,e.flags),l.positionals=e.positionals,l}if("record"===n){let e=[];for(let t=0;t<s.length;t+=1){let n=s[t];if("--hide-touches"===n){l.flags.hideTouches=!0;continue}if("--fps"===n&&t+1<s.length){let e=Number(s[t+1]);Number.isFinite(e)&&(l.flags.fps=Math.floor(e)),t+=1;continue}if("--quality"===n&&t+1<s.length){let e=i(s[t+1]);void 0!==e&&(l.flags.quality=e),t+=1;continue}if("--max-size"===n&&t+1<s.length){let e=Number(s[t+1]);Number.isFinite(e)&&(l.flags.screenshotMaxSize=Math.floor(e)),t+=1;continue}e.push(n)}return l.positionals=e,l}if("screenshot"===n){let e=[];for(let t=0;t<s.length;t+=1){let n=s[t],r=o({args:s,index:t,flags:l.flags});if(r.handled){t=r.nextIndex;continue}e.push(n)}return l.positionals=e,l}return l.positionals=s,l}(a);f&&(t.push(f),n.push(e+1),l=!0)}return{actions:t,actionLines:n}}function O(e){let t=e.split(/\r?\n/),n={};for(let[e,i]of t.entries()){let t=i.trim();if(0===t.length||t.startsWith("#"))continue;if(L(t)){!function(e,t,n){let{key:i,value:o}=function(e,t){let n=e.slice(3).replace(/^[\s]+/,""),i=n.indexOf("=");if(i<=0)throw new r("INVALID_ARGS",`Invalid env directive on line ${t}: expected "env KEY=VALUE".`);let o=n.slice(0,i);if(!d.test(o))throw new r("INVALID_ARGS",`Invalid env key "${o}" on line ${t}: keys must be uppercase letters, digits, and underscores (e.g. APP_ID).`);if(o.startsWith("AD_"))throw new r("INVALID_ARGS",`Invalid env key "${o}" on line ${t}: the AD_* namespace is reserved for built-in variables. Rename ${o} to avoid the AD_ prefix.`);return{key:o,value:function(e,t){if(0===e.length)return"";if(e.startsWith('"'))try{let t=JSON.parse(e);if("string"!=typeof t)throw Error("not a string literal");return t}catch{throw new r("INVALID_ARGS",`Invalid quoted env value on line ${t}.`)}return e}(n.slice(i+1),t)}}(t,n),s=e.env??{};if(Object.prototype.hasOwnProperty.call(s,i))throw new r("INVALID_ARGS",`Duplicate env directive "${i}" on line ${n}.`);s[i]=o,e.env=s}(n,t,e+1);continue}if(!t.startsWith("context "))break;let o=t.match(/(?:^|\s)platform=([^\s]+)/);if(o){let e=o[1];e&&D.has(e)&&j(n,"platform",e)}let s=t.match(/(?:^|\s)target=([^\s]+)/);if(s){let e=s[1];e&&M.has(e)&&j(n,"target",e)}let l=t.match(/(?:^|\s)timeout=(\d+)/);if(l){let e=Number(l[1]);Number.isFinite(e)&&e>=1&&j(n,"timeoutMs",Math.floor(e))}let a=t.match(/(?:^|\s)retries=(\d+)/);if(a){let e=Number(a[1]);Number.isFinite(e)&&e>=0&&j(n,"retries",Math.floor(e))}}return n}function L(e){return"env"===e||e.startsWith("env ")||e.startsWith("env ")}function j(e,t,n){let i=e[t];if(void 0!==i)throw new r("INVALID_ARGS",i===n?`Duplicate replay test metadata "${t}" in context header.`:`Conflicting replay test metadata "${t}" in context header: ${String(i)} vs ${String(n)}.`);e[t]=n}function V(e){return!!e&&!Number.isNaN(Number(e))}function k(t,n,r){let i=[];if(r){let e=r.device.kind?` kind=${r.device.kind}`:"",t=r.device.target?` target=${r.device.target}`:"";i.push(`context platform=${r.device.platform}${t} device=${a(r.device.name)}${e} theme=unknown`)}for(let e of n)i.push(f(e,{runtimeIncludeAllPositionals:!0}));let o=`${i.join("\n")}
|
|
2
2
|
`,s=`${t}.tmp-${process.pid}-${Date.now()}`;e.writeFileSync(s,o),e.renameSync(s,t)}function E(e){let n=t(e);for(let e of n)if(e.errors.length>0){let t=e.errors[0]?.message??"Invalid Maestro YAML flow.";throw new r("INVALID_ARGS",`Invalid Maestro YAML flow: ${t}`)}return n.map(e=>e.toJSON()).filter(e=>null!==e)}function G(e){return`${e.map(e=>n(e).trimEnd()).join("\n---\n")}
|
|
3
3
|
`}function C(e,t=[],n){return{ts:Date.now(),command:e,positionals:t,flags:n??{}}}function P(e,t,n){let r=new Set(n),i=Object.keys(e).filter(e=>!r.has(e));if(i.length>0)throw J(`Maestro ${t} field "${i[0]}" is not supported yet.`)}function W(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function F(e){return e.map((e,t)=>{if("string"==typeof e||W(e))return e;throw new r("INVALID_ARGS",`Unsupported Maestro command at index ${t+1}: expected a scalar or one-key map.`)})}function K(e){if(e){let t;return"android"===(t=e.trim().toLowerCase())?"android":"ios"===t?"ios":void 0}}function z(e,t){if(null==e)return{};if(!W(e))throw new r("INVALID_ARGS",`${t} expects a map.`);let n={};for(let[t,r]of Object.entries(e))("string"==typeof r||"number"==typeof r||"boolean"==typeof r)&&(n[t]=String(r));return n}function U(e,t){return W(e)&&"number"==typeof e.timeout&&Number.isFinite(e.timeout)?Math.max(0,Math.floor(e.timeout)):t}function q(e,t){if(e.appId)return e.appId;throw new r("INVALID_ARGS",`${t} requires appId in the Maestro flow config.`)}function Y(e,t){if("string"==typeof t)return t;throw new r("INVALID_ARGS",`${e} expects a string value.`)}function Z(e,t){return e.replace(/\$\{([A-Za-z_][A-Za-z0-9_.]*)\}/g,(e,n)=>Object.prototype.hasOwnProperty.call(t.env,n)?String(t.env[n]):e)}function H(e){throw J(`Maestro command "${e}" is not supported yet.`)}function J(e){throw new r("INVALID_ARGS",`${e} See supported/unsupported Maestro compatibility at ${s}. If this syntax matters for your flows, comment there or open a focused issue at ${l}.`)}function T(e,t){return`${e},${t}`}function B(e){let t=e.match(/^(\d+),(\d+)$/);if(!t)throw J('Only absolute Maestro point selectors like "100,200" are supported.');return{x:Number(t[1]),y:Number(t[2])}}function Q(e){let t=e.match(/^\s*(\d+)\s*,\s*(\d+)\s*$/);if(t)return{kind:"absolute",x:Number(t[1]),y:Number(t[2])};let n=e.match(/^\s*(\d+(?:\.\d+)?)%\s*,\s*(\d+(?:\.\d+)?)%\s*$/);if(n)return{kind:"percent",x:Number(n[1]),y:Number(n[2])};throw J('Only Maestro swipe coordinates like "100,200" or "50%,75%" are supported.')}export{P as assertOnlyKeys,y as buildReplayVarScope,b as collectReplayShellEnv,T as formatMaestroPoint,W as isPlainRecord,w as mergeReplayVarScopeValues,F as normalizeCommandList,K as normalizePlatform,B as parseAbsolutePoint,Q as parseMaestroPoint,E as parseMaestroYamlDocuments,I as parseReplayCliEnvEntries,x as parseReplayScriptDetailed,z as readEnvMap,$ as readReplayCliEnvEntries,O as readReplayScriptMetadata,S as readReplayShellEnvSource,U as readTimeoutMs,q as requireAppId,Y as requireStringValue,Z as resolveMaestroString,N as resolveReplayAction,G as stringifyMaestroYamlDocuments,C as support_action,H as unsupportedCommand,J as unsupportedMaestroSyntax,k as writeReplayScript};
|
package/dist/src/587.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AppError as e}from"./733.js";let t=["
|
|
1
|
+
import{AppError as e}from"./733.js";let t=new Set(["id","role","text","label","value","appname","windowtitle"]),n=new Set(["visible","hidden","editable","selected","enabled","hittable"]),r=new Set([...t,...n]),i=new Map([['"','"'],["'","'"],["\\","\\"],["/","/"],["b","\b"],["f","\f"],["n","\n"],["r","\r"],["t"," "]]);function l(t){let n=t.trim();if(!n)throw new e("INVALID_ARGS","Selector expression cannot be empty");let r=function(t){let n=[],r="",i=null;for(let l=0;l<t.length;l+=1){let o=t[l];if(('"'===o||"'"===o)&&!h(t,l)){i=a(i,o),r+=o;continue}if(!i&&"|"===o&&"|"===t[l+1]){let i=r.trim();if(!i)throw new e("INVALID_ARGS",`Invalid selector fallback expression: ${t}`);n.push(i),r="",l+=1;continue}r+=o}let l=r.trim();if(!l)throw new e("INVALID_ARGS",`Invalid selector fallback expression: ${t}`);return n.push(l),n}(n);if(0===r.length)throw new e("INVALID_ARGS","Selector expression cannot be empty");return{raw:n,selectors:r.map(t=>(function(t){let n=t.trim();if(!n)throw new e("INVALID_ARGS","Selector segment cannot be empty");let r=function(t){let n=[],r="",i=null;for(let e=0;e<t.length;e+=1){let l=t.charAt(e);if(('"'===l||"'"===l)&&!h(t,e)){i=a(i,l),r+=l;continue}if(!i&&/\s/.test(l)){r.trim()&&n.push(r.trim()),r="";continue}r+=l}if(i)throw new e("INVALID_ARGS",`Unclosed quote in selector: ${t}`);return r.trim()&&n.push(r.trim()),n}(n);if(0===r.length)throw new e("INVALID_ARGS",`Invalid selector segment: ${t}`);return{raw:n,terms:r.map(c)}})(t))}}function o(e){try{return l(e)}catch{return null}}function u(e){let t=e.trim();if(!t)return!1;if("||"===t)return!0;let n=t.indexOf("=");if(-1!==n){let e=t.slice(0,n).trim().toLowerCase();return r.has(e)}return r.has(t.toLowerCase())}function s(e,t={}){if(0===e.length)return null;let n=t.preferTrailingValue??!1,r=0,i=[];for(;r<e.length;){let t=e[r];if(void 0===t||!u(t))break;r+=1;let n=e.slice(0,r).join(" ").trim();n&&o(n)&&i.push(r)}if(0===i.length)return null;let l=i.at(-1);if(void 0===l)return null;let c=l;if(n)for(let t=i.length-1;t>=0;t-=1){let n=i[t];if(void 0!==n&&n<e.length){c=n;break}}let a=e.slice(0,c).join(" ").trim();return a?{selectorExpression:a,rest:e.slice(c)}:null}function c(t){let i=t.trim();if(!i)throw new e("INVALID_ARGS","Empty selector term");let l=i.indexOf("=");if(-1===l){let r=i.toLowerCase();if(!n.has(r))throw new e("INVALID_ARGS",`Invalid selector term "${t}", expected key=value`);return{key:r,value:!0}}let o=i.slice(0,l).trim().toLowerCase(),u=i.slice(l+1).trim();if(!r.has(o))throw new e("INVALID_ARGS",`Unknown selector key: ${o}`);if(!u)throw new e("INVALID_ARGS",`Missing selector value for key: ${o}`);if(n.has(o)){let t,n="true"===(t=f(u).toLowerCase())||"false"!==t&&null;if(null===n)throw new e("INVALID_ARGS",`Invalid boolean value for ${o}: ${u}`);return{key:o,value:n}}return{key:o,value:f(u)}}function a(e,t){return e?e===t?null:e:t}function f(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?function(e){let t="",n=0;for(;n<e.length;){var r;let l=e.charAt(n);if("\\"!==l){t+=l,n+=1;continue}let o=e.charAt(n+1);if(!o){t+=l,n+=1;continue}let u=(r=o,i.get(r)??null);if(null!==u){t+=u,n+=2;continue}if("u"===o){let r=e.slice(n+2,n+6);if(/^[0-9a-fA-F]{4}$/.test(r)){t+=String.fromCharCode(Number.parseInt(r,16)),n+=6;continue}}t+=l,n+=1}return t}(t.slice(1,-1)):t}function h(e,t){let n=0;for(let r=t-1;r>=0&&"\\"===e[r];r-=1)n+=1;return n%2==1}let w=["any","text","label","value","role","id"],m=["text","label","value","role","id"];function p(e,t,n,r={}){let i=A(n);if(!i)return{matches:[],score:0};let l=0,o=[];for(let n of e){if(r.requireRect&&!n.rect)continue;let e=function(e,t,n){switch(t){case"role":return function(e,t){let n=I(e??"");return n?n===t?2:+!!n.includes(t):0}(e.type,n);case"label":return d(e.label,n);case"value":return d(e.value,n);case"id":return d(e.identifier,n);default:return Math.max(d(e.label,n),d(e.value,n),d(e.identifier,n))}}(n,t,i);if(!(e<=0)){if(e>l){l=e,o.length=0,o.push(n);continue}e===l&&o.push(n)}}return{matches:o,score:l}}function d(e,t){let n=A(e??"");return n?n===t?2:+!!n.includes(t):0}function A(e){return e.trim().toLowerCase().replace(/\s+/g," ")}function I(e){let t=e.trim();return t?t=(t.split(".").pop()??t).replace(/XCUIElementType/gi,"").toLowerCase():""}function S(t){let n="any",r=0;m.includes(t[0])&&(n=t[0],r=1);let i=t[r]??"",l=t.slice(r+1);if(0===l.length)return{locator:n,query:i,action:"click"};let o=l[0]?.toLowerCase();if("get"===o){let t=l[1]?.toLowerCase();if("text"===t)return{locator:n,query:i,action:"get_text"};if("attrs"===t)return{locator:n,query:i,action:"get_attrs"};throw new e("INVALID_ARGS","find get only supports text or attrs")}if("wait"===o)return{locator:n,query:i,action:"wait",timeoutMs:function(e){if(!e)return null;let t=Number(e);return Number.isFinite(t)?t:null}(l[1])??void 0};if("exists"===o)return{locator:n,query:i,action:"exists"};if("click"===o)return{locator:n,query:i,action:"click"};if("focus"===o)return{locator:n,query:i,action:"focus"};if("fill"===o)return{locator:n,query:i,action:"fill",value:l.slice(1).join(" ")};if("type"===o)return{locator:n,query:i,action:"type",value:l.slice(1).join(" ")};throw new e("INVALID_ARGS",`Unsupported find action: ${l[0]}`)}function g(e,t){return"any"===e&&(t.includes("=")||t.includes("||"))?o(t):null}export{w as FIND_LOCATORS,p as findBestMatchesByLocator,u as isSelectorToken,I as normalizeRole,A as normalizeText,S as parseFindArgs,g as parseFindSelectorExpression,l as parseSelectorChain,s as splitSelectorFromArgs,o as tryParseSelectorChain};
|
package/dist/src/7394.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import e from"node:crypto";import t from"node:fs";import r from"node:fs/promises";import n from"node:os";import i from"node:path";import o from"node:net";import{AppError as a}from"./733.js";import{intersectArea as s,isScrollableType as l}from"./6024.js";import{emitDiagnostic as u}from"./432.js";import{installAndroidAdbPackage as d}from"./2954.js";let c="android-snapshot-helper",h="com.callstack.agentdevice.snapshothelper",p="com.callstack.agentdevice.snapshothelper/.SnapshotInstrumentation",f="android-snapshot-helper-v1",w="uiautomator-xml",m={"-r":"replace","-t":"allowTestPackages","-d":"allowDowngrade","-g":"grantPermissions"};async function A(e){let t=await x(e.apkPath);if(t!==e.manifest.sha256)throw new a("COMMAND_FAILED","Android snapshot helper APK checksum mismatch",{apkPath:e.apkPath,expectedSha256:e.manifest.sha256,actualSha256:t})}async function M(e){let t=e.fetch??fetch,o=await t(e.manifestUrl);if(!o.ok)throw new a("COMMAND_FAILED","Failed to download Android snapshot helper manifest",{manifestUrl:e.manifestUrl,status:o.status,statusText:o.statusText});let s=g(JSON.parse((await v(o,65536,"Android snapshot helper manifest")).toString("utf8")));if(!s.apkUrl)throw new a("COMMAND_FAILED","Android snapshot helper manifest does not include apkUrl",{manifestUrl:e.manifestUrl});let l=e.cacheDir??i.join(n.tmpdir(),`agent-device-android-snapshot-helper-${s.version}`),u=!e.cacheDir;await r.mkdir(l,{recursive:!0});let d=s.assetName??`agent-device-android-snapshot-helper-${s.version}.apk`,c=i.join(l,d),h=await t(s.apkUrl);if(!h.ok)throw new a("COMMAND_FAILED","Failed to download Android snapshot helper APK",{apkUrl:s.apkUrl,status:h.status,statusText:h.statusText});await r.writeFile(c,await v(h,0x1400000,"Android snapshot helper APK"));let p={apkPath:c,manifest:s};return await A(p),{...p,cleanup:async()=>{await r.rm(u?l:c,{recursive:u,force:!0})}}}function g(e){var t,r;if(!e||"object"!=typeof e||Array.isArray(e))throw new a("INVALID_ARGS","Android snapshot helper manifest must be an object.");return{name:D(e.name,"name",c),version:y(e.version,"version"),releaseTag:I(e.releaseTag),assetName:I(e.assetName),apkUrl:(t=e.apkUrl,r="apkUrl",null===t?null:y(t,r)),sha256:function(e){let t=y(e,"sha256").trim().toLowerCase();if(64!==t.length||!function(e){for(let t of e){let e=t.charCodeAt(0),r=e>=48&&e<=57,n=e>=97&&e<=102;if(!r&&!n)return!1}return!0}(t))throw new a("INVALID_ARGS","Android snapshot helper manifest sha256 must be a 64-character hex string.");return t}(e.sha256),checksumName:I(e.checksumName),packageName:y(e.packageName,"packageName"),versionCode:C(e.versionCode,"versionCode"),instrumentationRunner:y(e.instrumentationRunner,"instrumentationRunner"),minSdk:C(e.minSdk,"minSdk"),targetSdk:void 0===e.targetSdk?void 0:C(e.targetSdk,"targetSdk"),outputFormat:D(e.outputFormat,"outputFormat",w),statusProtocol:D(e.statusProtocol,"statusProtocol",f),installArgs:N(e.installArgs)}}async function v(e,t,r){let n=e.headers.get("content-length");if(null!==n){let e=Number(n);if(Number.isFinite(e)&&e>t)throw new a("COMMAND_FAILED",`${r} download exceeds size limit`,{contentLength:e,maxBytes:t})}if(!e.body){let n=Buffer.from(await e.arrayBuffer());if(n.length>t)throw new a("COMMAND_FAILED",`${r} download exceeds size limit`,{contentLength:n.length,maxBytes:t});return n}let i=e.body.getReader(),o=[],s=0;try{for(;;){let{done:e,value:n}=await i.read();if(e)break;if((s+=n.byteLength)>t)throw new a("COMMAND_FAILED",`${r} download exceeds size limit`,{contentLength:s,maxBytes:t});o.push(Buffer.from(n))}}finally{i.releaseLock()}return Buffer.concat(o,s)}function N(e){let t=function(e,t){if(!Array.isArray(e)||!e.every(e=>"string"==typeof e))throw new a("INVALID_ARGS",`Android snapshot helper manifest ${t} must be a string array.`);return e}(e,"installArgs");if("install"!==t[0])throw new a("INVALID_ARGS",'Android snapshot helper manifest installArgs must start with "install".');if(t.some(e=>e.includes("\0")))throw new a("INVALID_ARGS","Android snapshot helper manifest installArgs must not contain null bytes.");let r=t.slice(1).find(e=>void 0===b(e));if(r)throw new a("INVALID_ARGS",`Android snapshot helper manifest installArgs contains unsupported install flag "${r}".`);return t}async function x(r){return await new Promise((n,i)=>{let o=e.createHash("sha256"),a=t.createReadStream(r);a.on("error",i),a.on("data",e=>o.update(e)),a.on("end",()=>n(o.digest("hex")))})}function y(e,t){if("string"!=typeof e||0===e.trim().length)throw new a("INVALID_ARGS",`Android snapshot helper manifest ${t} is required.`);return e}function I(e){return"string"==typeof e&&e.trim().length>0?e:void 0}function C(e,t){if("number"!=typeof e||!Number.isInteger(e))throw new a("INVALID_ARGS",`Android snapshot helper manifest ${t} must be an integer.`);return e}function D(e,t,r){if(e!==r)throw new a("INVALID_ARGS",`Android snapshot helper manifest ${t} must be "${r}".`);return r}function b(e){if(Object.hasOwn(m,e))return m[e]}function*S(e){let t=/<node\b[^>]*>/g,r=t.exec(e);for(;r;)yield _(r[0]),r=t.exec(e)}function _(e){let t,r,n,i,o,a=(t=function(e){let t=new Map,r=e.indexOf(" "),n=e.lastIndexOf(">");if(r<0||n<=r)return t;let i=r;for(;i<n;){let r=function(e,t,r){var n,i;if((t=F(e,t,r))>=r||"/"===(n=e[t])||">"===n)return;let o=t;t=function(e,t,r){for(var n;t<r&&!("="===(n=e[t]??"")||"/"===n||">"===n||L(n));)t+=1;return t}(e,t,r);let a=e.slice(o,t);if(t=F(e,t,r),!a||"="!==e[t])return;t=F(e,t+1,r);let s=e[t];if('"'!==(i=s)&&"'"!==i)return;let l=t+1,u=e.indexOf(s,l);if(!(u<0)&&!(u>=r))return{name:a,value:function(e){let t="",r=0;for(;r<e.length;){let n=e.indexOf("&",r);if(n<0){t+=e.slice(r);break}t+=e.slice(r,n);let i=e.indexOf(";",n+1);if(i<0){t+=e.slice(n);break}t+=function(e){switch(e){case"amp":return"&";case"lt":return"<";case"gt":return">";case"quot":return'"';case"apos":return"'";default:return function(e){if(!e.startsWith("#"))return;let t=e[1]?.toLowerCase()==="x"?16:10,r=16===t?e.slice(2):e.slice(1);if(!r||!function(e,t){for(let r of e){let e=r.charCodeAt(0),n=e>=48&&e<=57;if(10===t){if(!n)return!1;continue}let i=e>=65&&e<=70,o=e>=97&&e<=102;if(!n&&!i&&!o)return!1}return!0}(r,t))return;let n=Number.parseInt(r,t);if(Number.isFinite(n))try{return String.fromCodePoint(n)}catch{return}}(e)}}(e.slice(n+1,i))??e.slice(n,i+1),r=i+1}return t}(e.slice(l,u)),nextCursor:u+1}}(e,i,n);if(!r)break;t.set(r.name,r.value),i=r.nextCursor}return t}(e),r=e=>{let r=O(t,e);if(null!==r)return"true"===r},n=(e,r)=>{let n=(e=>{let r=O(t,e);if(null===r||""===r.trim())return;let n=Number(r);return Number.isFinite(n)?n:void 0})(r);return void 0===n?{}:{[e]:n}},i=(e,t)=>{let n=r(t);return void 0===n?{}:{[e]:n}},{text:O(t,"text"),desc:O(t,"content-desc"),resourceId:O(t,"resource-id"),packageName:O(t,"package"),className:O(t,"class"),bounds:O(t,"bounds"),clickable:r("clickable"),enabled:r("enabled"),focusable:r("focusable"),focused:r("focused"),password:r("password"),...i("visibleToUser","visible-to-user"),...n("drawingOrder","drawing-order"),...i("scrollable","scrollable"),...i("canScrollForward","can-scroll-forward"),...i("canScrollBackward","can-scroll-backward"),...n("windowIndex","window-index"),...n("windowType","window-type"),...n("windowLayer","window-layer"),...i("windowActive","window-active"),...i("windowFocused","window-focused"),...void 0===(o=E(O(t,"window-bounds")))?{}:{windowRect:o}}),s=E(a.bounds);return{...a,...s?{rect:s}:{}}}function T(e,t,r){let{sourceNodes:n,...i}=k(P(e),t,r);return i}function k(e,t,r){let n={nodes:[],sourceNodes:[],...void 0!==t?{maxNodes:t}:{},maxDepth:r.depth??1/0,options:r,analysis:function(e){let t=0,r=0,n=[...e.children];for(;n.length>0;){let e=n.pop();t+=1,r=Math.max(r,e.depth),n.push(...e.children)}return{rawNodeCount:t,maxDepth:r}}(e),interactiveDescendantMemo:new Map,truncated:!1},i=r.scope?function(e,t){let r=t.toLowerCase(),n=[...e.children],i=0;for(;i<n.length;){let e=n[i++],t=e.label?.toLowerCase()??"",o=e.value?.toLowerCase()??"",a=e.identifier?.toLowerCase()??"";if(t.includes(r)||o.includes(r)||a.includes(r))return e;n.push(...e.children)}return null}(e,r.scope):null;for(let t of i?[i]:e.children)if(function e(t,r,n,i,o=!1,a=!1){if(void 0!==t.maxNodes&&t.nodes.length>=t.maxNodes){t.truncated=!0;return}if(n>t.maxDepth)return;let s=t.options.raw||function(e,t,r,n,i){var o,a,s;if(!1===e.visibleToUser)return!1;let u=function(e){let t=V(e.type),r=!!(e.label&&e.label.trim().length>0),n=!!(e.identifier&&e.identifier.trim().length>0);return{type:t,hasMeaningfulText:r&&!B(e.label??""),hasMeaningfulId:n&&!B(e.identifier??""),isStructural:function(e){let t=e.split(".").pop()??e;return t.includes("layout")||"viewgroup"===t||"view"===t}(t),isVisual:"imageview"===t||"imagebutton"===t}}(e);return t.interactiveOnly?function(e,t,r,n,i){var o,a,s,u,d;return!((o=e).rect&&(o.rect.width<=0||o.rect.height<=0))&&(!!(e.hittable||l(t.type)&&n)||(a=t,s=r,u=n,d=i,(!!a.hasMeaningfulText||!!a.hasMeaningfulId)&&!a.isVisual&&(!a.isStructural||!!d)&&(s||u||d)))}(e,u,r,n,i):!u.isStructural&&!u.isVisual||(o=e,a=u,s=n,!!o.hittable||!!a.hasMeaningfulText||!!a.hasMeaningfulId||s)}(r,t.options,o,function e(t,r){let n=t.interactiveDescendantMemo.get(r);if(void 0!==n)return n;for(let n of r.children)if(!1!==n.visibleToUser&&(n.hittable||e(t,n)))return t.interactiveDescendantMemo.set(r,!0),!0;return t.interactiveDescendantMemo.set(r,!1),!1}(t,r),a)?function(e,t,r,n){let i=e.nodes.length;return e.sourceNodes.push(t),e.nodes.push({index:i,type:t.type??void 0,label:t.label??void 0,value:t.value??void 0,identifier:t.identifier??void 0,bundleId:t.packageName??void 0,rect:t.rect,enabled:t.enabled,visibleToUser:t.visibleToUser,hittable:t.hittable,depth:r,parentIndex:n,...t.hiddenContentAbove?{hiddenContentAbove:!0}:{},...t.hiddenContentBelow?{hiddenContentBelow:!0}:{}}),i}(t,r,n,i):i,u=o||!!r.hittable,d=a||function(e){if(!e)return!1;let t=V(e);return t.includes("recyclerview")||t.includes("listview")||t.includes("gridview")}(r.type);for(let i of r.children)if(e(t,i,n+1,s,u,d),t.truncated)return}(n,t,0),n.truncated)break;let o={nodes:n.nodes,sourceNodes:n.sourceNodes,analysis:n.analysis};return n.truncated?{...o,truncated:!0}:o}function F(e,t,r){for(;t<r&&L(e[t]??"");)t+=1;return t}function L(e){return" "===e||"\n"===e||"\r"===e||" "===e}function O(e,t){return e.get(t)??null}function E(e){if(!e)return;let t=/\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]/.exec(e);if(!t)return;let r=Number(t[1]),n=Number(t[2]);return{x:r,y:n,width:Math.max(0,Number(t[3])-r),height:Math.max(0,Number(t[4])-n)}}function P(e){let t={type:null,label:null,value:null,identifier:null,packageName:null,depth:-1,children:[]},r=[t],n=/<node\b[^>]*>|<\/node>/g,i=n.exec(e);for(;i;){let t=i[0];if(t.startsWith("</node")){r.length>1&&r.pop(),i=n.exec(e);continue}let o=_(t),a=r[r.length-1],s={type:o.className,label:o.text||o.desc,value:o.text,identifier:o.resourceId,packageName:o.packageName,rect:o.rect,enabled:o.enabled,visibleToUser:o.visibleToUser,drawingOrder:o.drawingOrder,hittable:o.clickable??o.focusable,scrollable:o.scrollable,canScrollForward:o.canScrollForward,canScrollBackward:o.canScrollBackward,windowIndex:o.windowIndex,windowType:o.windowType,windowLayer:o.windowLayer,windowActive:o.windowActive,windowFocused:o.windowFocused,windowRect:o.windowRect,depth:a.depth+1,parentIndex:void 0,children:[]};a.children.push(s),t.endsWith("/>")||r.push(s),i=n.exec(e)}return function e(t){let r=0;for(let n of t.children)!1!==n.visibleToUser&&(e(n),t.children[r]=n,r+=1);r<t.children.length&&(t.children.length=r)}(t),function(e){let t,r=e.children.filter(U);if(r.length<2)return;let n=r.filter(e=>$(e)&&H(e));if(0===n.length)return;let i=(t=n.map(e=>e.windowLayer).filter(e=>void 0!==e)).length>0?Math.max(...t):void 0;e.children=e.children.filter(e=>!$(e)||!!H(e)&&(void 0===i||e.windowLayer===i))}(t),function e(t,r){for(let n of t.children)e(n,r);if(t.children.length<2)return;let n=t.children,i=n.filter(e=>{var t,n;return t=e,n=r,!1!==t.visibleToUser&&void 0!==t.drawingOrder&&R(t)&&function e(t,r){let n=r.agentVisibleContentMemo.get(t);if(void 0!==n)return n;let i=function(t,r){if(!1===t.visibleToUser)return!1;if(t.hittable)return!0;let n=t.label?.trim()??"";if(n&&!B(n))return!0;let i=t.identifier?.trim()??"";return!(!i||B(i))||t.children.some(t=>e(t,r))}(t,r);return r.agentVisibleContentMemo.set(t,i),i}(t,n)});0!==i.length&&(t.children=n.filter(e=>!function(e,t){if(!1===e.visibleToUser||void 0===e.drawingOrder||!R(e))return!1;for(let r of t)if(r!==e&&!(r.drawingOrder<=e.drawingOrder)&&function(e,t){let r=t.width*t.height;return r<=0?0:s(e,t)/r}(r.rect,e.rect)>=.9)return!0;return!1}(e,i)))}(t,{agentVisibleContentMemo:new WeakMap}),function(e){let t=[...e.children];for(;t.length>0;){let e=t.pop();t.push(...e.children),function(e){if(!e.scrollable||!l(e.type)||`${e.type??""}`.toLowerCase().includes("horizontalscrollview"))return!1;let t=function(e){if(!e.rect||0===e.children.length)return null;let t=e.children.map(e=>e.rect).filter(e=>void 0!==e);if(0===t.length)return null;let r=Math.min(...t.map(e=>e.x)),n=Math.max(...t.map(e=>e.x+e.width)),i=Math.min(...t.map(e=>e.y)),o=Math.max(...t.map(e=>e.y+e.height));return{horizontal:Math.max(0,n-r-e.rect.width),vertical:Math.max(0,o-i-e.rect.height)}}(e);return!t||!(t.horizontal>t.vertical)||!(t.horizontal>16)}(e)&&(e.canScrollBackward&&(e.hiddenContentAbove=!0),e.canScrollForward&&(e.hiddenContentBelow=!0))}}(t),t}function R(e){return!!(e.rect&&e.rect.width>0&&e.rect.height>0)}function U(e){return void 0!==e.windowIndex||void 0!==e.windowType}function $(e){return 1===e.windowType}function H(e){return!0===e.windowActive||!0===e.windowFocused}function V(e){return e?e.toLowerCase():""}function B(e){let t=e.trim();return!!t&&/^[\w.]+:id\/[\w.-]+$/i.test(t)}async function K(e){let t=G(e),r=await e.adb(W(t),{allowFailure:!0,timeoutMs:t.commandTimeoutMs}),{output:n,cleanupDone:i}=await X(e,t,r);if(t.outputPath&&!i&&await J(e.adb,t.outputPath),0!==r.exitCode)throw new a("COMMAND_FAILED","Android snapshot helper failed",{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode,helper:n.metadata});return n}function G(e){let t=Q(e.timeoutMs,8e3),r=Q(e.packageName,h);return{waitForIdleTimeoutMs:Q(e.waitForIdleTimeoutMs,500),waitForIdleQuietMs:Q(e.waitForIdleQuietMs,100),timeoutMs:t,commandTimeoutMs:Q(e.commandTimeoutMs,t+5e3),maxDepth:Q(e.maxDepth,128),maxNodes:Q(e.maxNodes,5e3),packageName:r,runner:Q(e.instrumentationRunner,`${r}/.SnapshotInstrumentation`),...e.outputPath?{outputPath:e.outputPath}:{},...void 0!==e.emitChunks?{emitChunks:e.emitChunks}:{}}}function Q(e,t){return void 0===e?t:e}function W(e){return["shell","am","instrument","-w","-e","waitForIdleTimeoutMs",String(e.waitForIdleTimeoutMs),"-e","waitForIdleQuietMs",String(e.waitForIdleQuietMs),"-e","timeoutMs",String(e.timeoutMs),"-e","maxDepth",String(e.maxDepth),"-e","maxNodes",String(e.maxNodes),...e.outputPath?["-e","outputPath",e.outputPath]:[],...void 0!==e.emitChunks?["-e","emitChunks",String(e.emitChunks)]:[],e.runner]}async function X(e,t,r){try{return{output:Y(`${r.stdout}
|
|
1
|
+
import e from"node:crypto";import t from"node:fs";import r from"node:fs/promises";import n from"node:os";import i from"node:path";import o from"node:net";import{AppError as a}from"./733.js";import{intersectArea as s,isScrollableType as l}from"./6024.js";import{emitDiagnostic as u}from"./432.js";import{installAndroidAdbPackage as d}from"./2954.js";let c="android-snapshot-helper",h="com.callstack.agentdevice.snapshothelper",p="com.callstack.agentdevice.snapshothelper/.SnapshotInstrumentation",f="android-snapshot-helper-v1",w="uiautomator-xml",m={"-r":"replace","-t":"allowTestPackages","-d":"allowDowngrade","-g":"grantPermissions"};async function A(e){let t=await y(e.apkPath);if(t!==e.manifest.sha256)throw new a("COMMAND_FAILED","Android snapshot helper APK checksum mismatch",{apkPath:e.apkPath,expectedSha256:e.manifest.sha256,actualSha256:t})}async function M(e){let t=e.fetch??fetch,o=await t(e.manifestUrl);if(!o.ok)throw new a("COMMAND_FAILED","Failed to download Android snapshot helper manifest",{manifestUrl:e.manifestUrl,status:o.status,statusText:o.statusText});let s=g(JSON.parse((await v(o,65536,"Android snapshot helper manifest")).toString("utf8")));if(!s.apkUrl)throw new a("COMMAND_FAILED","Android snapshot helper manifest does not include apkUrl",{manifestUrl:e.manifestUrl});let l=e.cacheDir??i.join(n.tmpdir(),`agent-device-android-snapshot-helper-${s.version}`),u=!e.cacheDir;await r.mkdir(l,{recursive:!0});let d=s.assetName??`agent-device-android-snapshot-helper-${s.version}.apk`,c=i.join(l,d),h=await t(s.apkUrl);if(!h.ok)throw new a("COMMAND_FAILED","Failed to download Android snapshot helper APK",{apkUrl:s.apkUrl,status:h.status,statusText:h.statusText});await r.writeFile(c,await v(h,0x1400000,"Android snapshot helper APK"));let p={apkPath:c,manifest:s};return await A(p),{...p,cleanup:async()=>{await r.rm(u?l:c,{recursive:u,force:!0})}}}function g(e){var t,r;if(!e||"object"!=typeof e||Array.isArray(e))throw new a("INVALID_ARGS","Android snapshot helper manifest must be an object.");return{name:C(e.name,"name",c),version:x(e.version,"version"),releaseTag:I(e.releaseTag),assetName:I(e.assetName),apkUrl:(t=e.apkUrl,r="apkUrl",null===t?null:x(t,r)),sha256:function(e){let t=x(e,"sha256").trim().toLowerCase();if(64!==t.length||!function(e){for(let t of e){let e=t.charCodeAt(0),r=e>=48&&e<=57,n=e>=97&&e<=102;if(!r&&!n)return!1}return!0}(t))throw new a("INVALID_ARGS","Android snapshot helper manifest sha256 must be a 64-character hex string.");return t}(e.sha256),checksumName:I(e.checksumName),packageName:x(e.packageName,"packageName"),versionCode:D(e.versionCode,"versionCode"),instrumentationRunner:x(e.instrumentationRunner,"instrumentationRunner"),minSdk:D(e.minSdk,"minSdk"),targetSdk:void 0===e.targetSdk?void 0:D(e.targetSdk,"targetSdk"),outputFormat:C(e.outputFormat,"outputFormat",w),statusProtocol:C(e.statusProtocol,"statusProtocol",f),installArgs:N(e.installArgs)}}async function v(e,t,r){let n=e.headers.get("content-length");if(null!==n){let e=Number(n);if(Number.isFinite(e)&&e>t)throw new a("COMMAND_FAILED",`${r} download exceeds size limit`,{contentLength:e,maxBytes:t})}if(!e.body){let n=Buffer.from(await e.arrayBuffer());if(n.length>t)throw new a("COMMAND_FAILED",`${r} download exceeds size limit`,{contentLength:n.length,maxBytes:t});return n}let i=e.body.getReader(),o=[],s=0;try{for(;;){let{done:e,value:n}=await i.read();if(e)break;if((s+=n.byteLength)>t)throw new a("COMMAND_FAILED",`${r} download exceeds size limit`,{contentLength:s,maxBytes:t});o.push(Buffer.from(n))}}finally{i.releaseLock()}return Buffer.concat(o,s)}function N(e){let t=function(e,t){if(!Array.isArray(e)||!e.every(e=>"string"==typeof e))throw new a("INVALID_ARGS",`Android snapshot helper manifest ${t} must be a string array.`);return e}(e,"installArgs");if("install"!==t[0])throw new a("INVALID_ARGS",'Android snapshot helper manifest installArgs must start with "install".');if(t.some(e=>e.includes("\0")))throw new a("INVALID_ARGS","Android snapshot helper manifest installArgs must not contain null bytes.");let r=t.slice(1).find(e=>void 0===b(e));if(r)throw new a("INVALID_ARGS",`Android snapshot helper manifest installArgs contains unsupported install flag "${r}".`);return t}async function y(r){return await new Promise((n,i)=>{let o=e.createHash("sha256"),a=t.createReadStream(r);a.on("error",i),a.on("data",e=>o.update(e)),a.on("end",()=>n(o.digest("hex")))})}function x(e,t){if("string"!=typeof e||0===e.trim().length)throw new a("INVALID_ARGS",`Android snapshot helper manifest ${t} is required.`);return e}function I(e){return"string"==typeof e&&e.trim().length>0?e:void 0}function D(e,t){if("number"!=typeof e||!Number.isInteger(e))throw new a("INVALID_ARGS",`Android snapshot helper manifest ${t} must be an integer.`);return e}function C(e,t,r){if(e!==r)throw new a("INVALID_ARGS",`Android snapshot helper manifest ${t} must be "${r}".`);return r}function b(e){if(Object.hasOwn(m,e))return m[e]}function*S(e){let t=/<node\b[^>]*>/g,r=t.exec(e);for(;r;)yield _(r[0]),r=t.exec(e)}function _(e){let t,r,n,i,o,a=(t=function(e){let t=new Map,r=e.indexOf(" "),n=e.lastIndexOf(">");if(r<0||n<=r)return t;let i=r;for(;i<n;){let r=function(e,t,r){var n,i;if((t=k(e,t,r))>=r||"/"===(n=e[t])||">"===n)return;let o=t;t=function(e,t,r){for(var n;t<r&&!("="===(n=e[t]??"")||"/"===n||">"===n||L(n));)t+=1;return t}(e,t,r);let a=e.slice(o,t);if(t=k(e,t,r),!a||"="!==e[t])return;t=k(e,t+1,r);let s=e[t];if('"'!==(i=s)&&"'"!==i)return;let l=t+1,u=e.indexOf(s,l);if(!(u<0)&&!(u>=r))return{name:a,value:function(e){let t="",r=0;for(;r<e.length;){let n=e.indexOf("&",r);if(n<0){t+=e.slice(r);break}t+=e.slice(r,n);let i=e.indexOf(";",n+1);if(i<0){t+=e.slice(n);break}t+=function(e){switch(e){case"amp":return"&";case"lt":return"<";case"gt":return">";case"quot":return'"';case"apos":return"'";default:return function(e){if(!e.startsWith("#"))return;let t=e[1]?.toLowerCase()==="x"?16:10,r=16===t?e.slice(2):e.slice(1);if(!r||!function(e,t){for(let r of e){let e=r.charCodeAt(0),n=e>=48&&e<=57;if(10===t){if(!n)return!1;continue}let i=e>=65&&e<=70,o=e>=97&&e<=102;if(!n&&!i&&!o)return!1}return!0}(r,t))return;let n=Number.parseInt(r,t);if(Number.isFinite(n))try{return String.fromCodePoint(n)}catch{return}}(e)}}(e.slice(n+1,i))??e.slice(n,i+1),r=i+1}return t}(e.slice(l,u)),nextCursor:u+1}}(e,i,n);if(!r)break;t.set(r.name,r.value),i=r.nextCursor}return t}(e),r=e=>{let r=O(t,e);if(null!==r)return"true"===r},n=(e,r)=>{let n=(e=>{let r=O(t,e);if(null===r||""===r.trim())return;let n=Number(r);return Number.isFinite(n)?n:void 0})(r);return void 0===n?{}:{[e]:n}},i=(e,t)=>{let n=r(t);return void 0===n?{}:{[e]:n}},{text:O(t,"text"),desc:O(t,"content-desc"),resourceId:O(t,"resource-id"),packageName:O(t,"package"),className:O(t,"class"),bounds:O(t,"bounds"),clickable:r("clickable"),enabled:r("enabled"),focusable:r("focusable"),focused:r("focused"),password:r("password"),...i("visibleToUser","visible-to-user"),...n("drawingOrder","drawing-order"),...i("scrollable","scrollable"),...i("canScrollForward","can-scroll-forward"),...i("canScrollBackward","can-scroll-backward"),...n("windowIndex","window-index"),...n("windowType","window-type"),...n("windowLayer","window-layer"),...i("windowActive","window-active"),...i("windowFocused","window-focused"),...void 0===(o=E(O(t,"window-bounds")))?{}:{windowRect:o}}),s=E(a.bounds);return{...a,...s?{rect:s}:{}}}function T(e,t,r){let{sourceNodes:n,...i}=F(P(e),t,r);return i}function F(e,t,r){let n={nodes:[],sourceNodes:[],...void 0!==t?{maxNodes:t}:{},maxDepth:r.depth??1/0,options:r,analysis:function(e){let t=0,r=0,n=[...e.children];for(;n.length>0;){let e=n.pop();t+=1,r=Math.max(r,e.depth),n.push(...e.children)}return{rawNodeCount:t,maxDepth:r}}(e),interactiveDescendantMemo:new Map,truncated:!1},i=r.scope?function(e,t){let r=t.toLowerCase(),n=[...e.children],i=0;for(;i<n.length;){let e=n[i++],t=e.label?.toLowerCase()??"",o=e.value?.toLowerCase()??"",a=e.identifier?.toLowerCase()??"";if(t.includes(r)||o.includes(r)||a.includes(r))return e;n.push(...e.children)}return null}(e,r.scope):null;for(let t of i?[i]:e.children)if(function e(t,r,n,i,o=!1,a=!1){if(void 0!==t.maxNodes&&t.nodes.length>=t.maxNodes){t.truncated=!0;return}if(n>t.maxDepth)return;let s=t.options.raw||function(e,t,r,n,i){var o,a,s;if(!1===e.visibleToUser)return!1;let u=function(e){let t=V(e.type),r=!!(e.label&&e.label.trim().length>0),n=!!(e.identifier&&e.identifier.trim().length>0);return{type:t,hasMeaningfulText:r&&!B(e.label??""),hasMeaningfulId:n&&!B(e.identifier??""),isStructural:function(e){let t=e.split(".").pop()??e;return t.includes("layout")||"viewgroup"===t||"view"===t}(t),isVisual:"imageview"===t||"imagebutton"===t}}(e);return t.interactiveOnly?function(e,t,r,n,i){var o,a,s,u,d;return!((o=e).rect&&(o.rect.width<=0||o.rect.height<=0))&&(!!(e.hittable||l(t.type)&&n)||(a=t,s=r,u=n,d=i,(!!a.hasMeaningfulText||!!a.hasMeaningfulId)&&!a.isVisual&&(!a.isStructural||!!d)&&(s||u||d)))}(e,u,r,n,i):!u.isStructural&&!u.isVisual||(o=e,a=u,s=n,!!o.hittable||!!a.hasMeaningfulText||!!a.hasMeaningfulId||s)}(r,t.options,o,function e(t,r){let n=t.interactiveDescendantMemo.get(r);if(void 0!==n)return n;for(let n of r.children)if(!1!==n.visibleToUser&&(n.hittable||e(t,n)))return t.interactiveDescendantMemo.set(r,!0),!0;return t.interactiveDescendantMemo.set(r,!1),!1}(t,r),a)?function(e,t,r,n){let i=e.nodes.length;return e.sourceNodes.push(t),e.nodes.push({index:i,type:t.type??void 0,label:t.label??void 0,value:t.value??void 0,identifier:t.identifier??void 0,bundleId:t.packageName??void 0,rect:t.rect,enabled:t.enabled,visibleToUser:t.visibleToUser,hittable:t.hittable,depth:r,parentIndex:n,...t.hiddenContentAbove?{hiddenContentAbove:!0}:{},...t.hiddenContentBelow?{hiddenContentBelow:!0}:{}}),i}(t,r,n,i):i,u=o||!!r.hittable,d=a||function(e){if(!e)return!1;let t=V(e);return t.includes("recyclerview")||t.includes("listview")||t.includes("gridview")}(r.type);for(let i of r.children)if(e(t,i,n+1,s,u,d),t.truncated)return}(n,t,0),n.truncated)break;let o={nodes:n.nodes,sourceNodes:n.sourceNodes,analysis:n.analysis};return n.truncated?{...o,truncated:!0}:o}function k(e,t,r){for(;t<r&&L(e[t]??"");)t+=1;return t}function L(e){return" "===e||"\n"===e||"\r"===e||" "===e}function O(e,t){return e.get(t)??null}function E(e){if(!e)return;let t=/\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]/.exec(e);if(!t)return;let r=Number(t[1]),n=Number(t[2]);return{x:r,y:n,width:Math.max(0,Number(t[3])-r),height:Math.max(0,Number(t[4])-n)}}function P(e){let t={type:null,label:null,value:null,identifier:null,packageName:null,depth:-1,children:[]},r=[t],n=/<node\b[^>]*>|<\/node>/g,i=n.exec(e);for(;i;){let t=i[0];if(t.startsWith("</node")){r.length>1&&r.pop(),i=n.exec(e);continue}let o=_(t),a=r[r.length-1],s={type:o.className,label:o.text||o.desc,value:o.text,identifier:o.resourceId,packageName:o.packageName,rect:o.rect,enabled:o.enabled,visibleToUser:o.visibleToUser,drawingOrder:o.drawingOrder,hittable:o.clickable??o.focusable,scrollable:o.scrollable,canScrollForward:o.canScrollForward,canScrollBackward:o.canScrollBackward,windowIndex:o.windowIndex,windowType:o.windowType,windowLayer:o.windowLayer,windowActive:o.windowActive,windowFocused:o.windowFocused,windowRect:o.windowRect,depth:a.depth+1,parentIndex:void 0,children:[]};a.children.push(s),t.endsWith("/>")||r.push(s),i=n.exec(e)}return function e(t){let r=0;for(let n of t.children)!1!==n.visibleToUser&&(e(n),t.children[r]=n,r+=1);r<t.children.length&&(t.children.length=r)}(t),function(e){let t,r=e.children.filter(U);if(r.length<2)return;let n=r.filter(e=>$(e)&&H(e));if(0===n.length)return;let i=(t=n.map(e=>e.windowLayer).filter(e=>void 0!==e)).length>0?Math.max(...t):void 0;e.children=e.children.filter(e=>!$(e)||!!H(e)&&(void 0===i||e.windowLayer===i))}(t),function e(t,r){for(let n of t.children)e(n,r);if(t.children.length<2)return;let n=t.children,i=n.filter(e=>{var t,n;return t=e,n=r,!1!==t.visibleToUser&&void 0!==t.drawingOrder&&R(t)&&(function(e){if(!1===e.visibleToUser)return!1;if(e.hittable)return!0;let t=e.label?.trim()??"";if(t&&!B(t))return!0;let r=e.identifier?.trim()??"";return!(!r||B(r))}(t)||function e(t,r){let n=r.actionableContentMemo.get(t);if(void 0!==n)return n;let i=t.children.some(t=>!1!==t.visibleToUser&&(!!t.hittable||e(t,r)));return r.actionableContentMemo.set(t,i),i}(t,n))});0!==i.length&&(t.children=n.filter(e=>!function(e,t){if(!1===e.visibleToUser||void 0===e.drawingOrder||!R(e))return!1;for(let r of t)if(r!==e&&!(r.drawingOrder<=e.drawingOrder)&&function(e,t){let r=t.width*t.height;return r<=0?0:s(e,t)/r}(r.rect,e.rect)>=.9)return!0;return!1}(e,i)))}(t,{actionableContentMemo:new WeakMap}),function(e){let t=[...e.children];for(;t.length>0;){let e=t.pop();t.push(...e.children),function(e){if(!e.scrollable||!l(e.type)||`${e.type??""}`.toLowerCase().includes("horizontalscrollview"))return!1;let t=function(e){if(!e.rect||0===e.children.length)return null;let t=e.children.map(e=>e.rect).filter(e=>void 0!==e);if(0===t.length)return null;let r=Math.min(...t.map(e=>e.x)),n=Math.max(...t.map(e=>e.x+e.width)),i=Math.min(...t.map(e=>e.y)),o=Math.max(...t.map(e=>e.y+e.height));return{horizontal:Math.max(0,n-r-e.rect.width),vertical:Math.max(0,o-i-e.rect.height)}}(e);return!t||!(t.horizontal>t.vertical)||!(t.horizontal>16)}(e)&&(e.canScrollBackward&&(e.hiddenContentAbove=!0),e.canScrollForward&&(e.hiddenContentBelow=!0))}}(t),t}function R(e){return!!(e.rect&&e.rect.width>0&&e.rect.height>0)}function U(e){return void 0!==e.windowIndex||void 0!==e.windowType}function $(e){return 1===e.windowType}function H(e){return!0===e.windowActive||!0===e.windowFocused}function V(e){return e?e.toLowerCase():""}function B(e){let t=e.trim();return!!t&&/^[\w.]+:id\/[\w.-]+$/i.test(t)}async function K(e){let t=G(e),r=await e.adb(W(t),{allowFailure:!0,timeoutMs:t.commandTimeoutMs}),{output:n,cleanupDone:i}=await X(e,t,r);if(t.outputPath&&!i&&await J(e.adb,t.outputPath),0!==r.exitCode)throw new a("COMMAND_FAILED","Android snapshot helper failed",{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode,helper:n.metadata});return n}function G(e){let t=Q(e.timeoutMs,8e3),r=Q(e.packageName,h);return{waitForIdleTimeoutMs:Q(e.waitForIdleTimeoutMs,500),waitForIdleQuietMs:Q(e.waitForIdleQuietMs,100),timeoutMs:t,commandTimeoutMs:Q(e.commandTimeoutMs,t+5e3),maxDepth:Q(e.maxDepth,128),maxNodes:Q(e.maxNodes,5e3),packageName:r,runner:Q(e.instrumentationRunner,`${r}/.SnapshotInstrumentation`),...e.outputPath?{outputPath:e.outputPath}:{},...void 0!==e.emitChunks?{emitChunks:e.emitChunks}:{}}}function Q(e,t){return void 0===e?t:e}function W(e){return["shell","am","instrument","-w","-e","waitForIdleTimeoutMs",String(e.waitForIdleTimeoutMs),"-e","waitForIdleQuietMs",String(e.waitForIdleQuietMs),"-e","timeoutMs",String(e.timeoutMs),"-e","maxDepth",String(e.maxDepth),"-e","maxNodes",String(e.maxNodes),...e.outputPath?["-e","outputPath",e.outputPath]:[],...void 0!==e.emitChunks?["-e","emitChunks",String(e.emitChunks)]:[],e.runner]}async function X(e,t,r){try{return{output:Y(`${r.stdout}
|
|
2
2
|
${r.stderr}`),cleanupDone:!1}}catch(n){return await z(e,t,r,n)}}async function z(e,t,r,n){if(n instanceof a&&0!==r.exitCode&&n.details?.helper)throw n;let i=await j(e,t,r);if(i)return{output:i,cleanupDone:!0};throw new a("COMMAND_FAILED",0===r.exitCode?"Android snapshot helper output could not be parsed":"Android snapshot helper failed before returning parseable output",{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode},n)}async function j(e,t,r){if(0===r.exitCode&&t.outputPath){var n;return await q(e.adb,t.outputPath,function(e){try{let t=er(e);return et(ee(t.results))}catch{return null}}(`${r.stdout}
|
|
3
|
-
${r.stderr}`)??{outputFormat:w,waitForIdleTimeoutMs:(n=t).waitForIdleTimeoutMs,waitForIdleQuietMs:n.waitForIdleQuietMs,timeoutMs:n.timeoutMs,maxDepth:n.maxDepth,maxNodes:n.maxNodes,transport:"instrumentation"})}}async function q(e,t,r){let n;try{var i;n=await e((i=t,["shell","sh","-c",'cat "$1"; status=$?; rm -f "$1"; exit "$status"',"agent-device-snapshot-helper-output",i]),{allowFailure:!0,timeoutMs:5e3})}catch{return}if(0!==n.exitCode)return;let o=n.stdout.trim();if(o.includes("<hierarchy")&&o.includes("</hierarchy>"))return{xml:o,metadata:r}}async function J(e,t){try{await e(["shell","rm","-f",t],{allowFailure:!0,timeoutMs:5e3})}catch{}}function Y(e){let t=er(e),r=ee(t.results);return{xml:function(e,t){if(0===e.length)throw new a("COMMAND_FAILED","Android snapshot helper did not return XML chunks",{helper:t});let r=function(e){let t=e[0]?.count??e.length;if(t<1||e.length!==t||e.some(e=>e.count!==t))throw new a("COMMAND_FAILED","Android snapshot helper returned incomplete XML chunks",{expectedChunks:t,actualChunks:e.length});return t}(e),n=Buffer.concat(function(e,t){let r=[];for(let n=0;n<t;n+=1){let i=e.get(n);if(void 0===i)throw new a("COMMAND_FAILED","Android snapshot helper returned incomplete XML chunks",{missingChunkIndex:n,expectedChunks:t});r.push(Buffer.from(i,"base64"))}return r}(function(e,t){let r=new Map;for(let n of e){if(void 0===n.index||n.index<0||n.index>=t)throw new a("COMMAND_FAILED","Android snapshot helper returned invalid chunk index",{chunkIndex:n.index,expectedChunks:t});if(r.has(n.index))throw new a("COMMAND_FAILED","Android snapshot helper returned duplicate XML chunks",{chunkIndex:n.index});r.set(n.index,n.payloadBase64)}return r}(e,r),r)).toString("utf8");if(!n.includes("<hierarchy")||!n.includes("</hierarchy>"))throw new a("COMMAND_FAILED","Android snapshot helper output did not contain XML",{xml:n});return n}(function(e){let t=[];for(let r of e){if(r.agentDeviceProtocol!==f||r.outputFormat!==w)continue;let{payloadBase64:e}=r;void 0!==e&&t.push({index:el(r.chunkIndex),count:el(r.chunkCount),payloadBase64:e})}return t}(t.status),r),metadata:{...et(r),transport:"instrumentation"}}}function Z(e,t={outputFormat:w},r={},n){return{...T(e,n,r),metadata:t}}function ee(e){let t=e.find(e=>e.agentDeviceProtocol===f);if(!t)throw new a("COMMAND_FAILED","Android snapshot helper did not return a final result");if("true"!==t.ok){var r;throw new a("COMMAND_FAILED",(r=t).message&&"null"!==r.message?r.message:r.errorType||"Android snapshot helper returned an error",{errorType:t.errorType,helper:t})}return t}function et(e){var t;return{helperApiVersion:e.helperApiVersion,outputFormat:w,waitForIdleTimeoutMs:el(e.waitForIdleTimeoutMs),waitForIdleQuietMs:el(e.waitForIdleQuietMs),timeoutMs:el(e.timeoutMs),maxDepth:el(e.maxDepth),maxNodes:el(e.maxNodes),rootPresent:eu(e.rootPresent),captureMode:"interactive-windows"===(t=e.captureMode)||"active-window"===t?t:void 0,windowCount:el(e.windowCount),nodeCount:el(e.nodeCount),truncated:eu(e.truncated),elapsedMs:el(e.elapsedMs)}}function er(e){var t;let r={status:[],results:[],currentStatus:null,currentResult:null};for(let t of e.split(/\r?\n/))!function(e,t){if(e.startsWith("INSTRUMENTATION_STATUS: ")){t.currentStatus??={},eo(e.slice(24),t.currentStatus);return}if(e.startsWith("INSTRUMENTATION_STATUS_CODE: "))return en(t);if(e.startsWith("INSTRUMENTATION_RESULT: ")){t.currentResult??={},eo(e.slice(24),t.currentResult);return}e.startsWith("INSTRUMENTATION_CODE: ")&&ei(t)}(t,r);return en(t=r),ei(t),{status:r.status,results:r.results}}function en(e){e.currentStatus&&(e.status.push(e.currentStatus),e.currentStatus=null)}function ei(e){e.currentResult&&(e.results.push(e.currentResult),e.currentResult=null)}function eo(e,t){let r=e.indexOf("=");r<0||(t[e.slice(0,r)]=e.slice(r+1))}function ea(e){if(void 0===e)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function es(e){return"true"===e||"false"!==e&&void 0}let el=ea,eu=es,ed=new Map,ec=new Map;async function eh(e){var t,r,n;let i;if(!(void 0===(i=process.env.AGENT_DEVICE_ANDROID_SNAPSHOT_HELPER_SESSION)||!/^(0|false|no|off)$/i.test(i))||!e.adbProvider?.spawn)return;let o=G(e),a=e.deviceKey??"android:default",s=(t=a,r=o,n=e,JSON.stringify({deviceKey:t,packageName:r.packageName,runner:r.runner,helperVersion:n.helperVersion,helperVersionCode:n.helperVersionCode,waitForIdleTimeoutMs:r.waitForIdleTimeoutMs,waitForIdleQuietMs:r.waitForIdleQuietMs,timeoutMs:r.timeoutMs,maxDepth:r.maxDepth,maxNodes:r.maxNodes}));if(ec.get(a)===s)return;let l=ed.get(a);if(l&&l.identity!==s&&(await ep(a),l=void 0),!l)try{l=await
|
|
4
|
-
`)}),s.on("data",e=>{l.push(Buffer.from(e))}),s.on("error",e=>{clearTimeout(u),i(e)}),s.on("close",()=>{clearTimeout(u),n(Buffer.concat(l).toString("utf8"))})})}async function
|
|
5
|
-
${n.stderr}`,o=t;let e=`package:${o}`;for(let t of i.split(/\r?\n/)){if(!t.startsWith(e)||t.length>e.length&&!/\s/.test(t[e.length]??""))continue;let r=/(?:^|\s)versionCode:(\d+)(?:\s|$)/.exec(t);if(r)return Number(r[1])}return}}async function
|
|
6
|
-
${o.stderr}`.includes("INSTALL_FAILED_UPDATE_INCOMPATIBLE")))return s;let l=await e(["uninstall",i.packageName],{allowFailure:!0,timeoutMs:i.timeoutMs}),u=await a();return 0===u.exitCode?u:{...u,stderr:[u.stderr,l.stderr?`Previous uninstall stderr after INSTALL_FAILED_UPDATE_INCOMPATIBLE: ${l.stderr}`:""].filter(Boolean).join("\n")}}export{c as ANDROID_SNAPSHOT_HELPER_NAME,w as ANDROID_SNAPSHOT_HELPER_OUTPUT_FORMAT,h as ANDROID_SNAPSHOT_HELPER_PACKAGE,f as ANDROID_SNAPSHOT_HELPER_PROTOCOL,p as ANDROID_SNAPSHOT_HELPER_RUNNER,S as androidUiNodes,
|
|
3
|
+
${r.stderr}`)??{outputFormat:w,waitForIdleTimeoutMs:(n=t).waitForIdleTimeoutMs,waitForIdleQuietMs:n.waitForIdleQuietMs,timeoutMs:n.timeoutMs,maxDepth:n.maxDepth,maxNodes:n.maxNodes,transport:"instrumentation"})}}async function q(e,t,r){let n;try{var i;n=await e((i=t,["shell","sh","-c",'cat "$1"; status=$?; rm -f "$1"; exit "$status"',"agent-device-snapshot-helper-output",i]),{allowFailure:!0,timeoutMs:5e3})}catch{return}if(0!==n.exitCode)return;let o=n.stdout.trim();if(o.includes("<hierarchy")&&o.includes("</hierarchy>"))return{xml:o,metadata:r}}async function J(e,t){try{await e(["shell","rm","-f",t],{allowFailure:!0,timeoutMs:5e3})}catch{}}function Y(e){let t=er(e),r=ee(t.results);return{xml:function(e,t){if(0===e.length)throw new a("COMMAND_FAILED","Android snapshot helper did not return XML chunks",{helper:t});let r=function(e){let t=e[0]?.count??e.length;if(t<1||e.length!==t||e.some(e=>e.count!==t))throw new a("COMMAND_FAILED","Android snapshot helper returned incomplete XML chunks",{expectedChunks:t,actualChunks:e.length});return t}(e),n=Buffer.concat(function(e,t){let r=[];for(let n=0;n<t;n+=1){let i=e.get(n);if(void 0===i)throw new a("COMMAND_FAILED","Android snapshot helper returned incomplete XML chunks",{missingChunkIndex:n,expectedChunks:t});r.push(Buffer.from(i,"base64"))}return r}(function(e,t){let r=new Map;for(let n of e){if(void 0===n.index||n.index<0||n.index>=t)throw new a("COMMAND_FAILED","Android snapshot helper returned invalid chunk index",{chunkIndex:n.index,expectedChunks:t});if(r.has(n.index))throw new a("COMMAND_FAILED","Android snapshot helper returned duplicate XML chunks",{chunkIndex:n.index});r.set(n.index,n.payloadBase64)}return r}(e,r),r)).toString("utf8");if(!n.includes("<hierarchy")||!n.includes("</hierarchy>"))throw new a("COMMAND_FAILED","Android snapshot helper output did not contain XML",{xml:n});return n}(function(e){let t=[];for(let r of e){if(r.agentDeviceProtocol!==f||r.outputFormat!==w)continue;let{payloadBase64:e}=r;void 0!==e&&t.push({index:el(r.chunkIndex),count:el(r.chunkCount),payloadBase64:e})}return t}(t.status),r),metadata:{...et(r),transport:"instrumentation"}}}function Z(e,t={outputFormat:w},r={},n){return{...T(e,n,r),metadata:t}}function ee(e){let t=e.find(e=>e.agentDeviceProtocol===f);if(!t)throw new a("COMMAND_FAILED","Android snapshot helper did not return a final result");if("true"!==t.ok){var r;throw new a("COMMAND_FAILED",(r=t).message&&"null"!==r.message?r.message:r.errorType||"Android snapshot helper returned an error",{errorType:t.errorType,helper:t})}return t}function et(e){var t;return{helperApiVersion:e.helperApiVersion,outputFormat:w,waitForIdleTimeoutMs:el(e.waitForIdleTimeoutMs),waitForIdleQuietMs:el(e.waitForIdleQuietMs),timeoutMs:el(e.timeoutMs),maxDepth:el(e.maxDepth),maxNodes:el(e.maxNodes),rootPresent:eu(e.rootPresent),captureMode:"interactive-windows"===(t=e.captureMode)||"active-window"===t?t:void 0,windowCount:el(e.windowCount),nodeCount:el(e.nodeCount),truncated:eu(e.truncated),elapsedMs:el(e.elapsedMs)}}function er(e){var t;let r={status:[],results:[],currentStatus:null,currentResult:null};for(let t of e.split(/\r?\n/))!function(e,t){if(e.startsWith("INSTRUMENTATION_STATUS: ")){t.currentStatus??={},eo(e.slice(24),t.currentStatus);return}if(e.startsWith("INSTRUMENTATION_STATUS_CODE: "))return en(t);if(e.startsWith("INSTRUMENTATION_RESULT: ")){t.currentResult??={},eo(e.slice(24),t.currentResult);return}e.startsWith("INSTRUMENTATION_CODE: ")&&ei(t)}(t,r);return en(t=r),ei(t),{status:r.status,results:r.results}}function en(e){e.currentStatus&&(e.status.push(e.currentStatus),e.currentStatus=null)}function ei(e){e.currentResult&&(e.results.push(e.currentResult),e.currentResult=null)}function eo(e,t){let r=e.indexOf("=");r<0||(t[e.slice(0,r)]=e.slice(r+1))}function ea(e){if(void 0===e)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function es(e){return"true"===e||"false"!==e&&void 0}let el=ea,eu=es,ed=new Map,ec=new Map;async function eh(e){var t,r,n;let i;if(!(void 0===(i=process.env.AGENT_DEVICE_ANDROID_SNAPSHOT_HELPER_SESSION)||!/^(0|false|no|off)$/i.test(i))||!e.adbProvider?.spawn)return;let o=G(e),a=e.deviceKey??"android:default",s=(t=a,r=o,n=e,JSON.stringify({deviceKey:t,packageName:r.packageName,runner:r.runner,helperVersion:n.helperVersion,helperVersionCode:n.helperVersionCode,waitForIdleTimeoutMs:r.waitForIdleTimeoutMs,waitForIdleQuietMs:r.waitForIdleQuietMs,timeoutMs:r.timeoutMs,maxDepth:r.maxDepth,maxNodes:r.maxNodes}));if(ec.get(a)===s)return;let l=ed.get(a);if(l&&l.identity!==s&&(await ep(a),l=void 0),!l)try{l=await em({deviceKey:a,identity:s,options:e,resolved:o})}catch(e){ec.set(a,s),u({level:"warn",phase:"android_snapshot_helper_session_disabled",data:{deviceKey:a,reason:e instanceof Error?e.message:String(e)}});return}try{let e=l.capturedCount>0,t=await eM(l,o);return l.capturedCount+=1,{xml:t.xml,metadata:{...t.metadata,transport:"persistent-session",sessionReused:e}}}catch(e){throw await ep(a),e}}async function ep(e){let t=ed.get(e);if(t){ed.delete(e);try{await eg(t,`quit ${Date.now()}`,1e3)}catch{}try{await t.process.kill("SIGTERM")}catch{}await eA(t.process,2e3);try{await ev(t)}catch{}u({phase:"android_snapshot_helper_session_stop",data:{deviceKey:e,port:t.port,capturedCount:t.capturedCount,lifetimeMs:Date.now()-t.startedAtMs}})}}async function ef(e){await ep(ew(e))}function ew(e){return`${e.platform}:${e.id}`}async function em(e){let t=await new Promise((e,t)=>{let r=o.createServer();r.unref(),r.on("error",t),r.listen(0,"127.0.0.1",()=>{let n=r.address();if(!n||"string"==typeof n)return void r.close(()=>t(Error("Failed to allocate a local TCP port")));let i=n.port;r.close(()=>e(i))})});await e.options.adb(["forward",`tcp:${t}`,`tcp:${t}`],{allowFailure:!1,timeoutMs:5e3});let r=W({...e.resolved,outputPath:void 0,emitChunks:!1}),n=r[r.length-1];if(!n)throw new a("INVALID_ARGS","Android snapshot helper runner was not resolved");let i=[...r.slice(0,-1),"-e","sessionPort",String(t),n],s=e.options.adbProvider.spawn(i,{allowFailure:!0,captureOutput:!1}),l={identity:e.identity,deviceKey:e.deviceKey,port:t,adb:e.options.adb,process:s,startedAtMs:Date.now(),capturedCount:0};try{var d;return await (d=s,new Promise((e,t)=>{let r="",n=setTimeout(()=>{t(new a("COMMAND_FAILED","Android snapshot helper session did not become ready",{output:r,timeoutMs:1e4}))},1e4),i=t=>{(r+=t.toString()).includes(`agentDeviceProtocol=${f}`)&&r.includes("sessionReady=true")&&(clearTimeout(n),e())};d.stdout?.on("data",i),d.stderr?.on("data",i),d.once("exit",(e,i)=>{clearTimeout(n),t(new a("COMMAND_FAILED","Android snapshot helper session exited before ready",{output:r,exitCode:e,signal:i}))}),d.on("error",e=>{clearTimeout(n),t(e)})})),ed.set(e.deviceKey,l),u({phase:"android_snapshot_helper_session_ready",data:{deviceKey:e.deviceKey,port:t,packageName:e.resolved.packageName,runner:e.resolved.runner}}),l}catch(e){await ev(l);try{s.kill("SIGTERM")}catch{}throw await eA(s,2e3),e}}function eA(e,t){return new Promise(r=>{let n=setTimeout(r,t);e.once("close",()=>{clearTimeout(n),r()}),e.once("exit",()=>{clearTimeout(n),r()})})}async function eM(e,t){let r=`snapshot-${Date.now()}-${Math.random().toString(16).slice(2)}`,n=Math.min(t.commandTimeoutMs,Math.max(t.timeoutMs+1e4,3e3));return function(e,t){var r;let{headers:n,xml:i}=function(e){let t=e.indexOf("\n\n");if(t<0)throw new a("COMMAND_FAILED","Android snapshot helper session returned malformed output",{response:e});return{headers:function(e){let t={};for(let r of e.split(/\r?\n/)){let e=r.indexOf("=");e<0||(t[r.slice(0,e)]=r.slice(e+1))}return t}(e.slice(0,t)),xml:e.slice(t+2)}}(e);return function(e,t){if(e.agentDeviceProtocol!==f)throw new a("COMMAND_FAILED","Android snapshot helper session returned wrong protocol",{headers:e});if(e.outputFormat!==w)throw new a("COMMAND_FAILED","Android snapshot helper session returned wrong output format",{headers:e});if(e.requestId!==t)throw new a("COMMAND_FAILED","Android snapshot helper session returned stale output",{headers:e,requestId:t});if("true"!==e.ok)throw new a("COMMAND_FAILED",e.message||e.errorType||"Android snapshot helper session returned an error",{helper:e})}(n,t),function(e,t){let r=ea(e.byteLength);if(void 0!==r&&Buffer.byteLength(t,"utf8")!==r)throw new a("COMMAND_FAILED","Android snapshot helper session returned truncated XML",{headers:e,actualByteLength:Buffer.byteLength(t,"utf8")});if(!t.includes("<hierarchy")||!t.includes("</hierarchy>"))throw new a("COMMAND_FAILED","Android snapshot helper session did not return XML",{headers:e,xml:t})}(n,i),{xml:i,metadata:{helperApiVersion:(r=n).helperApiVersion,outputFormat:w,waitForIdleTimeoutMs:ea(r.waitForIdleTimeoutMs),waitForIdleQuietMs:ea(r.waitForIdleQuietMs),timeoutMs:ea(r.timeoutMs),maxDepth:ea(r.maxDepth),maxNodes:ea(r.maxNodes),rootPresent:es(r.rootPresent),captureMode:"interactive-windows"===r.captureMode||"active-window"===r.captureMode?r.captureMode:void 0,windowCount:ea(r.windowCount),nodeCount:ea(r.nodeCount),truncated:es(r.truncated),elapsedMs:ea(r.elapsedMs)}}}(await eg(e,`snapshot ${r}`,n),r)}function eg(e,t,r){return new Promise((n,i)=>{let s=o.connect({host:"127.0.0.1",port:e.port}),l=[],u=setTimeout(()=>{s.destroy(),i(new a("COMMAND_FAILED","Android snapshot helper session request timed out",{command:t,timeoutMs:r,port:e.port}))},r);s.on("connect",()=>{s.write(`${t}
|
|
4
|
+
`)}),s.on("data",e=>{l.push(Buffer.from(e))}),s.on("error",e=>{clearTimeout(u),i(e)}),s.on("close",()=>{clearTimeout(u),n(Buffer.concat(l).toString("utf8"))})})}async function ev(e){await e.process.stdin?.end(),await e.process.stdout?.destroy(),await e.process.stderr?.destroy(),await eN(e)}async function eN(e){await e.adb(["forward","--remove",`tcp:${e.port}`],{allowFailure:!0,timeoutMs:5e3})}let ey=new Map;function ex(e){eD(eI(e.deviceKey,e.packageName,e.versionCode))}function eI(e,t,r){return e?`${e}\0${t}\0${r}`:void 0}function eD(e){e&&ey.delete(e)}async function eC(e){var t,r,n;let{adb:i,artifact:o}=e,s=e.installPolicy??"missing-or-outdated",l=o.manifest.packageName,u=o.manifest.versionCode;if("never"===s)return{packageName:l,versionCode:u,installed:!1,reason:"skipped"};let d=eI(e.deviceKey,l,u),c=d?ey.get(d):void 0;if(d&&"always"!==s&&void 0!==c)return{packageName:l,versionCode:u,installedVersionCode:c,installed:!1,reason:"current"};let h=await eb(i,l,e.timeoutMs),p=(t=s,r=h,n=u,"never"===t?"skipped":"always"===t?"forced":void 0===r?"missing":r<n?"outdated":"current");if("current"===p){if(void 0===h)throw Error("Expected installed versionCode for current Android snapshot helper");return d&&ey.set(d,h),{packageName:l,versionCode:u,installedVersionCode:h,installed:!1,reason:p}}await A(o);let f=await eS(i,e.adbProvider??i,o.apkPath,function(e){let t={};for(let r of e.slice(1)){let e=b(r);if(!e)throw new a("INVALID_ARGS",`Android snapshot helper manifest installArgs contains unsupported install flag "${r}".`);t[e]=!0}return t}(N(o.manifest.installArgs)),{packageName:l,timeoutMs:e.timeoutMs});if(0!==f.exitCode)throw eD(d),new a("COMMAND_FAILED","Failed to install Android snapshot helper",{packageName:l,versionCode:u,stdout:f.stdout,stderr:f.stderr,exitCode:f.exitCode});return d&&ey.set(d,u),{packageName:l,versionCode:u,installedVersionCode:h,installed:!0,reason:p}}async function eb(e,t,r){let n=await e(["shell","cmd","package","list","packages","--show-versioncode",t],{allowFailure:!0,timeoutMs:r});if(0===n.exitCode){var i=`${n.stdout}
|
|
5
|
+
${n.stderr}`,o=t;let e=`package:${o}`;for(let t of i.split(/\r?\n/)){if(!t.startsWith(e)||t.length>e.length&&!/\s/.test(t[e.length]??""))continue;let r=/(?:^|\s)versionCode:(\d+)(?:\s|$)/.exec(t);if(r)return Number(r[1])}return}}async function eS(e,t,r,n,i){var o;let a=async()=>await d(r,{allowFailure:!0,provider:t,...n,timeoutMs:i.timeoutMs}),s=await a();if(0===s.exitCode||(o=s,!`${o.stdout}
|
|
6
|
+
${o.stderr}`.includes("INSTALL_FAILED_UPDATE_INCOMPATIBLE")))return s;let l=await e(["uninstall",i.packageName],{allowFailure:!0,timeoutMs:i.timeoutMs}),u=await a();return 0===u.exitCode?u:{...u,stderr:[u.stderr,l.stderr?`Previous uninstall stderr after INSTALL_FAILED_UPDATE_INCOMPATIBLE: ${l.stderr}`:""].filter(Boolean).join("\n")}}export{c as ANDROID_SNAPSHOT_HELPER_NAME,w as ANDROID_SNAPSHOT_HELPER_OUTPUT_FORMAT,h as ANDROID_SNAPSHOT_HELPER_PACKAGE,f as ANDROID_SNAPSHOT_HELPER_PROTOCOL,p as ANDROID_SNAPSHOT_HELPER_RUNNER,S as androidUiNodes,F as buildUiHierarchySnapshot,K as captureAndroidSnapshotWithHelper,eh as captureAndroidSnapshotWithHelperSession,eC as ensureAndroidSnapshotHelper,ex as forgetAndroidSnapshotHelperInstall,ew as getAndroidSnapshotHelperSessionDeviceKey,g as parseAndroidSnapshotHelperManifest,Y as parseAndroidSnapshotHelperOutput,Z as parseAndroidSnapshotHelperXml,T as parseUiHierarchy,P as parseUiHierarchyTree,M as prepareAndroidSnapshotHelperArtifactFromManifestUrl,ep as stopAndroidSnapshotHelperSession,ef as stopAndroidSnapshotHelperSessionForDevice,A as verifyAndroidSnapshotHelperArtifact};
|
package/dist/src/8184.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{setSessionSnapshot as e,captureSnapshot as r,isNavigationSensitiveAction as t,markPendingInteractionOutcome as n,markPostGestureStabilization as o,getSnapshotReferenceFrame as i,recordTouchVisualizationEvent as a,markAndroidSnapshotFreshness as c,stripInternalInteractionFlags as s}from"./9722.js";import{isSparseSnapshotQualityVerdict as d,successText as f}from"./
|
|
1
|
+
import{setSessionSnapshot as e,captureSnapshot as r,isNavigationSensitiveAction as t,markPendingInteractionOutcome as n,markPostGestureStabilization as o,getSnapshotReferenceFrame as i,recordTouchVisualizationEvent as a,markAndroidSnapshotFreshness as c,stripInternalInteractionFlags as s}from"./9722.js";import{isSparseSnapshotQualityVerdict as d,successText as f}from"./2948.js";import{getAndroidScreenSize as u}from"./input-actions.js";import{emitDiagnostic as l}from"./432.js";async function h(t,n,o,i,a){let c={...n??{},snapshotInteractiveOnly:a.interactiveOnly},s=i(c,t.appBundleId,t.trace?.outPath),{snapshot:f}=await r({device:t.device,session:t,flags:c,outPath:c.out,logPath:s.logPath??"",includeRects:a.includeRects,androidFreshnessMode:a.androidFreshnessMode});return d(f.snapshotQuality)||(e(t,f),o.set(t.name,t)),f}function p(e){var r,t,n;let o,i,a,c,{data:s,fallbackX:d,fallbackY:u,referenceFrame:l,extra:h}=e,p=(r=h,t=d,n=u,o="string"==typeof r?.ref?r.ref:void 0,i="string"==typeof r?.button?r.button:void 0,a="string"==typeof r?.gesture?r.gesture:void 0,c=void 0===t||void 0===n?"":` (${t}, ${n})`,("string"==typeof r?.text?`Filled ${Array.from(r.text).length} chars`:o?"longpress"===a?`Long pressed @${o}${c}`:i&&"primary"!==i?`Clicked ${i} @${o}${c}`:`Tapped @${o}${c}`:void 0)??("string"==typeof s?.message?s.message:void 0));return{...void 0===d||void 0===u?{}:{x:d,y:u},...l??{},...h??{},...s??{},...f(p)}}function g(e){let{session:r,sessionStore:i,command:d,positionals:f,retryPositionals:u,flags:l,result:h,responseData:p,actionStartedAt:g,actionFinishedAt:_,androidFreshnessBaseline:m}=e,v=s(l);return i.recordAction(r,{command:d,positionals:f,flags:v??{},result:h}),n({session:r,command:d,positionals:u??f,flags:l,preSnapshot:r.snapshot}),t(d)&&c(r,d,m??r.snapshot),o(r,d,u??f,l),a(r,d,f,h,v??{},g,_),{ok:!0,data:p}}async function _(e){let{session:r,flags:t,sessionStore:n,contextFromFlags:o,captureSnapshotForSession:a}=e;if(!r.recording)return;if(r.recording.touchReferenceFrame)return r.recording.touchReferenceFrame;if("android"===r.device.platform){let e=await u(r.device),t={referenceWidth:e.width,referenceHeight:e.height};return r.recording&&(r.recording.touchReferenceFrame=t),t}let c=i(r.snapshot);if(c)return r.recording&&(r.recording.touchReferenceFrame=c),c;if(!r.recording)return;let s=i(await a(r,t,n,o,{interactiveOnly:!0}));return s&&r.recording&&(r.recording.touchReferenceFrame=s),s}async function m(e){try{return await _(e)}catch(r){l({level:"warn",phase:"touch_reference_frame_resolve_failed",data:{platform:e.session.device.platform,error:r instanceof Error?r.message:String(r)}});return}}function v(e){return i({nodes:e,createdAt:0})}export{p as buildTouchVisualizationResult,g as finalizeTouchInteraction,h as interaction_snapshot_captureSnapshotForSession,v as readSnapshotNodesReferenceFrame,m as resolveDirectTouchReferenceFrameSafely};
|
package/dist/src/8358.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import e from"node:crypto";import t from"node:fs";import n from"node:path";import{resolveUserPath as r,expandUserHomePath as o}from"./9612.js";import{readVersion as s,findProjectRoot as i}from"./1404.js";function a(s,u={}){var l,c;let p,f=(l=s,c=u,(p=(l??"").trim())?r(p,{env:c.env}):function(r={}){var s;let a,u,l,c=n.join(o("~",{env:r.env}),".agent-device"),p=r.projectRoot??i();return(s=p,t.existsSync(n.join(s,"package.json"))&&t.existsSync(n.join(s,"src","daemon.ts")))?n.join(c,"dev",(a=function(e){try{return t.realpathSync.native(e)}catch{return n.resolve(e)}}(p),u=n.basename(a).replaceAll(/[^a-zA-Z0-9._-]+/g,"-"),l=e.createHash("sha1").update(a).digest("hex").slice(0,12),`${u||"agent-device"}-${l}`)):c}(c));return{baseDir:f,infoPath:n.join(f,"daemon.json"),lockPath:n.join(f,"daemon.lock"),logPath:n.join(f,"daemon.log"),sessionsDir:n.join(f,"sessions")}}function u(e){let t=(e??"").trim().toLowerCase();return"http"===t?"http":"dual"===t?"dual":"socket"}function l(e){let t=(e??"").trim().toLowerCase();return"auto"===t?"auto":"socket"===t?"socket":"http"===t?"http":"auto"}function c(e){return"tenant"===(e??"").trim().toLowerCase()?"tenant":"none"}function p(e){if(!e)return;let t=e.trim();if(t&&/^[a-zA-Z0-9._-]{1,128}$/.test(t))return t}let f=/(?:^|[^\w$.])(?:import|export)\s+(?:type\s+)?(?:[^'"`]*?\s+from\s+)?['"]([^'"]+)['"]/gm,m=/import\(\s*['"]([^'"]+)['"]\s*\)/gm,d=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];function h(){let e=process.argv[1];return e?g(e):"unknown"}function g(r,o=i()){try{let s=n.resolve(o),i=[n.resolve(r)],a=new Set,u=[];for(;i.length>0;){let e=i.pop();if(!e||a.has(e))continue;a.add(e);let r=t.statSync(e);if(!r.isFile())continue;let o=n.relative(s,e)||e;u.push(`${o}:${r.size}:${Math.trunc(r.mtimeMs)}`);let l=t.readFileSync(e,"utf8");for(let t of function(e){let t=new Set;return M(e,f,t),M(e,m,t),[...t]}(l)){let r=function(e,t){let r=n.resolve(n.dirname(e),t),o=v(r);if(o)return o;for(let e of d){let t=v(`${r}${e}`);if(t)return t}for(let e of d){let t=v(n.join(r,`index${e}`));if(t)return t}return null}(e,t);r&&i.push(r)}}let l=u.sort().join("|"),c=e.createHash("sha1").update(l).digest("hex");return`graph:${u.length}:${c}`}catch{return"unknown"}}function M(e,t,n){t.lastIndex=0;let r=null;for(;null!==(r=t.exec(e));){let e=r[1]?.trim();e?.startsWith(".")&&n.add(e)}}function v(e){try{return t.statSync(e).isFile()?e:null}catch{return null}}let y=/^[A-Za-z0-9_@%+=:,./-]+$/;function S(e){return`'${e.replaceAll("'","'\\''")}'`}function j(e){return y.test(e)?e:S(e)}function x(e,t){let n=[],r=e+t.toString(),o=r.indexOf("\n");for(;-1!==o;){let e=r.slice(0,o).trim();r=r.slice(o+1),e&&n.push(e),o=r.indexOf("\n")}return{lines:n,buffer:r}}function $(e){return e.meta?.requestProgress==="replay-test"}function b(e){return!!e&&"object"==typeof e&&"progress"===e.type&&!!e.event}function w(e){return!!e&&"object"==typeof e&&"response"===e.type&&!!e.response}function D(e){return`${JSON.stringify({type:"progress",event:e})}
|
|
2
|
+
`}function k(e){return`${JSON.stringify({type:"response",response:e})}
|
|
3
|
+
`}function P(e){return`${JSON.stringify({type:"response",response:e})}
|
|
4
|
+
`}function _(e,t={}){return{ok:!0,service:e,version:s(),rpcProtocolVersion:1,...void 0!==t.upstream?{upstream:t.upstream}:{}}}function A(e,t){e&&(e.snapshotDiagnostics??={samples:[]}).samples.push({...t,durationMs:Math.max(0,Math.round(t.durationMs))})}function z(e){let t=e?.snapshotDiagnostics?.samples;if(t&&0!==t.length)return C(t)}function C(e){if(0===e.length)return;let t=R(e);return{stats:t,...t.p95Ms>=1500?{warning:N(t)}:{}}}function O(e){let t=e.flatMap(e=>(function(e){if(!e||e.count<=0)return[];let t=e.platform;return 1===e.count?[{durationMs:e.maxMs,platform:t}]:2===e.count?[{durationMs:e.p50Ms,platform:t},{durationMs:e.maxMs,platform:t}]:[...Array.from({length:e.count-3},()=>({durationMs:e.p50Ms,platform:t})),{durationMs:e.p50Ms,platform:t},{durationMs:e.p95Ms,platform:t},{durationMs:e.maxMs,platform:t}]})(e?.stats));if(0===t.length)return;let n=R(t);return{stats:n,...n.p95Ms>=1500?{warning:N(n)}:{}}}function E(e){if(!e||"object"!=typeof e||Array.isArray(e))return;let t=function(e){let t=H(e);if(!t)return;let n=function(e){let t={count:e.count,p50Ms:e.p50Ms,p95Ms:e.p95Ms,maxMs:e.maxMs,slowThresholdMs:e.slowThresholdMs};if(!Object.values(t).some(e=>"number"!=typeof e))return t}(t);if(n){var r;let e,o,s,i;return{...n,...(o="string"==typeof(r=t).platform?r.platform:void 0,i=(s=H(r.backends))&&(e=Object.entries(s).filter(e=>"number"==typeof e[1])).length>0?Object.fromEntries(e):void 0,{...o?{platform:o}:{},...i?{backends:i}:{}})}}}(e.stats);if(!t)return;let n="string"==typeof e.warning?e.warning:void 0;return{stats:t,...n?{warning:n}:{}}}function R(e){let t,n=e.map(e=>e.durationMs).sort((e,t)=>e-t);return{count:n.length,p50Ms:T(n,50),p95Ms:T(n,95),maxMs:n[n.length-1]??0,slowThresholdMs:1500,...1===new Set(t=e.map(e=>e.platform).filter(e=>!!e)).size?{platform:t[0]}:{},...function(e){let t={};for(let n of e)n.backend&&(t[n.backend]=(t[n.backend]??0)+1);return Object.keys(t).length>0?{backends:t}:{}}(e)}}function T(e,t){if(0===e.length)return 0;let n=Math.max(0,Math.ceil(t/100*e.length)-1);return e[Math.min(n,e.length-1)]??0}function N(e){let t=e.platform?`${e.platform} `:"";return`Warning: ${t}snapshots are slow in this run: p95 ${e.p95Ms}ms over ${e.count} captures. Possible causes: device load, app or dev server stuck, helper fallback, or stale daemon.`}function H(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:void 0}export{_ as buildDaemonHealthPayload,g as computeDaemonCodeSignature,x as consumeTextLines,b as isDaemonProgressEnvelope,w as isDaemonResponseEnvelope,O as mergeSnapshotDiagnostics,p as normalizeTenantId,E as readSnapshotDiagnosticsSummary,A as recordSnapshotTiming,h as resolveDaemonCodeSignature,a as resolveDaemonPaths,u as resolveDaemonServerMode,l as resolveDaemonTransportPreference,c as resolveSessionIsolationMode,D as serializeDaemonProgressEnvelope,k as serializeDaemonResponseEnvelope,P as serializeDaemonRpcResponseEnvelope,S as shellQuote,j as shellQuoteIfNeeded,$ as shouldStreamRequestProgress,z as summarizeSnapshotDiagnostics,C as summarizeSnapshotTimingSamples};
|
package/dist/src/9581.js
CHANGED
|
@@ -1,4 +1,15 @@
|
|
|
1
|
-
import{COMMON_COMMAND_SUPPORTED_FLAG_KEYS as e,
|
|
1
|
+
import{COMMON_COMMAND_SUPPORTED_FLAG_KEYS as e,listCommandFamilyCliSchemas as t,METRO_PREPARE_FLAGS as o,listCommandMetadata as a}from"./2948.js";let n={auth:{usageOverride:"auth status|login|logout",listUsageOverride:"auth",helpDescription:"Manage cloud login state used by remote daemon and cloud device workflows.",summary:"Manage cloud login state used by remote daemon and cloud device workflows",positionalArgs:["status|login|logout"],supportedFlags:["remoteConfig","stateDir"]},connect:{usageOverride:"connect [--remote-config <path>] [--daemon-base-url <url>] [--tenant <id>] [--run-id <id>] [--lease-id <id>] [--lease-backend <backend>] [--force] [--no-login]",helpDescription:"Connect to a remote daemon, authenticate when needed, and save remote session state. AGENT_DEVICE_CLOUD_BASE_URL is the bridge/control-plane API origin; use AGENT_DEVICE_DAEMON_AUTH_TOKEN=adc_live_... for CI/service-token automation.",listUsageOverride:"connect",summary:"Attach CLI commands to a saved remote daemon/cloud lease; inspect for remote runs, tenants, or service-token CI",allowedFlags:["remoteConfig","daemonBaseUrl","tenant","runId","leaseId","leaseBackend","force","noLogin"],supportedFlags:["stateDir","daemonAuthToken","session","platform",...o,"launchUrl"]},connection:{usageOverride:"connection status",listUsageOverride:"connection",helpDescription:"Inspect active remote connection state",summary:"Inspect the active saved remote connection before assuming commands are local",positionalArgs:["status"],supportedFlags:["remoteConfig","stateDir","session"]},disconnect:{helpDescription:"Disconnect remote daemon state, stop owned Metro companion, and release lease",listUsageOverride:"disconnect",summary:"Clear remote connection state, stop owned Metro companions, and release remote leases",allowedFlags:["shutdown"],supportedFlags:["remoteConfig","stateDir","session"]},mcp:{helpDescription:"Start the official stdio MCP server. It exposes structured command tools backed by the agent-device client.",summary:"Start MCP server"},proxy:{usageOverride:"proxy [--host <host>] [--port <port>] [--daemon-auth-token <token>] [--state-dir <path>]",listUsageOverride:"proxy",helpDescription:`Expose the local daemon HTTP contract through a tunnel-friendly reverse proxy.
|
|
2
|
+
|
|
3
|
+
Run this on the host that has access to simulators/devices, then point another machine at the printed daemon base URL with --daemon-base-url or AGENT_DEVICE_DAEMON_BASE_URL.
|
|
4
|
+
|
|
5
|
+
The proxy starts or reuses a local HTTP daemon, accepts /health, /rpc, /upload, and /artifacts/*, and also accepts the same routes under /agent-device/*. Health is unauthenticated for reachability probes. Other routes require the generated bearer token printed at startup, or the explicit --daemon-auth-token value when provided. The proxy rewrites authorized client requests to the upstream daemon token instead of exposing the local daemon token.
|
|
6
|
+
|
|
7
|
+
Use the /agent-device base path when connecting through cloudflared, ngrok, or another shared origin. Treat the bearer token as a secret; anyone with it can control the proxied daemon. This direct proxy flow does not use agent-device auth.
|
|
8
|
+
|
|
9
|
+
Examples:
|
|
10
|
+
agent-device proxy --port 4310
|
|
11
|
+
cloudflared tunnel --url http://127.0.0.1:4310
|
|
12
|
+
agent-device devices --daemon-base-url https://example.trycloudflare.com/agent-device --daemon-auth-token <token>`,summary:"Expose a local daemon through cloudflared, ngrok, or another HTTP tunnel",allowedFlags:["proxyHost","proxyPort","daemonAuthToken","stateDir"]},"react-devtools":{usageOverride:"react-devtools [...args]",listUsageOverride:"react-devtools",helpDescription:"Run pinned agent-react-devtools commands for React Native performance profiling, component trees, props/state/hooks, and render analysis",summary:"Inspect React Native components, props, hooks, errors, slow renders, and rerender profiles",positionalArgs:["args?"],allowsExtraPositionals:!0,supportedFlags:e},web:{usageOverride:"web setup | web doctor",listUsageOverride:"web setup|doctor",helpDescription:`Install and inspect the managed web automation backend used by --platform web.
|
|
2
13
|
|
|
3
14
|
First-run flow:
|
|
4
15
|
agent-device web setup
|
|
@@ -8,4 +19,4 @@ First-run flow:
|
|
|
8
19
|
|
|
9
20
|
Runtime web commands do not install the backend implicitly. If the managed backend is missing, run agent-device web setup. The backend is resolved only from the managed install in the effective agent-device state dir.
|
|
10
21
|
|
|
11
|
-
Use web setup to install or reuse the pinned backend. Use web doctor after setup to verify browser backend health.`,summary:"Manage web automation backend",positionalArgs:["setup|doctor"],supportedFlags:["stateDir"]}},
|
|
22
|
+
Use web setup to install or reuse the pinned backend. Use web doctor after setup to verify browser backend health.`,summary:"Manage web automation backend",positionalArgs:["setup|doctor"],supportedFlags:["stateDir"]}},r=t(),s=new Map(a().map(t=>[t.name,{helpDescription:t.description,supportedFlags:e}]));function i(e){if(e)return c(e)}function d(e){let t=c(e);if(!t)throw Error(`Missing command schema for ${e}`);return t}function c(e){let t=Object.hasOwn(n,e)?n[e]:void 0;if(t)return t;let o=s.get(e),a=Object.hasOwn(r,e)?r[e]:void 0;if(o)return a?{...o,...a}:o}function l(e,t){let o=i(e);if(!o?.defaults)return!1;let a=!1;for(let[e,n]of Object.entries(o.defaults))void 0===t[e]&&(t[e]=n,a=!0);return a}export{l as applyCommandDefaults,d as getCliCommandSchema,i as getCommandSchema};
|