agent-device 0.17.8 → 0.17.10
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 +18 -0
- package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.17.8.apk → agent-device-android-multitouch-helper-0.17.10.apk} +0 -0
- package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.17.10.apk.sha256 +1 -0
- package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.17.8.manifest.json → agent-device-android-multitouch-helper-0.17.10.manifest.json} +4 -4
- package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.17.8.apk → agent-device-android-snapshot-helper-0.17.10.apk} +0 -0
- package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.17.10.apk.sha256 +1 -0
- package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.17.8.manifest.json → agent-device-android-snapshot-helper-0.17.10.manifest.json} +6 -6
- package/dist/src/1404.js +1 -0
- package/dist/src/2133.js +1 -1
- package/dist/src/2577.js +1 -1
- 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 +1 -1
- package/dist/src/9581.js +2 -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 +93 -27
- package/dist/src/cli-output.js +1 -4
- package/dist/src/cli.js +18 -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/skills/agent-device/SKILL.md +1 -0
- package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.17.8.apk.sha256 +0 -1
- package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.17.8.apk.sha256 +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/9836.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AppError as e}from"./733.js";import{normalizeText as t}from"./587.js";function n(e){var t;let n=i(e.label),r=i(e.value),l=i(e.identifier),u=(t=l)&&!/^[\w.]+:id\/[\w.-]+$/i.test(t)&&!/^_?NS:\d+$/i.test(t)?l:"";return o(e.type??"")?r||n||u:n||r||u}function r(e){let t=e.replace(/\s+/g," ").trim();return t.length<=48?t:`${t.slice(0,45)}...`}function l(e,t){var r;let l=n(e),i=function(e,t){if("text-view"===t||"text-field"===t||"search"===t)return!0;let n=u(e.type??""),r=`${e.role??""} ${e.subrole??""}`.toLowerCase();return n.includes("textview")||n.includes("textarea")||n.includes("textfield")||n.includes("securetextfield")||n.includes("searchfield")||n.includes("edittext")||r.includes("text area")||r.includes("text field")}(e,t);return{text:l,isLargeSurface:i,shouldSummarize:i&&!!(r=l)&&(r.length>80||/[\r\n]/.test(r))}}function i(e){return"string"==typeof e?e.trim():""}function u(e){let t=e.trim().replace(/XCUIElementType/gi,"").replace(/^AX/,"").toLowerCase(),n=Math.max(t.lastIndexOf("."),t.lastIndexOf("/"));return -1!==n&&(t=t.slice(n+1)),t}function o(e){let t=u(e);return t.includes("textfield")||t.includes("securetextfield")||t.includes("searchfield")||t.includes("edittext")||t.includes("textview")||t.includes("textarea")}let a=new Set(["id","role","text","label","value","appname","windowtitle"]),c=new Set(["visible","hidden","editable","selected","enabled","hittable"]),s=new Set([...a,...c]),f=new Map([['"','"'],["'","'"],["\\","\\"],["/","/"],["b","\b"],["f","\f"],["n","\n"],["r","\r"],["t"," "]]);function d(t){let n=t.trim();if(!n)throw new e("INVALID_ARGS","Selector expression cannot be empty");let r=function(t){let n=[],r="",l=null;for(let i=0;i<t.length;i+=1){let u=t[i];if(('"'===u||"'"===u)&&!g(t,i)){l=w(l,u),r+=u;continue}if(!l&&"|"===u&&"|"===t[i+1]){let l=r.trim();if(!l)throw new e("INVALID_ARGS",`Invalid selector fallback expression: ${t}`);n.push(l),r="",i+=1;continue}r+=u}let i=r.trim();if(!i)throw new e("INVALID_ARGS",`Invalid selector fallback expression: ${t}`);return n.push(i),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="",l=null;for(let e=0;e<t.length;e+=1){let i=t.charAt(e);if(('"'===i||"'"===i)&&!g(t,e)){l=w(l,i),r+=i;continue}if(!l&&/\s/.test(i)){r.trim()&&n.push(r.trim()),r="";continue}r+=i}if(l)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(b)}})(t))}}function h(e){try{return d(e)}catch{return null}}function p(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 s.has(e)}return s.has(t.toLowerCase())}function m(e,t={}){if(0===e.length)return null;let n=t.preferTrailingValue??!1,r=0,l=[];for(;r<e.length;){let t=e[r];if(void 0===t||!p(t))break;r+=1;let n=e.slice(0,r).join(" ").trim();n&&h(n)&&l.push(r)}if(0===l.length)return null;let i=l.at(-1);if(void 0===i)return null;let u=i;if(n)for(let t=l.length-1;t>=0;t-=1){let n=l[t];if(void 0!==n&&n<e.length){u=n;break}}let o=e.slice(0,u).join(" ").trim();return o?{selectorExpression:o,rest:e.slice(u)}:null}function b(t){let n=t.trim();if(!n)throw new e("INVALID_ARGS","Empty selector term");let r=n.indexOf("=");if(-1===r){let r=n.toLowerCase();if(!c.has(r))throw new e("INVALID_ARGS",`Invalid selector term "${t}", expected key=value`);return{key:r,value:!0}}let l=n.slice(0,r).trim().toLowerCase(),i=n.slice(r+1).trim();if(!s.has(l))throw new e("INVALID_ARGS",`Unknown selector key: ${l}`);if(!i)throw new e("INVALID_ARGS",`Missing selector value for key: ${l}`);if(c.has(l)){let t,n="true"===(t=x(i).toLowerCase())||"false"!==t&&null;if(null===n)throw new e("INVALID_ARGS",`Invalid boolean value for ${l}: ${i}`);return{key:l,value:n}}return{key:l,value:x(i)}}function w(e,t){return e?e===t?null:e:t}function x(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 i=e.charAt(n+1);if(!i){t+=l,n+=1;continue}let u=(r=i,f.get(r)??null);if(null!==u){t+=u,n+=2;continue}if("u"===i){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 g(e,t){let n=0;for(let r=t-1;r>=0&&"\\"===e[r];r-=1)n+=1;return n%2==1}function v(e){let t=e[0]??"",n=m(e.slice(1),{preferTrailingValue:"text"===t});return{predicate:t,split:n}}function S(e,t){let n=t.toLowerCase();return e.find(e=>{let t=(e.label??"").toLowerCase(),r=(e.value??"").toLowerCase(),l=(e.identifier??"").toLowerCase();return t.includes(n)||r.includes(n)||l.includes(n)})??null}function I(e,t){let n=[e.label,e.value,e.identifier].map(e=>"string"==typeof e?e.trim():"").find(e=>e&&e.length>0);return n&&A(n)?n:function(e,t){if(!e.rect)return;let n=e.rect.y+e.rect.height/2,r=null;for(let e of t){if(!e.rect)continue;let t=[e.label,e.value,e.identifier].map(e=>"string"==typeof e?e.trim():"").find(e=>e&&e.length>0);if(!t||!A(t))continue;let l=Math.abs(e.rect.y+e.rect.height/2-n);(!r||l<r.distance)&&(r={label:t,distance:l})}return r?.label}(e,t)??(n&&A(n)?n:void 0)}function A(e){let t=e.trim();return!(!t||/^(true|false)$/i.test(t)||/^\d+$/.test(t))}function $(e){let t=[],n=[];for(let r of e){let e=r.depth??0;for(;t.length>0&&e<=t[t.length-1];)t.pop();let l=u(r.type??""),i=[r.label,r.value,r.identifier].map(e=>"string"==typeof e?e.trim():"").find(e=>e&&e.length>0),o=!!i&&A(i);if(("group"===l||"ioscontentgroup"===l)&&!o){t.push(e);continue}let a=Math.max(0,e-t.length);n.push({...r,depth:a})}return n}function y(e,t){let n=u(e);return!n||("android"===t?n.includes("edittext")||n.includes("autocompletetextview"):n.includes("textfield")||n.includes("securetextfield")||n.includes("searchfield")||n.includes("textview")||n.includes("textarea")||"search"===n)}function N(e,t){return t.hittable?t:R(e,t,e=>!0===e.hittable)}function L(e){return new Map(e.map(e=>[e.index,e]))}function C(e,t,n,r){let l=t,i=new Set;for(;"number"==typeof l.parentIndex&&!i.has(l.index)&&(i.add(l.index),l=n.get(l.parentIndex)??e[l.parentIndex]);){let e=r(l);if(null!==e)return e}return null}function _(e,t,n,r){return!!C(e,t,r,e=>e===n||e.index===n.index?e:null)}function R(e,t,n){let r=L(e);return C(e,t,r,e=>n(e)?e:null)}function V(e){return[e.label,e.value,e.identifier].map(e=>"string"==typeof e?e.trim():"").filter(e=>e.length>0)[0]??""}function T(e){return n(e)}function D(e){return!0===e.hittable||!!e.rect&&e.rect.width>0&&e.rect.height>0}function G(e,t){return y(e.type??"",t)&&!1!==e.enabled}function k(e,t,n){return t.terms.every(t=>(function(e,t,n){switch(t.key){case"id":return M(e.identifier,String(t.value));case"role":return M(u(e.type??""),String(t.value));case"label":return M(e.label,String(t.value));case"value":return M(e.value,String(t.value));case"text":return M(V(e),String(t.value));case"appname":return M(e.appName,String(t.value));case"windowtitle":return M(e.windowTitle,String(t.value));case"visible":return D(e)===!!t.value;case"hidden":return!D(e)==!!t.value;case"editable":return G(e,n)===!!t.value;case"selected":return!0===e.selected==!!t.value;case"enabled":return!1!==e.enabled==!!t.value;case"hittable":return!0===e.hittable==!!t.value;default:return!1}})(e,t,n))}function M(e,n){return t(e??"")===t(n)}function q(e,t,n){let r=n.requireRect??!1,l=n.requireUnique??!0,i=[];for(let[u,o]of t.selectors.entries()){let t=function(e,t,n,r){let l=0,i=null,u=null,o=!1;for(let a of e){if(r&&!a.rect||!k(a,t,n))continue;if(l+=1,i??=a,!u){u=a;continue}let e=function(e,t){let n=e.depth??0,r=t.depth??0;if(n!==r)return n>r?1:-1;let l=U(e),i=U(t);return l!==i?l<i?1:-1:0}(a,u);e>0?(u=a,o=!1):0===e&&(o=!0)}return{count:l,firstNode:i,disambiguated:o?null:u}}(e,o,n.platform,r);if(i.push({selector:o.raw,matches:t.count}),0!==t.count&&t.firstNode){if(l&&1!==t.count){if(!n.disambiguateAmbiguous||!t.disambiguated)continue;return{node:t.disambiguated,selector:o,selectorIndex:u,matches:t.count,diagnostics:i}}return{node:t.firstNode,selector:o,selectorIndex:u,matches:t.count,diagnostics:i}}}return null}function F(e,t,n){let r=n.requireRect??!1,l=[];for(let[i,u]of t.selectors.entries()){let t=function(e,t,n,r){let l=0;for(let i of e)(!r||i.rect)&&k(i,t,n)&&(l+=1);return l}(e,u,n.platform,r);if(l.push({selector:u.raw,matches:t}),t>0)return{selectorIndex:i,selector:u,matches:t,diagnostics:l}}return null}function O(e,t,n){if(0===t.length)return`Selector did not match: ${e.raw}`;let r=t.map(e=>`${e.selector} -> ${e.matches}`).join(", ");return n.unique??!0?`Selector did not resolve uniquely (${r})`:`Selector did not match (${r})`}function U(e){return e.rect?e.rect.width*e.rect.height:1/0}function E(e,t,n={}){let r=[],l=u(e.type??""),i=P(e.identifier),o=P(e.label),a=P(e.value),c=P(V(e)),s="fill"===n.action;i&&r.push(`id=${K(i)}`),l&&o&&r.push(s?`role=${K(l)} label=${K(o)} editable=true`:`role=${K(l)} label=${K(o)}`),o&&r.push(s?`label=${K(o)} editable=true`:`label=${K(o)}`),a&&r.push(s?`value=${K(a)} editable=true`:`value=${K(a)}`),c&&c!==o&&c!==a&&r.push(s?`text=${K(c)} editable=true`:`text=${K(c)}`),l&&s&&!r.some(e=>e.includes("editable=true"))&&r.push(`role=${K(l)} editable=true`);let f=Array.from(new Set(r));return 0===f.length&&l&&f.push(s?`role=${K(l)} editable=true`:`role=${K(l)}`),0===f.length&&D(e)&&f.push("visible=true"),f}function K(e){return JSON.stringify(e)}function P(e){if(!e)return null;let t=e.trim();return t||null}export{E as buildSelectorChainForNode,L as buildSnapshotNodeByIndex,r as buildTextPreview,l as describeTextSurface,T as extractNodeReadText,V as extractNodeText,n as extractReadableText,R as findNearestAncestor,N as findNearestHittableAncestor,S as findNodeByLabel,F as findSelectorChainMatch,C as findSnapshotAncestor,O as formatSelectorFailure,_ as isDescendantOfSnapshotNode,y as isFillableType,G as isNodeEditable,D as isNodeVisible,p as isSelectorToken,k as matchesSelector,u as normalizeType,d as parseSelectorChain,o as prefersValueForReadableText,$ as pruneGroupNodes,I as resolveRefLabel,q as resolveSelectorChain,v as splitIsSelectorArgs,m as splitSelectorFromArgs,i as trimText,h as tryParseSelectorChain};
|
|
1
|
+
import{splitSelectorFromArgs as e,normalizeText as t}from"./587.js";function n(e){var t;let n=l(e.label),r=l(e.value),i=l(e.identifier),u=(t=i)&&!/^[\w.]+:id\/[\w.-]+$/i.test(t)&&!/^_?NS:\d+$/i.test(t)?i:"";return a(e.type??"")?r||n||u:n||r||u}function r(e){let t=e.replace(/\s+/g," ").trim();return t.length<=48?t:`${t.slice(0,45)}...`}function i(e,t){var r;let i=n(e),l=function(e,t){if("text-view"===t||"text-field"===t||"search"===t)return!0;let n=u(e.type??""),r=`${e.role??""} ${e.subrole??""}`.toLowerCase();return n.includes("textview")||n.includes("textarea")||n.includes("textfield")||n.includes("securetextfield")||n.includes("searchfield")||n.includes("edittext")||r.includes("text area")||r.includes("text field")}(e,t);return{text:i,isLargeSurface:l,shouldSummarize:l&&!!(r=i)&&(r.length>80||/[\r\n]/.test(r))}}function l(e){return"string"==typeof e?e.trim():""}function u(e){let t=e.trim().replace(/XCUIElementType/gi,"").replace(/^AX/,"").toLowerCase(),n=Math.max(t.lastIndexOf("."),t.lastIndexOf("/"));return -1!==n&&(t=t.slice(n+1)),t}function a(e){let t=u(e);return t.includes("textfield")||t.includes("securetextfield")||t.includes("searchfield")||t.includes("edittext")||t.includes("textview")||t.includes("textarea")}function c(t){let n=t[0]??"",r=e(t.slice(1),{preferTrailingValue:"text"===n});return{predicate:n,split:r}}function o(e,t){let n=t.toLowerCase();return e.find(e=>{let t=(e.label??"").toLowerCase(),r=(e.value??"").toLowerCase(),i=(e.identifier??"").toLowerCase();return t.includes(n)||r.includes(n)||i.includes(n)})??null}function s(e,t){let n=[e.label,e.value,e.identifier].map(e=>"string"==typeof e?e.trim():"").find(e=>e&&e.length>0);return n&&d(n)?n:function(e,t){if(!e.rect)return;let n=e.rect.y+e.rect.height/2,r=null;for(let e of t){if(!e.rect)continue;let t=[e.label,e.value,e.identifier].map(e=>"string"==typeof e?e.trim():"").find(e=>e&&e.length>0);if(!t||!d(t))continue;let i=Math.abs(e.rect.y+e.rect.height/2-n);(!r||i<r.distance)&&(r={label:t,distance:i})}return r?.label}(e,t)??(n&&d(n)?n:void 0)}function d(e){let t=e.trim();return!(!t||/^(true|false)$/i.test(t)||/^\d+$/.test(t))}function f(e){let t=[],n=[];for(let r of e){let e=r.depth??0;for(;t.length>0&&e<=t[t.length-1];)t.pop();let i=u(r.type??""),l=[r.label,r.value,r.identifier].map(e=>"string"==typeof e?e.trim():"").find(e=>e&&e.length>0),a=!!l&&d(l);if(("group"===i||"ioscontentgroup"===i)&&!a){t.push(e);continue}let c=Math.max(0,e-t.length);n.push({...r,depth:c})}return n}function h(e,t){let n=u(e);return!n||("android"===t?n.includes("edittext")||n.includes("autocompletetextview"):n.includes("textfield")||n.includes("securetextfield")||n.includes("searchfield")||n.includes("textview")||n.includes("textarea")||"search"===n)}function p(e,t){return t.hittable?t:g(e,t,e=>!0===e.hittable)}function b(e){return new Map(e.map(e=>[e.index,e]))}function x(e,t,n,r){let i=t,l=new Set;for(;"number"==typeof i.parentIndex&&!l.has(i.index)&&(l.add(i.index),i=n.get(i.parentIndex)??e[i.parentIndex]);){let e=r(i);if(null!==e)return e}return null}function m(e,t,n,r){return!!x(e,t,r,e=>e===n||e.index===n.index?e:null)}function g(e,t,n){let r=b(e);return x(e,t,r,e=>n(e)?e:null)}function v(e){return[e.label,e.value,e.identifier].map(e=>"string"==typeof e?e.trim():"").filter(e=>e.length>0)[0]??""}function w(e){return n(e)}function S(e){return!0===e.hittable||!!e.rect&&e.rect.width>0&&e.rect.height>0}function $(e,t){return h(e.type??"",t)&&!1!==e.enabled}function y(e,t,n){return t.terms.every(t=>(function(e,t,n){switch(t.key){case"id":return N(e.identifier,String(t.value));case"role":return N(u(e.type??""),String(t.value));case"label":return N(e.label,String(t.value));case"value":return N(e.value,String(t.value));case"text":return N(v(e),String(t.value));case"appname":return N(e.appName,String(t.value));case"windowtitle":return N(e.windowTitle,String(t.value));case"visible":return S(e)===!!t.value;case"hidden":return!S(e)==!!t.value;case"editable":return $(e,n)===!!t.value;case"selected":return!0===e.selected==!!t.value;case"enabled":return!1!==e.enabled==!!t.value;case"hittable":return!0===e.hittable==!!t.value;default:return!1}})(e,t,n))}function N(e,n){return t(e??"")===t(n)}function C(e,t,n){let r=n.requireRect??!1,i=n.requireUnique??!0,l=[];for(let[u,a]of t.selectors.entries()){let t=function(e,t,n,r){let i=0,l=null,u=null,a=!1;for(let c of e){if(r&&!c.rect||!y(c,t,n))continue;if(i+=1,l??=c,!u){u=c;continue}let e=function(e,t){let n=e.depth??0,r=t.depth??0;if(n!==r)return n>r?1:-1;let i=A(e),l=A(t);return i!==l?i<l?1:-1:0}(c,u);e>0?(u=c,a=!1):0===e&&(a=!0)}return{count:i,firstNode:l,disambiguated:a?null:u}}(e,a,n.platform,r);if(l.push({selector:a.raw,matches:t.count}),0!==t.count&&t.firstNode){if(i&&1!==t.count){if(!n.disambiguateAmbiguous||!t.disambiguated)continue;return{node:t.disambiguated,selector:a,selectorIndex:u,matches:t.count,diagnostics:l}}return{node:t.firstNode,selector:a,selectorIndex:u,matches:t.count,diagnostics:l}}}return null}function T(e,t,n){let r=n.requireRect??!1,i=[];for(let[l,u]of t.selectors.entries()){let t=function(e,t,n,r){let i=0;for(let l of e)(!r||l.rect)&&y(l,t,n)&&(i+=1);return i}(e,u,n.platform,r);if(i.push({selector:u.raw,matches:t}),t>0)return{selectorIndex:l,selector:u,matches:t,diagnostics:i}}return null}function I(e,t,n){if(0===t.length)return`Selector did not match: ${e.raw}`;let r=t.map(e=>`${e.selector} -> ${e.matches}`).join(", ");return n.unique??!0?`Selector did not resolve uniquely (${r})`:`Selector did not match (${r})`}function A(e){return e.rect?e.rect.width*e.rect.height:1/0}function L(e,t,n={}){let r=[],i=u(e.type??""),l=q(e.identifier),a=q(e.label),c=q(e.value),o=q(v(e)),s="fill"===n.action;l&&r.push(`id=${R(l)}`),i&&a&&r.push(s?`role=${R(i)} label=${R(a)} editable=true`:`role=${R(i)} label=${R(a)}`),a&&r.push(s?`label=${R(a)} editable=true`:`label=${R(a)}`),c&&r.push(s?`value=${R(c)} editable=true`:`value=${R(c)}`),o&&o!==a&&o!==c&&r.push(s?`text=${R(o)} editable=true`:`text=${R(o)}`),i&&s&&!r.some(e=>e.includes("editable=true"))&&r.push(`role=${R(i)} editable=true`);let d=Array.from(new Set(r));return 0===d.length&&i&&d.push(s?`role=${R(i)} editable=true`:`role=${R(i)}`),0===d.length&&S(e)&&d.push("visible=true"),d}function R(e){return JSON.stringify(e)}function q(e){if(!e)return null;let t=e.trim();return t||null}export{L as buildSelectorChainForNode,b as buildSnapshotNodeByIndex,r as buildTextPreview,i as describeTextSurface,w as extractNodeReadText,v as extractNodeText,n as extractReadableText,g as findNearestAncestor,p as findNearestHittableAncestor,o as findNodeByLabel,T as findSelectorChainMatch,x as findSnapshotAncestor,I as formatSelectorFailure,m as isDescendantOfSnapshotNode,h as isFillableType,$ as isNodeEditable,S as isNodeVisible,y as matchesSelector,u as normalizeType,a as prefersValueForReadableText,f as pruneGroupNodes,s as resolveRefLabel,C as resolveSelectorChain,c as splitIsSelectorArgs,l as trimText};
|
package/dist/src/9919.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import e from"node:fs";import t from"node:http";import a from"node:https";import r from"node:path";import{pipeline as n}from"node:stream/promises";import i from"node:os";import{createHash as o,randomUUID as s}from"node:crypto";import{Writable as l}from"node:stream";import c from"node:net";import d from"node:fs/promises";import{toAppErrorCode as u,AppError as f}from"./733.js";import{runCmdDetachedMonitored as p,runCmd as m,runCmdSync as h}from"./8875.js";import{createRequestId as y,withDiagnosticTimer as w,emitDiagnostic as g}from"./432.js";import{isAgentDeviceDaemonProcess as v,stopProcessForTakeover as b}from"./5628.js";import{readSnapshotDiagnosticsSummary as I,consumeTextLines as A,shellQuote as S,shouldStreamRequestProgress as M,isDaemonResponseEnvelope as _,isDaemonProgressEnvelope as P,resolveDaemonPaths as D,resolveDaemonServerMode as k,computeDaemonCodeSignature as x,resolveDaemonTransportPreference as E}from"./8358.js";import{colorize as N,supportsColor as $}from"./6311.js";import{INTERNAL_COMMANDS as T,PUBLIC_COMMANDS as C}from"./2133.js";import{readVersion as U,findProjectRoot as L}from"./7244.js";import{sleep as R}from"./5560.js";import{normalizeSession as O,readRequiredString as F,readSerializedSnapshotCaptureAnnotations as B,readOptionalString as j,normalizeMaterializationReleaseResult as q,readSnapshotNodes as V,normalizeDeployResult as K,appDaemonWriters as G,observabilityDaemonWriters as H,normalizeOpenDevice as z,replayDaemonWriters as Y,buildMeta as W,systemDaemonWriters as J,resolveSessionName as X,buildFlags as Q,reactNativeDaemonWriters as Z,interactionDaemonWriters as ee,captureDaemonWriters as et,perfDaemonWriters as ea,gestureDaemonWriters as er,selectorDaemonWriters as en,createBatchDaemonWriter as ei,normalizeRuntimeHints as eo,normalizeDevice as es,recordingDaemonWriters as el,readScreenshotOverlayRefs as ec,normalizeStartupSample as ed,normalizeInstallFromSourceResult as eu}from"./9873.js";import{reloadMetro as ef,prepareMetroRuntime as ep}from"./8275.js";function em(e){return new Promise((t,a)=>{let r="";e.setEncoding("utf8"),e.on("data",e=>{r+=e}),e.on("end",()=>t(r)),e.on("error",a)})}let eh="sha256";async function ey(e){let t=await ew(e.localPath,e.platform),a=e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`;try{let r=await eI({normalizedBase:a,token:e.token,artifact:t});if(r?.kind==="cache-hit")return r.uploadId;if(r?.kind==="direct-upload")try{return await eA(t.payloadPath,r),await eP({normalizedBase:a,token:e.token,uploadId:r.uploadId})}catch{}return await eb({normalizedBase:a,token:e.token,artifact:t})}finally{t.cleanup()}}async function ew(t,a){var n,i,o;let s,l=e.statSync(t),c=r.basename(t),d=l.isDirectory(),u=("ios"===(n=a)||"android"===n?n:void 0)??(i=t,o=l,s=i.toLowerCase(),o.isDirectory()&&s.endsWith(".app")||s.endsWith(".ipa")?"ios":s.endsWith(".apk")||s.endsWith(".aab")?"android":void 0),f=[];try{let a=d?await eg(t,f):t,r=e.statSync(a);return{payloadPath:a,fileName:c,artifactType:d?"app-bundle":"file",platform:u,contentType:d?"application/gzip":"application/octet-stream",sha256:await eD(a),sizeBytes:r.size,cleanup:()=>ev(f)}}catch(e){throw ev(f),e}}async function eg(t,a){let n=e.mkdtempSync(r.join(i.tmpdir(),`agent-device-upload-${s()}-`));a.push(n);let o=r.join(n,`${r.basename(t)}.tar.gz`);return await m("tar",["czf",o,"-C",r.dirname(t),r.basename(t)],{env:{...process.env,COPYFILE_DISABLE:"1"}}),o}function ev(t){for(let a of t)e.rmSync(a,{recursive:!0,force:!0})}async function eb(e){let{normalizedBase:t,token:a,artifact:r}=e,n=new URL("upload",t),i={"content-type":r.contentType,"x-artifact-type":r.artifactType,"x-artifact-filename":r.fileName,"x-artifact-hash":r.sha256,"x-artifact-hash-algorithm":eh,"transfer-encoding":"chunked"};a&&(i.authorization=`Bearer ${a}`,i["x-agent-device-token"]=a);let o=await eS({url:n,method:"POST",headers:i,payloadPath:r.payloadPath,timeoutMessage:"Artifact upload timed out",timeoutHint:"The upload to the remote daemon exceeded the 5-minute timeout.",errorMessage:"Failed to upload artifact to remote daemon",errorHint:"Verify the remote daemon is reachable and supports artifact uploads."});try{let e=JSON.parse(o.body);if(!e.ok||!e.uploadId)throw new f("COMMAND_FAILED",`Upload failed: ${o.body}`);return e.uploadId}catch(e){if(e instanceof f)throw e;throw new f("COMMAND_FAILED",`Invalid upload response: ${o.body}`)}}async function eI(e){let t=new URL("upload/preflight",e.normalizedBase),a={"content-type":"application/json"};e.token&&(a.authorization=`Bearer ${e.token}`,a["x-agent-device-token"]=e.token);let r=await fetch(t,{method:"POST",headers:a,signal:AbortSignal.timeout(3e4),body:JSON.stringify({sha256:e.artifact.sha256,fileName:e.artifact.fileName,sizeBytes:e.artifact.sizeBytes,artifactType:e.artifact.artifactType,...e.artifact.platform?{platform:e.artifact.platform}:{},contentType:e.artifact.contentType})}).catch(()=>void 0);if(r?.ok)return function(e){var t;if(!e||"object"!=typeof e||!0!==e.ok||"string"!=typeof e.uploadId)return;if(!0===e.cacheHit)return{kind:"cache-hit",uploadId:e.uploadId};let a=e.upload;if(!a||"string"!=typeof a.url)return;let r=a.headers??{};if(!(!(t=r)||"object"!=typeof t||Array.isArray(t))&&Object.values(t).every(e=>"string"==typeof e))return{kind:"direct-upload",uploadId:e.uploadId,url:a.url,headers:r}}(await r.json().catch(()=>void 0))}async function eA(e,t){let a=await eS({url:new URL(t.url),method:"PUT",headers:t.headers,payloadPath:e,timeoutMessage:"Direct artifact upload timed out",timeoutHint:"The direct upload ticket did not accept the artifact within the timeout.",errorMessage:"Failed to upload artifact with direct upload ticket"});if(a.statusCode<200||a.statusCode>=300)throw new f("COMMAND_FAILED","Direct artifact upload failed",{statusCode:a.statusCode,statusMessage:a.statusMessage})}async function eS(e){return await eM({...e,url:e.url,redirectCount:0,startOffset:0})}async function eM(r){var i,o,s;let l="https:"===r.url.protocol?a:t,c=e.statSync(r.payloadPath).size,d=(i=r.headers,o=r.startOffset,s=c,o<=0?i:{...i,"content-length":Math.max(s-o,0),"content-range":`bytes ${o}-${s-1}/${s}`});return await new Promise((t,a)=>{let i=!1,o=l.request({protocol:r.url.protocol,host:r.url.hostname,port:r.url.port,method:r.method,path:r.url.pathname+r.url.search,headers:d},e=>{i=!0,em(e).then(n=>{clearTimeout(s);let i=e.statusCode??500,o=e.headers.location;if(o&&[301,302,303,307,308].includes(i)){if(r.redirectCount>=5)return void a(new f("COMMAND_FAILED","Artifact upload exceeded redirect limit",{maxRedirects:5,url:r.url.toString()}));let e=new URL(o,r.url);return void eM({...r,url:e,redirectCount:r.redirectCount+1}).then(t,a)}let l=308===i?function(e,t){let a=function(e){let t=e_(e);if(void 0===t)return;let a=Number(t);return Number.isSafeInteger(a)&&a>=0?a:void 0}(e["x-upload-offset"]??e["upload-offset"]);if(void 0!==a)return Math.min(a,t);let r=e_(e.range),n=r?.match(/^bytes=0-(\d+)$/);if(!n)return;let i=Number(n[1]);if(Number.isSafeInteger(i)&&!(i<0))return Math.min(i+1,t)}(e.headers,c):void 0;void 0!==l?l>=c?t({statusCode:200,statusMessage:"Upload already complete",body:""}):l<=r.startOffset?a(new f("COMMAND_FAILED","Artifact upload resume did not advance",{offset:l,previousOffset:r.startOffset,url:r.url.toString()})):eM({...r,startOffset:l}).then(t,a):t({statusCode:i,statusMessage:e.statusMessage,body:n})}).catch(a)}),s=setTimeout(()=>{o.destroy(),a(new f("COMMAND_FAILED",r.timeoutMessage,{timeoutMs:3e5,...r.timeoutHint?{hint:r.timeoutHint}:{}}))},3e5);o.on("error",e=>{i||(clearTimeout(s),a(new f("COMMAND_FAILED",r.errorMessage,r.errorHint?{hint:r.errorHint}:{},e)))}),o.on("close",()=>clearTimeout(s)),n(e.createReadStream(r.payloadPath,{start:r.startOffset}),o).catch(e=>{i||(o.destroy(),a(new f("COMMAND_FAILED","Failed to read local artifact",{},e instanceof Error?e:Error(String(e)))))})})}function e_(e){return Array.isArray(e)?e[0]:e}async function eP(e){let t=new URL("upload/finalize",e.normalizedBase),a={"content-type":"application/json"};e.token&&(a.authorization=`Bearer ${e.token}`,a["x-agent-device-token"]=e.token);let r=await fetch(t,{method:"POST",headers:a,signal:AbortSignal.timeout(3e4),body:JSON.stringify({uploadId:e.uploadId})}).catch(e=>{throw new f("COMMAND_FAILED","Failed to finalize direct artifact upload",{},e)});if(!r.ok)throw new f("COMMAND_FAILED","Direct artifact upload finalize failed",{status:r.status,statusText:r.statusText});let n=await r.json().catch(()=>void 0);if(!n?.ok||!n.uploadId)throw new f("COMMAND_FAILED","Invalid upload finalize response");return n.uploadId}async function eD(t){let a=o(eh),r=new l({write(e,t,r){a.update(e),r()}});return await n(e.createReadStream(t),r).catch(e=>{throw new f("COMMAND_FAILED","Failed to read local artifact",{},e instanceof Error?e:void 0)}),a.digest("hex")}async function ek(e,t){var a;let n,i=[...e.positionals??[]],o=e.flags?{...e.flags}:void 0,s=e.meta?.installSource,l={};if(!("string"==typeof(a=t).baseUrl&&a.baseUrl.length>0))return eE({positionals:i,flags:o,installSource:s,uploadedArtifactId:n,clientArtifactPaths:l});o=function(e,t,a,n){var i,o;let s=function(e,t){if("screenshot"===e.command){let a=e$(e,"path",".png");return t[0]?{field:"path",localPath:a,positionalIndex:0,positionalPath:eT("screenshot",".png")}:{field:"path",localPath:a,positionalIndex:0,flagPath:eT("screenshot",".png")}}if("record"===e.command&&"start"===(t[0]??"").toLowerCase()){let t=e$(e,"outPath",".mp4",1);return{field:"outPath",localPath:t,positionalIndex:1,positionalPath:eT("recording",r.extname(t)||".mp4")}}return null}(e,t);if(!s)return a;void 0!==s.positionalPath&&(t[s.positionalIndex]=s.positionalPath);let l=(i=a,void 0===(o=s.flagPath)?i:{...i??{},out:o});return n[s.field]=s.localPath,l}(e,i,o,l);let c=await eN(e,t);c&&(s=c.installSource,n=c.uploadedArtifactId??n);let d=()=>eE({positionals:i,flags:o,installSource:s,uploadedArtifactId:n,clientArtifactPaths:l});return"install"!==e.command&&"reinstall"!==e.command||(n=await ex(e,t,i)??n),d()}async function ex(t,a,n){var i,o;let s,l=n[1];if(void 0===l)return;if(l.startsWith("remote:")){n[1]=l.slice(7);return}let c=(i=l,o=t.meta?.cwd,s=r.isAbsolute(i)?i:r.resolve(o??process.cwd(),i),e.existsSync(s)?s:void 0);if(c)return await ey({localPath:c,baseUrl:a.baseUrl,token:a.token,platform:t.flags?.platform})}function eE(e){return{positionals:e.positionals,flags:e.flags,installSource:e.installSource,uploadedArtifactId:e.uploadedArtifactId,...Object.keys(e.clientArtifactPaths).length>0?{clientArtifactPaths:e.clientArtifactPaths}:{}}}async function eN(t,a){let n=t.meta?.installSource;if("install_source"!==t.command||!n||"path"!==n.kind)return null;let i=n.path.trim();if(!i)return{installSource:n};if(i.startsWith("remote:"))return{installSource:{...n,path:i.slice(7)}};let o=r.isAbsolute(i)?i:r.resolve(t.meta?.cwd??process.cwd(),i);if(!e.existsSync(o))return{installSource:{...n,path:o}};let s=await ey({localPath:o,baseUrl:a.baseUrl,token:a.token,platform:t.flags?.platform});return{installSource:{...n,path:o},uploadedArtifactId:s}}function e$(e,t,a,n=0){let i=e.positionals?.[n]??e.flags?.out,o=`${"path"===t?"screenshot":"recording"}-${Date.now()}${a}`,s=i&&i.trim().length>0?i:o;return r.isAbsolute(s)?s:r.resolve(e.meta?.cwd??process.cwd(),s)}function eT(e,t){let a=t.startsWith(".")?t:`.${t}`;return r.posix.join("/tmp",`agent-device-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}${a}`)}async function eC(e,t,a){let n=Array.isArray(a.data?.artifacts)?a.data.artifacts:[];if(0===n.length||!e.baseUrl)return a;let i=a.data?{...a.data}:{},o=[];for(let a of n){if(!a||"object"!=typeof a||"string"!=typeof a.artifactId){o.push(a);continue}let n=function(e,t){if(e.localPath&&e.localPath.trim().length>0)return e.localPath;let a=t.meta?.clientArtifactPaths?.[e.field];if(a&&a.trim().length>0)return a;let n=e.fileName?.trim()||`${e.field}-${Date.now()}`;return r.resolve(t.meta?.cwd??process.cwd(),n)}(a,t);await eU({baseUrl:e.baseUrl,token:e.token,artifactId:a.artifactId,destinationPath:n,requestId:t.meta?.requestId}),i[a.field]=n,o.push({...a,localPath:n})}return i.artifacts=o,{ok:!0,data:i}}async function eU(i){var o,s;let l,c=new URL((o=i.baseUrl,s=i.artifactId,l=o.endsWith("/")?o:`${o}/`,new URL(`artifacts/${encodeURIComponent(s)}`,l).toString())),d="https:"===c.protocol?a:t;await e.promises.mkdir(r.dirname(i.destinationPath),{recursive:!0}),await new Promise((t,a)=>{let r=!1,o=i.timeoutMs??9e4,s=n=>{if(!r){if(r=!0,clearTimeout(u),n)return void e.promises.rm(i.destinationPath,{force:!0}).finally(()=>a(n));t()}},l=d.request({protocol:c.protocol,host:c.hostname,port:c.port,method:"GET",path:c.pathname+c.search,headers:i.token?{authorization:`Bearer ${i.token}`,"x-agent-device-token":i.token}:void 0},t=>{if((t.statusCode??500)>=400){let e="";t.setEncoding("utf8"),t.on("data",t=>{e+=t}),t.on("end",()=>{s(new f("COMMAND_FAILED","Failed to download remote artifact",{artifactId:i.artifactId,statusCode:t.statusCode,requestId:i.requestId,body:e}))});return}t.on("aborted",()=>{s(new f("COMMAND_FAILED","Remote artifact download was interrupted",{artifactId:i.artifactId,requestId:i.requestId}))}),n(t,e.createWriteStream(i.destinationPath)).then(()=>s(),e=>s(e instanceof Error?e:Error(String(e))))}),u=setTimeout(()=>{let e=new f("COMMAND_FAILED","Remote artifact download timed out",{artifactId:i.artifactId,requestId:i.requestId,timeoutMs:o});s(e),l.destroy(e)},o);l.on("error",e=>{e instanceof f?s(e):s(new f("COMMAND_FAILED","Failed to download remote artifact",{artifactId:i.artifactId,requestId:i.requestId,timeoutMs:o},e instanceof Error?e:void 0))}),l.end()})}function eL(e){var t,a,r;let n,i,o=eG(e);if(!o||"object"!=typeof o)return null;let s="string"==typeof(t=o).token&&t.token.length>0?t.token:null;if(!s)return null;let l=(n=eO((a=o).port),i=eO(a.httpPort),void 0===n&&void 0===i?null:{port:n,httpPort:i});return l?{token:s,...l,transport:"socket"===(r=o.transport)||"http"===r||"dual"===r?r:void 0,pid:eO(o.pid)??0,version:eR(o.version),codeSignature:eR(o.codeSignature),processStartTime:eR(o.processStartTime)}:null}function eR(e){return"string"==typeof e?e:void 0}function eO(e){return Number.isInteger(e)&&Number(e)>0?Number(e):void 0}function eF(e){let t=eG(e);return t&&"object"==typeof t&&Number.isInteger(t.pid)&&Number(t.pid)>0?{pid:Number(t.pid),processStartTime:"string"==typeof t.processStartTime?t.processStartTime:void 0,startedAt:"number"==typeof t.startedAt?t.startedAt:void 0}:null}async function eB(t,a,r={}){let n=r.stopLiveProcesses??!0,i={reason:a,removedInfo:!1,removedLock:!1,stoppedInfoProcess:!1,stoppedLockProcess:!1};try{var o,s,l,c;let a=e.existsSync(t.infoPath),r=eL(t.infoPath);if(r){let e=v(r.pid,r.processStartTime);e&&!n?i.retainedInfoProcess=!0:(e&&(await eV(r),i.stoppedInfoProcess=!0),o=t.infoPath,eH(o),i.removedInfo=!0)}else a&&(s=t.infoPath,eH(s),i.removedInfo=!0);let d=e.existsSync(t.lockPath),u=eF(t.lockPath);if(u){let e=v(u.pid,u.processStartTime);e&&!n?i.retainedLockProcess=!0:(e&&(await b(u.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:u.processStartTime}),i.stoppedLockProcess=!0),l=t.lockPath,eH(l),i.removedLock=!0)}else d&&(c=t.lockPath,eH(c),i.removedLock=!0)}catch(e){i.error=e instanceof Error?e.message:String(e)}return g({level:i.error?"warn":"info",phase:"daemon_startup_metadata_cleanup",data:i}),i}function ej(t){return{hasInfo:e.existsSync(t.infoPath),hasLock:e.existsSync(t.lockPath)}}async function eq(e){let t=ej(e);if(!t.hasLock||t.hasInfo)return!1;let a=eF(e.lockPath);return!(a&&v(a.pid,a.processStartTime))&&(eH(e.lockPath),!0)}async function eV(e){await b(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}function eK(e){return"string"==typeof e.baseUrl&&e.baseUrl.length>0}function eG(t){if(!e.existsSync(t))return null;try{return JSON.parse(e.readFileSync(t,"utf8"))}catch{return null}}function eH(t){try{e.existsSync(t)&&e.unlinkSync(t)}catch{}}function ez(e){let t=Math.max(0,e)/1e3;return t>=10?`${t.toFixed(1)}s`:t>=1?`${t.toFixed(2)}s`:`${t.toFixed(3).replace(/0+$/,"").replace(/\.$/,"")}s`}function eY(e){let t=eW(e),a=t.findIndex(({stop:e})=>!1===e.ok);if(a<0)return[];let r=t.slice(Math.max(0,a-2),a+1);return[e.attempts>1?`steps (attempt ${e.attempts}):`:"steps:",...r.map(({stop:e,start:t})=>eZ(e,t))]}function eW(t){var a,n;let i=(a=t).artifactsDir?r.join(a.artifactsDir,`attempt-${a.attempts}`,"replay-timing.ndjson"):void 0;if(!i)return[];let o=function(t){try{return e.readFileSync(t,"utf8").split(/\r?\n/).filter(e=>e.trim().length>0).flatMap(e=>{try{let t=JSON.parse(e);return e1(t)?[t]:[]}catch{return[]}})}catch{return[]}}(i);if(0===o.length)return[];let s=[],l=[];for(let e of o){if("replay_action_start"===(n=e).type&&eJ(n)&&eX(n,"line")&&eQ(n,"command")&&(void 0===n.positionals||Array.isArray(n.positionals))){s.push(e);continue}(function(e){var t;return["replay_action_stop"===e.type&&eJ(e)&&eX(e,"line")&&eQ(e,"command"),void 0===(t=e).ok||"boolean"==typeof t.ok,eX(e,"durationMs"),eQ(e,"errorCode"),void 0===e.resultTiming||e1(e.resultTiming)].every(Boolean)})(e)&&l.push({stop:e,start:function(e,t){let a=t.command,r=e.findIndex(e=>e.step===t.step&&(void 0===a||void 0===e.command||e.command===a));if(!(r<0))return e.splice(r,1)[0]}(s,e)})}return l}function eJ(e){return"number"==typeof e.step}function eX(e,t){return void 0===e[t]||"number"==typeof e[t]}function eQ(e,t){return void 0===e[t]||"string"==typeof e[t]}function eZ(e,t){var a,r,n,i;let o,s,l=!1===e.ok?"[FAIL] ":!0===e.ok?"":"[info] ";return` ${l}${a=t,r=e,[function(e){if(!e)return"unknown";if(!e.startsWith("__maestro"))return e;let t=e.slice(9);return t.length>0?t[0].toLowerCase()+t.slice(1):e}(a?.command??r.command),...(a?.positionals??[]).map(e0)].join(" ")}${n=e,i=t,(s=["number"==typeof(o=i?.line??n.line)?`line ${o}`:"","number"==typeof n.durationMs?ez(n.durationMs):"",n.errorCode??"",n.resultTiming?`timing ${JSON.stringify(n.resultTiming)}`:""].filter(Boolean)).length>0?` (${s.join(", ")})`:""}`}function e0(e){return"string"==typeof e?JSON.stringify(e):"number"==typeof e||"boolean"==typeof e?String(e):JSON.stringify(e)}function e1(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function e3(e,t){return N(e,t,{validateStream:!1})}function e2(e){if("number"!=typeof e.shardIndex)return"";let t="number"==typeof e.shardCount?e.shardCount:"?",a="string"==typeof e.deviceId?` ${e.deviceId}`:"";return` [shard ${e.shardIndex+1}/${t}${a}]`}function e5(e){return`\r\x1b[2K${e}`}function e4(e){return"number"==typeof e&&Number.isFinite(e)&&e>0?Math.floor(e):80}function e6(e,t){let a=e4(t);return e.length<=a?e:a<=0?"":a<=3?".".repeat(a):`${e.slice(0,a-3)}...`}function e8(e){return{file:e.file,title:e.title,durationMs:e.durationMs??0,attempts:e.attempt??1,artifactsDir:e.artifactsDir,session:e.session??""}}function e7(e){return function(e={}){let t=new Set,a=!1;return{render(n){var i,o;if("replay-test-suite"===n.type){t.clear(),a=!1;return}if("replay-test"!==n.type)return;if("progress"===n.status){if(!e.liveProgress)return;return a=!0,{text:e5(function(e,t){let a=e.title?.trim(),n=r.basename(e.file),i=e2(e),o=e.stepIndex??0,s=e.stepTotal??0,l=`${i} [${o}/${s}]`,c="⊙ ";if(!a)return e6(`${c}${n}${l}`,t.columns);let d=`${c}"`,u=`" in ${n}${l}`,f=e6(a,Math.max(0,e4(t.columns)-d.length-u.length));return e6(`${d}${f}${u}`,t.columns)}(n,e)),newline:!1}}if("pass"===(i=n).status||"skip"===i.status||"fail"===i.status&&!i.retrying){let e,a=(e="number"==typeof(o=n).shardIndex?o.shardIndex:"",[o.status,o.index,o.total,o.file,o.title??"",e].join("\0"));if(t.has(a))return;t.add(a)}let s=function(e,t={}){if("replay-test"===e.type)return function(e,t){var a,n,i,o;let s,l,c,d,u,f;if("start"===e.status||"progress"===e.status||"fail"===e.status&&e.retrying)return;let p=[(c=function(e){let t=$(process.stderr);if("pass"===e.status){let a=e.attempt&&e.attempt>1?"yellow":"green";return t?e3("✓",a):"✓"}return"fail"===e.status?t?e3("⨯","red"):"⨯":"progress"===e.status?"⊙":t?e3("-","dim"):"-"}(a=e),d=(n=a,s=n.title?.trim(),l=r.basename(n.file),s?`${JSON.stringify(s)} in ${l}`:l),u=e2(a),f=void 0!==a.durationMs?` (${ez(a.durationMs??0)})`:"",`${c} ${d}${u}${f}`)];return function(e,t,a){if(a.verbose&&"fail"===t.status)return;let r=t.message?.replace(/\s+/g," ").trim();r&&e.push(` ${"fail"===t.status?`failed at: ${r}`:r}`),"fail"===t.status&&!t.retrying&&(t.session&&e.push(` session: ${t.session}`),t.artifactsDir&&e.push(` artifacts: ${t.artifactsDir}`))}(p,e,t),t.verbose&&p.push(...("pass"===(i=e).status||"fail"===i.status)&&i.artifactsDir&&i.attempt?(function(e){if("skipped"===e.status)return[];let t=eW(e);return 0===t.length?[]:[e.attempts>1?`steps (attempt ${e.attempts}):`:"steps:",...t.map(({stop:e,start:t})=>eZ(e,t))]})("pass"===i.status?{...e8(i),status:"passed",replayed:0,healed:0}:{...e8(o=i),status:"failed",error:{code:"COMMAND_FAILED",message:o.message??"Unknown test failure"}}).map(e=>` ${e}`):[]),p.join("\n")}(e,t)}(n,e);if(!s)return;let l=a?e5(s):s;return a=!1,{text:l,newline:!0}}}}({verbose:!!(e.flags?.verbose||e.meta?.debug),liveProgress:!0===process.stderr.isTTY&&!process.env.CI,columns:process.stderr.columns})}function e9(e,t){let a=t.render(e);a&&process.stderr.write(a.newline?`${a.text}
|
|
2
|
-
`:a.text)}function
|
|
3
|
-
`)}),d=!1,u="number"==typeof r?setTimeout(()=>{d=!0,l.destroy(),o(
|
|
4
|
-
`)}catch{}}(r,n,e.paths.baseDir),await eV(r),eH(e.paths.infoPath),null)}async function tA(t){let a,r,n=0,i=[];for(let o=1;o<=2;o+=1){let s;try{r={pid:(s=function(t){let a=tP(),r=a.useSrc?["--experimental-strip-types",a.srcPath]:[a.distPath],n={...process.env,AGENT_DEVICE_STATE_DIR:t.paths.baseDir,AGENT_DEVICE_DAEMON_SERVER_MODE:t.serverMode};e.mkdirSync(t.paths.baseDir,{recursive:!0});let i=e.openSync(t.paths.logPath,"a"),o=e.openSync(t.paths.logPath,"a");try{return p(process.execPath,r,{env:n,stdio:["ignore",i,o]})}finally{e.closeSync(i),e.closeSync(o)}}(t)).pid}}catch(e){if(a=e instanceof Error?e.message:String(e),i.push(await eB(t.paths,"start_error")),o<2){await R(150);continue}break}let l=await t_(15e3,t,s);if("ready"===l.kind)return{info:l.info,startedByClient:!0};if("early_exit"===l.kind){if(r=l.exit,a=tk(l.exit),i.push(await eB(t.paths,"start_error")),o<2){await R(150);continue}break}if(await eq(t.paths)){n+=1;continue}let c=ej(t.paths),d=o<2,u=await eB(t.paths,"startup_timeout",{stopLiveProcesses:!1});if(i.push(u),u.retainedInfoProcess||u.retainedLockProcess){let e=await t_(15e3,t,s);if("ready"===e.kind)return{info:e.info,startedByClient:!0};"early_exit"===e.kind&&(r=e.exit,a=tk(e.exit));break}if(!d)break;c.hasInfo||c.hasLock||await R(150)}let o=ej(t.paths),s=function(t){try{if(!e.existsSync(t))return;let a=e.statSync(t);if(a.size<=0)return;let r=Math.min(a.size,64e3),n=e.openSync(t,"r");try{let t=Buffer.alloc(r);e.readSync(n,t,0,r,a.size-r);let i=t.toString("utf8").trim();return i.length>0?i:void 0}finally{e.closeSync(n)}}catch{return}}(t.paths.logPath);throw new f("COMMAND_FAILED","Failed to start daemon",{kind:"daemon_startup_failed",stateDir:t.paths.baseDir,infoPath:t.paths.infoPath,lockPath:t.paths.lockPath,logPath:t.paths.logPath,startupTimeoutMs:15e3,startupAttempts:2,lockRecoveryCount:n,cleanupResults:i,startError:a,daemonProcess:r,...s?{daemonLogTail:s}:{},metadataState:o,hint:function(e,t=D(process.env.AGENT_DEVICE_STATE_DIR)){var a;let r=(a=t,`rm -f ${S(a.infoPath)} ${S(a.lockPath)}`);return e.hasLock&&!e.hasInfo?`agent-device attempted to clean stale daemon metadata automatically, but ${t.lockPath} still exists without ${t.infoPath}. Retry with --debug; if this persists after confirming no agent-device daemon process is running, run: ${r}`:e.hasLock&&e.hasInfo?`agent-device attempted to clean stale daemon metadata automatically, but ${t.infoPath} and ${t.lockPath} still remain. Retry with --debug; if this persists after confirming no agent-device daemon process is running, run: ${r}`:e.hasInfo?`agent-device did not observe reachable daemon metadata after retrying, and ${t.infoPath} still remains. Stale metadata was cleaned automatically when safe; retry with --debug. If this persists after confirming no agent-device daemon process is running, run: ${r}`:`agent-device did not observe reachable daemon metadata after retrying. Stale metadata was cleaned automatically when safe; retry with --debug and check daemon diagnostics logs. If stale metadata returns after confirming no agent-device daemon process is running, run: ${r}`}(o,t.paths)})}async function tS(t,a,r){if(!tM(t.command)||!a.startedByClient&&!r.ownedStateDir||eK(a.info))return;let n={pid:a.info.pid,removedInfo:!1,removedLock:!1,removedStateDir:!1,error:void 0};try{await eV(a.info)}catch(e){n.error=e instanceof Error?e.message:String(e)}finally{let t=e.existsSync(r.paths.infoPath);eH(r.paths.infoPath),n.removedInfo=t&&!e.existsSync(r.paths.infoPath);let a=e.existsSync(r.paths.lockPath);eH(r.paths.lockPath),n.removedLock=a&&!e.existsSync(r.paths.lockPath),r.ownedStateDir&&(e.rmSync(r.paths.baseDir,{recursive:!0,force:!0}),n.removedStateDir=!e.existsSync(r.paths.baseDir))}g({level:n.error?"warn":"info",phase:"daemon_replay_cleanup",data:n})}function tM(e){return e===C.replay||e===C.test}async function t_(e,t,a){let r,n=Date.now();for(a.exited.then(e=>{r=e});Date.now()-n<e;){if(r)return{kind:"early_exit",exit:r};let e=eL(t.paths.infoPath);if(e&&await tn(e,t.transportPreference))return{kind:"ready",info:e};if(r)return{kind:"early_exit",exit:r};await R(100)}return{kind:"timeout"}}function tP(){let t=L(),a=[r.join(t,"dist","src","internal","daemon.js"),r.join(t,"dist","src","daemon.js")],n=a[0];if(void 0===n)throw new f("COMMAND_FAILED","Daemon dist path list is empty");let i=a.find(t=>e.existsSync(t))??n,o=r.join(t,"src","daemon.ts"),s=a.some(t=>e.existsSync(t)),l=e.existsSync(o);if(!s&&!l)throw new f("COMMAND_FAILED","Daemon entry not found",{distPaths:a,srcPath:o});return{root:t,distPath:i,distPaths:a,srcPath:o,useSrc:process.execArgv.includes("--experimental-strip-types")?l:!s&&l}}function tD(){let e=tP();return x(e.useSrc?e.srcPath:e.distPath,e.root)}function tk(e){return e.error?`daemon process ${e.pid} failed to start: ${e.error}`:e.signal?`daemon process ${e.pid} exited before readiness with signal ${e.signal}`:`daemon process ${e.pid} exited before readiness with code ${e.exitCode??0}`}async function tx(e){let t=e.meta?.requestId??y(),a=!!(e.meta?.debug||e.flags?.verbose),r=tg(e),n=function(e){if(e.command!==C.test){var t;return"number"==typeof e.flags?.timeoutMs&&((t=e.command)===C.prepare||t===C.replay||t===C.snapshot)?e.flags.timeoutMs:e.command===C.prepare?24e4:9e4}}(e),i=await w("daemon_startup",async()=>await tv(r),{requestId:t,session:e.session}),o=i.info,s=await ek(e,o),l={...e,positionals:s.positionals,flags:s.flags,token:o.token,meta:{...e.meta??{},requestId:t,debug:a,cwd:e.meta?.cwd,sessionExplicit:e.meta?.sessionExplicit,tenantId:e.meta?.tenantId??e.flags?.tenant,runId:e.meta?.runId??e.flags?.runId,leaseId:e.meta?.leaseId??e.flags?.leaseId,sessionIsolation:e.meta?.sessionIsolation??e.flags?.sessionIsolation,lockPolicy:e.meta?.lockPolicy,lockPlatform:e.meta?.lockPlatform,...s.uploadedArtifactId?{uploadedArtifactId:s.uploadedArtifactId}:{},...s.clientArtifactPaths?{clientArtifactPaths:s.clientArtifactPaths}:{},...s.installSource?{installSource:s.installSource}:{}}};g({level:"info",phase:"daemon_request_prepare",data:{requestId:t,command:e.command,session:e.session}});try{return await w("daemon_request",async()=>await tl(o,l,r.transportPreference,r.paths,n),{requestId:t,command:e.command})}finally{await tS(e,i,r)}}tw.addSubnet("127.0.0.0",8,"ipv4"),tw.addAddress("::1","ipv6"),tw.addSubnet("::ffff:127.0.0.0",104,"ipv6");let tE=/^[0-9a-fA-F-]{32,36}$/;function tN(e){if(e&&tE.test(e))return e.replaceAll("-","").toUpperCase()}function t$(e,t){return`${e.uuid}:${tT(t)}`}function tT(e){return`0x${e.toString(16)}`}function tC(e){return"string"==typeof e&&e.length>0?e:void 0}function tU(...e){for(let t of e){let e=tC(t);if(e)return e}}function tL(e){return"object"==typeof e&&null!==e}function tR(e){return tL(e)?e:void 0}function tO(e){try{let t=JSON.parse(e);return tL(t)?t:null}catch{return null}}function tF(e){if("number"==typeof e&&Number.isSafeInteger(e))return e;if("string"==typeof e){let t=e.startsWith("0x")?Number.parseInt(e,16):Number(e);return Number.isSafeInteger(t)?t:void 0}}function tB(e,t,a){var r;if(!Object.hasOwn(e,t))return;let n="bigint"==typeof(r=e[t])?r:"number"==typeof r&&Number.isSafeInteger(r)?BigInt(r):"string"!=typeof r?void 0:/^(?:0x[0-9a-fA-F]+|\d+)$/.test(r)?BigInt(r):void 0;if(void 0!==n)return n;tj(a,t)}function tj(e,t){throw new f("INVALID_ARGS",`Invalid ${e} numeric field: ${t}`,{hint:"Crash artifact numeric fields must be integer numbers or integer numeric strings."})}function tq(e){return[...new Set(e)]}let tV=/^(?:arm64e?|arm64_32|x86_64|armv7[sk]?|i386)$/;async function tK(e){return e.dsym&&e.searchPath?[tJ(e.cwd,e.dsym),...await tG(tJ(e.cwd,e.searchPath))]:e.dsym?[tJ(e.cwd,e.dsym)]:e.searchPath?await tG(tJ(e.cwd,e.searchPath)):[]}async function tG(e){let t=[],a=0;async function n(i){if(!(t.length>=200)){if((a+=1)>1e4)throw new f("COMMAND_FAILED","debug symbols search-path scan exceeded bounds.",{searchPath:e,maxEntries:1e4,hint:"Pass --dsym <App.dSYM> directly or narrow --search-path to the build products directory."});if(!(await tH(i,e)).isDirectory()){i===e&&function(e){throw new f("INVALID_ARGS",`debug symbols search path is not a directory: ${e}`,{hint:"Pass an existing build products directory to --search-path, or pass --dsym <App.dSYM> directly."})}(e);return}if(i.endsWith(".dSYM"))return void t.push(i);for(let e of(await d.readdir(i,{withFileTypes:!0})))e.isDirectory()&&await n(r.join(i,e.name))}}return await n(e),t}async function tH(e,t){try{return await d.stat(e)}catch{throw new f("INVALID_ARGS",`debug symbols search path does not exist: ${t}`,{hint:"Pass an existing build products directory to --search-path, or pass --dsym <App.dSYM> directly."})}}async function tz(e,t){let a=(await Promise.all(tq(e).map(e=>tY(e,t)))).flat();if(0===a.length)throw new f("COMMAND_FAILED","No UUIDs found in dSYM bundle.",{hint:"Verify the path points to a built .dSYM bundle with DWARF contents."});return a}async function tY(e,t){var a;await tW(e);let r=await m(t,["--uuid",e],{timeoutMs:15e3,allowFailure:!0});if(0!==r.exitCode)throw new f("COMMAND_FAILED",`Failed to inspect dSYM UUIDs: ${e}`,{stderr:r.stderr,hint:"Verify the dSYM bundle is valid and readable."});return a=e,r.stdout.split("\n").flatMap(e=>{let t=e.match(/^UUID:\s+([0-9a-fA-F-]{32,36})\s+\(([^)]+)\)\s+(.+)$/),r=tN(t?.[1]);return t&&r?[{dsymPath:a,uuid:r,arch:t[2],binaryPath:t[3].trim()}]:[]})}async function tW(e){let t=await d.stat(e).catch(()=>null);if(!(t?.isDirectory()&&e.endsWith(".dSYM")))throw new f("INVALID_ARGS",`Not a .dSYM bundle: ${e}`,{hint:"Pass the .dSYM bundle path, not the DWARF executable inside it."})}function tJ(e,t){return r.resolve(e,t)}function tX(e,t){let a=`${t}:`,r=e.find(e=>e.trimStart().startsWith(a));return r&&r.slice(r.indexOf(":")+1).trim()||void 0}function tQ(e,t,a,r){return{index:e,image:t.name,address:tT(a),symbol:r.get(t$(t,a))?.text}}function tZ(e){var t;let a;return[(a=(t=e).topFrames.find(e=>e.symbol))?`Start with ${a.symbol} in ${a.image}; it is the first symbolicated frame captured on the crashed thread.`:t.topFrames.length>0?"No symbolicated frame was found on the crashed thread; verify matching dSYMs for the top images.":void 0,e.exceptionType?`Exception: ${e.exceptionType}`:void 0,e.terminationReason?`Termination: ${e.terminationReason}`:void 0].filter(e=>!!e).slice(0,3)}async function t0(e,t,a){let r=new Map;for(let n of(function(e,t){let a=new Map;for(let r of e){let e=t.get(r.image.uuid);if(!e)continue;let n=`${r.image.uuid}:${e.dsym.binaryPath}`,i=a.get(n)??{...e,addresses:[]};i.addresses.push(r.address),a.set(n,i)}return a})(e,t).values())for(let e of(await t1(a,n)))r.set(t$(e.image,e.address),e);return r}async function t1(e,t){var a,r,n,i;let o,s,l=tq(t.addresses.map(tT)),c=await m(e,(a=t,r=l,["-arch",a.image.arch??a.dsym.arch??"arm64","-o",a.dsym.binaryPath,"-l",tT(a.image.base),...r]),{timeoutMs:3e4,allowFailure:!0});return 0!==c.exitCode&&function(e){throw new f("COMMAND_FAILED","atos failed while symbolicating crash frames.",{stderr:e,hint:"Verify the crash artifact and dSYM were produced from the same build and architecture."})}(c.stderr),n=t.image,i=l,s=(""===(o=c.stdout.split(/\r?\n/)).at(-1)&&o.pop(),o),i.map((e,t)=>{let a=s[t]?.trim();return{image:n,address:BigInt(e),text:!function(e,t){if(!e)return!1;let a=e.trim().toLowerCase();return!!a&&"??"!==a&&a!==t.toLowerCase()&&!a.startsWith("0x")}(a,e)?void 0:a}})}async function t3(){return{dwarfdump:await t2("dwarfdump"),atos:await t2("atos")}}async function t2(e){try{let t=await m("xcrun",["--find",e],{timeoutMs:5e3,allowFailure:!0}),a=t.stdout.trim();if(0===t.exitCode&&a.length>0)return a}catch{}throw new f("TOOL_MISSING",`Apple symbolication tool not found: ${e}`,{hint:"Install Xcode Command Line Tools and verify xcrun --find dwarfdump and xcrun --find atos succeed."})}async function t5(e){var t,a,n,i,o,s,l,c,u,p,m,h,y,w,g,v,b,I,A,S,M,_,P,D,k,x,E;let N,$,T,C,U,L,R,O,F;if(void 0!==e.action&&"symbols"!==e.action)throw new f("INVALID_ARGS","debug supports only the symbols workflow.",{hint:"Use debug symbols --artifact <crash.ips|crash.log> --dsym <App.dSYM> or --search-path <dir> --out <path>."});let B=e.cwd??process.cwd(),j=t8(B,e.artifact),q=t8(B,e.out??(a=j,$=(N=r.extname(a))?a.slice(0,-N.length):a,`${$}-symbolicated${N||".log"}`)),V=function(e){var t;let a,n=function(e){let t=tO(e);if(t)return{payload:t};let a=e.indexOf("\n");if(-1===a)return null;let r=e.slice(0,a),n=tO(e.slice(a+1));return n?{header:r,payload:n}:null}(e);if(!n)return null;let i=(Array.isArray(n.payload.usedImages)?n.payload.usedImages:[]).flatMap((e,t)=>(function(e,t){if(!e||"object"!=typeof e)return[];let a=tN(tC(e.uuid)),n=tB(e,"base","IPS usedImages");if(!a||void 0===n)return[];let i=tC(e.path);return[{index:t,name:tC(e.name)??(i?r.basename(i):`image-${t}`),uuid:a,arch:tC(e.arch),base:n,path:i}]})(e,t));if(0===i.length)return null;let o=(t=Array.isArray(n.payload.threads)?n.payload.threads:[],a=new Map(i.map(e=>[e.index,e])),t.flatMap((e,t)=>(function(e){if(!e||"object"!=typeof e)return[];let t=e.frames;return Array.isArray(t)?t.filter(e=>tL(e)):[]})(e).flatMap((e,r)=>(function(e,t,a,r){let n=function(e,t,a){if(!Object.hasOwn(e,t))return;let r=tF(e[t]);if(void 0!==r)return r;tj(a,t)}(e,"imageIndex","IPS frame"),i=tB(e,"imageOffset","IPS frame");if(void 0===n||void 0===i)return[];let o=t.get(n);return o?[{frame:e,frameIndex:r,threadIndex:a,image:o,address:o.base+i}]:[]})(e,a,t,r))));return{format:"ips",images:i,addresses:o.map(({frame:e,...t})=>t),document:n,frameMatches:o,write:e=>(function(e,t,a){for(let e of t){let t=a.get(t$(e.image,e.address))?.text;t&&function(e,t){let a,r=(a=t.match(/^(.*) \+ (\d+)$/))?{symbol:a[1],location:Number(a[2])}:{symbol:t};e.symbol=r.symbol,void 0!==r.location&&(e.symbolLocation=r.location)}(e.frame,t)}e.payload.agentDeviceSymbolication={tool:"agent-device debug symbols",symbolicatedFrames:[...a.values()].filter(e=>e.text).length};let r=`${JSON.stringify(e.payload,null,2)}
|
|
1
|
+
import e from"node:fs";import t from"node:http";import a from"node:https";import r from"node:path";import{pipeline as n}from"node:stream/promises";import i from"node:os";import{createHash as o,randomUUID as s}from"node:crypto";import{Writable as l}from"node:stream";import c from"node:net";import d from"node:fs/promises";import{toAppErrorCode as u,AppError as f}from"./733.js";import{runCmdDetachedMonitored as p,runCmd as m,runCmdSync as h}from"./8875.js";import{createRequestId as y,withDiagnosticTimer as w,emitDiagnostic as g}from"./432.js";import{isAgentDeviceDaemonProcess as b,stopProcessForTakeover as v}from"./5628.js";import{readSnapshotDiagnosticsSummary as I,consumeTextLines as A,shellQuote as S,shouldStreamRequestProgress as M,isDaemonResponseEnvelope as _,isDaemonProgressEnvelope as D,resolveDaemonPaths as P,resolveDaemonServerMode as k,computeDaemonCodeSignature as E,resolveDaemonTransportPreference as N}from"./8358.js";import{listCommandFamilyDaemonWriters as x,normalizeSession as $,readSerializedSnapshotCaptureAnnotations as T,readRequiredString as C,findCommandMetadata as U,normalizeMaterializationReleaseResult as L,colorize as O,readSnapshotNodes as R,normalizeDeployResult as F,normalizeOpenDevice as B,buildMeta as j,readOptionalString as q,resolveSessionName as V,supportsColor as H,buildRequestFlags as G,createBatchDaemonWriter as K,readMetadataCommandFlags as z,normalizeDevice as Y,normalizeStartupSample as W,readScreenshotOverlayRefs as J,normalizeRuntimeHints as X,normalizeInstallFromSourceResult as Q}from"./2948.js";import{INTERNAL_COMMANDS as Z,PUBLIC_COMMANDS as ee}from"./2133.js";import{readVersion as et,findProjectRoot as ea}from"./1404.js";import{sleep as er}from"./5560.js";import{reloadMetro as en,prepareMetroRuntime as ei}from"./8275.js";let eo="/agent-device";function es(e){return el(e,eo)}function el(e,t){let a=e.endsWith("/")?e:`${e}/`;return new URL(t.replace(/^\/+/,""),a).toString()}function ec(e){let t=e?.trim();return t?{authorization:`Bearer ${t}`,"x-agent-device-token":t}:{}}function ed(e){return new Promise((t,a)=>{let r="";e.setEncoding("utf8"),e.on("data",e=>{r+=e}),e.on("end",()=>t(r)),e.on("error",a)})}let eu="sha256";async function ef(e){let t=await ep(e.localPath,e.platform),a=e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`;try{let r=await ew({normalizedBase:a,token:e.token,artifact:t});if(r?.kind==="cache-hit")return r.uploadId;if(r?.kind==="direct-upload")try{return await eg(t.payloadPath,r),await eA({normalizedBase:a,token:e.token,uploadId:r.uploadId})}catch{}return await ey({normalizedBase:a,token:e.token,artifact:t})}finally{t.cleanup()}}async function ep(t,a){var n,i,o;let s,l=e.statSync(t),c=r.basename(t),d=l.isDirectory(),u=("ios"===(n=a)||"android"===n?n:void 0)??(i=t,o=l,s=i.toLowerCase(),o.isDirectory()&&s.endsWith(".app")||s.endsWith(".ipa")?"ios":s.endsWith(".apk")||s.endsWith(".aab")?"android":void 0),f=[];try{let a=d?await em(t,f):t,r=e.statSync(a);return{payloadPath:a,fileName:c,artifactType:d?"app-bundle":"file",platform:u,contentType:d?"application/gzip":"application/octet-stream",sha256:await eS(a),sizeBytes:r.size,cleanup:()=>eh(f)}}catch(e){throw eh(f),e}}async function em(t,a){let n=e.mkdtempSync(r.join(i.tmpdir(),`agent-device-upload-${s()}-`));a.push(n);let o=r.join(n,`${r.basename(t)}.tar.gz`);return await m("tar",["czf",o,"-C",r.dirname(t),r.basename(t)],{env:{...process.env,COPYFILE_DISABLE:"1"}}),o}function eh(t){for(let a of t)e.rmSync(a,{recursive:!0,force:!0})}async function ey(e){let{normalizedBase:t,token:a,artifact:r}=e,n=new URL("upload",t),i={"content-type":r.contentType,"x-artifact-type":r.artifactType,"x-artifact-filename":r.fileName,"x-artifact-hash":r.sha256,"x-artifact-hash-algorithm":eu,"transfer-encoding":"chunked"};Object.assign(i,ec(a));let o=await eb({url:n,method:"POST",headers:i,payloadPath:r.payloadPath,timeoutMessage:"Artifact upload timed out",timeoutHint:"The upload to the remote daemon exceeded the 5-minute timeout.",errorMessage:"Failed to upload artifact to remote daemon",errorHint:"Verify the remote daemon is reachable and supports artifact uploads."});try{let e=JSON.parse(o.body);if(!e.ok||!e.uploadId)throw new f("COMMAND_FAILED",`Upload failed: ${o.body}`);return e.uploadId}catch(e){if(e instanceof f)throw e;throw new f("COMMAND_FAILED",`Invalid upload response: ${o.body}`)}}async function ew(e){let t=new URL("upload/preflight",e.normalizedBase),a={"content-type":"application/json"};Object.assign(a,ec(e.token));let r=await fetch(t,{method:"POST",headers:a,signal:AbortSignal.timeout(3e4),body:JSON.stringify({sha256:e.artifact.sha256,fileName:e.artifact.fileName,sizeBytes:e.artifact.sizeBytes,artifactType:e.artifact.artifactType,...e.artifact.platform?{platform:e.artifact.platform}:{},contentType:e.artifact.contentType})}).catch(()=>void 0);if(r?.ok)return function(e){var t;if(!e||"object"!=typeof e||!0!==e.ok||"string"!=typeof e.uploadId)return;if(!0===e.cacheHit)return{kind:"cache-hit",uploadId:e.uploadId};let a=e.upload;if(!a||"string"!=typeof a.url)return;let r=a.headers??{};if(!(!(t=r)||"object"!=typeof t||Array.isArray(t))&&Object.values(t).every(e=>"string"==typeof e))return{kind:"direct-upload",uploadId:e.uploadId,url:a.url,headers:r}}(await r.json().catch(()=>void 0))}async function eg(e,t){let a=await eb({url:new URL(t.url),method:"PUT",headers:t.headers,payloadPath:e,timeoutMessage:"Direct artifact upload timed out",timeoutHint:"The direct upload ticket did not accept the artifact within the timeout.",errorMessage:"Failed to upload artifact with direct upload ticket"});if(a.statusCode<200||a.statusCode>=300)throw new f("COMMAND_FAILED","Direct artifact upload failed",{statusCode:a.statusCode,statusMessage:a.statusMessage})}async function eb(e){return await ev({...e,url:e.url,redirectCount:0,startOffset:0})}async function ev(r){var i,o,s;let l="https:"===r.url.protocol?a:t,c=e.statSync(r.payloadPath).size,d=(i=r.headers,o=r.startOffset,s=c,o<=0?i:{...i,"content-length":Math.max(s-o,0),"content-range":`bytes ${o}-${s-1}/${s}`});return await new Promise((t,a)=>{let i=!1,o=l.request({protocol:r.url.protocol,host:r.url.hostname,port:r.url.port,method:r.method,path:r.url.pathname+r.url.search,headers:d},e=>{i=!0,ed(e).then(n=>{clearTimeout(s);let i=e.statusCode??500,o=e.headers.location;if(o&&[301,302,303,307,308].includes(i)){if(r.redirectCount>=5)return void a(new f("COMMAND_FAILED","Artifact upload exceeded redirect limit",{maxRedirects:5,url:r.url.toString()}));let e=new URL(o,r.url);return void ev({...r,url:e,redirectCount:r.redirectCount+1}).then(t,a)}let l=308===i?function(e,t){let a=function(e){let t=eI(e);if(void 0===t)return;let a=Number(t);return Number.isSafeInteger(a)&&a>=0?a:void 0}(e["x-upload-offset"]??e["upload-offset"]);if(void 0!==a)return Math.min(a,t);let r=eI(e.range),n=r?.match(/^bytes=0-(\d+)$/);if(!n)return;let i=Number(n[1]);if(Number.isSafeInteger(i)&&!(i<0))return Math.min(i+1,t)}(e.headers,c):void 0;void 0!==l?l>=c?t({statusCode:200,statusMessage:"Upload already complete",body:""}):l<=r.startOffset?a(new f("COMMAND_FAILED","Artifact upload resume did not advance",{offset:l,previousOffset:r.startOffset,url:r.url.toString()})):ev({...r,startOffset:l}).then(t,a):t({statusCode:i,statusMessage:e.statusMessage,body:n})}).catch(a)}),s=setTimeout(()=>{o.destroy(),a(new f("COMMAND_FAILED",r.timeoutMessage,{timeoutMs:3e5,...r.timeoutHint?{hint:r.timeoutHint}:{}}))},3e5);o.on("error",e=>{i||(clearTimeout(s),a(new f("COMMAND_FAILED",r.errorMessage,r.errorHint?{hint:r.errorHint}:{},e)))}),o.on("close",()=>clearTimeout(s)),n(e.createReadStream(r.payloadPath,{start:r.startOffset}),o).catch(e=>{i||(o.destroy(),a(new f("COMMAND_FAILED","Failed to read local artifact",{},e instanceof Error?e:Error(String(e)))))})})}function eI(e){return Array.isArray(e)?e[0]:e}async function eA(e){let t=new URL("upload/finalize",e.normalizedBase),a={"content-type":"application/json"};Object.assign(a,ec(e.token));let r=await fetch(t,{method:"POST",headers:a,signal:AbortSignal.timeout(3e4),body:JSON.stringify({uploadId:e.uploadId})}).catch(e=>{throw new f("COMMAND_FAILED","Failed to finalize direct artifact upload",{},e)});if(!r.ok)throw new f("COMMAND_FAILED","Direct artifact upload finalize failed",{status:r.status,statusText:r.statusText});let n=await r.json().catch(()=>void 0);if(!n?.ok||!n.uploadId)throw new f("COMMAND_FAILED","Invalid upload finalize response");return n.uploadId}async function eS(t){let a=o(eu),r=new l({write(e,t,r){a.update(e),r()}});return await n(e.createReadStream(t),r).catch(e=>{throw new f("COMMAND_FAILED","Failed to read local artifact",{},e instanceof Error?e:void 0)}),a.digest("hex")}async function eM(e,t){var a;let n,i=[...e.positionals??[]],o=e.flags?{...e.flags}:void 0,s=e.meta?.installSource,l={};if(!("string"==typeof(a=t).baseUrl&&a.baseUrl.length>0))return eD({positionals:i,flags:o,installSource:s,uploadedArtifactId:n,clientArtifactPaths:l});o=function(e,t,a,n){var i,o;let s=function(e,t){if("screenshot"===e.command){let a=ek(e,"path",".png");return t[0]?{field:"path",localPath:a,positionalIndex:0,positionalPath:eE("screenshot",".png")}:{field:"path",localPath:a,positionalIndex:0,flagPath:eE("screenshot",".png")}}if("record"===e.command&&"start"===(t[0]??"").toLowerCase()){let t=ek(e,"outPath",".mp4",1);return{field:"outPath",localPath:t,positionalIndex:1,positionalPath:eE("recording",r.extname(t)||".mp4")}}return null}(e,t);if(!s)return a;void 0!==s.positionalPath&&(t[s.positionalIndex]=s.positionalPath);let l=(i=a,void 0===(o=s.flagPath)?i:{...i??{},out:o});return n[s.field]=s.localPath,l}(e,i,o,l);let c=await eP(e,t);c&&(s=c.installSource,n=c.uploadedArtifactId??n);let d=()=>eD({positionals:i,flags:o,installSource:s,uploadedArtifactId:n,clientArtifactPaths:l});return"install"!==e.command&&"reinstall"!==e.command||(n=await e_(e,t,i)??n),d()}async function e_(t,a,n){var i,o;let s,l=n[1];if(void 0===l)return;if(l.startsWith("remote:")){n[1]=l.slice(7);return}let c=(i=l,o=t.meta?.cwd,s=r.isAbsolute(i)?i:r.resolve(o??process.cwd(),i),e.existsSync(s)?s:void 0);if(c)return await ef({localPath:c,baseUrl:a.baseUrl,token:a.token,platform:t.flags?.platform})}function eD(e){return{positionals:e.positionals,flags:e.flags,installSource:e.installSource,uploadedArtifactId:e.uploadedArtifactId,...Object.keys(e.clientArtifactPaths).length>0?{clientArtifactPaths:e.clientArtifactPaths}:{}}}async function eP(t,a){let n=t.meta?.installSource;if("install_source"!==t.command||!n||"path"!==n.kind)return null;let i=n.path.trim();if(!i)return{installSource:n};if(i.startsWith("remote:"))return{installSource:{...n,path:i.slice(7)}};let o=r.isAbsolute(i)?i:r.resolve(t.meta?.cwd??process.cwd(),i);if(!e.existsSync(o))return{installSource:{...n,path:o}};let s=await ef({localPath:o,baseUrl:a.baseUrl,token:a.token,platform:t.flags?.platform});return{installSource:{...n,path:o},uploadedArtifactId:s}}function ek(e,t,a,n=0){let i=e.positionals?.[n]??e.flags?.out,o=`${"path"===t?"screenshot":"recording"}-${Date.now()}${a}`,s=i&&i.trim().length>0?i:o;return r.isAbsolute(s)?s:r.resolve(e.meta?.cwd??process.cwd(),s)}function eE(e,t){let a=t.startsWith(".")?t:`.${t}`;return r.posix.join("/tmp",`agent-device-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}${a}`)}async function eN(e,t,a){let n=Array.isArray(a.data?.artifacts)?a.data.artifacts:[];if(0===n.length||!e.baseUrl)return a;let i=a.data?{...a.data}:{},o=[];for(let a of n){if(!a||"object"!=typeof a||"string"!=typeof a.artifactId){o.push(a);continue}let n=function(e,t){if(e.localPath&&e.localPath.trim().length>0)return e.localPath;let a=t.meta?.clientArtifactPaths?.[e.field];if(a&&a.trim().length>0)return a;let n=e.fileName?.trim()||`${e.field}-${Date.now()}`;return r.resolve(t.meta?.cwd??process.cwd(),n)}(a,t);await ex({baseUrl:e.baseUrl,token:e.token,artifactId:a.artifactId,destinationPath:n,requestId:t.meta?.requestId}),i[a.field]=n,o.push({...a,localPath:n})}return i.artifacts=o,{ok:!0,data:i}}async function ex(i){var o,s;let l,c=new URL((o=i.baseUrl,s=i.artifactId,l=o.endsWith("/")?o:`${o}/`,new URL(`artifacts/${encodeURIComponent(s)}`,l).toString())),d="https:"===c.protocol?a:t;await e.promises.mkdir(r.dirname(i.destinationPath),{recursive:!0}),await new Promise((t,a)=>{let r=!1,o=i.timeoutMs??9e4,s=n=>{if(!r){if(r=!0,clearTimeout(u),n)return void e.promises.rm(i.destinationPath,{force:!0}).finally(()=>a(n));t()}},l=d.request({protocol:c.protocol,host:c.hostname,port:c.port,method:"GET",path:c.pathname+c.search,headers:ec(i.token)},t=>{if((t.statusCode??500)>=400){let e="";t.setEncoding("utf8"),t.on("data",t=>{e+=t}),t.on("end",()=>{s(new f("COMMAND_FAILED","Failed to download remote artifact",{artifactId:i.artifactId,statusCode:t.statusCode,requestId:i.requestId,body:e}))});return}t.on("aborted",()=>{s(new f("COMMAND_FAILED","Remote artifact download was interrupted",{artifactId:i.artifactId,requestId:i.requestId}))}),n(t,e.createWriteStream(i.destinationPath)).then(()=>s(),e=>s(e instanceof Error?e:Error(String(e))))}),u=setTimeout(()=>{let e=new f("COMMAND_FAILED","Remote artifact download timed out",{artifactId:i.artifactId,requestId:i.requestId,timeoutMs:o});s(e),l.destroy(e)},o);l.on("error",e=>{e instanceof f?s(e):s(new f("COMMAND_FAILED","Failed to download remote artifact",{artifactId:i.artifactId,requestId:i.requestId,timeoutMs:o},e instanceof Error?e:void 0))}),l.end()})}function e$(e){var t,a,r;let n,i,o=ej(e);if(!o||"object"!=typeof o)return null;let s="string"==typeof(t=o).token&&t.token.length>0?t.token:null;if(!s)return null;let l=(n=eC((a=o).port),i=eC(a.httpPort),void 0===n&&void 0===i?null:{port:n,httpPort:i});return l?{token:s,...l,transport:"socket"===(r=o.transport)||"http"===r||"dual"===r?r:void 0,pid:eC(o.pid)??0,version:eT(o.version),codeSignature:eT(o.codeSignature),processStartTime:eT(o.processStartTime)}:null}function eT(e){return"string"==typeof e?e:void 0}function eC(e){return Number.isInteger(e)&&Number(e)>0?Number(e):void 0}function eU(e){let t=ej(e);return t&&"object"==typeof t&&Number.isInteger(t.pid)&&Number(t.pid)>0?{pid:Number(t.pid),processStartTime:"string"==typeof t.processStartTime?t.processStartTime:void 0,startedAt:"number"==typeof t.startedAt?t.startedAt:void 0}:null}async function eL(t,a,r={}){let n=r.stopLiveProcesses??!0,i={reason:a,removedInfo:!1,removedLock:!1,stoppedInfoProcess:!1,stoppedLockProcess:!1};try{var o,s,l,c;let a=e.existsSync(t.infoPath),r=e$(t.infoPath);if(r){let e=b(r.pid,r.processStartTime);e&&!n?i.retainedInfoProcess=!0:(e&&(await eF(r),i.stoppedInfoProcess=!0),o=t.infoPath,eq(o),i.removedInfo=!0)}else a&&(s=t.infoPath,eq(s),i.removedInfo=!0);let d=e.existsSync(t.lockPath),u=eU(t.lockPath);if(u){let e=b(u.pid,u.processStartTime);e&&!n?i.retainedLockProcess=!0:(e&&(await v(u.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:u.processStartTime}),i.stoppedLockProcess=!0),l=t.lockPath,eq(l),i.removedLock=!0)}else d&&(c=t.lockPath,eq(c),i.removedLock=!0)}catch(e){i.error=e instanceof Error?e.message:String(e)}return g({level:i.error?"warn":"info",phase:"daemon_startup_metadata_cleanup",data:i}),i}function eO(t){return{hasInfo:e.existsSync(t.infoPath),hasLock:e.existsSync(t.lockPath)}}async function eR(e){let t=eO(e);if(!t.hasLock||t.hasInfo)return!1;let a=eU(e.lockPath);return!(a&&b(a.pid,a.processStartTime))&&(eq(e.lockPath),!0)}async function eF(e){await v(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}function eB(e){return"string"==typeof e.baseUrl&&e.baseUrl.length>0}function ej(t){if(!e.existsSync(t))return null;try{return JSON.parse(e.readFileSync(t,"utf8"))}catch{return null}}function eq(t){try{e.existsSync(t)&&e.unlinkSync(t)}catch{}}function eV(e){let t=Math.max(0,e)/1e3;return t>=10?`${t.toFixed(1)}s`:t>=1?`${t.toFixed(2)}s`:`${t.toFixed(3).replace(/0+$/,"").replace(/\.$/,"")}s`}function eH(e){let t=eG(e),a=t.findIndex(({stop:e})=>!1===e.ok);if(a<0)return[];let r=t.slice(Math.max(0,a-2),a+1);return[e.attempts>1?`steps (attempt ${e.attempts}):`:"steps:",...r.map(({stop:e,start:t})=>eW(e,t))]}function eG(t){var a,n;let i=(a=t).artifactsDir?r.join(a.artifactsDir,`attempt-${a.attempts}`,"replay-timing.ndjson"):void 0;if(!i)return[];let o=function(t){try{return e.readFileSync(t,"utf8").split(/\r?\n/).filter(e=>e.trim().length>0).flatMap(e=>{try{let t=JSON.parse(e);return eX(t)?[t]:[]}catch{return[]}})}catch{return[]}}(i);if(0===o.length)return[];let s=[],l=[];for(let e of o){if("replay_action_start"===(n=e).type&&eK(n)&&ez(n,"line")&&eY(n,"command")&&(void 0===n.positionals||Array.isArray(n.positionals))){s.push(e);continue}(function(e){var t;return["replay_action_stop"===e.type&&eK(e)&&ez(e,"line")&&eY(e,"command"),void 0===(t=e).ok||"boolean"==typeof t.ok,ez(e,"durationMs"),eY(e,"errorCode"),void 0===e.resultTiming||eX(e.resultTiming)].every(Boolean)})(e)&&l.push({stop:e,start:function(e,t){let a=t.command,r=e.findIndex(e=>e.step===t.step&&(void 0===a||void 0===e.command||e.command===a));if(!(r<0))return e.splice(r,1)[0]}(s,e)})}return l}function eK(e){return"number"==typeof e.step}function ez(e,t){return void 0===e[t]||"number"==typeof e[t]}function eY(e,t){return void 0===e[t]||"string"==typeof e[t]}function eW(e,t){var a,r,n,i;let o,s,l=!1===e.ok?"[FAIL] ":!0===e.ok?"":"[info] ";return` ${l}${a=t,r=e,[function(e){if(!e)return"unknown";if(!e.startsWith("__maestro"))return e;let t=e.slice(9);return t.length>0?t[0].toLowerCase()+t.slice(1):e}(a?.command??r.command),...(a?.positionals??[]).map(eJ)].join(" ")}${n=e,i=t,(s=["number"==typeof(o=i?.line??n.line)?`line ${o}`:"","number"==typeof n.durationMs?eV(n.durationMs):"",n.errorCode??"",n.resultTiming?`timing ${JSON.stringify(n.resultTiming)}`:""].filter(Boolean)).length>0?` (${s.join(", ")})`:""}`}function eJ(e){return"string"==typeof e?JSON.stringify(e):"number"==typeof e||"boolean"==typeof e?String(e):JSON.stringify(e)}function eX(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function eQ(e,t){return O(e,t,{validateStream:!1})}function eZ(e){if("number"!=typeof e.shardIndex)return"";let t="number"==typeof e.shardCount?e.shardCount:"?",a="string"==typeof e.deviceId?` ${e.deviceId}`:"";return` [shard ${e.shardIndex+1}/${t}${a}]`}function e0(e){return`\r\x1b[2K${e}`}function e1(e){return"number"==typeof e&&Number.isFinite(e)&&e>0?Math.floor(e):80}function e3(e,t){let a=e1(t);return e.length<=a?e:a<=0?"":a<=3?".".repeat(a):`${e.slice(0,a-3)}...`}function e2(e){return{file:e.file,title:e.title,durationMs:e.durationMs??0,attempts:e.attempt??1,artifactsDir:e.artifactsDir,session:e.session??""}}function e5(e){return function(e={}){let t=new Set,a=!1;return{render(n){var i,o;if("replay-test-suite"===n.type){t.clear(),a=!1;return}if("replay-test"!==n.type)return;if("progress"===n.status){if(!e.liveProgress)return;return a=!0,{text:e0(function(e,t){let a=e.title?.trim(),n=r.basename(e.file),i=eZ(e),o=e.stepIndex??0,s=e.stepTotal??0,l=`${i} [${o}/${s}]`,c="⊙ ";if(!a)return e3(`${c}${n}${l}`,t.columns);let d=`${c}"`,u=`" in ${n}${l}`,f=e3(a,Math.max(0,e1(t.columns)-d.length-u.length));return e3(`${d}${f}${u}`,t.columns)}(n,e)),newline:!1}}if("pass"===(i=n).status||"skip"===i.status||"fail"===i.status&&!i.retrying){let e,a=(e="number"==typeof(o=n).shardIndex?o.shardIndex:"",[o.status,o.index,o.total,o.file,o.title??"",e].join("\0"));if(t.has(a))return;t.add(a)}let s=function(e,t={}){if("replay-test"===e.type)return function(e,t){var a,n,i,o;let s,l,c,d,u,f;if("start"===e.status||"progress"===e.status||"fail"===e.status&&e.retrying)return;let p=[(c=function(e){let t=H(process.stderr);if("pass"===e.status){let a=e.attempt&&e.attempt>1?"yellow":"green";return t?eQ("✓",a):"✓"}return"fail"===e.status?t?eQ("⨯","red"):"⨯":"progress"===e.status?"⊙":t?eQ("-","dim"):"-"}(a=e),d=(n=a,s=n.title?.trim(),l=r.basename(n.file),s?`${JSON.stringify(s)} in ${l}`:l),u=eZ(a),f=void 0!==a.durationMs?` (${eV(a.durationMs??0)})`:"",`${c} ${d}${u}${f}`)];return function(e,t,a){if(a.verbose&&"fail"===t.status)return;let r=t.message?.replace(/\s+/g," ").trim();r&&e.push(` ${"fail"===t.status?`failed at: ${r}`:r}`),"fail"===t.status&&!t.retrying&&(t.session&&e.push(` session: ${t.session}`),t.artifactsDir&&e.push(` artifacts: ${t.artifactsDir}`))}(p,e,t),t.verbose&&p.push(...("pass"===(i=e).status||"fail"===i.status)&&i.artifactsDir&&i.attempt?(function(e){if("skipped"===e.status)return[];let t=eG(e);return 0===t.length?[]:[e.attempts>1?`steps (attempt ${e.attempts}):`:"steps:",...t.map(({stop:e,start:t})=>eW(e,t))]})("pass"===i.status?{...e2(i),status:"passed",replayed:0,healed:0}:{...e2(o=i),status:"failed",error:{code:"COMMAND_FAILED",message:o.message??"Unknown test failure"}}).map(e=>` ${e}`):[]),p.join("\n")}(e,t)}(n,e);if(!s)return;let l=a?e0(s):s;return a=!1,{text:l,newline:!0}}}}({verbose:!!(e.flags?.verbose||e.meta?.debug),liveProgress:!0===process.stderr.isTTY&&!process.env.CI,columns:process.stderr.columns})}function e4(e,t){let a=t.render(e);a&&process.stderr.write(a.newline?`${a.text}
|
|
2
|
+
`:a.text)}function e8(e,t){let{info:a,req:r,resolve:n,reject:i}=t;try{var o,s,l;let t=(o=e,JSON.parse(o));if(t.error){let e;return void i((s=t.error,l=r.meta?.requestId,e=s.data??{},new f(u(null!=e.code?String(e.code):void 0,"COMMAND_FAILED"),String(e.message??s.message??"Daemon RPC request failed"),{..."object"==typeof e.details&&e.details?e.details:{},hint:"string"==typeof e.hint?e.hint:void 0,diagnosticId:"string"==typeof e.diagnosticId?e.diagnosticId:void 0,logPath:"string"==typeof e.logPath?e.logPath:void 0,requestId:l})))}if(!t.result||"object"!=typeof t.result)return void i(new f("COMMAND_FAILED","Invalid daemon RPC response",{requestId:r.meta?.requestId}));e6(a,r,t.result,n,i)}catch(t){i(new f("COMMAND_FAILED","Invalid daemon response",{requestId:r.meta?.requestId,line:e},t instanceof Error?t:void 0))}}async function e6(e,t,a,r,n){try{r(e.baseUrl&&a.ok?await eN(e,t,a):a)}catch(e){n(e)}}let e7=["xcodebuild .*AgentDeviceRunnerUITests/RunnerTests/testCommand","xcodebuild .*AgentDeviceRunner\\.env\\.session-","xcodebuild build-for-testing .*ios-runner/AgentDeviceRunner/AgentDeviceRunner\\.xcodeproj"];function e9(e,t,a,r,n,i){let o=n?{terminated:0}:function(){let e=0;try{for(let t of e7){let a=h("pkill",["-f",t],{allowFailure:!0});0===a.exitCode&&(e+=1)}return{terminated:e}}catch(t){return{terminated:e,error:t instanceof Error?t.message:String(t)}}}(),s=!n&&"snapshot"!==r,l=s?function(e,t){let a=!1;try{b(e.pid,e.processStartTime)&&(process.kill(e.pid,"SIGKILL"),a=!0)}catch{eF(e)}finally{eq(t.infoPath),eq(t.lockPath)}return{forcedKill:a}}(e,t):{forcedKill:!1};return g({level:"error",phase:"daemon_request_timeout",data:{timeoutMs:i,requestId:a,command:r,timedOutRunnerPidsTerminated:o.terminated,timedOutRunnerCleanupError:o.error,daemonPidReset:s?e.pid:void 0,daemonPidForceKilled:s?l.forcedKill:void 0,daemonPreservedAfterTimeout:!n&&!s,daemonBaseUrl:e.baseUrl}}),new f("COMMAND_FAILED","Daemon request timed out",{timeoutMs:i,requestId:a,hint:function(e){let{remote:t,resetDaemon:a,command:r}=e;if(t)return"Retry with --debug and verify the remote daemon URL, auth token, and remote host logs.";if(!a){let e=r===ee.snapshot?" If this was the first Apple-platform snapshot on the device, run agent-device prepare ios-runner with the same --platform before snapshot/test so runner startup is handled explicitly.":"";return`Retry with --debug and check daemon diagnostics logs. The timed-out ${r??"request"} request was canceled and Apple runner work was aborted when detected; the daemon was kept alive so the session can still be closed or inspected.${e}`}return"Retry with --debug and check daemon diagnostics logs. Timed-out Apple runner xcodebuild processes were terminated when detected."}({remote:n,resetDaemon:s,command:r})})}let te="Daemon HTTP endpoint is unavailable",tt="Daemon socket endpoint is unavailable";async function ta(e,t){let a=tl(e,t);if(await tr(e,a))return!0;let r=td(e,t,a);return!!r&&await tr(e,r)}async function tr(e,t){var a;return"http"===t?await ti(e).then(e=>e.reachable):await ((a=e.port)?new Promise(e=>{let t=!1,r=c.createConnection({host:"127.0.0.1",port:a},()=>{n(!0)}),n=a=>{t||(t=!0,r.destroy(),e(a))};r.setTimeout(500),r.on("timeout",()=>{n(!1)}),r.on("error",()=>{n(!1)})}):Promise.resolve(!1))}async function tn(e){let t=await ti(e);if(!e.baseUrl||!t.reachable)return t;if("number"==typeof t.rpcProtocolVersion&&1!==t.rpcProtocolVersion)throw new f("COMMAND_FAILED","Remote daemon RPC protocol is incompatible",{daemonBaseUrl:e.baseUrl,clientVersion:et(),remoteVersion:t.version,remoteService:t.service,supportedRpcProtocolVersion:1,remoteRpcProtocolVersion:t.rpcProtocolVersion,hint:"Upgrade agent-device on the client or remote host so both support the same daemon RPC protocol."});return t}function ti(e){let r=e.baseUrl?el(e.baseUrl,"health"):e.httpPort?`http://127.0.0.1:${e.httpPort}/health`:null;if(!r)return Promise.resolve({reachable:!1});let n=new URL(r),i="https:"===n.protocol?a:t,o=e.baseUrl?3e3:500;return new Promise(t=>{let a=e.baseUrl?ec(e.token):{},r=i.request({protocol:n.protocol,host:n.hostname,port:n.port,path:n.pathname+n.search,method:"GET",timeout:o,headers:a},e=>{let a="";e.setEncoding("utf8"),e.on("data",e=>{a+=e}),e.on("end",()=>{let r=e.statusCode??500;t({reachable:r<500,statusCode:r,...function(e){try{let t=JSON.parse(e);return{service:"string"==typeof t.service?t.service:void 0,version:"string"==typeof t.version?t.version:void 0,rpcProtocolVersion:"number"==typeof t.rpcProtocolVersion?t.rpcProtocolVersion:void 0}}catch{return{}}}(a)})})});r.on("timeout",()=>{r.destroy(),t({reachable:!1})}),r.on("error",()=>{t({reachable:!1})}),r.end()})}async function to(e,t,a,r,n){let i=tl(e,a);try{return await ts(e,t,r,n,i)}catch(l){var o;let s=td(e,a,i);if(!s||(o=l,"socket"!==i||!(o instanceof f)||"COMMAND_FAILED"!==o.code||"Failed to communicate with daemon"!==o.message||o.details?.daemonSocketRequestWritten!==!1))throw l;return await ts(e,t,r,n,s)}}async function ts(e,t,a,r,n){return"http"===n?await tp(e,t,a,r):await tf(e,t,a,r)}function tl(e,t){if(e.baseUrl){if("socket"===t)throw new f("COMMAND_FAILED","Remote daemon endpoint only supports HTTP transport",{daemonBaseUrl:e.baseUrl});return"http"}if("http"===t||"socket"===t){var a=e,r=t;if(tc(a,r))return r;throw new f("COMMAND_FAILED","http"===r?te:tt)}let n=("socket"===e.transport||"dual"===e.transport?["socket","http"]:["http","socket"]).find(t=>tc(e,t));if(n)return n;throw new f("COMMAND_FAILED","Daemon metadata has no reachable transport")}function tc(e,t){return"http"===t?!!e.httpPort:!!e.port}function td(e,t,a){if("auto"!==t||e.baseUrl)return null;let r="socket"===a?"http":"socket";return tc(e,r)?r:null}function tu(e,t,a,r={}){return g({level:"error",phase:"daemon_request_socket_error",data:{requestId:t,message:e instanceof Error?e.message:String(e)}}),new f("COMMAND_FAILED","Failed to communicate with daemon",{...r,requestId:t,hint:a?"Retry command. If this persists, verify the remote daemon URL, auth token, and remote host reachability.":"Retry command. If this persists, clean stale daemon metadata and start a fresh session."},e instanceof Error?e:void 0)}async function tf(e,t,a,r){let n=e.port;if(!n)throw new f("COMMAND_FAILED",tt);return new Promise((i,o)=>{let s=!1,l=c.createConnection({host:"127.0.0.1",port:n},()=>{s=!0,l.write(`${JSON.stringify(t)}
|
|
3
|
+
`)}),d=!1,u="number"==typeof r?setTimeout(()=>{d=!0,l.destroy(),o(e9(e,a,t.meta?.requestId,t.command,!1,r))},r):void 0;!function(e,t){let{req:a,isSettled:r,resolve:n,reject:i,clearTimeout:o}=t,s="",l=e5(a),c=(e,t)=>{o(),i(new f("COMMAND_FAILED","Invalid daemon response",{requestId:a.meta?.requestId,line:e},t instanceof Error?t:void 0))};e.setEncoding("utf8"),e.on("data",t=>{if(r())return;let a=A(s,t);for(let t of(s=a.buffer,a.lines))try{let a=JSON.parse(t);if(D(a)){e4(a.event,l);continue}let r=_(a)?a.response:a;o(),n(r),e.end();return}catch(e){c(t,e);return}})}(l,{req:t,isSettled:()=>d,clearTimeout:()=>{u&&clearTimeout(u)},resolve:e=>{d=!0,i(e)},reject:e=>{d=!0,o(e)}}),l.on("error",e=>{d||(d=!0,u&&clearTimeout(u),o(tu(e,t.meta?.requestId,!1,{daemonSocketRequestWritten:s})))})})}async function tp(e,r,n,i){var o,s;let l,c=e.baseUrl?new URL(el(e.baseUrl,"rpc")):e.httpPort?new URL(`http://127.0.0.1:${e.httpPort}/rpc`):null;if(!c)throw new f("COMMAND_FAILED",te);let d=JSON.stringify((o={includeTokenParam:!e.baseUrl},l=r.meta?.requestId??y(),"lease_allocate"!==(s=r.command)&&"lease_heartbeat"!==s&&"lease_release"!==s?{jsonrpc:"2.0",id:l,method:"agent_device.command",params:r}:{jsonrpc:"2.0",id:l,method:function(e){switch(e){case"lease_allocate":return"agent_device.lease.allocate";case"lease_heartbeat":return"agent_device.lease.heartbeat";case"lease_release":return"agent_device.lease.release"}}(r.command),params:function(e,t,a){let r={...a.includeTokenParam?{token:e.token}:{},session:e.session,tenantId:e.meta?.tenantId,runId:e.meta?.runId};switch(t){case"lease_allocate":return{...r,ttlMs:e.meta?.leaseTtlMs,backend:e.meta?.leaseBackend};case"lease_heartbeat":return{...r,leaseId:e.meta?.leaseId,ttlMs:e.meta?.leaseTtlMs};case"lease_release":return{...r,leaseId:e.meta?.leaseId}}}(r,r.command,o)})),u={"content-type":"application/json","content-length":Buffer.byteLength(d)};return e.baseUrl&&Object.assign(u,ec(e.token)),await new Promise((o,s)=>{let l=("https:"===c.protocol?a:t).request({protocol:c.protocol,host:c.hostname,port:c.port,method:"POST",path:c.pathname+c.search,headers:u},t=>{var a;(a=t.headers?.["content-type"],M(r)&&String(Array.isArray(a)?a.join(","):a??"").includes("application/x-ndjson"))?function(e,t){let{req:a,handleResponseBody:r,reject:n,clearTimeout:i}=t,o="",s=!1,l=e5(a),c=e=>{try{let t=JSON.parse(e);if(D(t))return e4(t.event,l),!1;if(_(t))return s=!0,i(),r(JSON.stringify(t.response)),!0;throw Error("Missing daemon progress response envelope")}catch(t){return s=!0,i(),n(new f("COMMAND_FAILED","Invalid daemon response",{requestId:a.meta?.requestId,line:e},t instanceof Error?t:void 0)),!0}};e.setEncoding("utf8"),e.on("data",e=>{if(s)return;let t=A(o,e);for(let e of(o=t.buffer,t.lines))if(e&&c(e))return}),e.on("end",()=>{if(s)return;let e=o.trim();e&&c(e)||(s=!0,i(),n(new f("COMMAND_FAILED","Invalid daemon response",{requestId:a.meta?.requestId,line:e})))}),e.on("error",e=>{s||(s=!0,i(),n(new f("COMMAND_FAILED","Failed to read daemon response",{requestId:a.meta?.requestId},e instanceof Error?e:void 0)))})}(t,{req:r,reject:s,clearTimeout:()=>{m&&clearTimeout(m)},handleResponseBody:t=>e8(t,{info:e,req:r,resolve:o,reject:s})}):ed(t).then(t=>{m&&clearTimeout(m),e8(t,{info:e,req:r,resolve:o,reject:s})}).catch(e=>{m&&clearTimeout(m),s(new f("COMMAND_FAILED","Failed to read daemon response",{requestId:r.meta?.requestId},e instanceof Error?e:void 0))})}),p=eB(e),m="number"==typeof i?setTimeout(()=>{l.destroy(),s(e9(e,n,r.meta?.requestId,r.command,p,i))},i):void 0;l.on("error",e=>{m&&clearTimeout(m),s(tu(e,r.meta?.requestId,p))}),l.write(d),l.end()})}let tm=new c.BlockList;function th(t){var a,n,o,s,l;let d,u,p,m=(a=t,a.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR),h=(n=t,u=function(e){let t;if(e){try{t=new URL(e)}catch(t){throw new f("INVALID_ARGS","Invalid daemon base URL",{daemonBaseUrl:e},t instanceof Error?t:void 0)}if("http:"!==t.protocol&&"https:"!==t.protocol)throw new f("INVALID_ARGS","Daemon base URL must use http or https",{daemonBaseUrl:e});return t.toString().replace(/\/+$/,"")}}(d=n.flags?.daemonBaseUrl??process.env.AGENT_DEVICE_DAEMON_BASE_URL),function(e,t){let a;if(!(!e||"localhost"===(a=new URL(e).hostname.trim().toLowerCase().replace(/^\[(.*)\]$/,"$1"))||(c.isIPv4(a)?tm.check(a,"ipv4"):!!c.isIPv6(a)&&tm.check(a,"ipv6")))&&("string"!=typeof t||!(t.trim().length>0)))throw new f("INVALID_ARGS","Remote daemon base URL for non-loopback hosts requires daemon authentication",{daemonBaseUrl:e,hint:"Provide --daemon-auth-token or AGENT_DEVICE_DAEMON_AUTH_TOKEN when using a non-loopback remote daemon URL."})}(u,p=n.flags?.daemonAuthToken??process.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN),{rawBaseUrl:d,remoteBaseUrl:u,authToken:p}),y=function(e,t){let a=e.flags?.daemonTransport??process.env.AGENT_DEVICE_DAEMON_TRANSPORT,r=N(a);if(t&&"socket"===r)throw new f("INVALID_ARGS","Remote daemon base URL only supports HTTP transport. Remove --daemon-transport socket.",{daemonBaseUrl:t});return{preference:r,serverMode:k(e.flags?.daemonServerMode??process.env.AGENT_DEVICE_DAEMON_SERVER_MODE??("dual"===a?"dual":void 0))}}(t,h.remoteBaseUrl),w=(o=t,s=m,l=h.rawBaseUrl,tA(o.command)&&!s&&!l);return{paths:P(w?e.mkdtempSync(r.join(i.tmpdir(),"agent-device-replay-daemon-")):m),transportPreference:y.preference,serverMode:y.serverMode,ownedStateDir:w,remoteBaseUrl:h.remoteBaseUrl,remoteAuthToken:h.authToken}}async function ty(e){if(e.remoteBaseUrl)return await tw(e);let t=await tg(e);return t?{info:t,startedByClient:!1}:(!function(e){let t=eO(e);if(!t.hasLock||t.hasInfo)return;let a=eU(e.lockPath);if(!a)return eq(e.lockPath);b(a.pid,a.processStartTime)||eq(e.lockPath)}(e.paths),await tv(e))}async function tw(e){let t={transport:"http",token:e.remoteAuthToken??"",pid:0,baseUrl:e.remoteBaseUrl};if((await tn(t)).reachable)return{info:t,startedByClient:!1};throw new f("COMMAND_FAILED","Remote daemon is unavailable",{daemonBaseUrl:e.remoteBaseUrl,hint:"Verify AGENT_DEVICE_DAEMON_BASE_URL points to a reachable daemon with GET /health and POST /rpc."})}async function tg(e){var t,a;let r=e$(e.paths.infoPath);if(!r)return null;let n=await tb(r,e.transportPreference);return(t=r,a=n,t.version===et()&&t.codeSignature===t_()&&a)?r:(function(e,t,a){try{var r,n;let i=e.version?`pid ${e.pid}, v${e.version}`:`pid ${e.pid}`,o=(r=e,n=t,r.version!==et()?`version mismatch (client v${et()})`:r.codeSignature!==t_()?"code-signature mismatch":n?"not reusable":"unreachable");process.stderr.write(`Replacing daemon (${i}) in ${a}: ${o}
|
|
4
|
+
`)}catch{}}(r,n,e.paths.baseDir),await eF(r),eq(e.paths.infoPath),null)}async function tb(e,t){try{return await ta(e,t)}catch(e){var a;if((a=e)instanceof f&&"COMMAND_FAILED"===a.code&&(a.message===te||a.message===tt))return!1;throw e}}async function tv(t){let a,r,n=0,i=[];for(let o=1;o<=2;o+=1){let s;try{r={pid:(s=function(t){let a=tM(),r=a.useSrc?["--experimental-strip-types",a.srcPath]:[a.distPath],n={...process.env,AGENT_DEVICE_STATE_DIR:t.paths.baseDir,AGENT_DEVICE_DAEMON_SERVER_MODE:t.serverMode};e.mkdirSync(t.paths.baseDir,{recursive:!0});let i=e.openSync(t.paths.logPath,"a"),o=e.openSync(t.paths.logPath,"a");try{return p(process.execPath,r,{env:n,stdio:["ignore",i,o]})}finally{e.closeSync(i),e.closeSync(o)}}(t)).pid}}catch(e){if(a=e instanceof Error?e.message:String(e),i.push(await eL(t.paths,"start_error")),o<2){await er(150);continue}break}let l=await tS(15e3,t,s);if("ready"===l.kind)return{info:l.info,startedByClient:!0};if("early_exit"===l.kind){if(r=l.exit,a=tD(l.exit),i.push(await eL(t.paths,"start_error")),o<2){await er(150);continue}break}if(await eR(t.paths)){n+=1;continue}let c=eO(t.paths),d=o<2,u=await eL(t.paths,"startup_timeout",{stopLiveProcesses:!1});if(i.push(u),u.retainedInfoProcess||u.retainedLockProcess){let e=await tS(15e3,t,s);if("ready"===e.kind)return{info:e.info,startedByClient:!0};"early_exit"===e.kind&&(r=e.exit,a=tD(e.exit));break}if(!d)break;c.hasInfo||c.hasLock||await er(150)}let o=eO(t.paths),s=function(t){try{if(!e.existsSync(t))return;let a=e.statSync(t);if(a.size<=0)return;let r=Math.min(a.size,64e3),n=e.openSync(t,"r");try{let t=Buffer.alloc(r);e.readSync(n,t,0,r,a.size-r);let i=t.toString("utf8").trim();return i.length>0?i:void 0}finally{e.closeSync(n)}}catch{return}}(t.paths.logPath);throw new f("COMMAND_FAILED","Failed to start daemon",{kind:"daemon_startup_failed",stateDir:t.paths.baseDir,infoPath:t.paths.infoPath,lockPath:t.paths.lockPath,logPath:t.paths.logPath,startupTimeoutMs:15e3,startupAttempts:2,lockRecoveryCount:n,cleanupResults:i,startError:a,daemonProcess:r,...s?{daemonLogTail:s}:{},metadataState:o,hint:function(e,t=P(process.env.AGENT_DEVICE_STATE_DIR)){var a;let r=(a=t,`rm -f ${S(a.infoPath)} ${S(a.lockPath)}`);return e.hasLock&&!e.hasInfo?`agent-device attempted to clean stale daemon metadata automatically, but ${t.lockPath} still exists without ${t.infoPath}. Retry with --debug; if this persists after confirming no agent-device daemon process is running, run: ${r}`:e.hasLock&&e.hasInfo?`agent-device attempted to clean stale daemon metadata automatically, but ${t.infoPath} and ${t.lockPath} still remain. Retry with --debug; if this persists after confirming no agent-device daemon process is running, run: ${r}`:e.hasInfo?`agent-device did not observe reachable daemon metadata after retrying, and ${t.infoPath} still remains. Stale metadata was cleaned automatically when safe; retry with --debug. If this persists after confirming no agent-device daemon process is running, run: ${r}`:`agent-device did not observe reachable daemon metadata after retrying. Stale metadata was cleaned automatically when safe; retry with --debug and check daemon diagnostics logs. If stale metadata returns after confirming no agent-device daemon process is running, run: ${r}`}(o,t.paths)})}async function tI(t,a,r){if(!tA(t.command)||!a.startedByClient&&!r.ownedStateDir||eB(a.info))return;let n={pid:a.info.pid,removedInfo:!1,removedLock:!1,removedStateDir:!1,error:void 0};try{await eF(a.info)}catch(e){n.error=e instanceof Error?e.message:String(e)}finally{let t=e.existsSync(r.paths.infoPath);eq(r.paths.infoPath),n.removedInfo=t&&!e.existsSync(r.paths.infoPath);let a=e.existsSync(r.paths.lockPath);eq(r.paths.lockPath),n.removedLock=a&&!e.existsSync(r.paths.lockPath),r.ownedStateDir&&(e.rmSync(r.paths.baseDir,{recursive:!0,force:!0}),n.removedStateDir=!e.existsSync(r.paths.baseDir))}g({level:n.error?"warn":"info",phase:"daemon_replay_cleanup",data:n})}function tA(e){return e===ee.replay||e===ee.test}async function tS(e,t,a){let r,n=Date.now();for(a.exited.then(e=>{r=e});Date.now()-n<e;){if(r)return{kind:"early_exit",exit:r};let e=e$(t.paths.infoPath);if(e&&await ta(e,t.transportPreference))return{kind:"ready",info:e};if(r)return{kind:"early_exit",exit:r};await er(100)}return{kind:"timeout"}}function tM(){let t=ea(),a=[r.join(t,"dist","src","internal","daemon.js"),r.join(t,"dist","src","daemon.js")],n=a[0];if(void 0===n)throw new f("COMMAND_FAILED","Daemon dist path list is empty");let i=a.find(t=>e.existsSync(t))??n,o=r.join(t,"src","daemon.ts"),s=a.some(t=>e.existsSync(t)),l=e.existsSync(o);if(!s&&!l)throw new f("COMMAND_FAILED","Daemon entry not found",{distPaths:a,srcPath:o});return{root:t,distPath:i,distPaths:a,srcPath:o,useSrc:process.execArgv.includes("--experimental-strip-types")?l:!s&&l}}function t_(){let e=tM();return E(e.useSrc?e.srcPath:e.distPath,e.root)}function tD(e){return e.error?`daemon process ${e.pid} failed to start: ${e.error}`:e.signal?`daemon process ${e.pid} exited before readiness with signal ${e.signal}`:`daemon process ${e.pid} exited before readiness with code ${e.exitCode??0}`}async function tP(e){let t=e.meta?.requestId??y(),a=!!(e.meta?.debug||e.flags?.verbose),r=th(e),n=function(e){if(e.command!==ee.test){var t;return"number"==typeof e.flags?.timeoutMs&&((t=e.command)===ee.prepare||t===ee.replay||t===ee.snapshot)?e.flags.timeoutMs:e.command===ee.prepare?24e4:9e4}}(e),i=await w("daemon_startup",async()=>await ty(r),{requestId:t,session:e.session}),o=i.info,s=await eM(e,o),l={...e,positionals:s.positionals,flags:s.flags,token:o.token,meta:{...e.meta??{},requestId:t,debug:a,cwd:e.meta?.cwd,sessionExplicit:e.meta?.sessionExplicit,tenantId:e.meta?.tenantId??e.flags?.tenant,runId:e.meta?.runId??e.flags?.runId,leaseId:e.meta?.leaseId??e.flags?.leaseId,sessionIsolation:e.meta?.sessionIsolation??e.flags?.sessionIsolation,lockPolicy:e.meta?.lockPolicy,lockPlatform:e.meta?.lockPlatform,...s.uploadedArtifactId?{uploadedArtifactId:s.uploadedArtifactId}:{},...s.clientArtifactPaths?{clientArtifactPaths:s.clientArtifactPaths}:{},...s.installSource?{installSource:s.installSource}:{}}};g({level:"info",phase:"daemon_request_prepare",data:{requestId:t,command:e.command,session:e.session}});try{return await w("daemon_request",async()=>await to(o,l,r.transportPreference,r.paths,n),{requestId:t,command:e.command})}finally{await tI(e,i,r)}}tm.addSubnet("127.0.0.0",8,"ipv4"),tm.addAddress("::1","ipv6"),tm.addSubnet("::ffff:127.0.0.0",104,"ipv6");let tk=/^[0-9a-fA-F-]{32,36}$/;function tE(e){if(e&&tk.test(e))return e.replaceAll("-","").toUpperCase()}function tN(e,t){return`${e.uuid}:${tx(t)}`}function tx(e){return`0x${e.toString(16)}`}function t$(e){return"string"==typeof e&&e.length>0?e:void 0}function tT(...e){for(let t of e){let e=t$(t);if(e)return e}}function tC(e){return"object"==typeof e&&null!==e}function tU(e){return tC(e)?e:void 0}function tL(e){try{let t=JSON.parse(e);return tC(t)?t:null}catch{return null}}function tO(e){if("number"==typeof e&&Number.isSafeInteger(e))return e;if("string"==typeof e){let t=e.startsWith("0x")?Number.parseInt(e,16):Number(e);return Number.isSafeInteger(t)?t:void 0}}function tR(e,t,a){var r;if(!Object.hasOwn(e,t))return;let n="bigint"==typeof(r=e[t])?r:"number"==typeof r&&Number.isSafeInteger(r)?BigInt(r):"string"!=typeof r?void 0:/^(?:0x[0-9a-fA-F]+|\d+)$/.test(r)?BigInt(r):void 0;if(void 0!==n)return n;tF(a,t)}function tF(e,t){throw new f("INVALID_ARGS",`Invalid ${e} numeric field: ${t}`,{hint:"Crash artifact numeric fields must be integer numbers or integer numeric strings."})}function tB(e){return[...new Set(e)]}let tj=/^(?:arm64e?|arm64_32|x86_64|armv7[sk]?|i386)$/;async function tq(e){return e.dsym&&e.searchPath?[tY(e.cwd,e.dsym),...await tV(tY(e.cwd,e.searchPath))]:e.dsym?[tY(e.cwd,e.dsym)]:e.searchPath?await tV(tY(e.cwd,e.searchPath)):[]}async function tV(e){let t=[],a=0;async function n(i){if(!(t.length>=200)){if((a+=1)>1e4)throw new f("COMMAND_FAILED","debug symbols search-path scan exceeded bounds.",{searchPath:e,maxEntries:1e4,hint:"Pass --dsym <App.dSYM> directly or narrow --search-path to the build products directory."});if(!(await tH(i,e)).isDirectory()){i===e&&function(e){throw new f("INVALID_ARGS",`debug symbols search path is not a directory: ${e}`,{hint:"Pass an existing build products directory to --search-path, or pass --dsym <App.dSYM> directly."})}(e);return}if(i.endsWith(".dSYM"))return void t.push(i);for(let e of(await d.readdir(i,{withFileTypes:!0})))e.isDirectory()&&await n(r.join(i,e.name))}}return await n(e),t}async function tH(e,t){try{return await d.stat(e)}catch{throw new f("INVALID_ARGS",`debug symbols search path does not exist: ${t}`,{hint:"Pass an existing build products directory to --search-path, or pass --dsym <App.dSYM> directly."})}}async function tG(e,t){let a=(await Promise.all(tB(e).map(e=>tK(e,t)))).flat();if(0===a.length)throw new f("COMMAND_FAILED","No UUIDs found in dSYM bundle.",{hint:"Verify the path points to a built .dSYM bundle with DWARF contents."});return a}async function tK(e,t){var a;await tz(e);let r=await m(t,["--uuid",e],{timeoutMs:15e3,allowFailure:!0});if(0!==r.exitCode)throw new f("COMMAND_FAILED",`Failed to inspect dSYM UUIDs: ${e}`,{stderr:r.stderr,hint:"Verify the dSYM bundle is valid and readable."});return a=e,r.stdout.split("\n").flatMap(e=>{let t=e.match(/^UUID:\s+([0-9a-fA-F-]{32,36})\s+\(([^)]+)\)\s+(.+)$/),r=tE(t?.[1]);return t&&r?[{dsymPath:a,uuid:r,arch:t[2],binaryPath:t[3].trim()}]:[]})}async function tz(e){let t=await d.stat(e).catch(()=>null);if(!(t?.isDirectory()&&e.endsWith(".dSYM")))throw new f("INVALID_ARGS",`Not a .dSYM bundle: ${e}`,{hint:"Pass the .dSYM bundle path, not the DWARF executable inside it."})}function tY(e,t){return r.resolve(e,t)}function tW(e,t){let a=`${t}:`,r=e.find(e=>e.trimStart().startsWith(a));return r&&r.slice(r.indexOf(":")+1).trim()||void 0}function tJ(e,t,a,r){return{index:e,image:t.name,address:tx(a),symbol:r.get(tN(t,a))?.text}}function tX(e){var t;let a;return[(a=(t=e).topFrames.find(e=>e.symbol))?`Start with ${a.symbol} in ${a.image}; it is the first symbolicated frame captured on the crashed thread.`:t.topFrames.length>0?"No symbolicated frame was found on the crashed thread; verify matching dSYMs for the top images.":void 0,e.exceptionType?`Exception: ${e.exceptionType}`:void 0,e.terminationReason?`Termination: ${e.terminationReason}`:void 0].filter(e=>!!e).slice(0,3)}async function tQ(e,t,a){let r=new Map;for(let n of(function(e,t){let a=new Map;for(let r of e){let e=t.get(r.image.uuid);if(!e)continue;let n=`${r.image.uuid}:${e.dsym.binaryPath}`,i=a.get(n)??{...e,addresses:[]};i.addresses.push(r.address),a.set(n,i)}return a})(e,t).values())for(let e of(await tZ(a,n)))r.set(tN(e.image,e.address),e);return r}async function tZ(e,t){var a,r,n,i;let o,s,l=tB(t.addresses.map(tx)),c=await m(e,(a=t,r=l,["-arch",a.image.arch??a.dsym.arch??"arm64","-o",a.dsym.binaryPath,"-l",tx(a.image.base),...r]),{timeoutMs:3e4,allowFailure:!0});return 0!==c.exitCode&&function(e){throw new f("COMMAND_FAILED","atos failed while symbolicating crash frames.",{stderr:e,hint:"Verify the crash artifact and dSYM were produced from the same build and architecture."})}(c.stderr),n=t.image,i=l,s=(""===(o=c.stdout.split(/\r?\n/)).at(-1)&&o.pop(),o),i.map((e,t)=>{let a=s[t]?.trim();return{image:n,address:BigInt(e),text:!function(e,t){if(!e)return!1;let a=e.trim().toLowerCase();return!!a&&"??"!==a&&a!==t.toLowerCase()&&!a.startsWith("0x")}(a,e)?void 0:a}})}async function t0(){return{dwarfdump:await t1("dwarfdump"),atos:await t1("atos")}}async function t1(e){try{let t=await m("xcrun",["--find",e],{timeoutMs:5e3,allowFailure:!0}),a=t.stdout.trim();if(0===t.exitCode&&a.length>0)return a}catch{}throw new f("TOOL_MISSING",`Apple symbolication tool not found: ${e}`,{hint:"Install Xcode Command Line Tools and verify xcrun --find dwarfdump and xcrun --find atos succeed."})}async function t3(e){var t,a,n,i,o,s,l,c,u,p,m,h,y,w,g,b,v,I,A,S,M,_,D,P,k,E,N;let x,$,T,C,U,L,O,R,F;if(void 0!==e.action&&"symbols"!==e.action)throw new f("INVALID_ARGS","debug supports only the symbols workflow.",{hint:"Use debug symbols --artifact <crash.ips|crash.log> --dsym <App.dSYM> or --search-path <dir> --out <path>."});let B=e.cwd??process.cwd(),j=t4(B,e.artifact),q=t4(B,e.out??(a=j,$=(x=r.extname(a))?a.slice(0,-x.length):a,`${$}-symbolicated${x||".log"}`)),V=function(e){var t;let a,n=function(e){let t=tL(e);if(t)return{payload:t};let a=e.indexOf("\n");if(-1===a)return null;let r=e.slice(0,a),n=tL(e.slice(a+1));return n?{header:r,payload:n}:null}(e);if(!n)return null;let i=(Array.isArray(n.payload.usedImages)?n.payload.usedImages:[]).flatMap((e,t)=>(function(e,t){if(!e||"object"!=typeof e)return[];let a=tE(t$(e.uuid)),n=tR(e,"base","IPS usedImages");if(!a||void 0===n)return[];let i=t$(e.path);return[{index:t,name:t$(e.name)??(i?r.basename(i):`image-${t}`),uuid:a,arch:t$(e.arch),base:n,path:i}]})(e,t));if(0===i.length)return null;let o=(t=Array.isArray(n.payload.threads)?n.payload.threads:[],a=new Map(i.map(e=>[e.index,e])),t.flatMap((e,t)=>(function(e){if(!e||"object"!=typeof e)return[];let t=e.frames;return Array.isArray(t)?t.filter(e=>tC(e)):[]})(e).flatMap((e,r)=>(function(e,t,a,r){let n=function(e,t,a){if(!Object.hasOwn(e,t))return;let r=tO(e[t]);if(void 0!==r)return r;tF(a,t)}(e,"imageIndex","IPS frame"),i=tR(e,"imageOffset","IPS frame");if(void 0===n||void 0===i)return[];let o=t.get(n);return o?[{frame:e,frameIndex:r,threadIndex:a,image:o,address:o.base+i}]:[]})(e,a,t,r))));return{format:"ips",images:i,addresses:o.map(({frame:e,...t})=>t),document:n,frameMatches:o,write:e=>(function(e,t,a){for(let e of t){let t=a.get(tN(e.image,e.address))?.text;t&&function(e,t){let a,r=(a=t.match(/^(.*) \+ (\d+)$/))?{symbol:a[1],location:Number(a[2])}:{symbol:t};e.symbol=r.symbol,void 0!==r.location&&(e.symbolLocation=r.location)}(e.frame,t)}e.payload.agentDeviceSymbolication={tool:"agent-device debug symbols",symbolicatedFrames:[...a.values()].filter(e=>e.text).length};let r=`${JSON.stringify(e.payload,null,2)}
|
|
5
5
|
`;return e.header?`${e.header}
|
|
6
|
-
${r}`:r})(n,o,e)}}(t=await t4(j,"crash artifact"))??function(e){let t=e.split("\n"),a=function(e){let t=[],a=e.findIndex(e=>/^Binary Images:/i.test(e.trim()));if(-1===a)return t;for(let n of e.slice(a+1)){let e=function(e){let t=e.match(/^\s*(0x[0-9a-fA-F]+)\s*-\s*(0x[0-9a-fA-F]+)\s+\+?(.+?)\s+<([0-9a-fA-F-]{32,36})>\s+(.+)$/);if(!t)return null;let a=tN(t[4]);if(!a)return null;let n=function(e,t){let a=e.split(/\s+/),n=a.at(-1);if(n&&tV.test(n))return{name:a.slice(0,-1).join(" ").trim(),arch:n};let i=r.basename(t);return{name:e.startsWith(i)?i:e}}(t[3].trim(),t[5].trim());return{name:n.name,arch:n.arch,uuid:a,base:BigInt(t[1]),end:BigInt(t[2]),path:t[5].trim()}}(n);e&&t.push(e)}return t}(t);if(0===a.length)return null;let n=function(e,t){let a,r=[];for(let[n,i]of e.entries()){let e=i.match(/^Thread\s+(\d+)\s+Crashed:/);e?a=Number(e[1]):(0===i.trim().length||/^Thread\s+\d+/.test(i))&&(a=void 0);let o=function(e,t){let a=e.match(/^\s*\d+\s+(.+?)\s+(0x[0-9a-fA-F]+)\b/);if(!a)return null;let r=a[1].trim(),n=BigInt(a[2]),i=function(e,t,a){let r=e.filter(e=>e.name===t);return r.find(e=>{var t,r;return t=e,r=a,void 0!==t.end&&t.base<=r&&r<=t.end})??(1===r.length?r[0]:void 0)}(t,r,n);return i?{image:i,address:n}:null}(i,t),s=i.match(/^\s*(\d+)/);o&&s&&r.push({...o,frameIndex:Number(s[1]),lineIndex:n,threadIndex:a})}return r}(t,a);return{format:"text",images:a,addresses:n,lines:t,frameMatches:n,write(e){let a=new Map(n.map(e=>[e.lineIndex,e]));return t.map((t,r)=>{let n=a.get(r);if(!n)return t;let i=e.get(t$(n.image,n.address))?.text;return!i||t.includes(i)?t:`${t} // ${i}`}).join("\n")}}}(t);V||function(){throw new f("UNSUPPORTED_OPERATION","debug symbols currently supports Apple crash artifacts with Binary Images or IPS usedImages.",{hint:"For Android Java/R8 crashes, use retrace with mapping.txt. For Android native crashes, use ndk-stack or addr2line with unstripped .so symbols. Capture the crash with logs, then symbolicate externally until Android support is added."})}();let K=await tK({cwd:B,dsym:e.dsym,searchPath:e.searchPath});if(0===K.length)throw new f("INVALID_ARGS","debug symbols requires --dsym or --search-path.",{hint:"Pass a matching .dSYM bundle directly, or pass --search-path <dir> so agent-device can match crash image UUIDs to local dSYMs."});let G=await t3(),H=await tz(K,G.dwarfdump),z=function(e,t,a){let r=new Map;for(let a of e){let e=t.find(e=>e.uuid===a.uuid&&(void 0===a.arch||void 0===e.arch||e.arch===a.arch));e&&r.set(a.uuid,{image:a,dsym:e})}if(r.size>0)return r;let n=tq(e.map(e=>e.uuid)),i=tq(t.map(e=>e.uuid));throw new f("COMMAND_FAILED",a?"dSYM UUID does not match any Apple image in the crash artifact.":"No matching dSYM UUID found under search path.",{artifactUuidCount:n.length,artifactUuidSample:n.slice(0,5),dsymUuidCount:i.length,dsymUuidSample:i.slice(0,5),hint:"Use dwarfdump --uuid <App.dSYM> and compare it with the crash Binary Images or usedImages UUID, then pass the matching dSYM/search path."})}(V.images,H,!!e.dsym),Y=await t0(V.addresses,z,G.atos),W=V.write(Y);await d.mkdir(r.dirname(q),{recursive:!0}),await d.writeFile(q,W,"utf8");let J=[...z.values()].map(({image:e,dsym:t})=>({name:e.name,uuid:e.uuid,arch:e.arch??t.arch,dsymPath:t.dsymPath,binaryPath:t.binaryPath})),X=[...Y.values()].filter(e=>e.text).length,Q=V.images.length-J.length,Z=Q>0?[`${Q} Apple image${1===Q?"":"s"} had no matching dSYM and were left unchanged.`]:void 0;return{kind:"debugSymbols",platform:"apple",artifactPath:j,outPath:q,crash:"ips"===V.format?(n=V.document,i=V.frameMatches,o=Y,U=function(e){let t=tF(e.faultingThread);if(void 0!==t)return t;let a=(Array.isArray(e.threads)?e.threads:[]).findIndex(e=>tR(e)?.triggered===!0);return -1===a?void 0:a}(n.payload),{...L={format:"ips",...(T=(s=n).payload,C=(l=s.header)?tO(l):null,{appName:(c=T,u=C,tU(c.procName,u?.app_name,u?.name)),bundleId:(p=T,m=C,tU(tR(p.bundleInfo)?.CFBundleIdentifier,m?.bundleID)),version:(h=T,y=C,tU(tR(h.bundleInfo)?.CFBundleShortVersionString,y?.app_version)),incident:(w=T,g=C,tU(w.incident,g?.incident_id)),timestamp:(v=T,b=C,tU(v.captureTime,b?.timestamp)),exceptionType:(I=T.exception,tC(tR(I)?.type)),exceptionCodes:function(e){let t=tR(e);if(t)return tU(t.codes,t.rawCodes)}(T.exception),terminationReason:function(e){let t=tR(e);if(t){let e;return(e=[tC(t.namespace),tC(t.code),tC(t.reason)].filter(e=>!!e)).length>0?e.join(" "):void 0}}(T.termination)}),crashedThread:U,topFrames:(A=i,S=U,M=o,A.filter(e=>void 0===S||e.threadIndex===S).slice(0,5).map(e=>tQ(e.frameIndex,e.image,e.address,M))),findings:[]},findings:tZ(L)}):(_=V.lines,P=V.frameMatches,D=Y,O=function(e){let t=tX(e,"Triggered by Thread"),a=t?Number.parseInt(t,10):NaN;if(Number.isSafeInteger(a))return a;for(let t of e){let e=t.match(/^Thread\s+(\d+)\s+Crashed:/);if(e)return Number(e[1])}}(_),{...F={format:"text",appName:(R=tX(_,"Process"),R?.replace(/\s+\[\d+\]$/,"")),bundleId:tX(_,"Identifier"),version:tX(_,"Version"),incident:tX(_,"Incident Identifier"),timestamp:tX(_,"Date/Time"),exceptionType:tX(_,"Exception Type"),exceptionCodes:tX(_,"Exception Codes"),terminationReason:tX(_,"Termination Reason"),crashedThread:O,topFrames:(k=P,x=O,E=D,void 0===x?[]:k.filter(e=>e.threadIndex===x).slice(0,5).map(e=>tQ(e.frameIndex,e.image,e.address,E))),findings:[]},findings:tZ(F)}),matchedImages:J,symbolicatedFrames:X,skippedImages:Q,warnings:Z,message:`Symbolicated ${X} frame${1===X?"":"s"} -> ${q}`}}async function t4(e,t){await t6(e,t);try{return await d.readFile(e,"utf8")}catch(a){throw new f("INVALID_ARGS",`Failed to read ${t}: ${e}`,{message:a instanceof Error?a.message:String(a)})}}async function t6(e,t){try{let a=await d.stat(e);if(a.size<=0x4000000)return;throw new f("INVALID_ARGS",`${t} is too large: ${e}`,{actualBytes:a.size,maxBytes:0x4000000,hint:"Pass a bounded Apple .ips/.crash artifact. For very large logs, first narrow the log to the crash report, or use logs grep/tail for lead-up context."})}catch(a){if(a instanceof f)throw a;throw new f("INVALID_ARGS",`Failed to read ${t}: ${e}`,{message:a instanceof Error?a.message:String(a)})}}function t8(e,t){return r.resolve(e,t)}let t7={...G,...et,...ee,...er,...en,...H,...ea,...Z,...el,...Y,...J,batch:ei(function(e,t){let a=t7[e];if(!a)throw Error(`Missing daemon writer for batch command: ${e}`);return a(t)})};function t9(e={},t={}){let a=t.transport??tx,r=async(t,r=[],n={})=>{let i=at(e,n),o=await a({session:X(i.session),command:t,positionals:r,flags:Q(i),runtime:i.runtime,meta:W(i)});return o.ok||function(e){throw new f(u(e.code),e.message,{...e.details??{},hint:e.hint,diagnosticId:e.diagnosticId,logPath:e.logPath})}(o.error),o.data??{}},n=async(e={})=>{let t=await r(T.sessionList,[],e);return(Array.isArray(t.sessions)?t.sessions:[]).map(O)},i=async(e,t={})=>{let a=t7[e](t);return await r(a.command,a.positionals,a.options)},o=(t={})=>X(at(e,t).session);return{command:{wait:async e=>await i("wait",e),alert:async(e={})=>await i("alert",e),appState:async(e={})=>await i("appstate",e),back:async(e={})=>await i("back",e),home:async(e={})=>await i("home",e),rotate:async e=>await i("rotate",e),appSwitcher:async(e={})=>await i("app-switcher",e),keyboard:async(e={})=>await i("keyboard",e),clipboard:async e=>await i("clipboard",e),reactNative:async e=>await i("react-native",e),prepare:async e=>await i("prepare",e)},devices:{list:async(e={})=>{let t=await i("devices",e);return(Array.isArray(t.devices)?t.devices:[]).map(es)},boot:async(e={})=>await i("boot",e),shutdown:async(e={})=>await i("shutdown",e)},sessions:{list:async(e={})=>await n(e),stateDir:async(t={})=>D(at(e,t).stateDir??process.env.AGENT_DEVICE_STATE_DIR).baseDir,close:async(e={})=>{let t=o(e),a=(await i("close",e)).shutdown;return{session:t,shutdown:"object"==typeof a&&null!==a?a:void 0,identifiers:{session:t}}}},apps:{install:async e=>K(await i("install",e),o(e)),reinstall:async e=>K(await i("reinstall",e),o(e)),installFromSource:async e=>eu(await i("install-from-source",e),o(e)),list:async(e={})=>{let t=await i("apps",e);return Array.isArray(t.apps)?t.apps.filter(e=>"string"==typeof e):[]},open:async e=>{let t=o(e),a=await i("open",e),r=z(a),n=j(a,"appBundleId");return{session:t,sessionStateDir:j(a,"sessionStateDir"),appName:j(a,"appName"),appBundleId:n,appId:n,startup:ed(a.startup),runtime:eo(a.runtime),device:r,identifiers:{session:t,deviceId:r?.id,deviceName:r?.name,udid:r?.ios?.udid,serial:r?.android?.serial,appId:n,appBundleId:n}}},close:async(e={})=>{let t=o(e),a=(await i("close",e)).shutdown;return{session:t,closedApp:e.app,shutdown:"object"==typeof a&&null!==a?a:void 0,identifiers:{session:t}}},push:async e=>await i("push",e),triggerEvent:async e=>await i("trigger-app-event",e)},materializations:{release:async e=>q(await r(T.releaseMaterializedPaths,[],{...e,materializationId:e.materializationId}))},leases:{allocate:async e=>aa(await r(T.leaseAllocate,[],{...e,leaseId:void 0,leaseTtlMs:e.ttlMs})),heartbeat:async e=>aa(await r(T.leaseHeartbeat,[],{...e,leaseTtlMs:e.ttlMs})),release:async e=>({released:!0===(await r(T.leaseRelease,[],e)).released})},metro:{prepare:async t=>await ep({projectRoot:t.projectRoot??e.cwd,kind:t.kind,publicBaseUrl:t.publicBaseUrl,proxyBaseUrl:t.proxyBaseUrl,proxyBearerToken:t.bearerToken,bridgeScope:t.bridgeScope,launchUrl:t.launchUrl,companionProfileKey:t.companionProfileKey,companionConsumerKey:t.companionConsumerKey,metroPort:t.port,listenHost:t.listenHost,statusHost:t.statusHost,startupTimeoutMs:t.startupTimeoutMs,probeTimeoutMs:t.probeTimeoutMs,reuseExisting:t.reuseExisting,installDependenciesIfNeeded:t.installDependenciesIfNeeded,runtimeFilePath:t.runtimeFilePath,logPath:t.logPath}),reload:async(t={})=>await ef({metroHost:t.metroHost,metroPort:t.metroPort,bundleUrl:t.bundleUrl,runtime:e.runtime,timeoutMs:t.timeoutMs})},capture:{snapshot:async(e={})=>{var t,a,r;let n,s,l,c,d=o(e);return t=await i("snapshot",e),a=d,n=j(t,"appBundleId"),{nodes:V(t.nodes),truncated:!0===t.truncated,appName:j(t,"appName"),appBundleId:n,...(s=ae((r=t).visibility),l=ae(r.unchanged),c=I(r.snapshotDiagnostics),{...s?{visibility:s}:{},...B(r),...l?{unchanged:l}:{},...c?{snapshotDiagnostics:c}:{}}),identifiers:{session:a,appId:n,appBundleId:n}}},screenshot:async(e={})=>{let t=o(e),a=await i("screenshot",e);return{path:F(a,"path"),overlayRefs:ec(a),identifiers:{session:t}}},diff:async e=>await i("diff",e)},interactions:{click:async e=>await i("click",e),press:async e=>await i("press",e),longPress:async e=>await i("longpress",e),swipe:async e=>await i("swipe",e),pan:async e=>await i("gesture-pan",e),fling:async e=>await i("gesture-fling",e),swipeGesture:async e=>await i("gesture-swipe",e),focus:async e=>await i("focus",e),type:async e=>await i("type",e),fill:async e=>await i("fill",e),scroll:async e=>await i("scroll",e),pinch:async e=>await i("gesture-pinch",e),rotateGesture:async e=>await i("gesture-rotate",e),transformGesture:async e=>await i("gesture-transform",e),get:async e=>await i("get",e),is:async e=>await i("is",e),find:async e=>await i("find",e)},replay:{run:async e=>await i("replay",e),test:async e=>await i("test",e)},batch:{run:async e=>await i("batch",e)},observability:{perf:async(e={})=>await i("perf",e),logs:async(e={})=>await i("logs",e),network:async(e={})=>await i("network",e)},debug:{symbols:async t=>await t5({cwd:t.cwd??e.cwd,...t})},recording:{record:async e=>await i("record",e),trace:async e=>await i("trace",e)},settings:{update:async e=>await i("settings",e)}}}function ae(e){return"object"==typeof e&&null!==e?e:void 0}function at(e,t){return{...e,...t}}function aa(e){let t=e.lease;if(!t||"object"!=typeof t||Array.isArray(t))throw Error("Invalid lease response from daemon");return{leaseId:F(t,"leaseId"),tenantId:F(t,"tenantId"),runId:F(t,"runId"),backend:F(t,"backend"),createdAt:"number"==typeof t.createdAt?t.createdAt:void 0,heartbeatAt:"number"==typeof t.heartbeatAt?t.heartbeatAt:void 0,expiresAt:"number"==typeof t.expiresAt?t.expiresAt:void 0}}export{t9 as createAgentDeviceClient,tv as ensureDaemon,ez as formatDurationSeconds,eY as replayTestFailureStepLines,tg as resolveClientSettings,tx as sendToDaemon};
|
|
6
|
+
${r}`:r})(n,o,e)}}(t=await t2(j,"crash artifact"))??function(e){let t=e.split("\n"),a=function(e){let t=[],a=e.findIndex(e=>/^Binary Images:/i.test(e.trim()));if(-1===a)return t;for(let n of e.slice(a+1)){let e=function(e){let t=e.match(/^\s*(0x[0-9a-fA-F]+)\s*-\s*(0x[0-9a-fA-F]+)\s+\+?(.+?)\s+<([0-9a-fA-F-]{32,36})>\s+(.+)$/);if(!t)return null;let a=tE(t[4]);if(!a)return null;let n=function(e,t){let a=e.split(/\s+/),n=a.at(-1);if(n&&tj.test(n))return{name:a.slice(0,-1).join(" ").trim(),arch:n};let i=r.basename(t);return{name:e.startsWith(i)?i:e}}(t[3].trim(),t[5].trim());return{name:n.name,arch:n.arch,uuid:a,base:BigInt(t[1]),end:BigInt(t[2]),path:t[5].trim()}}(n);e&&t.push(e)}return t}(t);if(0===a.length)return null;let n=function(e,t){let a,r=[];for(let[n,i]of e.entries()){let e=i.match(/^Thread\s+(\d+)\s+Crashed:/);e?a=Number(e[1]):(0===i.trim().length||/^Thread\s+\d+/.test(i))&&(a=void 0);let o=function(e,t){let a=e.match(/^\s*\d+\s+(.+?)\s+(0x[0-9a-fA-F]+)\b/);if(!a)return null;let r=a[1].trim(),n=BigInt(a[2]),i=function(e,t,a){let r=e.filter(e=>e.name===t);return r.find(e=>{var t,r;return t=e,r=a,void 0!==t.end&&t.base<=r&&r<=t.end})??(1===r.length?r[0]:void 0)}(t,r,n);return i?{image:i,address:n}:null}(i,t),s=i.match(/^\s*(\d+)/);o&&s&&r.push({...o,frameIndex:Number(s[1]),lineIndex:n,threadIndex:a})}return r}(t,a);return{format:"text",images:a,addresses:n,lines:t,frameMatches:n,write(e){let a=new Map(n.map(e=>[e.lineIndex,e]));return t.map((t,r)=>{let n=a.get(r);if(!n)return t;let i=e.get(tN(n.image,n.address))?.text;return!i||t.includes(i)?t:`${t} // ${i}`}).join("\n")}}}(t);V||function(){throw new f("UNSUPPORTED_OPERATION","debug symbols currently supports Apple crash artifacts with Binary Images or IPS usedImages.",{hint:"For Android Java/R8 crashes, use retrace with mapping.txt. For Android native crashes, use ndk-stack or addr2line with unstripped .so symbols. Capture the crash with logs, then symbolicate externally until Android support is added."})}();let H=await tq({cwd:B,dsym:e.dsym,searchPath:e.searchPath});if(0===H.length)throw new f("INVALID_ARGS","debug symbols requires --dsym or --search-path.",{hint:"Pass a matching .dSYM bundle directly, or pass --search-path <dir> so agent-device can match crash image UUIDs to local dSYMs."});let G=await t0(),K=await tG(H,G.dwarfdump),z=function(e,t,a){let r=new Map;for(let a of e){let e=t.find(e=>e.uuid===a.uuid&&(void 0===a.arch||void 0===e.arch||e.arch===a.arch));e&&r.set(a.uuid,{image:a,dsym:e})}if(r.size>0)return r;let n=tB(e.map(e=>e.uuid)),i=tB(t.map(e=>e.uuid));throw new f("COMMAND_FAILED",a?"dSYM UUID does not match any Apple image in the crash artifact.":"No matching dSYM UUID found under search path.",{artifactUuidCount:n.length,artifactUuidSample:n.slice(0,5),dsymUuidCount:i.length,dsymUuidSample:i.slice(0,5),hint:"Use dwarfdump --uuid <App.dSYM> and compare it with the crash Binary Images or usedImages UUID, then pass the matching dSYM/search path."})}(V.images,K,!!e.dsym),Y=await tQ(V.addresses,z,G.atos),W=V.write(Y);await d.mkdir(r.dirname(q),{recursive:!0}),await d.writeFile(q,W,"utf8");let J=[...z.values()].map(({image:e,dsym:t})=>({name:e.name,uuid:e.uuid,arch:e.arch??t.arch,dsymPath:t.dsymPath,binaryPath:t.binaryPath})),X=[...Y.values()].filter(e=>e.text).length,Q=V.images.length-J.length,Z=Q>0?[`${Q} Apple image${1===Q?"":"s"} had no matching dSYM and were left unchanged.`]:void 0;return{kind:"debugSymbols",platform:"apple",artifactPath:j,outPath:q,crash:"ips"===V.format?(n=V.document,i=V.frameMatches,o=Y,U=function(e){let t=tO(e.faultingThread);if(void 0!==t)return t;let a=(Array.isArray(e.threads)?e.threads:[]).findIndex(e=>tU(e)?.triggered===!0);return -1===a?void 0:a}(n.payload),{...L={format:"ips",...(T=(s=n).payload,C=(l=s.header)?tL(l):null,{appName:(c=T,u=C,tT(c.procName,u?.app_name,u?.name)),bundleId:(p=T,m=C,tT(tU(p.bundleInfo)?.CFBundleIdentifier,m?.bundleID)),version:(h=T,y=C,tT(tU(h.bundleInfo)?.CFBundleShortVersionString,y?.app_version)),incident:(w=T,g=C,tT(w.incident,g?.incident_id)),timestamp:(b=T,v=C,tT(b.captureTime,v?.timestamp)),exceptionType:(I=T.exception,t$(tU(I)?.type)),exceptionCodes:function(e){let t=tU(e);if(t)return tT(t.codes,t.rawCodes)}(T.exception),terminationReason:function(e){let t=tU(e);if(t){let e;return(e=[t$(t.namespace),t$(t.code),t$(t.reason)].filter(e=>!!e)).length>0?e.join(" "):void 0}}(T.termination)}),crashedThread:U,topFrames:(A=i,S=U,M=o,A.filter(e=>void 0===S||e.threadIndex===S).slice(0,5).map(e=>tJ(e.frameIndex,e.image,e.address,M))),findings:[]},findings:tX(L)}):(_=V.lines,D=V.frameMatches,P=Y,R=function(e){let t=tW(e,"Triggered by Thread"),a=t?Number.parseInt(t,10):NaN;if(Number.isSafeInteger(a))return a;for(let t of e){let e=t.match(/^Thread\s+(\d+)\s+Crashed:/);if(e)return Number(e[1])}}(_),{...F={format:"text",appName:(O=tW(_,"Process"),O?.replace(/\s+\[\d+\]$/,"")),bundleId:tW(_,"Identifier"),version:tW(_,"Version"),incident:tW(_,"Incident Identifier"),timestamp:tW(_,"Date/Time"),exceptionType:tW(_,"Exception Type"),exceptionCodes:tW(_,"Exception Codes"),terminationReason:tW(_,"Termination Reason"),crashedThread:R,topFrames:(k=D,E=R,N=P,void 0===E?[]:k.filter(e=>e.threadIndex===E).slice(0,5).map(e=>tJ(e.frameIndex,e.image,e.address,N))),findings:[]},findings:tX(F)}),matchedImages:J,symbolicatedFrames:X,skippedImages:Q,warnings:Z,message:`Symbolicated ${X} frame${1===X?"":"s"} -> ${q}`}}async function t2(e,t){await t5(e,t);try{return await d.readFile(e,"utf8")}catch(a){throw new f("INVALID_ARGS",`Failed to read ${t}: ${e}`,{message:a instanceof Error?a.message:String(a)})}}async function t5(e,t){try{let a=await d.stat(e);if(a.size<=0x4000000)return;throw new f("INVALID_ARGS",`${t} is too large: ${e}`,{actualBytes:a.size,maxBytes:0x4000000,hint:"Pass a bounded Apple .ips/.crash artifact. For very large logs, first narrow the log to the crash report, or use logs grep/tail for lead-up context."})}catch(a){if(a instanceof f)throw a;throw new f("INVALID_ARGS",`Failed to read ${t}: ${e}`,{message:a instanceof Error?a.message:String(a)})}}function t4(e,t){return r.resolve(e,t)}let t8={...x(),batch:K(function(e,t,a){let r=t8[e];if(!r)throw Error(`Missing daemon writer for batch command: ${e}`);let n=U(e);if(!n)throw Error(`Missing command metadata for batch command: ${e}`);try{return t6(r,n,n.readInput(t))}catch(r){let t=r instanceof Error?r.message:String(r);throw new f("INVALID_ARGS",`Batch step ${a} ${e} input is invalid: ${t}`,void 0,r)}})};function t6(e,t,a){let r=e(a);return{...r,...t?{metadataFlags:z(t,r.options)}:{}}}function t7(e={},t={}){let a=t.transport??tP,r=async(t,r=[],n={},i)=>{let o=ae(e,n),s=await a({session:V(o.session),command:t,positionals:r,flags:G(o,i),runtime:o.runtime,meta:j(o)});return s.ok||function(e){throw new f(u(e.code),e.message,{...e.details??{},hint:e.hint,diagnosticId:e.diagnosticId,logPath:e.logPath})}(s.error),s.data??{}},n=async(e={})=>{let t=await r(Z.sessionList,[],e);return(Array.isArray(t.sessions)?t.sessions:[]).map($)},i=async(e,t={})=>{let a=function(e,t){let a=t8[e];if(!a)throw Error(`Missing daemon writer for command: ${e}`);return t6(a,U(e),t)}(e,t);return await r(a.command,a.positionals,a.options,a.metadataFlags)},o=(t={})=>V(ae(e,t).session);return{command:{wait:async e=>await i("wait",e),alert:async(e={})=>await i("alert",e),appState:async(e={})=>await i("appstate",e),back:async(e={})=>await i("back",e),home:async(e={})=>await i("home",e),rotate:async e=>await i("rotate",e),appSwitcher:async(e={})=>await i("app-switcher",e),keyboard:async(e={})=>await i("keyboard",e),clipboard:async e=>await i("clipboard",e),reactNative:async e=>await i("react-native",e),prepare:async e=>await i("prepare",e),viewport:async e=>await i("viewport",e)},devices:{list:async(e={})=>{let t=await i("devices",e);return(Array.isArray(t.devices)?t.devices:[]).map(Y)},boot:async(e={})=>await i("boot",e),shutdown:async(e={})=>await i("shutdown",e)},sessions:{list:async(e={})=>await n(e),stateDir:async(t={})=>P(ae(e,t).stateDir??process.env.AGENT_DEVICE_STATE_DIR).baseDir,close:async(e={})=>{let t=o(e),a=(await i("close",e)).shutdown;return{session:t,shutdown:"object"==typeof a&&null!==a?a:void 0,identifiers:{session:t}}}},apps:{install:async e=>F(await i("install",e),o(e)),reinstall:async e=>F(await i("reinstall",e),o(e)),installFromSource:async e=>Q(await i("install-from-source",e),o(e)),list:async(e={})=>{let t=await i("apps",e);return Array.isArray(t.apps)?t.apps.filter(e=>"string"==typeof e):[]},open:async e=>{let t=o(e),a=await i("open",e),r=B(a),n=q(a,"appBundleId");return{session:t,sessionStateDir:q(a,"sessionStateDir"),appName:q(a,"appName"),appBundleId:n,appId:n,startup:W(a.startup),runtime:X(a.runtime),device:r,identifiers:{session:t,deviceId:r?.id,deviceName:r?.name,udid:r?.ios?.udid,serial:r?.android?.serial,appId:n,appBundleId:n}}},close:async(e={})=>{let t=o(e),a=(await i("close",e)).shutdown;return{session:t,closedApp:e.app,shutdown:"object"==typeof a&&null!==a?a:void 0,identifiers:{session:t}}},push:async e=>await i("push",e),triggerEvent:async e=>await i("trigger-app-event",e)},materializations:{release:async e=>L(await r(Z.releaseMaterializedPaths,[],{...e,materializationId:e.materializationId}))},leases:{allocate:async e=>at(await r(Z.leaseAllocate,[],{...e,leaseId:void 0,leaseTtlMs:e.ttlMs})),heartbeat:async e=>at(await r(Z.leaseHeartbeat,[],{...e,leaseTtlMs:e.ttlMs})),release:async e=>({released:!0===(await r(Z.leaseRelease,[],e)).released})},metro:{prepare:async t=>await ei({projectRoot:t.projectRoot??e.cwd,kind:t.kind,publicBaseUrl:t.publicBaseUrl,proxyBaseUrl:t.proxyBaseUrl,proxyBearerToken:t.bearerToken,bridgeScope:t.bridgeScope,launchUrl:t.launchUrl,companionProfileKey:t.companionProfileKey,companionConsumerKey:t.companionConsumerKey,metroPort:t.port,listenHost:t.listenHost,statusHost:t.statusHost,startupTimeoutMs:t.startupTimeoutMs,probeTimeoutMs:t.probeTimeoutMs,reuseExisting:t.reuseExisting,installDependenciesIfNeeded:t.installDependenciesIfNeeded,runtimeFilePath:t.runtimeFilePath,logPath:t.logPath}),reload:async(t={})=>await en({metroHost:t.metroHost,metroPort:t.metroPort,bundleUrl:t.bundleUrl,runtime:e.runtime,timeoutMs:t.timeoutMs})},capture:{snapshot:async(e={})=>{var t,a,r;let n,s,l,c,d=o(e);return t=await i("snapshot",e),a=d,n=q(t,"appBundleId"),{nodes:R(t.nodes),truncated:!0===t.truncated,appName:q(t,"appName"),appBundleId:n,...(s=t9((r=t).visibility),l=t9(r.unchanged),c=I(r.snapshotDiagnostics),{...s?{visibility:s}:{},...T(r),...l?{unchanged:l}:{},...c?{snapshotDiagnostics:c}:{}}),identifiers:{session:a,appId:n,appBundleId:n}}},screenshot:async(e={})=>{let t=o(e),a=await i("screenshot",e);return{path:C(a,"path"),overlayRefs:J(a),identifiers:{session:t}}},diff:async e=>await i("diff",e)},interactions:{click:async e=>await i("click",e),press:async e=>await i("press",e),longPress:async e=>await i("longpress",e),swipe:async e=>await i("swipe",e),pan:async e=>await i("gesture-pan",e),fling:async e=>await i("gesture-fling",e),swipeGesture:async e=>await i("gesture-swipe",e),focus:async e=>await i("focus",e),type:async e=>await i("type",e),fill:async e=>await i("fill",e),scroll:async e=>await i("scroll",e),pinch:async e=>await i("gesture-pinch",e),rotateGesture:async e=>await i("gesture-rotate",e),transformGesture:async e=>await i("gesture-transform",e),get:async e=>await i("get",e),is:async e=>await i("is",e),find:async e=>await i("find",e)},replay:{run:async e=>await i("replay",e),test:async e=>await i("test",e)},batch:{run:async e=>await i("batch",e)},observability:{perf:async(e={})=>await i("perf",e),logs:async(e={})=>await i("logs",e),network:async(e={})=>await i("network",e)},debug:{symbols:async t=>await t3({cwd:t.cwd??e.cwd,...t})},recording:{record:async e=>await i("record",e),trace:async e=>await i("trace",e)},settings:{update:async e=>await i("settings",e)}}}function t9(e){return"object"==typeof e&&null!==e?e:void 0}function ae(e,t){return{...e,...t}}function at(e){let t=e.lease;if(!t||"object"!=typeof t||Array.isArray(t))throw Error("Invalid lease response from daemon");return{leaseId:C(t,"leaseId"),tenantId:C(t,"tenantId"),runId:C(t,"runId"),backend:C(t,"backend"),createdAt:"number"==typeof t.createdAt?t.createdAt:void 0,heartbeatAt:"number"==typeof t.heartbeatAt?t.heartbeatAt:void 0,expiresAt:"number"==typeof t.expiresAt?t.expiresAt:void 0}}export{eo as DAEMON_HTTP_BASE_PATH,ec as buildDaemonHttpAuthHeaders,es as buildDaemonHttpBaseUrl,el as buildDaemonHttpUrl,t7 as createAgentDeviceClient,ty as ensureDaemon,eV as formatDurationSeconds,eH as replayTestFailureStepLines,th as resolveClientSettings,tP as sendToDaemon};
|
package/dist/src/android.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import e from"node:crypto";import t from"node:fs/promises";import r from"node:path";import{promises as i}from"node:fs";import{normalizeError as a,AppError as n}from"./733.js";import{withDiagnosticTimer as o,emitDiagnostic as s}from"./432.js";import{readVersion as d,findProjectRoot as l}from"./
|
|
2
|
-
${i.stderr}`)}catch(e){if(e instanceof n){if(e.code===
|
|
1
|
+
import e from"node:crypto";import t from"node:fs/promises";import r from"node:path";import{promises as i}from"node:fs";import{normalizeError as a,AppError as n}from"./733.js";import{withDiagnosticTimer as o,emitDiagnostic as s}from"./432.js";import{readVersion as d,findProjectRoot as l}from"./1404.js";import{resolveAndroidTouchInjector as u,resolveAndroidAdbProvider as c,resolveAndroidAdbExecutor as p,installAndroidAdbPackage as m}from"./2954.js";import{appSwitcherAndroid as h,homeAndroid as f,scrollAndroid as w,longPressAndroid as _,typeAndroid as A,getAndroidScreenSize as g,pressAndroid as y,focusAndroid as N,swipeAndroid as I,rotateAndroid as v,fillAndroid as M,backAndroid as C}from"./input-actions.js";import{requireLocationCoordinates as S,snapshotCaptureAnnotationsFrom as R}from"./2948.js";import{parseAppearanceAction as D,summarizeCommandAttemptFailures as E,parseSettingState as x,parsePermissionTarget as k,parsePermissionAction as b}from"./8225.js";import{openAndroidDevice as O,runAndroidAdb as L,openAndroidApp as F,resolveAndroidApp as P,closeAndroidApp as T}from"./3340.js";import{writeAndroidClipboardText as U,readAndroidClipboardText as $}from"./9624.js";import{snapshotAndroid as G}from"./9722.js";import{sleep as K}from"./5560.js";let V="android-multitouch-helper-v1",H="ANDROID_MULTITOUCH_HELPER_NO_FINAL_RESULT",B="ANDROID_MULTITOUCH_HELPER_REPORTED_FAILURE";async function q(e,t){let r=await Q(e,{kind:"swipe",...t});if(r)return r;try{return await Y(e,{kind:"swipe",...t})}catch(r){return s({level:"warn",phase:"android_swipe_helper_fallback",data:{error:a(r).message}}),await I(e,t.x1,t.y1,t.x2,t.y2,t.durationMs),{backend:"adb-input-swipe-fallback"}}}async function j(e,t){if(!Number.isFinite(t.scale)||t.scale<=0)throw new n("INVALID_ARGS","gesture pinch requires scale > 0");let r=await W(e,t.x,t.y);return await X(e,{kind:"pinch",x:r.x,y:r.y,scale:t.scale,durationMs:t.durationMs})}async function z(e,t){if(!Number.isFinite(t.degrees))throw new n("INVALID_ARGS","gesture rotate requires finite degrees");if(void 0!==t.velocity&&(!Number.isFinite(t.velocity)||0===t.velocity))throw new n("INVALID_ARGS","gesture rotate velocity must be a non-zero number");let r=await W(e,t.x,t.y),i=t.degrees;return await X(e,{kind:"rotate",x:r.x,y:r.y,degrees:i,durationMs:t.durationMs})}async function J(e,t){if(!Number.isFinite(t.scale)||t.scale<=0)throw new n("INVALID_ARGS","gesture transform requires scale > 0");if(!Number.isFinite(t.degrees))throw new n("INVALID_ARGS","gesture transform requires finite degrees");if(![t.x,t.y,t.dx,t.dy].every(Number.isFinite))throw new n("INVALID_ARGS","gesture transform requires finite x y dx dy");return await X(e,{kind:"transform",x:t.x,y:t.y,dx:t.dx,dy:t.dy,scale:t.scale,degrees:t.degrees,durationMs:t.durationMs})}async function W(e,t,r){if(void 0!==t&&void 0!==r)return{x:t,y:r};let i=await g(e);return{x:Math.round(i.width/2),y:Math.round(i.height/2)}}async function X(e,t){let r=await Q(e,t);return r||await Y(e,t)}async function Q(e,t){let r=u(e);if(r)return{backend:"provider-native-touch",...await r(t)??{}}}async function Y(e,t){let r=p(e),i=await et(),a=c(e),n=await o("android_multitouch_helper_install",async()=>{var t;return await er({adb:r,adbProvider:a,artifact:i,deviceKey:(t=e,`${t.platform}:${t.id}`)})},{packageName:i.manifest.packageName,versionCode:i.manifest.versionCode});s({phase:"android_multitouch_helper_install_decision",data:n});let d=await o("android_multitouch_helper_gesture",async()=>await Z({adb:r,request:function(e){var t;let r=Math.round(void 0!==(t=e).durationMs?t.durationMs:"swipe"===t.kind||"pinch"===t.kind?300:Math.min(Math.max(300,16*Math.ceil(Math.abs(t.degrees)/3)),2400));switch(e.kind){case"swipe":return{kind:"swipe",x1:Math.round(e.x1),y1:Math.round(e.y1),x2:Math.round(e.x2),y2:Math.round(e.y2),durationMs:r};case"pinch":return{kind:"pinch",x:Math.round(e.x),y:Math.round(e.y),scale:e.scale,radius:160,durationMs:r};case"rotate":return{kind:"rotate",x:Math.round(e.x),y:Math.round(e.y),degrees:e.degrees,radius:160,durationMs:r};case"transform":return{kind:"transform",x:Math.round(e.x),y:Math.round(e.y),dx:Math.round(e.dx),dy:Math.round(e.dy),scale:e.scale,degrees:e.degrees,durationMs:r}}}(t),packageName:i.manifest.packageName,instrumentationRunner:i.manifest.instrumentationRunner}),{packageName:i.manifest.packageName,version:i.manifest.version});return{backend:"android-multitouch-helper",helperVersion:i.manifest.version,installReason:n.reason,...d}}async function Z(e){let t,r=Buffer.from(JSON.stringify({protocol:V,...e.request})).toString("base64"),i=await e.adb(["shell","am","instrument","-w","-e","payloadBase64",r,e.instrumentationRunner],{allowFailure:!0,timeoutMs:45e3});try{t=function(e){let t=(function(e){let t=[],r=null;for(let i of e.split(/\r?\n/))i.startsWith("INSTRUMENTATION_RESULT: ")?(r??={},function(e,t){let r=e.indexOf("=");r>=0&&(t[e.slice(0,r)]=e.slice(r+1))}(i.slice(24),r)):i.startsWith("INSTRUMENTATION_CODE: ")&&r&&(t.push(r),r=null);return r&&t.push(r),t})(e).find(e=>e.agentDeviceProtocol===V);if(!t)throw new n(H,"Android multi-touch helper did not return a final result");if("true"!==t.ok){var r;throw new n(B,(r=t).message&&"null"!==r.message?r.message:r.errorType||"Android multi-touch helper returned an error",{errorType:t.errorType,helper:t})}return{kind:t.kind,helperApiVersion:t.helperApiVersion,injectedEvents:ee(t.injectedEvents),elapsedMs:ee(t.elapsedMs)}}(`${i.stdout}
|
|
2
|
+
${i.stderr}`)}catch(e){if(e instanceof n){if(e.code===B)throw new n("COMMAND_FAILED",e.message,e.details,e);if(e.code!==H)throw e}throw new n("COMMAND_FAILED",0===i.exitCode?"Android multi-touch helper output could not be parsed":"Android multi-touch helper failed before returning parseable output",{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode},e)}if(0!==i.exitCode)throw new n("COMMAND_FAILED","Android multi-touch helper failed",{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode,helper:t});return t}function ee(e){if(void 0===e)return;let t=Number(e);return Number.isFinite(t)?t:void 0}async function et(){let e=d(),i=r.join(l(),"android-multitouch-helper","dist"),o=r.join(i,`agent-device-android-multitouch-helper-${e}.manifest.json`);try{let e=function(e){if(!e||"object"!=typeof e||Array.isArray(e))throw new n("INVALID_ARGS","Android multi-touch helper manifest must be an object.");return{name:ed(e.name,"name","android-multitouch-helper"),version:es(e.version,"version"),assetName:es(e.assetName,"assetName"),sha256:function(e){let t=es(e,"sha256").trim().toLowerCase();if(64!==t.length||!/^[0-9a-f]+$/.test(t))throw new n("INVALID_ARGS","Android multi-touch helper manifest sha256 must be a 64-character hex string.");return t}(e.sha256),packageName:ed(e.packageName,"packageName","com.callstack.agentdevice.multitouchhelper"),versionCode:function(e,t){if(!Number.isInteger(e))throw new n("INVALID_ARGS",`Android multi-touch helper manifest ${t} must be an integer.`);return e}(e.versionCode,"versionCode"),instrumentationRunner:ed(e.instrumentationRunner,"instrumentationRunner","com.callstack.agentdevice.multitouchhelper/.MultiTouchInstrumentation"),statusProtocol:ed(e.statusProtocol,"statusProtocol",V)}}(JSON.parse(await t.readFile(o,"utf8"))),a=r.join(i,e.assetName);return await t.access(a),{apkPath:a,manifest:e}}catch(e){throw new n("UNSUPPORTED_OPERATION","Android touch gestures require the bundled Android touch helper artifact, but it was not found or could not be read",{manifestPath:o,error:a(e).message},e)}}async function er(e){let{adb:t,artifact:r}=e,i=r.manifest.packageName,a=r.manifest.versionCode,o=`${e.deviceKey}\0${i}\0${a}`;if(ei.has(o))return{packageName:i,versionCode:a,installed:!1,reason:"current"};let s=await ea(t,i);if(void 0!==s&&s>=a)return ei.add(o),{packageName:i,versionCode:a,installedVersionCode:s,installed:!1,reason:"current"};await en(r);let d=await m(r.apkPath,{provider:e.adbProvider,replace:!0,allowTestPackages:!0,allowFailure:!0,timeoutMs:3e4});if(0!==d.exitCode)throw new n("COMMAND_FAILED","Failed to install Android multi-touch helper",{packageName:i,versionCode:a,stdout:d.stdout,stderr:d.stderr,exitCode:d.exitCode});return ei.add(o),{packageName:i,versionCode:a,installedVersionCode:s,installed:!0,reason:void 0===s?"missing":"outdated"}}let ei=new Set;async function ea(e,t){let r=await e(["shell","cmd","package","list","packages","--show-versioncode",t],{allowFailure:!0,timeoutMs:5e3});if(0!==r.exitCode)return;let i=RegExp(`package:${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:\\s|$).*versionCode:(\\d+)`).exec(`${r.stdout}
|
|
3
3
|
${r.stderr}`);return i?Number(i[1]):void 0}async function en(e){let t=await eo(e.apkPath);if(t!==e.manifest.sha256)throw new n("COMMAND_FAILED","Android multi-touch helper APK checksum mismatch",{apkPath:e.apkPath,expectedSha256:e.manifest.sha256,actualSha256:t})}async function eo(r){let i=e.createHash("sha256");return i.update(await t.readFile(r)),i.digest("hex")}function es(e,t){if("string"!=typeof e||0===e.length)throw new n("INVALID_ARGS",`Android multi-touch helper manifest ${t} is required.`);return e}function ed(e,t,r){if(e!==r)throw new n("INVALID_ARGS",`Android multi-touch helper manifest ${t} must be "${r}".`);return r}let el=["window_animation_scale","transition_animation_scale","animator_duration_scale"];async function eu(e,t,r,i,a){switch(t.toLowerCase()){case"wifi":{let t=x(r);await L(e,["shell","svc","wifi",t?"enable":"disable"]);return}case"airplane":{let t=x(r);await L(e,["shell","settings","put","global","airplane_mode_on",t?"1":"0"]),await L(e,["shell","am","broadcast","-a","android.intent.action.AIRPLANE_MODE","--ez","state",t?"true":"false"]);return}case"location":{if("set"===r.toLowerCase()){if("emulator"!==e.kind)throw new n("UNSUPPORTED_OPERATION","Android precise location coordinates are supported only on emulators.",{deviceId:e.id,hint:"Use an Android emulator for adb emu geo fix, or configure location through device/provider tooling."});let{latitude:t,longitude:r}=S(a);return await L(e,["emu","geo","fix",String(r),String(t)]),{latitude:t,longitude:r}}let t=x(r);await L(e,["shell","settings","put","secure","location_mode",t?"3":"0"]);return}case"animations":{let t=x(r)?"1":"0";for(let r of el)await L(e,["shell","settings","put","global",r,t]);return{scale:t,keys:[...el]}}case"appearance":{let t=await ep(e,r);await L(e,["shell","cmd","uimode","night","dark"===t?"yes":"no"]);return}case"clear-app-state":{if("clear"!==r.toLowerCase())throw new n("INVALID_ARGS","settings clear-app-state only supports clear.");if(!i)throw new n("INVALID_ARGS","settings clear-app-state requires an app id or an active app session.");let t=await P(e,i);if("intent"===t.type)throw new n("INVALID_ARGS","settings clear-app-state requires a package name, not an intent.");await L(e,["shell","am","force-stop",t.value],{allowFailure:!0});let a=await L(e,["shell","pm","clear",t.value],{allowFailure:!0});if(0!==a.exitCode||!/\bSuccess\b/i.test(a.stdout))throw new n("COMMAND_FAILED",`Failed to clear Android app data for ${t.value}`,{package:t.value,stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode});return{package:t.value,cleared:!0}}case"fingerprint":{let t=function(e){let t=e.trim().toLowerCase();if("match"===t)return"match";if("nonmatch"===t)return"nonmatch";throw new n("INVALID_ARGS",`Invalid fingerprint state: ${e}. Use match|nonmatch.`)}(r);await ec(e,t);return}case"permission":{if(!i)throw new n("INVALID_ARGS","permission setting requires an active app in session");let t=b(r),o=function(e,t){let r=k(e);if(t?.trim())throw new n("INVALID_ARGS",`Permission mode is only supported for photos. Received: ${t}.`);if("camera"===r)return{kind:"pm",value:"android.permission.CAMERA",type:"camera"};if("microphone"===r)return{kind:"pm",value:"android.permission.RECORD_AUDIO",type:"microphone"};if("photos"===r)return{kind:"pm",value:"android.permission.READ_MEDIA_IMAGES",type:"photos"};if("contacts"===r)return{kind:"pm",value:"android.permission.READ_CONTACTS",type:"contacts"};if("notifications"===r)return{kind:"notifications",appOps:"POST_NOTIFICATION",permission:"android.permission.POST_NOTIFICATIONS"};throw new n("INVALID_ARGS",`Unsupported permission target on Android: ${e}. Use camera|microphone|photos|contacts|notifications.`)}(a?.permissionTarget,a?.permissionMode);if("notifications"===o.kind)return void await eh(e,i,t,o);let s="grant"===t?"grant":"revoke";if("photos"===o.type)return void await em(e,i,s);await L(e,["shell","pm",s,i,o.value]);return}default:throw new n("INVALID_ARGS",`Unsupported setting: ${t}`)}}async function ec(e,t){var r;let i,a,o=(r=e,a=[["shell","cmd","fingerprint","touch",i="match"===t?"1":"9999"],["shell","cmd","fingerprint","finger",i]],"emulator"===r.kind&&a.push(["emu","finger","touch",i]),a),s=[];for(let t of o){let r=await L(e,t,{allowFailure:!0});if(0===r.exitCode)return;s.push({args:t,stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode})}let d=E(s);if(s.length>0&&s.every(e=>{var t,r;let i;return t=e.stdout,r=e.stderr,(i=`${t}
|
|
4
4
|
${r}`.toLowerCase()).includes("unknown command")||i.includes("can't find service: fingerprint")||i.includes("service fingerprint was not found")||i.includes("fingerprint cmd unavailable")||i.includes("emu command is not supported")||i.includes("emulator console is not running")||i.includes("fingerprint")&&i.includes("not found")}))throw new n("UNSUPPORTED_OPERATION","Android fingerprint simulation is not supported on this target/runtime.",{deviceId:e.id,action:t,hint:"Use an Android emulator with biometric support, or a device/runtime that exposes cmd fingerprint.",attempts:d});throw new n("COMMAND_FAILED","Failed to simulate Android fingerprint.",{deviceId:e.id,action:t,attempts:d})}async function ep(e,t){let r=D(t);if("toggle"!==r)return r;let i=await L(e,["shell","cmd","uimode","night"],{allowFailure:!0});if(0!==i.exitCode)throw new n("COMMAND_FAILED","Failed to read current Android appearance",{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode});let a=function(e,t){let r=/night mode:\s*(yes|no|auto)\b/i.exec(`${e}
|
|
5
|
-
${t}`);if(!r)return null;let i=r[1]?.toLowerCase();return"yes"===i?"dark":"no"===i?"light":"auto"===i?"auto":null}(i.stdout,i.stderr);if(!a)throw new n("COMMAND_FAILED","Unable to determine current Android appearance for toggle",{stdout:i.stdout,stderr:i.stderr});return"auto"===a?"dark":"dark"===a?"light":"dark"}async function em(e,t,r){let i=await ef(e),a=[];for(let n of null!==i&&i>=33?["android.permission.READ_MEDIA_IMAGES","android.permission.READ_EXTERNAL_STORAGE"]:["android.permission.READ_EXTERNAL_STORAGE","android.permission.READ_MEDIA_IMAGES"]){let i=await L(e,["shell","pm",r,t,n],{allowFailure:!0});if(0===i.exitCode)return;a.push({permission:n,stderr:i.stderr,exitCode:i.exitCode})}throw new n("COMMAND_FAILED",`Failed to ${r} Android photos permission`,{appPackage:t,sdkInt:i,attempts:a})}async function eh(e,t,r,i){"grant"===r?await L(e,["shell","pm","grant",t,i.permission],{allowFailure:!0}):(await L(e,["shell","pm","revoke",t,i.permission],{allowFailure:!0}),"reset"===r&&(await L(e,["shell","pm","clear-permission-flags",t,i.permission,"user-set"],{allowFailure:!0}),await L(e,["shell","pm","clear-permission-flags",t,i.permission,"user-fixed"],{allowFailure:!0}))),await L(e,["shell","appops","set",t,i.appOps,"grant"===r?"allow":"deny"===r?"deny":"default"])}async function ef(e){let t=await L(e,["shell","getprop","ro.build.version.sdk"],{allowFailure:!0});if(0!==t.exitCode)return null;let r=Number.parseInt(t.stdout.trim(),10);return!Number.isFinite(r)||r<=0?null:r}let ew=Buffer.from([137,80,78,71,13,10,26,10]);async function e_(e,t,r={}){if(!1===r.stabilize)return void await ey(e,t);await eA(e);try{await K(1e3),await ey(e,t)}finally{await eg(e).catch(()=>{})}}async function eA(e){let t=t=>L(e,["shell",t],{allowFailure:!0});await t("settings put global sysui_demo_allowed 1");let r=e=>t(`am broadcast -a com.android.systemui.demo -e command ${e}`);await r("clock -e hhmm 0941"),await r("notifications -e visible false")}async function eg(e){await L(e,["shell","am broadcast -a com.android.systemui.demo -e command exit"],{allowFailure:!0})}async function ey(e,t){let r=await L(e,["exec-out","screencap","-p"],{binaryStdout:!0});if(!r.stdoutBuffer)throw new n("COMMAND_FAILED","Failed to capture screenshot");let a=r.stdoutBuffer.indexOf(ew);if(a<0)throw new n("COMMAND_FAILED","Screenshot data does not contain a valid PNG header");let o=function(e,t){let r=t+ew.length;for(;r+8<=e.length;){let t=e.readUInt32BE(r),i=r+4,a=e.toString("ascii",i,i+4),n=r+12+t;if(n>e.length)break;if("IEND"===a)return n;r=n}return null}(r.stdoutBuffer,a);if(!o)throw new n("COMMAND_FAILED","Screenshot data does not contain a complete PNG payload");await i.writeFile(t,r.stdoutBuffer.subarray(a,o))}function eN(e){return{open:(t,r)=>F(e,t,{activity:r?.activity,appBundleId:r?.appBundleId,launchArgs:r?.launchArgs,url:r?.url}),openDevice:()=>O(e),close:t=>T(e,t),tap:(t,r)=>y(e,t,r),doubleTap:async(t,r)=>{await y(e,t,r),await y(e,t,r)},swipe:(t,r,i,a,n)=>
|
|
5
|
+
${t}`);if(!r)return null;let i=r[1]?.toLowerCase();return"yes"===i?"dark":"no"===i?"light":"auto"===i?"auto":null}(i.stdout,i.stderr);if(!a)throw new n("COMMAND_FAILED","Unable to determine current Android appearance for toggle",{stdout:i.stdout,stderr:i.stderr});return"auto"===a?"dark":"dark"===a?"light":"dark"}async function em(e,t,r){let i=await ef(e),a=[];for(let n of null!==i&&i>=33?["android.permission.READ_MEDIA_IMAGES","android.permission.READ_EXTERNAL_STORAGE"]:["android.permission.READ_EXTERNAL_STORAGE","android.permission.READ_MEDIA_IMAGES"]){let i=await L(e,["shell","pm",r,t,n],{allowFailure:!0});if(0===i.exitCode)return;a.push({permission:n,stderr:i.stderr,exitCode:i.exitCode})}throw new n("COMMAND_FAILED",`Failed to ${r} Android photos permission`,{appPackage:t,sdkInt:i,attempts:a})}async function eh(e,t,r,i){"grant"===r?await L(e,["shell","pm","grant",t,i.permission],{allowFailure:!0}):(await L(e,["shell","pm","revoke",t,i.permission],{allowFailure:!0}),"reset"===r&&(await L(e,["shell","pm","clear-permission-flags",t,i.permission,"user-set"],{allowFailure:!0}),await L(e,["shell","pm","clear-permission-flags",t,i.permission,"user-fixed"],{allowFailure:!0}))),await L(e,["shell","appops","set",t,i.appOps,"grant"===r?"allow":"deny"===r?"deny":"default"])}async function ef(e){let t=await L(e,["shell","getprop","ro.build.version.sdk"],{allowFailure:!0});if(0!==t.exitCode)return null;let r=Number.parseInt(t.stdout.trim(),10);return!Number.isFinite(r)||r<=0?null:r}let ew=Buffer.from([137,80,78,71,13,10,26,10]);async function e_(e,t,r={}){if(!1===r.stabilize)return void await ey(e,t);await eA(e);try{await K(1e3),await ey(e,t)}finally{await eg(e).catch(()=>{})}}async function eA(e){let t=t=>L(e,["shell",t],{allowFailure:!0});await t("settings put global sysui_demo_allowed 1");let r=e=>t(`am broadcast -a com.android.systemui.demo -e command ${e}`);await r("clock -e hhmm 0941"),await r("notifications -e visible false")}async function eg(e){await L(e,["shell","am broadcast -a com.android.systemui.demo -e command exit"],{allowFailure:!0})}async function ey(e,t){let r=await L(e,["exec-out","screencap","-p"],{binaryStdout:!0});if(!r.stdoutBuffer)throw new n("COMMAND_FAILED","Failed to capture screenshot");let a=r.stdoutBuffer.indexOf(ew);if(a<0)throw new n("COMMAND_FAILED","Screenshot data does not contain a valid PNG header");let o=function(e,t){let r=t+ew.length;for(;r+8<=e.length;){let t=e.readUInt32BE(r),i=r+4,a=e.toString("ascii",i,i+4),n=r+12+t;if(n>e.length)break;if("IEND"===a)return n;r=n}return null}(r.stdoutBuffer,a);if(!o)throw new n("COMMAND_FAILED","Screenshot data does not contain a complete PNG payload");await i.writeFile(t,r.stdoutBuffer.subarray(a,o))}function eN(e){return{open:(t,r)=>F(e,t,{activity:r?.activity,appBundleId:r?.appBundleId,launchArgs:r?.launchArgs,url:r?.url}),openDevice:()=>O(e),close:t=>T(e,t),tap:(t,r)=>y(e,t,r),doubleTap:async(t,r)=>{await y(e,t,r),await y(e,t,r)},swipe:(t,r,i,a,n)=>q(e,{x1:t,y1:r,x2:i,y2:a,durationMs:n}),pan:(t,r,i,a,n)=>q(e,{x1:t,y1:r,x2:i,y2:a,durationMs:n}),fling:(t,r,i,a,n)=>q(e,{x1:t,y1:r,x2:i,y2:a,durationMs:n}),longPress:(t,r,i)=>_(e,t,r,i),focus:(t,r)=>N(e,t,r),type:(t,r)=>A(e,t,r),fill:(t,r,i,a)=>M(e,t,r,i,a),scroll:(t,r)=>w(e,t,r),pinch:(t,r,i)=>j(e,{scale:t,x:r,y:i}),screenshot:(t,r)=>e_(e,t,r),snapshot:async t=>{let r=await o("snapshot_capture",async()=>await G(e,{appBundleId:t?.appBundleId,interactiveOnly:t?.interactiveOnly,depth:t?.depth,scope:t?.scope,raw:t?.raw,helperSessionScope:t?.appBundleId?"daemon-session":"command"}),{backend:"android"});return{nodes:r.nodes??[],truncated:r.truncated??!1,backend:"android",...R(r)}},back:t=>C(e),home:()=>f(e),rotate:t=>v(e,t),rotateGesture:(t,r,i,a)=>z(e,{degrees:t,x:r,y:i,velocity:a}),transformGesture:t=>J(e,t),appSwitcher:()=>h(e),readClipboard:()=>$(e),writeClipboard:t=>U(e,t),setSetting:(t,r,i,a)=>eu(e,t,r,i,a)}}export{eN as createAndroidInteractor};
|
package/dist/src/apple.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readSnapshotQualityVerdict as
|
|
1
|
+
import{readSnapshotQualityVerdict as a,normalizeScrollDurationMs as e,buildScrollGesturePlan as t,assertScrollGestureInput as n}from"./2948.js";import{parseRunnerSequenceResult as o,buildRunnerSequenceCommand as d,runMacOsScreenshotAction as i,runIosRunnerCommand as r}from"./9722.js";import{writeIosClipboardText as s,openIosApp as u,openIosDevice as l,screenshotIos as p,closeIosApp as c,setIosSetting as m,readIosClipboardText as y}from"./apps.js";import{withDiagnosticTimer as v}from"./432.js";import{AppError as f}from"./733.js";function I(a,e,n,o={includeDuration:!0}){let d=w(a.referenceWidth),i=w(a.referenceHeight);if(void 0===d||void 0===i)return B(a,{amount:n?.amount});let r=t({direction:e,amount:n?.amount,pixels:n?.pixels,referenceWidth:d,referenceHeight:i});return B(a,{amount:n?.amount,pixels:r.pixels,durationMs:o?.includeDuration?n?.durationMs:void 0,preferProvidedPixels:!0})}function h(a,e={includeDuration:!0}){return{...a?.amount!==void 0?{amount:a.amount}:{},...a?.pixels!==void 0?{pixels:a.pixels}:{},...e?.includeDuration&&a?.durationMs!==void 0?{durationMs:a.durationMs}:{}}}function w(a){return"number"==typeof a&&Number.isFinite(a)?a:void 0}function B(a,e){var t,n,o,d;let i,r,s,u,{x1:l,y1:p,x2:c,y2:m}=(i=w((t=a).x),r=w(t.y),s=w(t.x2),u=w(t.y2),{...void 0!==i?{x1:i}:{},...void 0!==r?{y1:r}:{},...void 0!==s?{x2:s}:{},...void 0!==u?{y2:u}:{}}),y=w(a.referenceWidth),v=w(a.referenceHeight),f=(n=e,o=void 0!==l&&void 0!==c?Math.round(Math.abs(c-l)):void 0,d=void 0!==p&&void 0!==m?Math.round(Math.abs(m-p)):void 0,n?.preferProvidedPixels&&void 0!==n.pixels?n.pixels:void 0!==o&&o>0?o:void 0!==d&&d>0?d:void 0);return{...void 0!==l?{x1:l}:{},...void 0!==p?{y1:p}:{},...void 0!==c?{x2:c}:{},...void 0!==m?{y2:m}:{},...void 0!==y?{referenceWidth:y}:{},...void 0!==v?{referenceHeight:v}:{},...e?.amount!==void 0?{amount:e.amount}:{},...void 0!==f?{pixels:f}:{},...e?.durationMs!==void 0?{durationMs:e.durationMs}:{}}}async function M(a,e,t,n,o,d){return I(await a(e,{command:"desktopScroll",direction:o,...h(d,{includeDuration:!0}),appBundleId:t.appBundleId},n),o,d,{includeDuration:!0})}function g(a,e,t,n){return{command:"tap",x:t,y:n,..._(a)?{synthesized:!0}:{},appBundleId:e.appBundleId}}function _(a){return"ios"===a.platform&&"tv"!==a.target}function x(a,e,t,n,o,d,i,r){var s,u;let l="ios"===a.platform&&"tv"!==a.target?(s=i,u=r.defaultDurationMs,void 0===s?u:Math.min(1e4,Math.max(16,Math.round(s)))):i??r.legacyDefaultDurationMs;return{command:"drag",x:t,y:n,x2:o,y2:d,...void 0!==l?{durationMs:l}:{},...!0===r.synthesized?{synthesized:!0}:{},appBundleId:e.appBundleId}}function b(a,e,t){return{command:"remotePress",remoteButton:a,...void 0!==t?{durationMs:t}:{},...void 0!==e?{appBundleId:e}:{}}}async function D(a,t,o,d,i,r){return(e(r?.durationMs,{invalidMessage:"scroll durationMs must be a non-negative integer at most 10000"}),"tv"===t.target)?B(await a(t,b(i,o.appBundleId,r?.durationMs),d),{amount:r?.amount,durationMs:r?.durationMs}):(n(r??{}),"macos"===t.platform)?await M(a,t,o,d,i,r):I(await a(t,{command:"scroll",direction:i,...h(r),appBundleId:o.appBundleId},d),i,r)}function C(e,t){let n,{overrides:I,runnerOpts:h}={runnerOpts:n={verbose:t.verbose,logPath:t.logPath,traceLogPath:t.traceLogPath,requestId:t.requestId,iosXctestrunFile:t.iosXctestrunFile,iosXctestDerivedDataPath:t.iosXctestDerivedDataPath,iosXctestEnvDir:t.iosXctestEnvDir},overrides:{tap:async(a,o)=>await r(e,g(e,t,a,o),n),tapElementSelector:async a=>await r(e,{command:"tap",selectorKey:a.key,selectorValue:a.value,allowNonHittableCoordinateFallback:a.allowNonHittableCoordinateFallback,appBundleId:t.appBundleId},n),doubleTap:async(a,i)=>{let s=await r(e,d([{kind:"doubleTap",x:a,y:i}],t.appBundleId),n);return o(s),s},swipe:async(a,o,d,i,s)=>await r(e,x(e,t,a,o,d,i,s,{defaultDurationMs:250,synthesized:_(e)}),n),pan:async(a,o,d,i,s)=>await r(e,x(e,t,a,o,d,i,s,{defaultDurationMs:500,legacyDefaultDurationMs:500,synthesized:_(e)}),n),fling:async(a,o,d,i,s)=>await r(e,x(e,t,a,o,d,i,s,{defaultDurationMs:16,legacyDefaultDurationMs:16,synthesized:_(e)}),n),longPress:async(a,o,d)=>await r(e,{command:"longPress",x:a,y:o,durationMs:d,appBundleId:t.appBundleId},n),focus:async(a,o)=>await r(e,g(e,t,a,o),n),type:async(a,o)=>{await r(e,{command:"type",text:a,delayMs:o,textEntryMode:"\n"===a?void 0:"append",appBundleId:t.appBundleId},n)},fillElementSelector:async(a,o,d)=>await r(e,{command:"type",selectorKey:a.key,selectorValue:a.value,allowNonHittableCoordinateFallback:a.allowNonHittableCoordinateFallback,text:o,delayMs:d,textEntryMode:"replace",appBundleId:t.appBundleId},n),fill:async(a,o,d,i)=>await r(e,{command:"type",x:a,y:o,text:d,delayMs:i,textEntryMode:"replace",appBundleId:t.appBundleId},n),scroll:async(a,o)=>await D(r,e,t,n,a,o),pinch:async(a,o,d)=>{await r(e,{command:"pinch",scale:a,x:o,y:d,appBundleId:t.appBundleId},n)},rotateGesture:async(a,o,d,i)=>{await r(e,{command:"rotateGesture",degrees:a,x:o,y:d,velocity:i,appBundleId:t.appBundleId},n)},transformGesture:async a=>await r(e,{command:"transformGesture",x:a.x,y:a.y,dx:a.dx,dy:a.dy,scale:a.scale,degrees:a.degrees,durationMs:a.durationMs,appBundleId:t.appBundleId},n)}};return{open:(a,t)=>u(e,a,{appBundleId:t?.appBundleId,launchConsole:t?.launchConsole,launchArgs:t?.launchArgs,url:t?.url}),openDevice:()=>l(e),close:a=>c(e,a),screenshot:async(a,t)=>{"macos"===e.platform&&t?.surface&&"app"!==t.surface?await i(a,{surface:t.surface,fullscreen:t.fullscreen}):await p(e,a,t?.appBundleId,t?.fullscreen,h)},snapshot:async t=>{var n;let o={nodes:Array.isArray((n=await v("snapshot_capture",async()=>await r(e,{command:"snapshot",appBundleId:t?.appBundleId,interactiveOnly:t?.interactiveOnly,depth:t?.depth,scope:t?.scope,raw:t?.raw},h),{backend:"xctest"})).nodes)?n.nodes:void 0,truncated:"boolean"==typeof n.truncated?n.truncated:void 0,quality:a(n.snapshotQuality),message:"string"==typeof n.message&&n.message.trim().length>0?n.message:void 0},d=o.nodes??[];if(0===d.length&&"simulator"===e.kind)throw new f("COMMAND_FAILED","XCTest snapshot returned 0 nodes on iOS simulator.");return{nodes:d,truncated:o.truncated??!1,backend:"xctest",...o.quality?{quality:o.quality}:{},...!o.quality&&o.message?{warnings:[o.message]}:{}}},back:async a=>{"tv"===e.target?await r(e,b("menu",t.appBundleId),h):await r(e,{command:"system"===a?"backSystem":"backInApp",appBundleId:t.appBundleId},h)},home:async()=>{"tv"===e.target?await r(e,b("home",t.appBundleId),h):await r(e,{command:"home",appBundleId:t.appBundleId},h)},rotate:async a=>{await r(e,{command:"rotate",orientation:a,appBundleId:t.appBundleId},h)},appSwitcher:async()=>{await r(e,{command:"appSwitcher",appBundleId:t.appBundleId},h)},readClipboard:()=>y(e),writeClipboard:a=>s(e,a),setSetting:(a,t,n,o)=>m(e,a,t,n,o),...I}}export{C as createAppleInteractor};
|