agent-device 0.17.0 → 0.17.2
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 +1 -1
- package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.17.0.apk → agent-device-android-multitouch-helper-0.17.2.apk} +0 -0
- package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.17.2.apk.sha256 +1 -0
- package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.17.0.manifest.json → agent-device-android-multitouch-helper-0.17.2.manifest.json} +4 -4
- package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.17.0.apk → agent-device-android-snapshot-helper-0.17.2.apk} +0 -0
- package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.17.2.apk.sha256 +1 -0
- package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.17.0.manifest.json → agent-device-android-snapshot-helper-0.17.2.manifest.json} +6 -6
- package/dist/src/123.js +1 -0
- package/dist/src/1352.js +1 -1
- package/dist/src/1534.js +1 -0
- package/dist/src/1620.js +1 -0
- package/dist/src/1644.js +2 -0
- package/dist/src/2284.js +1 -0
- package/dist/src/2403.js +3 -0
- package/dist/src/2415.js +28 -29
- package/dist/src/2474.js +1 -0
- package/dist/src/2672.js +1 -0
- package/dist/src/3393.js +1 -0
- package/dist/src/4778.js +1 -1
- package/dist/src/5898.js +1 -0
- package/dist/src/7556.js +1 -1
- package/dist/src/7847.js +1 -1
- package/dist/src/8173.js +27 -0
- package/dist/src/8407.js +1 -0
- package/dist/src/8699.js +1 -1
- package/dist/src/8806.js +3 -3
- package/dist/src/9010.js +1 -0
- package/dist/src/9238.js +3 -3
- package/dist/src/9471.js +1 -1
- package/dist/src/9542.js +3 -3
- package/dist/src/9616.js +1 -0
- package/dist/src/9673.js +1 -0
- package/dist/src/9974.js +1 -0
- package/dist/src/android-adb.d.ts +12 -6
- package/dist/src/android-adb.js +1 -1
- package/dist/src/android-snapshot-helper.d.ts +15 -7
- package/dist/src/android.js +1 -1
- package/dist/src/apple.js +1 -1
- package/dist/src/apps.js +2 -2
- package/dist/src/args.js +2 -2
- package/dist/src/batch.d.ts +16 -4
- package/dist/src/cli.js +18 -42
- package/dist/src/command-surface.js +1 -1
- package/dist/src/contracts.d.ts +28 -4
- package/dist/src/contracts.js +1 -1
- package/dist/src/find.js +1 -1
- package/dist/src/finders.d.ts +3 -1
- package/dist/src/generic.js +13 -11
- package/dist/src/index.d.ts +142 -73
- package/dist/src/index.js +1 -1
- package/dist/src/input-actions.js +1 -1
- package/dist/src/interaction.js +1 -1
- package/dist/src/internal/png-worker.d.ts +26 -0
- package/dist/src/internal/png-worker.js +1 -0
- package/dist/src/metro.d.ts +3 -1
- package/dist/src/react-native.js +1 -1
- package/dist/src/record-trace-recording.js +26 -0
- package/dist/src/record-trace.js +1 -26
- package/dist/src/remote-config.d.ts +33 -7
- package/dist/src/selector-runtime.js +1 -1
- package/dist/src/selectors.d.ts +3 -3
- package/dist/src/selectors.js +1 -1
- package/dist/src/server.js +2 -2
- package/dist/src/session.js +10 -11
- package/dist/src/snapshot.js +1 -1
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +6 -2
- package/package.json +7 -4
- package/server.json +2 -2
- package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.17.0.apk.sha256 +0 -1
- package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.17.0.apk.sha256 +0 -1
- package/dist/src/1998.js +0 -1
- package/dist/src/2805.js +0 -1
- package/dist/src/4057.js +0 -1
- package/dist/src/5792.js +0 -1
- package/dist/src/6085.js +0 -1
- package/dist/src/6232.js +0 -1
- package/dist/src/8020.js +0 -1
- package/dist/src/8502.js +0 -1
- package/dist/src/940.js +0 -1
- package/dist/src/9404.js +0 -1
- package/dist/src/9533.js +0 -1
- package/dist/src/command-metadata.js +0 -1
- /package/dist/src/{1393.js → 3675.js} +0 -0
- /package/dist/src/{5310.js → 695.js} +0 -0
package/dist/src/2474.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{defineStringEnum as e}from"./5898.js";let t={devices:"List available devices.",boot:"Boot or prepare a selected device without using CLI positional arguments.",shutdown:"Shutdown a selected simulator or emulator.",apps:"List installed apps.",session:"List active sessions or print daemon state directory.",open:"Open an app, deep link, URL, or platform surface.",prepare:"Prepare platform helper infrastructure.",close:"Close an app or end the active session.",install:"Install an app binary.",reinstall:"Reinstall an app binary.","install-from-source":"Install an app from a structured source.",push:"Deliver a push payload.","trigger-app-event":"Trigger an app-defined event.",snapshot:"Capture an accessibility snapshot.",screenshot:"Capture a screenshot.",diff:"Diff accessibility snapshots.",wait:"Wait for duration, text, ref, or selector.",alert:"Inspect or handle platform alerts.",appstate:"Show foreground app or activity.",back:"Navigate back.",home:"Go to the home screen.",rotate:"Rotate device orientation.","app-switcher":"Open the app switcher.",keyboard:"Inspect or dismiss the keyboard.",clipboard:"Read or write clipboard text.","react-native":"Run supported React Native app automation helpers.",replay:"Replay a recorded session.",test:"Run one or more replay scripts.",perf:"Show session performance metrics and frame health.",logs:"Manage session app logs.",network:"Show recent HTTP traffic.",record:"Start or stop screen recording.",trace:"Start or stop trace capture.",settings:"Change OS settings and app permissions.",metro:"Prepare Metro runtime or reload React Native apps.",click:"Click or tap a semantic UI target by ref, selector, or point.",press:"Press a semantic UI target by ref, selector, or point.",fill:"Fill text into a semantic UI target by ref, selector, or point.",longpress:"Long press by ref, selector, or point.",swipe:"Swipe between two points.",focus:"Focus input at coordinates.",type:"Type text in the focused field.",scroll:"Scroll in a direction or to an edge.",get:"Get element text or attributes.",is:"Assert UI state.",find:"Find an element and optionally act on it.",gesture:"Run a structured gesture.",batch:"Run multiple structured command steps in one daemon request."};function r(e){let r=t[e];if(!r)throw Error(`Missing command description for ${e}`);return r}function a(){return Object.entries(t).map(([e,t])=>({name:e,description:t}))}let s=["app","frontmost-app","desktop","menubar"],o=e(s,{normalize:e=>e.trim().toLowerCase(),message:e=>`Invalid surface: ${e}. Use ${s.join("|")}.`});function n(e){return o.parse(e)}export{s as SESSION_SURFACES,a as listCommandDescriptionMetadata,n as parseSessionSurface,r as requireCommandDescription};
|
package/dist/src/2672.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{withSuccessText as e,successText as a}from"./1534.js";import{defineStringEnum as t}from"./5898.js";function i(e){let a=e.appId??e.bundleId??e.packageName;return{session:e.session,appId:a,appBundleId:e.bundleId,package:e.packageName}}function n(e,a,t){return{deviceId:a,deviceName:t,..."android"===e?{serial:a}:"ios"===e?{udid:a}:{}}}function r(e,a={}){let t=a.includeAndroidSerial??!0;return{platform:e.platform,target:e.target,device:e.name,id:e.id,..."ios"===e.platform?{device_udid:e.ios?.udid??e.id,ios_simulator_device_set:e.ios?.simulatorSetPath??null}:{},..."android"===e.platform&&t?{serial:e.android?.serial??e.id}:{}}}function s(e){return{name:e.name,...e.sessionStateDir?{sessionStateDir:e.sessionStateDir}:{},...e.runnerLogPath?{runnerLogPath:e.runnerLogPath}:{},...r(e.device,{includeAndroidSerial:!1}),createdAt:e.createdAt}}function d(e){return{platform:e.platform,id:e.id,name:e.name,kind:e.kind,target:e.target,..."boolean"==typeof e.booted?{booted:e.booted}:{}}}function p(e){return e.bundleId??e.package??e.app}function o(a){return e({app:a.app,appPath:a.appPath,platform:a.platform,...a.appId?{appId:a.appId}:{},...a.bundleId?{bundleId:a.bundleId}:{},...a.package?{package:a.package}:{}},`Installed: ${p(a)}`)}function l(e){return e.appName??e.bundleId??e.packageName??e.launchTarget}function u(a){return e({launchTarget:a.launchTarget,...a.appName?{appName:a.appName}:{},...a.appId?{appId:a.appId}:{},...a.bundleId?{bundleId:a.bundleId}:{},...a.packageName?{package:a.packageName}:{},...a.installablePath?{installablePath:a.installablePath}:{},...a.archivePath?{archivePath:a.archivePath}:{},...a.materializationId?{materializationId:a.materializationId}:{},...a.materializationExpiresAt?{materializationExpiresAt:a.materializationExpiresAt}:{}},`Installed: ${l(a)}`)}function c(a){let t=a.appName??a.appBundleId??a.session;return e({session:a.session,...a.sessionStateDir?{sessionStateDir:a.sessionStateDir}:{},...a.runnerLogPath?{runnerLogPath:a.runnerLogPath}:{},...a.requestLogPath?{requestLogPath:a.requestLogPath}:{},...a.appName?{appName:a.appName}:{},...a.appBundleId?{appBundleId:a.appBundleId}:{},...a.startup?{startup:a.startup}:{},...a.runtime?{runtime:a.runtime}:{},...a.device?r(a.device):{}},t?`Opened: ${t}`:"Opened")}function m(e){return{session:e.session,...e.shutdown?{shutdown:e.shutdown}:{},...a(e.session?`Closed: ${e.session}`:"Closed")}}function I(e){return{nodes:e.nodes,truncated:e.truncated,...e.appName?{appName:e.appName}:{},...e.appBundleId?{appBundleId:e.appBundleId}:{},...e.visibility?{visibility:e.visibility}:{},...e.androidSnapshot?{androidSnapshot:e.androidSnapshot}:{},...e.warnings&&e.warnings.length>0?{warnings:e.warnings}:{},...e.unchanged?{unchanged:e.unchanged}:{}}}let g=["path","start","stop","doctor","mark","clear"],h=["metrics","frames"],f=["sample"],S=t(h),P=t(f),_="perf area must be metrics or frames",b="perf action must be sample",A=S.is,N=P.is;export{g as LOG_ACTION_VALUES,b as PERF_ACTION_ERROR_MESSAGE,f as PERF_ACTION_VALUES,_ as PERF_AREA_ERROR_MESSAGE,h as PERF_AREA_VALUES,i as buildAppIdentifiers,n as buildDeviceIdentifiers,N as isPerfAction,A as isPerfArea,p as resolveDeployResultTarget,l as resolveInstallFromSourceResultTarget,m as serializeCloseResult,o as serializeDeployResult,d as serializeDevice,u as serializeInstallFromSourceResult,c as serializeOpenResult,s as serializeSessionListEntry,I as serializeSnapshotResult};
|
package/dist/src/3393.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{splitSelectorFromArgs as e}from"./8407.js";function t(t){if(t[0]?.startsWith("@")){let e=i(t.slice(1));return{ref:t[0],...void 0===e?{}:{label:e}}}let r=e(t);return r?{selector:r.selectorExpression}:{x:Number(t[0]),y:Number(t[1])}}function r(t){let r=t[0];if(r?.startsWith("@")){let e=t.length>=3?t.slice(2).join(" "):t.slice(1).join(" ");return{kind:"ref",target:{ref:r,label:t.length>=3?i(t.slice(1,2)):void 0},text:e}}let n=e(t,{preferTrailingValue:!0});return n?{kind:"selector",target:{selector:n.selectorExpression},text:n.rest.join(" ")}:{kind:"point",target:{x:Number(t[0]),y:Number(t[1])},text:t.slice(2).join(" ")}}function i(e){return e.join(" ").trim()||void 0}export{r as readFillTargetFromPositionals,t as readInteractionTargetFromPositionals};
|
package/dist/src/4778.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function t(t){let e=`${t??""}`.toLowerCase();return e.includes("scroll")||e.includes("recyclerview")||e.includes("listview")||e.includes("gridview")||e.includes("collectionview")||"table"===e}function e(e){return!!t(e.type)||`${e.role??""} ${e.subrole??""}`.toLowerCase().includes("scroll")}function i(t){let e=1/0,i=1/0,n=-1/0,r=-1/0;for(let h of t)e=Math.min(e,h.x),i=Math.min(i,h.y),n=Math.max(n,h.x+h.width),r=Math.max(r,h.y+h.height);return{x:e,y:i,width:n-e,height:r-i}}function
|
|
1
|
+
function t(t){let e=`${t??""}`.toLowerCase();return e.includes("scroll")||e.includes("recyclerview")||e.includes("listview")||e.includes("gridview")||e.includes("collectionview")||"table"===e}function e(e){return!!t(e.type)||`${e.role??""} ${e.subrole??""}`.toLowerCase().includes("scroll")}function i(t){return t}function n(t){let e=1/0,i=1/0,n=-1/0,r=-1/0;for(let h of t)e=Math.min(e,h.x),i=Math.min(i,h.y),n=Math.max(n,h.x+h.width),r=Math.max(r,h.y+h.height);return{x:e,y:i,width:n-e,height:r-i}}function r(t,e){return{x:t.x-e,y:t.y-e,width:t.width+2*e,height:t.height+2*e}}function h(t,e){let i=Math.max(t.x,e.x),n=Math.max(t.y,e.y),r=Math.min(t.x+t.width,e.x+e.width),h=Math.min(t.y+t.height,e.y+e.height);return r<=i||h<=n?0:(r-i)*(h-n)}function c(t){return{x:t.x+t.width/2,y:t.y+t.height/2}}function l(t,e){return(t.x-e.x)**2+(t.y-e.y)**2}function o(t,e,i){return Math.min(Math.max(t,e),i)}export{o as clamp,r as expandRect,h as intersectArea,e as isScrollableNodeLike,t as isScrollableType,i as normalizedRect,c as rectCenter,l as squaredDistance,n as unionRects};
|
package/dist/src/5898.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{AppError as e}from"./9152.js";let t={alert:"alert",appState:"appstate",appSwitcher:"app-switcher",apps:"apps",back:"back",batch:"batch",boot:"boot",click:"click",close:"close",clipboard:"clipboard",devices:"devices",diff:"diff",fill:"fill",find:"find",focus:"focus",gesture:"gesture",get:"get",home:"home",install:"install",installFromSource:"install-from-source",is:"is",keyboard:"keyboard",logs:"logs",longPress:"longpress",network:"network",open:"open",perf:"perf",prepare:"prepare",press:"press",push:"push",record:"record",reactNative:"react-native",reinstall:"reinstall",replay:"replay",rotate:"rotate",scroll:"scroll",screenshot:"screenshot",settings:"settings",shutdown:"shutdown",snapshot:"snapshot",swipe:"swipe",test:"test",trace:"trace",triggerAppEvent:"trigger-app-event",type:"type",wait:"wait"},s={installSource:"install_source",leaseAllocate:"lease_allocate",leaseHeartbeat:"lease_heartbeat",leaseRelease:"lease_release",releaseMaterializedPaths:"release_materialized_paths",runtime:"runtime",sessionList:"session_list"},r={auth:"auth",connect:"connect",connection:"connection",disconnect:"disconnect",mcp:"mcp",metro:"metro",reactDevtools:"react-devtools",session:"session"},o=["pan","fling","swipe","pinch","rotate","transform"],a=`gesture requires one of: ${o.join(", ")}`,n=[t.devices,t.boot,t.shutdown,t.apps,t.open,t.close,t.install,t.reinstall,t.installFromSource,t.push,t.triggerAppEvent,t.snapshot,t.screenshot,t.diff,t.wait,t.alert,t.settings,t.click,t.press,t.longPress,t.swipe,t.focus,t.type,t.fill,t.scroll,t.get,t.gesture,t.is,t.find,t.perf,t.logs,t.network,t.record,t.trace,t.test,t.appState,t.back,t.home,t.rotate,t.appSwitcher,t.keyboard,t.clipboard,t.reactNative],i=c(r.auth,r.connect,r.connection,r.disconnect,r.mcp,r.reactDevtools,t.prepare);function c(...e){return new Set(e)}function l(){return[...Object.values(t),...Object.values(r)].sort()}function p(e){return Object.values(t).includes(e)||e===r.metro||e===r.session}function u(){return l().filter(e=>!i.has(e))}function d(e,t){return e.includes(t)}function m(t,s,r={}){let o=void 0===s?void 0:r.normalize?.(s)??s;if(void 0!==o&&d(t,o))return o;throw new e("INVALID_ARGS",("function"==typeof r.message?r.message(s):r.message)??`Invalid value: ${s}. Use ${t.join("|")}.`)}function f(e,t={}){return{values:e,is:t=>d(e,t),parse:s=>m(e,s,t)}}c(r.auth,r.connect,r.connection,r.disconnect,r.mcp,r.metro,r.reactDevtools,r.session,t.appState,t.prepare,t.batch,t.devices,t.gesture,t.replay,t.test,t.trace);export{n as BATCH_COMMAND_NAMES,o as GESTURE_KINDS,a as GESTURE_SUBCOMMAND_ERROR,s as INTERNAL_COMMANDS,t as PUBLIC_COMMANDS,f as defineStringEnum,p as isClientBackedCliCommandName,d as isStringMember,l as listCliCommandNames,u as listMcpExposedCommandNames,m as parseStringMember};
|
package/dist/src/7556.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AppError as e}from"./9152.js";function
|
|
1
|
+
import{AppError as e}from"./9152.js";let t=["any","text","label","value","role","id"],r=["text","label","value","role","id"];function i(e,t,r,u={}){let a=l(r);if(!a)return{matches:[],score:0};let c=0,s=[];for(let r of e){if(u.requireRect&&!r.rect)continue;let e=function(e,t,r){switch(t){case"role":return function(e,t){let r=o(e??"");return r?r===t?2:+!!r.includes(t):0}(e.type,r);case"label":return n(e.label,r);case"value":return n(e.value,r);case"id":return n(e.identifier,r);default:return Math.max(n(e.label,r),n(e.value,r),n(e.identifier,r))}}(r,t,a);if(!(e<=0)){if(e>c){c=e,s.length=0,s.push(r);continue}e===c&&s.push(r)}}return{matches:s,score:c}}function n(e,t){let r=l(e??"");return r?r===t?2:+!!r.includes(t):0}function l(e){return e.trim().toLowerCase().replace(/\s+/g," ")}function o(e){let t=e.trim();return t?t=(t.split(".").pop()??t).replace(/XCUIElementType/gi,"").toLowerCase():""}function u(t){let i="any",n=0;r.includes(t[0])&&(i=t[0],n=1);let l=t[n]??"",o=t.slice(n+1);if(0===o.length)return{locator:i,query:l,action:"click"};let u=o[0]?.toLowerCase();if("get"===u){let t=o[1]?.toLowerCase();if("text"===t)return{locator:i,query:l,action:"get_text"};if("attrs"===t)return{locator:i,query:l,action:"get_attrs"};throw new e("INVALID_ARGS","find get only supports text or attrs")}if("wait"===u)return{locator:i,query:l,action:"wait",timeoutMs:function(e){if(!e)return null;let t=Number(e);return Number.isFinite(t)?t:null}(o[1])??void 0};if("exists"===u)return{locator:i,query:l,action:"exists"};if("click"===u)return{locator:i,query:l,action:"click"};if("focus"===u)return{locator:i,query:l,action:"focus"};if("fill"===u)return{locator:i,query:l,action:"fill",value:o.slice(1).join(" ")};if("type"===u)return{locator:i,query:l,action:"type",value:o.slice(1).join(" ")};throw new e("INVALID_ARGS",`Unsupported find action: ${o[0]}`)}export{t as FIND_LOCATORS,i as findBestMatchesByLocator,o as normalizeRole,l as normalizeText,u as parseFindArgs};
|
package/dist/src/7847.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./
|
|
1
|
+
import{splitSelectorFromArgs as e}from"./8407.js";import{normalizeText as t}from"./7556.js";function r(t){let r=t[0]??"",n=e(t.slice(1),{preferTrailingValue:"text"===r});return{predicate:r,split:n}}function n(e){var t;let r=u(e.label),n=u(e.value),i=u(e.identifier),l=(t=i)&&!/^[\w.]+:id\/[\w.-]+$/i.test(t)&&!/^_?NS:\d+$/i.test(t)?i:"";return o(e.type??"")?n||r||l:r||n||l}function i(e){let t=e.replace(/\s+/g," ").trim();return t.length<=48?t:`${t.slice(0,45)}...`}function l(e,t){var r;let i=n(e),l=function(e,t){if("text-view"===t||"text-field"===t||"search"===t)return!0;let r=a(e.type??""),n=`${e.role??""} ${e.subrole??""}`.toLowerCase();return r.includes("textview")||r.includes("textarea")||r.includes("textfield")||r.includes("securetextfield")||r.includes("searchfield")||r.includes("edittext")||n.includes("text area")||n.includes("text field")}(e,t);return{text:i,isLargeSurface:l,shouldSummarize:l&&!!(r=i)&&(r.length>80||/[\r\n]/.test(r))}}function u(e){return"string"==typeof e?e.trim():""}function a(e){let t=e.trim().replace(/XCUIElementType/gi,"").replace(/^AX/,"").toLowerCase(),r=Math.max(t.lastIndexOf("."),t.lastIndexOf("/"));return -1!==r&&(t=t.slice(r+1)),t}function o(e){let t=a(e);return t.includes("textfield")||t.includes("securetextfield")||t.includes("searchfield")||t.includes("edittext")||t.includes("textview")||t.includes("textarea")}function c(e,t){let r=t.toLowerCase();return e.find(e=>{let t=(e.label??"").toLowerCase(),n=(e.value??"").toLowerCase(),i=(e.identifier??"").toLowerCase();return t.includes(r)||n.includes(r)||i.includes(r)})??null}function s(e,t){let r=[e.label,e.value,e.identifier].map(e=>"string"==typeof e?e.trim():"").find(e=>e&&e.length>0);return r&&d(r)?r:function(e,t){if(!e.rect)return;let r=e.rect.y+e.rect.height/2,n=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-r);(!n||i<n.distance)&&(n={label:t,distance:i})}return n?.label}(e,t)??(r&&d(r)?r:void 0)}function d(e){let t=e.trim();return!(!t||/^(true|false)$/i.test(t)||/^\d+$/.test(t))}function f(e){let t=[],r=[];for(let n of e){let e=n.depth??0;for(;t.length>0&&e<=t[t.length-1];)t.pop();let i=a(n.type??""),l=[n.label,n.value,n.identifier].map(e=>"string"==typeof e?e.trim():"").find(e=>e&&e.length>0),u=!!l&&d(l);if(("group"===i||"ioscontentgroup"===i)&&!u){t.push(e);continue}let o=Math.max(0,e-t.length);r.push({...n,depth:o})}return r}function h(e,t){let r=a(e);return!r||("android"===t?r.includes("edittext")||r.includes("autocompletetextview"):r.includes("textfield")||r.includes("securetextfield")||r.includes("searchfield")||r.includes("textview")||r.includes("textarea")||"search"===r)}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,r,n){let i=t,l=new Set;for(;"number"==typeof i.parentIndex&&!l.has(i.index)&&(l.add(i.index),i=r.get(i.parentIndex)??e[i.parentIndex]);){let e=n(i);if(null!==e)return e}return null}function m(e,t,r,n){return!!x(e,t,n,e=>e===r||e.index===r.index?e:null)}function g(e,t,r){let n=b(e);return x(e,t,n,e=>r(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 S(e){return n(e)}function w(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,r){return t.terms.every(t=>(function(e,t,r){switch(t.key){case"id":return N(e.identifier,String(t.value));case"role":return N(a(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 w(e)===!!t.value;case"hidden":return!w(e)==!!t.value;case"editable":return $(e,r)===!!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,r))}function N(e,r){return t(e??"")===t(r)}function C(e,t,r){let n=r.requireRect??!1,i=r.requireUnique??!0,l=[];for(let[u,a]of t.selectors.entries()){let t=function(e,t,r,n){let i=0,l=null,u=null,a=!1;for(let o of e){if(n&&!o.rect||!y(o,t,r))continue;if(i+=1,l??=o,!u){u=o;continue}let e=function(e,t){let r=e.depth??0,n=t.depth??0;if(r!==n)return r>n?1:-1;let i=_(e),l=_(t);return i!==l?i<l?1:-1:0}(o,u);e>0?(u=o,a=!1):0===e&&(a=!0)}return{count:i,firstNode:l,disambiguated:a?null:u}}(e,a,r.platform,n);if(l.push({selector:a.raw,matches:t.count}),0!==t.count&&t.firstNode){if(i&&1!==t.count){if(!r.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,r){let n=r.requireRect??!1,i=[];for(let[l,u]of t.selectors.entries()){let t=function(e,t,r,n){let i=0;for(let l of e)(!n||l.rect)&&y(l,t,r)&&(i+=1);return i}(e,u,r.platform,n);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,r){if(0===t.length)return`Selector did not match: ${e.raw}`;let n=t.map(e=>`${e.selector} -> ${e.matches}`).join(", ");return r.unique??!0?`Selector did not resolve uniquely (${n})`:`Selector did not match (${n})`}function _(e){return e.rect?e.rect.width*e.rect.height:1/0}function A(e,t,r={}){let n=[],i=a(e.type??""),l=R(e.identifier),u=R(e.label),o=R(e.value),c=R(v(e)),s="fill"===r.action;l&&n.push(`id=${L(l)}`),i&&u&&n.push(s?`role=${L(i)} label=${L(u)} editable=true`:`role=${L(i)} label=${L(u)}`),u&&n.push(s?`label=${L(u)} editable=true`:`label=${L(u)}`),o&&n.push(s?`value=${L(o)} editable=true`:`value=${L(o)}`),c&&c!==u&&c!==o&&n.push(s?`text=${L(c)} editable=true`:`text=${L(c)}`),i&&s&&!n.some(e=>e.includes("editable=true"))&&n.push(`role=${L(i)} editable=true`);let d=Array.from(new Set(n));return 0===d.length&&i&&d.push(s?`role=${L(i)} editable=true`:`role=${L(i)}`),0===d.length&&w(e)&&d.push("visible=true"),d}function L(e){return JSON.stringify(e)}function R(e){if(!e)return null;let t=e.trim();return t||null}export{A as buildSelectorChainForNode,b as buildSnapshotNodeByIndex,i as buildTextPreview,l as describeTextSurface,S as extractNodeReadText,v as extractNodeText,n as extractReadableText,g as findNearestAncestor,p as findNearestHittableAncestor,c as findNodeByLabel,T as findSelectorChainMatch,x as findSnapshotAncestor,I as formatSelectorFailure,m as isDescendantOfSnapshotNode,h as isFillableType,$ as isNodeEditable,w as isNodeVisible,y as matchesSelector,a as normalizeType,o as prefersValueForReadableText,f as pruneGroupNodes,s as resolveRefLabel,C as resolveSelectorChain,r as splitIsSelectorArgs,u as trimText};
|
package/dist/src/8173.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import e from"node:path";import{styleText as t}from"node:util";import{buildMobileSnapshotPresentation as n,CLICK_BUTTONS as r,SCROLL_DIRECTIONS as i,formatSnapshotLine as o,SCROLL_INPUT_DIRECTIONS as a,SWIPE_PRESETS as s,displayNodeLabel as u,SWIPE_PATTERNS as l,buildSnapshotDisplayLines as d}from"./1620.js";import{normalizeError as p,AppError as c}from"./9152.js";import{PERF_AREA_VALUES as f,serializeOpenResult as h,serializeSessionListEntry as m,serializeDeployResult as g,serializeSnapshotResult as $,LOG_ACTION_VALUES as y,serializeCloseResult as x,PERF_ACTION_VALUES as v,serializeInstallFromSourceResult as b,serializeDevice as w}from"./2672.js";import{DEVICE_ROTATIONS as M,readCommandMessage as C}from"./1534.js";import{listMcpExposedCommandNames as S,BATCH_COMMAND_NAMES as k,GESTURE_KINDS as P}from"./5898.js";import{readInputRecord as A,selectorSnapshotFields as I,elementTargetField as N,stringSchema as j,stringArrayField as _,jsonSchemaField as O,booleanSchema as B,integerSchema as F,integerField as R,customField as T,assertAllowedKeys as D,booleanField as L,enumField as H,requiredEnum as K,looseObjectField as E,readPoint as U,requiredField as z,pointField as W,readFieldInput as J,stringField as q,interactionTargetField as G,fieldsInputSchema as V,requiredNumber as X,readCommonInput as Y,repeatedFields as Q,looseObjectSchema as Z,numberField as ee,optionalInteger as et}from"./9974.js";import{NETWORK_INCLUDE_MODES as en}from"./9616.js";import{requireCommandDescription as er,SESSION_SURFACES as ei}from"./2474.js";import{FIND_LOCATORS as eo}from"./7556.js";function ea(e){return e.width>0&&e.height>0}function es(e,t){return!!e&&!!t&&e.x>=t.x-2&&e.y>=t.y-2&&e.x+e.width<=t.x+t.width+2&&e.y+e.height<=t.y+t.height+2}function eu(e){return"number"!=typeof e.parentIndex}function el(e){let t=(e.type??"").toLowerCase(),n=(e.identifier??"").trim().toLowerCase();return t.includes("edittext")||t.includes("textfield")||"composer"===n}function ed(e){let t=(e.type??"").toLowerCase();return t.includes("scroll")||t.includes("list")||t.includes("recyclerview")}function ep(e){var t;let n=u(e);if(!n||n!==e.identifier?.trim()||(t=n,!/^[\w.]+:id\/[\w.-]+$/i.test(t)))return n;let r=(e.type??"").toLowerCase();return r.includes("view")||r.includes("layout")||r.includes("image")||r.includes("list")||r.includes("recyclerview")||r.includes("collection")?"":n}function ec(e){let t=e.trim().replace(/\s+/g," ").toLowerCase();return!t||/^(true|false|\d+)$/.test(t)?null:t}function ef(e,t){let n=[],r=[t];for(;r.length>0;){let t=r.pop();for(let i of e)i.parentIndex===t&&(n.push(i),r.push(i.index))}return n}function eh(e,t,n){let r=[t];for(;r.length>0;){let t=r.pop();if(!n.has(t))for(let i of(n.add(t),e))i.parentIndex!==t||n.has(i.index)||r.push(i.index)}}let em=["button","switch","checkbox","radio"],eg=["button","image","textview","view"];function e$(e){if(!0===e.hittable||el(e))return!1;let t=(e.type??"").toLowerCase();return t.includes("text")||t.includes("image")||t.includes("icon")}function ey(e){if(!e.rect||!ea(e.rect)||eu(e)||el(e))return!1;let t=(e.type??"").toLowerCase();return"text"===t||eb(t,eg)}function ex(e,t){let n=ev(e);return ev(t)>n?t:e}function ev(e){let t=(e.type??"").toLowerCase(),n=0;return eb(t,em)?n+=100:t.includes("image")?n+=30:t.includes("textview")||"text"===t?n+=20:t.includes("view")&&(n+=10),!0===e.hittable&&(n+=20),!1!==e.enabled&&(n+=5),n}function eb(e,t){return t.some(t=>e.includes(t))}function ew(e){process.stdout.write(`${JSON.stringify(e,null,2)}
|
|
2
|
+
`)}function eM(e,t={}){let n=e instanceof c?p(e):e;process.stderr.write(`Error (${n.code}): ${n.message}
|
|
3
|
+
`),n.hint&&process.stderr.write(`Hint: ${n.hint}
|
|
4
|
+
`),n.diagnosticId&&process.stderr.write(`Diagnostic ID: ${n.diagnosticId}
|
|
5
|
+
`),n.logPath&&process.stderr.write(`Diagnostics Log: ${n.logPath}
|
|
6
|
+
`),t.showDetails&&n.details&&process.stderr.write(`${JSON.stringify(n.details,null,2)}
|
|
7
|
+
`)}function eC(e){return e&&e.summaryLines.length>0?`
|
|
8
|
+
${e.summaryLines.join("\n")}`:""}function eS(e){var n;let r=!0===e.baselineInitialized,i=e.summary??{},o=e_(i.additions),a=e_(i.removals),s=e_(i.unchanged),u=eO(),l=eF(e),d=l.length>0?`${l.join("\n")}
|
|
9
|
+
`:"";if(r)return`${d}Baseline initialized (${s} lines).
|
|
10
|
+
`;let p=(function(e){if(0===e.length)return e;let t=e.map((e,t)=>({index:t,kind:e.kind})).filter(e=>"added"===e.kind||"removed"===e.kind).map(e=>e.index);if(0===t.length)return e;let n=Array(e.length).fill(!1);for(let r of t){let t=Math.max(0,r-1),i=Math.min(e.length-1,r+1);for(let e=t;e<=i;e+=1)n[e]=!0}return e.filter((e,t)=>n[t])})(Array.isArray(e.lines)?e.lines:[]).map(e=>{let n="string"==typeof e.text?e.text:"";if("added"===e.kind){let e=n.startsWith(" ")?`+${n}`:`+ ${n}`;return u?t("green",e):e}if("removed"===e.kind){let e=n.startsWith(" ")?`-${n}`:`- ${n}`;return u?t("red",e):e}return u?t("dim",n):n}),c=p.length>0?`${p.join("\n")}
|
|
11
|
+
`:"";if(!u)return`${d}${c}${o} additions, ${a} removals, ${s} unchanged
|
|
12
|
+
`;let f=`${(n=String(o),t("green",n))} additions, ${t("red",String(a))} removals, ${t("dim",String(s))} unchanged`;return`${d}${c}${f}
|
|
13
|
+
`}function ek(e){var n,r,i,o;let a,s,u,l,d=eO(),p=!0===e.match,c=e.dimensionMismatch,f=[];return f.push(...function(e,n){if(!0===e.match){let e=n?function(e,n){return t(n,e)}("✓","green"):"✓";return[`${e} Screenshots match.`]}let r=e.dimensionMismatch,i=n?function(e,n){return t(n,e)}("✗","red"):"✗";if(r){let e=r.expected,t=r.actual;return[`${i} Screenshots have different dimensions: expected ${e?.width}x${e?.height}, got ${t?.width}x${t?.height}`]}let o=e_(e.differentPixels),a=e_(e.mismatchPercentage),s=0===a&&o>0?"<0.01":String(a),u=`${s}% pixels differ`;return[`${i} ${n?function(e,n){return t(n,e)}(u,"red"):u}`]}(e,d)),f.push(...function(e,n,r){if(n)return[];let i=[];if(e.diffPath){let n=ej(e.diffPath),o=r?function(e,n){return t(n,e)}("Diff image:","dim"):"Diff image:",a=r?function(e,n){return t(n,e)}(n,"green"):n;i.push(` ${o} ${a}`)}if(e.currentOverlayPath){let n=ej(e.currentOverlayPath),o=r?function(e,n){return t(n,e)}("Current overlay:","dim"):"Current overlay:",a=r?function(e,n){return t(n,e)}(n,"green"):n,s=e_(e.currentOverlayRefCount),u=s>0?` (${s} refs)`:"";i.push(` ${o} ${a}${u}`)}return i}(e,p,d)),p||c||(f.push(...(n=e,r=d,a=e_(n.differentPixels),s=e_(n.totalPixels),u=r?function(e,n){return t(n,e)}(String(a),"red"):String(a),[` ${u} different / ${s} total pixels`])),f.push(...(i=e,o=d,0===(l=function(e){let t=[];for(let n of(e.ocr?.movementClusters??[]).slice(0,2))t.push(`text movement cluster: ${function(e){let t=e.slice(0,4).map(e=>JSON.stringify(e)),n=e.length>t.length?` +${e.length-t.length} more`:"";return`${t.join(", ")}${n}`}(n.texts)} dx=${eN(n.xRange)}px dy=${eN(n.yRange)}px`);let n=(e.nonTextDeltas??[]).filter(e=>["icon","toggle","chevron"].includes(e.likelyKind)).slice(0,3);n.length>0&&t.push(`non-text controls: ${n.map(eI).join("; ")}`);let r=(e.nonTextDeltas??[]).filter(e=>"separator"===e.likelyKind).slice(0,2);return r.length>0&&t.push(`non-text boundaries: ${r.map(eI).join("; ")}`),t.slice(0,6)}(i)).length?[]:[` ${eB("Hints:",o)}`,...l.map(e=>` - ${e}`)])),f.push(...function(e,t){let n=Array.isArray(e.regions)?e.regions:[];if(0===n.length)return[];let r=[` ${eB("Changed regions:",t)}`];for(let e of n.slice(0,5))r.push(...function(e){let t=0===e.shareOfDiffPercentage&&e.differentPixels>0?"<0.01":String(e.shareOfDiffPercentage),n=e.rect,r=[` ${e.index}. ${e.location} x=${n.x} y=${n.y} ${n.width}x${n.height}, ${t}% of diff, change=${e.dominantChange}`],i=function(e){let t=[e.size?`size=${e.size}`:null,e.shape?`shape=${e.shape}`:null,"number"==typeof e.densityPercentage?`density=${e.densityPercentage}%`:null,e.averageBaselineColorHex&&e.averageCurrentColorHex?`avgColor=${e.averageBaselineColorHex}->${e.averageCurrentColorHex}`:null,"number"==typeof e.baselineLuminance&&"number"==typeof e.currentLuminance?`luminance=${e.baselineLuminance}->${e.currentLuminance}`:null].filter(e=>null!==e);return t.length>0?t.join(" "):null}(e);i&&r.push(` ${i}`);let o=e.currentOverlayMatches?.[0];if(o){let e=o.label?` "${o.label}"`:"";r.push(` overlaps @${o.ref}${e}, ${o.regionCoveragePercentage}% of region`)}return r}(e));return r}(e,d)),f.push(...function(e,t){let n=e.ocr?.matches??[];if(0===n.length)return[];let r=n.slice(0,8),i=[` ${eB(`OCR text deltas (${e.ocr?.provider}; baselineBlocks=${e.ocr?.baselineBlocks} currentBlocks=${e.ocr?.currentBlocks}; showing ${r.length}/${n.length}; px):`,t)}`,` ${eB("item | text | movePx | sizeDeltaPx | bboxBaseline | bboxCurrent | confidence | issueHint",t)}`];for(let[e,t]of r.entries()){let n=t.delta;i.push(` ${e+1} | ${JSON.stringify(t.text)} | ${eA(n.x)},${eA(n.y)} | ${eA(n.width)},${eA(n.height)} | ${eP(t.baselineRect)} | ${eP(t.currentRect)} | ${t.confidence} | ${t.possibleTextMetricMismatch?"ocr-bbox-size-change":"-"}`)}return i}(e,d)),f.push(...function(e,t){let n=e.nonTextDeltas??[];if(0===n.length)return[];let r=n.slice(0,8),i=[` ${eB(`Non-text visual deltas (showing ${r.length}/${n.length}; px):`,t)}`,` ${eB("item | region | slot | kind | bboxCurrent | nearestText",t)}`];for(let e of r)i.push(` ${e.index} | ${e.regionIndex?`r${e.regionIndex}`:"-"} | ${e.slot} | ${e.likelyKind} | ${eP(e.rect)} | ${e.nearestText?JSON.stringify(e.nearestText):"-"}`);return i}(e,d))),`${f.join("\n")}
|
|
14
|
+
`}function eP(e){return`x=${e.x},y=${e.y},w=${e.width},h=${e.height}`}function eA(e){return e>0?`+${e}`:String(e)}function eI(e){let t=e.nearestText?` near ${JSON.stringify(e.nearestText)}`:"",n=e.regionIndex?` r${e.regionIndex}`:"";return`${e.likelyKind}${t}${n}`}function eN(e){return e.min===e.max?eA(e.min):`${eA(e.min)}..${eA(e.max)}`}function ej(t){let n=process.cwd(),r=e.relative(n,t);return""!==r&&(r.startsWith("..")||e.isAbsolute(r))?t:""===r?".":`.${e.sep}${r}`}function e_(e){return"number"==typeof e&&Number.isFinite(e)?e:0}function eO(){let e=process.env.FORCE_COLOR;return"string"==typeof e?"0"!==e:"string"!=typeof process.env.NO_COLOR&&!!process.stdout.isTTY}function eB(e,n){return n?t("dim",e):e}function eF(e){let t=e.warnings;return Array.isArray(t)?t.filter(e=>"string"==typeof e&&e.length>0):[]}function eR(e,t){var n;let r="scroll-area"===(n=e.type)||"list"===n||"collection"===n||"table"===n?n:null;if(!r)return[];let i=[];if(e.node.hiddenContentAbove&&"below"!==t&&i.push(`[content above ${r} hidden]`),e.node.hiddenContentBelow&&"above"!==t&&i.push(`[content below ${r} hidden]`),0===i.length)return[];let o=" ".repeat(e.depth+1);return i.map(e=>`${o}${e}`)}function eT(e){return eL(g(e))}function eD(e){let t=e.ref??"",n=e.x,r=e.y;return t&&"number"==typeof n&&"number"==typeof r?{data:e,text:`Tapped @${t} (${n}, ${r})`}:eL(e)}function eL(e){return{data:e,text:C(e)}}function eH(e){let t=e.kind?` ${e.kind}`:"",n=e.target?` target=${e.target}`:"",r="boolean"==typeof e.booted?` booted=${e.booted}`:"";return`${e.name} (${e.platform}${t}${n})${r}`}function eK(e,t,n){"string"==typeof n&&e.push(` ${t}: ${n}`)}function eE(e,t){return t.map(t=>void 0!==e[t]&&null!==e[t]?`${t}=${e[t]}`:"").filter(Boolean).join(" ")||void 0}function eU(e){if(!Array.isArray(e))return;let t=e.filter(e=>"string"==typeof e&&e.length>0);return t.length>0?t.join("\n"):void 0}function ez(e){return e.filter(e=>!!e).join("\n")||void 0}function eW(e,t){return e?`Performance: ${e}`:`Frame health: unavailable - ${t}`}function eJ(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:void 0}function eq(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function eG(e){return`${Number.isInteger(e)?e:e.toFixed(1)}%`}function eV(e){let t=Math.max(0,Math.round(e));if(t<1e3)return`${t}ms`;let n=Math.round(t/1e3);if(n<60)return`${n}s`;let r=Math.floor(n/60),i=n%60;return i>0?`${r}m ${i}s`:`${r}m`}function eX(e){return({result:t})=>e(t)}let eY=eX(function(e){return eL(e)}),eQ={boot:eX(function(e){let t=e.platform??"unknown",n=e.device??e.id??"unknown";return{data:e,text:`Boot ready: ${n} (${t})`}}),shutdown:eX(function(e){let t=e.platform??"unknown",n=e.device??e.id??"unknown",r=e.shutdown,i=!!r&&"object"==typeof r&&"success"in r&&!0===r.success;return{data:e,text:`${i?"Shutdown":"Shutdown failed"}: ${n} (${t})`}}),click:eX(eD),press:eX(eD),batch:eX(function(e){let t="number"==typeof e.total?e.total:0,n="number"==typeof e.executed?e.executed:0,r="number"==typeof e.totalDurationMs?e.totalDurationMs:void 0,i=[`Batch completed: ${n}/${t} steps${void 0!==r?` in ${r}ms`:""}`];for(let t of Array.isArray(e.results)?e.results:[]){let e=function(e){let t=eJ(e);if(!t)return;let n="number"==typeof t.step?t.step:void 0,r="string"==typeof t.command?t.command:"step",i=!1!==t.ok,o=function(e,t,n){var r;return t?C(eJ(e.data))??n:(r=eJ(e.error),("string"==typeof r?.message&&r.message.length>0?r.message:null)??n)}(t,i,r),a=void 0!==n?`${n}. `:"- ",s="number"==typeof t.durationMs?t.durationMs:void 0,u=void 0!==s?` (${s}ms)`:"";return`${a}${i?"OK":"FAILED"} ${o}${u}`}(t);e&&i.push(e)}return{data:e,text:i.join("\n")}}),devices:eX(function(e){return{data:{devices:e.map(w)},text:e.map(eH).join("\n")}}),apps:({input:e,result:t})=>{var n;return{data:{apps:(n={result:t,appsFilter:e.appsFilter}).result},stderr:"all"===n.appsFilter?"Showing all apps, including system apps.\n":"Showing user-installed apps. Use --all to include system apps.\n",text:n.result.length>0?n.result.join("\n"):"all"===n.appsFilter?"No apps found.":"No user-installed apps found."}},session:eX(function(e){let t={sessions:e.sessions.map(m)};return{data:t,text:JSON.stringify(t,null,2)}}),open:eX(function(e){let t=h(e),n=[C(t)].filter(e=>!!e);return"string"==typeof t.sessionStateDir&&n.push(`Session state: ${t.sessionStateDir}`),{data:t,text:n.join("\n")||null}}),close:eX(function(e){return eL(x(e))}),install:eX(eT),reinstall:eX(eT),"install-from-source":eX(function(e){return eL(b(e))}),snapshot:({input:e,result:t})=>{var r;let i;return{data:i=$((r={result:t,raw:e.raw,interactiveOnly:e.interactiveOnly,scope:e.scope,depth:e.depth}).result),jsonData:function(e){let{unchanged:t,...n}=e;return n}(i),text:function(e,t={}){var r,i,a,s;let l,p,c,f,h,m=e.nodes,g=Array.isArray(m)?m:[],$="string"==typeof e.backend?e.backend:void 0,y=function(e,t,n){let r;if(n.raw||!((r=e.androidSnapshot)&&"object"==typeof r&&"android-helper"===r.backend))return{nodes:t,filteredCount:0};let i=function(e){var t,n;if(0===e.length)return e;let r=new Set,i=new Map,o=new Map(e.map(e=>[e.index,e]));(function(e,t){for(let n of e)!n.rect||ea(n.rect)||eu(n)||eh(e,n.index,t)})(e,r),function(e,t,n,r){for(let i of e){if(n.has(i.index)||i.rect||eu(i))continue;let o=function(e,t,n){let r=e;for(;"number"==typeof r.parentIndex;){let e=t.get(r.parentIndex);if(!e)break;if(n(e))return e;r=e}return null}(i,t,ed);o&&function(e,t,n){if(!n)return;let r=e.get(t.index)??t;e.set(t.index,{...r,hiddenContentAbove:!0===r.hiddenContentAbove||"above"===n||void 0,hiddenContentBelow:!0===r.hiddenContentBelow||"below"===n||void 0})}(r,o,function(e,t){let n=t.filter(t=>t.parentIndex===e.parentIndex&&t.rect&&ea(t.rect)).map(e=>e.index);return 0===n.length?null:e.index<Math.min(...n)?"above":e.index>Math.max(...n)?"below":null}(i,e)),eh(e,i.index,n)}}(e,o,r,i);for(let n of e){if(r.has(n.index)||!(!0===(t=n).hittable&&!el(t)&&t.rect&&ea(t.rect)&&0===ep(t).trim().length))continue;let o=function(e,t,n){let r=[],i=[],o=new Set;for(let a of e){if(n.has(a.index)||!e$(a)||!es(a.rect,t.rect))continue;let e=ep(a).trim().replace(/\s+/g," "),s=ec(e);i.push(a.index),!e||!s||o.has(s)||(o.add(s),r.push(e))}return{label:r.join(", "),removableIndexes:i}}(ef(e,n.index),n,r);if(o.label)for(let t of(i.set(n.index,{...n,...i.get(n.index),label:o.label}),o.removableIndexes))eh(e,t,r)}for(let t of e){if(r.has(t.index)||!(!0===(n=t).hittable&&!el(n)&&n.rect&&ea(n.rect)&&ec(ep(n))))continue;let i=ec(ep(t));if(!i)continue;let o=ef(e,t.index).filter(e=>!r.has(e.index)&&function(e,t,n){if(!ey(t)||!es(t.rect,e.rect))return!1;let r=ec(ep(t));return!!(r&&n!==r&&n.includes(r))}(t,e,i));for(let t of o.filter(e$))eh(e,t.index,r);let a=o.filter(e=>!e$(e)),s=new Set(a.map(e=>ec(ep(e))).filter(e=>!!e));if(!(a.length<2)&&!(s.size<2))for(let t of a)eh(e,t.index,r)}let a=new Map;for(let t of e){if(r.has(t.index)||!ey(t))continue;let n=ec(ep(t));if(!n)continue;let o=a.get(n);if(o&&function(e,t,n){var r,i,o,a;return!n.has(e.index)&&(r=e.rect,i=t.rect,!r||!i||Math.abs(r.y+r.height/2-(i.y+i.height/2))<=Math.max(r.height,i.height,1))&&(o=e,a=t,(o.parentIndex===a.parentIndex?3>=Math.abs(o.index-a.index):o.parentIndex!==a.index&&a.parentIndex!==o.index&&1>=Math.abs((o.depth??0)-(a.depth??0))&&2>=Math.abs(o.index-a.index))||function(e,t){let n=e.parentIndex===t.index?t:t.parentIndex===e.index?e:null,r=n?.index===e.index?t:n?.index===t.index?e:null;return!!n&&!!r&&ex(n,r).index===n.index}(e,t))}(o,t,r)){let s=function(e,t,n,r,i){var o,a,s;let u=ex(t,n),l=u.index===t.index?n:t,d=(l.type??"").toLowerCase().includes("image")?"has image":null,p=i.get(u.index)??u,c=i.get(l.index)?.presentationHints??l.presentationHints;return i.set(u.index,{...p,presentationHints:(o=p.presentationHints,a=c,s=d,[...new Set([...Array.isArray(o)?o:[],...Array.isArray(a)?a:[],...s?[s]:[]])])}),eh(e,l.index,r),i.get(u.index)??u}(e,o,t,r,i);a.set(n,s);continue}a.set(n,t)}return e.filter(e=>!r.has(e.index)).map(e=>i.get(e.index)??e)}(t);return{nodes:i,filteredCount:t.length-i.length}}(e,g,t),x=(l="string"==typeof(r=e).appName?r.appName:void 0,p="string"==typeof r.appBundleId?r.appBundleId:void 0,c=[],l&&c.push(`Page: ${l}`),p&&c.push(`App: ${p}`),c.length>0?`${c.join("\n")}
|
|
15
|
+
`:""),v=function(e,t,n,r={nodes:t,filteredCount:0}){let i=eF(e),o=function(e,t){if(!0===t.scoped||!0===t.depthLimited||e.length>3)return null;let n=1===e.length?"node":"nodes";return`Hint: sparse accessibility snapshot returned ${e.length} ${n}; snapshot state is invalid or unavailable for this screen. Use plain screenshot, not screenshot --overlay-refs, as visual truth. If screenshot shows the Home Screen or another app, run open for this app again first. Then navigate away with coordinates if needed and retry snapshot -i on the next screen.`}(t,n);o&&i.push(o),!n.raw&&r.filteredCount>0&&i.push(`Collapsed ${r.filteredCount} Android helper node${1===r.filteredCount?"":"s"} from the agent-facing text snapshot; use --raw or --json for the full hierarchy.`);let a=r.filteredCount>0?r.nodes:t;return!n.raw&&function(e){if(e.length<20)return!1;let t=new Map;for(let n of e){let e=(n.type??"").toLowerCase(),r=function(e){var t;let n=e.trim().replace(/\s+/g," ").toLowerCase();return!n||(t=n,/\S+@\S+\.\S+/.test(t))?null:n}(u(n));if(!r)continue;let i=`${e}|${r}`,o=t.get(i)??[];o.push(n),t.set(i,o)}let n=0;for(let e of t.values())!(e.length<=1)&&function(e){for(let r=0;r<e.length;r+=1)for(let i=r+1;i<e.length;i+=1){var t,n;if(t=e[r]?.rect,n=e[i]?.rect,!t||!n||!(t.x+t.width<=n.x+.5||n.x+n.width<=t.x+.5||t.y+t.height<=n.y+.5||n.y+n.height<=t.y+.5))return!0}return!1}(e)&&(n+=e.length);return n>=8}(a)&&i.push("Warning: possible repeated nav subtree detected."),i}(e,g,t,y),b=v.length>0?`${v.join("\n")}
|
|
16
|
+
`:"",w=t.raw?null:(f=e.unchanged)&&"object"==typeof f?"number"!=typeof f.ageMs||"number"!=typeof f.nodeCount?null:{ageMs:f.ageMs,nodeCount:f.nodeCount,interactiveOnly:!0===f.interactiveOnly||void 0,scope:"string"==typeof f.scope?f.scope:void 0}:null;if(w){let e;return`${x}${b}${e=function(e){if(e<1e3)return`${Math.round(e)}ms`;if(e<6e4)return`${(Math.round(e/100)/10).toFixed(1)}s`;let t=e/6e4;return t<60?`${(Math.round(10*t)/10).toFixed(1)}m`:`${(Math.round(t/60*10)/10).toFixed(1)}h`}((i=w).ageMs),i.scope?`Scoped snapshot unchanged for scope "${i.scope}" since previous read ${e} ago.
|
|
17
|
+
Previous refs in this scope remain valid. Use find/get/is for a targeted query, or --force-full to re-emit.`:i.interactiveOnly?`Interactive snapshot unchanged since previous read ${e} ago.
|
|
18
|
+
${i.nodeCount} visible nodes are unchanged. Previous @e refs are still valid. Use find/get/is for a targeted query, or --force-full to re-emit.`:`Snapshot unchanged since previous read ${e} ago.
|
|
19
|
+
Refs from the previous snapshot are still valid. Use --force-full to re-emit the tree, or use find/get/is for a targeted query.`}
|
|
20
|
+
`}let M=t.raw||"macos-helper"===$?null:n(y.nodes),C=!!e.truncated,S=M?.nodes??g,k=t.raw||"macos-helper"===$?null:function(e,t,n,r,i=0){let o,a=(o=e.visibility)&&"object"==typeof o&&"boolean"==typeof o.partial&&"number"==typeof o.visibleNodeCount&&"number"==typeof o.totalNodeCount&&Array.isArray(o.reasons)?{partial:o.partial,visibleNodeCount:o.visibleNodeCount,totalNodeCount:o.totalNodeCount,reasons:o.reasons.filter(e=>"string"==typeof e)}:null;if(0===i&&a)return a;let s=(t?.hiddenCount??0)+i,u=!!t&&t.nodes.some(e=>e.hiddenContentAbove||e.hiddenContentBelow);return s>0?{partial:!0,visibleNodeCount:n,totalNodeCount:Math.max(r,a?.totalNodeCount??r),reasons:[...new Set([...a?.reasons??[],"offscreen-nodes"])]}:a||(u?{partial:!0,visibleNodeCount:n,totalNodeCount:n,reasons:[]}:null)}(e,M,S.length,g.length,y.filteredCount),P=(a=g.length,s=k,h=C?" (truncated)":"",s?.partial?s.totalNodeCount>s.visibleNodeCount?`Snapshot: ${s.visibleNodeCount} visible nodes (${s.totalNodeCount} total)${h}`:`Snapshot: ${s.visibleNodeCount} visible nodes${h}`:`Snapshot: ${a} nodes${h}`);return 0===g.length?`${x}${P}
|
|
21
|
+
${b}`:t.raw?`${x}${P}
|
|
22
|
+
${b}${g.map(e=>JSON.stringify(e)).join("\n")}
|
|
23
|
+
`:t.flatten?`${x}${P}
|
|
24
|
+
${b}${d(S,{summarizeTextSurfaces:!0}).flatMap(e=>[o(e.node,0,!1,e.type,{summarizeTextSurfaces:!0}),...eR({...e,depth:0})]).join("\n")}${eC(M)}
|
|
25
|
+
`:`${x}${P}
|
|
26
|
+
${b}${(function(e){let t=[],n=[],r=new Map(e.map(e=>[e.node.index,e.node])),i=e=>{for(var i,o,a;n.length>0&&(!e||(i=e,o=n[n.length-1],a=r,!function(e,t,n){let r=e;for(;"number"==typeof r.parentIndex;){if(r.parentIndex===t.index)return!0;let e=n.get(r.parentIndex);if(!e)break;r=e}return!1}(i.node,o.node,a)&&i.depth<=o.depth));)t.push(...eR(n.pop(),"below"))};for(let r of e)i(r),t.push(r.text),t.push(...eR(r,"above")),r.node.hiddenContentBelow&&n.push(r);return i(),t})(d(S,{summarizeTextSurfaces:!0})).join("\n")}${eC(M)}
|
|
27
|
+
`}(i,{raw:r.raw,flatten:r.interactiveOnly,scoped:"string"==typeof r.scope&&r.scope.trim().length>0,depthLimited:"number"==typeof r.depth})}},wait:eY,alert:eY,appstate:eX(function(e){return{data:e,text:function(e){if("ios"===e.platform){let t=[`Foreground app: ${e.appName??e.appBundleId??"unknown"}`];return e.appBundleId&&t.push(`Bundle: ${e.appBundleId}`),e.source&&t.push(`Source: ${e.source}`),t.join("\n")}if("android"===e.platform){let t=[`Foreground app: ${e.package??"unknown"}`];return e.activity&&t.push(`Activity: ${e.activity}`),t.join("\n")}return null}(e)}}),back:eY,home:eY,rotate:eY,"app-switcher":eY,keyboard:eX(function(e){if("android"===e.platform&&"status"===e.action){var t;let n=[`Keyboard visible: ${!0===e.visible?"yes":"no"}`,`Input type: ${e.type??e.inputType??"unknown"}`,`Input owner: ${e.inputOwner??"unknown"}`];return e.inputMethodPackage&&n.push(`Input method: ${e.inputMethodPackage}`),e.focusedPackage&&n.push(`Focused package: ${e.focusedPackage}`),e.focusedResourceId&&n.push(`Focused resource: ${e.focusedResourceId}`),n.push(`Next action: ${(t=e.visible,"ime"===e.inputOwner?"Focused input appears to be owned by the keyboard/IME; dismiss or change the IME before retrying text entry.":!0===t?"Keyboard is visible and focused input appears app-owned; fill/type can proceed.":"Keyboard is hidden; focus an app field before type, or use fill with a concrete target.")}`),{data:e,text:n.join("\n")}}return eL(e)}),clipboard:eX(function(e){return"read"===e.action?{data:e,text:e.text}:eL(e)}),get:({input:e,result:t})=>{var n;let r;return r=(n={result:t,format:e.format}).result,"text"===n.format?{data:r,text:"string"==typeof r.text?r.text:""}:"attrs"===n.format?{data:r,text:JSON.stringify(r.node??{},null,2)}:eL(r)},is:eX(function(e){return{data:e,text:`Passed: is ${e.predicate??"assertion"}`}}),find:eX(function(e){return"string"==typeof e.text?{data:e,text:e.text}:"boolean"==typeof e.found?{data:e,text:`Found: ${e.found}`}:e.node?{data:e,text:JSON.stringify(e.node,null,2)}:eL(e)}),perf:eX(function(e){return{data:e,text:function(e){var t,n,r;let i,o=eJ(e.metrics),a=eJ(o?.fps),s=(t=o,(i=[function(e){if(e?.available!==!0)return;let t=eq(e.usagePercent);return void 0!==t?`CPU ${eG(t)}`:void 0}(eJ(t?.cpu)),function(e){let t;if(e?.available!==!0)return;let n=eq(e.residentMemoryKb)??eq(e.totalPssKb)??eq(e.totalRssKb);return void 0!==n?`memory ${t=n/1024,`${t>=10?Math.round(t):t.toFixed(1)}MB`}`:void 0}(eJ(t?.memory))].filter(e=>!!e)).length>0?i.join(", "):void 0);if(!a)return eW(s,"missing frame metric");if(!1===a.available){return eW(s,"string"==typeof(n=a).reason&&n.reason.length>0?n.reason:"not available")}let u=function(e){let t=eq(e.droppedFramePercent),n=eq(e.droppedFrameCount);if(void 0!==t&&void 0!==n){var r,i,o;return[`dropped ${eG(t)}`,(r=n,void 0!==(i=eq(e.totalFrameCount))?`(${Math.round(r)}/${Math.round(i)} frames)`:`(${Math.round(r)} dropped frames)`),void 0!==(o=eq(e.sampleWindowMs))?`window ${eV(o)}`:""].filter(Boolean).join(" ")}}(a);if(!u)return eW(s,"missing dropped-frame summary");let l=[`Frame health: ${u}`],d=(Array.isArray(r=a.worstWindows)?r.filter(e=>!!e&&"object"==typeof e&&!Array.isArray(e)):[]).flatMap(e=>{let t=function(e){let t=eq(e.startOffsetMs),n=eq(e.endOffsetMs),r=eq(e.missedDeadlineFrameCount);if(void 0===t||void 0===n||void 0===r)return;let i=eq(e.worstFrameMs),o=void 0===i?"":`, worst ${eV(i)}`;return`- +${eV(t)}-+${eV(n)}: ${Math.round(r)} missed-deadline frames${o}`}(e);return t?[t]:[]});return d.length>0&&l.push("Worst windows:",...d),l.join("\n")}(e)}}),prepare:eY,logs:eX(function(e){var t;return{data:e,text:"string"==typeof e.path?e.path:"",stderr:ez([eE(e,["active","state","backend","sizeBytes"]),(t=e,["started","stopped","marked","cleared","restarted","removedRotatedFiles"].map(e=>{var n,r;return n=e,!0===(r=t[e])?`${n}=true`:"number"==typeof r?`${n}=${r}`:""}).filter(Boolean).join(" ")||void 0),"string"==typeof e.hint?e.hint:void 0,eU(e.notes)])}}),network:eX(function(e){let t=[],n="string"==typeof e.path?e.path:"";n&&t.push(n);let r=Array.isArray(e.entries)?e.entries:[];if(0===r.length)t.push("No recent HTTP(s) entries found.");else for(let e of r)t.push(...function(e){let t=eJ(e)??{},n="string"==typeof t.method?t.method:"HTTP",r="string"==typeof t.url?t.url:"<unknown-url>",i="number"==typeof t.status?` status=${t.status}`:"",o="string"==typeof t.timestamp?`${t.timestamp} `:"",a="number"==typeof t.durationMs?` durationMs=${t.durationMs}`:"",s=[`${o}${n} ${r}${i}${a}`];return eK(s,"headers",t.headers),eK(s,"request",t.requestBody),eK(s,"response",t.responseBody),s}(e));return{data:e,text:t.join("\n"),stderr:ez([eE(e,["active","state","backend","include","scannedLines","matchedLines"]),eU(e.notes)])}}),record:eX(function(e){let t,n="string"==typeof e.outPath?e.outPath:"",r=Array.isArray(t=e.chunks)?t.flatMap(e=>e&&"object"==typeof e?"number"!=typeof e.index||"string"!=typeof e.path?[]:[{index:e.index,path:e.path}]:[]):[];if(r.length<=1){var i,o;let t;return{data:e,text:(i=e,t=[],(o=n)&&t.push(o),"string"==typeof i.sessionStateDir&&t.push(`Session state: ${i.sessionStateDir}`),"string"==typeof i.warning&&t.push(`Warning: ${i.warning}`),"string"==typeof i.overlayWarning&&t.push(`Overlay warning: ${i.overlayWarning}`),t.join("\n"))}}let a=["Recording chunks:"];for(let e of r)a.push(` ${e.index}: ${e.path}`);return"string"==typeof e.telemetryPath&&a.push(`Telemetry: ${e.telemetryPath}`),"string"==typeof e.warning&&a.push(`Warning: ${e.warning}`),"string"==typeof e.overlayWarning&&a.push(`Overlay warning: ${e.overlayWarning}`),{data:e,text:a.join("\n")}}),metro:({input:e,result:t})=>{var n;return{data:(n={result:t,action:e.action}).result,text:"reload"===n.action?`Reloaded React Native apps via ${n.result.reloadUrl}`:JSON.stringify(n.result,null,2)}}};function eZ(e){return eQ[e.name]?.({input:e.input??{},result:e.result})}function e0(e,t){return{...e,run:t,invoke:async(n,r)=>await t(n,e.readInput(r))}}function e1(e=k){var t;let n={steps:z(T({type:"array",description:"Structured batch steps. Each step uses a command name and the same input object as that command tool.",items:{type:"object",properties:{command:{type:"string",enum:t=e,description:"Command name to run with structured input."},input:{type:"object",additionalProperties:!0,description:"Structured command input for the nested command. Use the matching MCP tool schema for this object."},runtime:{type:"object",additionalProperties:!0,description:"Optional per-step runtime payload."}},required:["command","input"],additionalProperties:!1}},(e,n)=>(function(e,t){if(!Array.isArray(e))throw Error("Expected steps to be an array.");return e.map((e,n)=>{var r,i,o;let a;return r=e,i=n+1,o=t,D(a=function(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw Error(`Invalid batch step ${t}.`);return e}(r,i),["command","input","runtime"],`Batch step ${i}`),{command:K(a,"command",o),input:function(e,t){let n=e.input;if(!n||"object"!=typeof n||Array.isArray(n))throw Error(`Batch step ${t} input must be an object.`);return n}(a,i),...function(e,t){let n=e.runtime;if(void 0!==n&&(!n||"object"!=typeof n||Array.isArray(n)))throw Error(`Batch step ${t} runtime must be an object.`);return void 0===n?{}:{runtime:n}}(a,i)}})})(e[n],t))),onError:H(["stop"],"Batch failure policy."),maxSteps:R("Maximum number of steps accepted for this batch.",{min:1,max:1e3}),out:q("Optional output path for command artifacts.")};return{name:"batch",description:"Run multiple structured command steps in one daemon request.",inputSchema:V(n),readInput:e=>(function(e,t){let n=J(e,t),r=n.maxSteps??100;if(!Number.isInteger(r)||r<1||r>1e3)throw Error(`Invalid batch maxSteps: ${String(n.maxSteps)}`);if(n.steps.length>r)throw Error(`batch has ${n.steps.length} steps; max allowed is ${r}.`);return{...n}})(e,n)}}function e2(e,t,n){return{name:e,description:t,inputSchema:V(n),readInput:e=>J(e,n)}}let e6=["duration","text","ref","selector"],e5=["start","stop"],e3=[e4("devices",{}),e4("boot",{headless:L("Boot without showing simulator UI when supported.")}),e4("shutdown",{}),e4("prepare",{action:z(H(["ios-runner"])),timeoutMs:R("Maximum wall-clock time for the prepare command.")}),e4("apps",{appsFilter:H(["user-installed","all"])}),e4("session",{action:H(["list"])}),e4("open",{app:q("App name, bundle id, package, or URL."),url:q("Optional URL passed with an app shell."),surface:H(ei),activity:q("Android activity name."),launchConsole:q("Launch console mode."),launchArgs:_("Launch arguments forwarded verbatim to the platform launch command."),relaunch:L("Force relaunch."),saveScript:O({oneOf:[B(),j()]}),noDeviceHub:L("Skip Xcode Device Hub and use the standalone Simulator app when surfacing Apple simulators."),noRecord:L("Do not record this action.")}),e4("close",{app:q("Optional app to close."),shutdown:L("Shutdown the session/device where supported."),saveScript:O({oneOf:[B(),j()]})}),e4("install",{app:z(q()),appPath:z(q("Path to app binary."))}),e4("reinstall",{app:z(q()),appPath:z(q("Path to app binary."))}),e4("install-from-source",{source:z(O(Z("Install source object."))),retainPaths:L(),retentionMs:R()}),e4("push",{app:z(q()),payload:z(O({oneOf:[j(),Z()]}))}),e4("trigger-app-event",{event:z(q()),payload:E()}),e4("snapshot",{interactiveOnly:L(),compact:L(),depth:R(),scope:q(),raw:L(),forceFull:L(),timeoutMs:R("Maximum wall-clock time for the snapshot command.")}),e4("screenshot",{path:q("Output path."),overlayRefs:L(),fullscreen:L(),maxSize:R(),stabilize:L(),surface:H(ei)}),e4("diff",{kind:z(O({type:"string",const:"snapshot"})),out:q(),interactiveOnly:L(),compact:L(),depth:R(),scope:q(),raw:L()}),e4("wait",{kind:H(e6),durationMs:R(),text:q(),ref:q(),selector:q(),timeoutMs:R(),depth:R(),scope:q(),raw:L()}),e4("alert",{action:H(["get","accept","dismiss","wait"]),timeoutMs:R()}),e4("appstate",{}),e4("back",{mode:H(["in-app","system"])}),e4("home",{}),e4("rotate",{orientation:z(H(M))}),e4("app-switcher",{}),e4("keyboard",{action:H(["status","dismiss"])}),e4("clipboard",{action:z(H(["read","write"])),text:q()}),e4("react-native",{action:z(H(["dismiss-overlay"]))}),e4("replay",{path:z(q()),update:L(),backend:q(),maestro:L(),env:_()}),e4("test",{paths:z(_()),update:L(),backend:q(),maestro:L(),env:_(),failFast:L(),timeoutMs:R(),retries:R(),recordVideo:L(),artifactsDir:q(),reportJunit:q(),shardAll:R(),shardSplit:R()}),e4("perf",{area:H(f),action:H(v)}),e4("logs",{action:H(y),message:q(),restart:L()}),e4("network",{action:H(["dump","log"]),limit:R(),include:H(en)}),e4("record",{action:z(H(e5)),path:q(),fps:R(),quality:O(F()),hideTouches:L()}),e4("trace",{action:z(H(e5)),path:q()}),e4("settings",{setting:z(q()),state:z(q()),app:q(),latitude:ee(),longitude:ee(),permission:q(),mode:H(["full","limited"])}),e4("metro",{action:z(H(["prepare","reload"])),projectRoot:q(),kind:O(j()),publicBaseUrl:q(),proxyBaseUrl:q(),bearerToken:q(),bridgeScope:O({type:"object",additionalProperties:!0}),launchUrl:q(),port:R(),listenHost:q(),statusHost:q(),startupTimeoutMs:R(),probeTimeoutMs:R(),reuseExisting:L(),installDependenciesIfNeeded:L(),runtimeFilePath:q(),logPath:q(),metroHost:q(),metroPort:R(),bundleUrl:q(),timeoutMs:R()})];function e4(e,t){return e2(e,er(e),t)}let e8={target:z(G()),button:H(r,"Pointer button for platforms that support mouse buttons."),...I(),...Q()},e9={target:z(G()),...I(),...Q()},e7={target:z(G()),text:z(q("Text to enter into the target.")),delayMs:R("Delay between typed characters.",{min:0}),...I()},te={target:z(G()),durationMs:R("Long press duration in milliseconds.",{min:0}),...I()},tt={from:z(W("Swipe start point.")),to:z(W("Swipe end point.")),durationMs:R("Swipe duration in milliseconds.",{min:0}),count:R("Number of swipe repetitions.",{min:1}),pauseMs:R("Pause between repeated swipes.",{min:0}),pattern:H(l)},tn={x:z(ee("X coordinate.")),y:z(ee("Y coordinate."))},tr={text:z(q("Text to type.")),delayMs:R("Delay between typed characters.",{min:0})},ti={direction:z(H(a)),amount:ee("Platform scroll amount."),pixels:R("Pixel scroll amount.",{min:0})},to={format:z(H(["text","attrs"])),target:z(N()),...I()},ta={predicate:z(H(["visible","hidden","exists","editable","selected","text"])),selector:z(q()),value:q(),...I()},ts={locator:H(eo),query:z(q()),action:H(["click","focus","exists","getText","getAttrs","wait","fill","type"]),value:q(),timeoutMs:R(),first:L(),last:L(),depth:R(),raw:L()},tu={kind:z(H(P,"Gesture variant.")),direction:H(i,"Fling direction."),preset:H(s,"Swipe preset."),origin:W("Gesture origin point."),delta:W("Movement delta for pan or transform gestures."),distance:R("Fling distance.",{min:0}),scale:ee("Pinch or transform scale."),degrees:ee("Rotation in degrees."),velocity:R("Rotate gesture velocity.",{min:0}),durationMs:R("Gesture duration in milliseconds.",{min:0})},tl=[{name:"click",description:er("click"),inputSchema:V(e8),readInput:e=>J(e,e8)},{name:"press",description:er("press"),inputSchema:V(e9),readInput:e=>J(e,e9)},{name:"fill",description:er("fill"),inputSchema:V(e7),readInput:e=>J(e,e7)},td("longpress",te),td("swipe",tt),td("focus",tn),td("type",tr),td("scroll",ti),td("get",to),td("is",ta),td("find",ts),{name:"gesture",description:er("gesture"),inputSchema:V(tu),readInput:function(e){let t=A(e),n=Y(t),r=K(t,"kind",P);return"pan"===r?{...n,kind:r,origin:U(t,"origin"),delta:U(t,"delta"),durationMs:et(t,"durationMs",{min:0})}:"fling"===r?{...n,kind:r,direction:K(t,"direction",i),origin:U(t,"origin"),distance:et(t,"distance",{min:0}),durationMs:et(t,"durationMs",{min:0})}:"swipe"===r?{...n,kind:r,preset:K(t,"preset",s),durationMs:et(t,"durationMs",{min:0})}:"pinch"===r?{...n,kind:r,scale:X(t,"scale"),origin:tp(t,"origin")}:"rotate"===r?{...n,kind:r,degrees:X(t,"degrees"),origin:tp(t,"origin"),velocity:et(t,"velocity",{min:0})}:{...n,kind:r,origin:U(t,"origin"),delta:U(t,"delta"),scale:X(t,"scale"),degrees:X(t,"degrees"),durationMs:et(t,"durationMs",{min:0})}}}];function td(e,t){return e2(e,er(e),t)}function tp(e,t){return void 0===e[t]?void 0:U(e,t)}let tc=new Map([...tl,...e3,e1(k)].map(e=>[e.name,e]));function tf(){return S().map(e=>{var t;if(!th(e))throw Error(`Missing command metadata for MCP-exposed command: ${e}`);return t=e,tc.get(t)})}function th(e){return tc.has(e)}export{e6 as WAIT_KIND_VALUES,e3 as clientCommandMetadata,e1 as createBatchCommandMetadata,e0 as defineExecutableCommand,eZ as formatCliOutput,ek as formatScreenshotDiffText,eS as formatSnapshotDiffText,tl as interactionCommandMetadata,th as isCommandName,tf as listMcpCommandMetadata,eM as printHumanError,ew as printJson};
|
package/dist/src/8407.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{AppError as e}from"./9152.js";let t=new Set(["id","role","text","label","value","appname","windowtitle"]),n=new Set(["visible","hidden","editable","selected","enabled","hittable"]),r=new Set([...t,...n]),l=new Map([['"','"'],["'","'"],["\\","\\"],["/","/"],["b","\b"],["f","\f"],["n","\n"],["r","\r"],["t"," "]]);function i(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 o=t[i];if(('"'===o||"'"===o)&&!h(t,i)){l=a(l,o),r+=o;continue}if(!l&&"|"===o&&"|"===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+=o}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)&&!h(t,e)){l=a(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(f)}})(t))}}function o(e){try{return i(e)}catch{return null}}function u(e){let t=e.trim();if(!t)return!1;if("||"===t)return!0;let n=t.indexOf("=");if(-1!==n){let e=t.slice(0,n).trim().toLowerCase();return r.has(e)}return r.has(t.toLowerCase())}function s(e,t={}){if(0===e.length)return null;let n=t.preferTrailingValue??!1,r=0,l=[];for(;r<e.length;){let t=e[r];if(void 0===t||!u(t))break;r+=1;let n=e.slice(0,r).join(" ").trim();n&&o(n)&&l.push(r)}if(0===l.length)return null;let i=l.at(-1);if(void 0===i)return null;let f=i;if(n)for(let t=l.length-1;t>=0;t-=1){let n=l[t];if(void 0!==n&&n<e.length){f=n;break}}let a=e.slice(0,f).join(" ").trim();return a?{selectorExpression:a,rest:e.slice(f)}:null}function f(t){let l=t.trim();if(!l)throw new e("INVALID_ARGS","Empty selector term");let i=l.indexOf("=");if(-1===i){let r=l.toLowerCase();if(!n.has(r))throw new e("INVALID_ARGS",`Invalid selector term "${t}", expected key=value`);return{key:r,value:!0}}let o=l.slice(0,i).trim().toLowerCase(),u=l.slice(i+1).trim();if(!r.has(o))throw new e("INVALID_ARGS",`Unknown selector key: ${o}`);if(!u)throw new e("INVALID_ARGS",`Missing selector value for key: ${o}`);if(n.has(o)){let t,n="true"===(t=c(u).toLowerCase())||"false"!==t&&null;if(null===n)throw new e("INVALID_ARGS",`Invalid boolean value for ${o}: ${u}`);return{key:o,value:n}}return{key:o,value:c(u)}}function a(e,t){return e?e===t?null:e:t}function c(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 i=e.charAt(n);if("\\"!==i){t+=i,n+=1;continue}let o=e.charAt(n+1);if(!o){t+=i,n+=1;continue}let u=(r=o,l.get(r)??null);if(null!==u){t+=u,n+=2;continue}if("u"===o){let r=e.slice(n+2,n+6);if(/^[0-9a-fA-F]{4}$/.test(r)){t+=String.fromCharCode(Number.parseInt(r,16)),n+=6;continue}}t+=i,n+=1}return t}(t.slice(1,-1)):t}function h(e,t){let n=0;for(let r=t-1;r>=0&&"\\"===e[r];r-=1)n+=1;return n%2==1}export{u as isSelectorToken,i as parseSelectorChain,s as splitSelectorFromArgs,o as tryParseSelectorChain};
|
package/dist/src/8699.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{screenshotFlagsFromOptions as e}from"./5310.js";import{AppError as t}from"./9152.js";import{readRequiredString as r,readRequiredPlatform as i,readRequiredDeviceKind as a,readNullableString as n,readDeviceTarget as o,readRect as s,asRecord as l,stripUndefined as u,isRecord as c,readRequiredNumber as d,readPoint as p,readOptionalString as f}from"./7455.js";import{buildAppIdentifiers as m,buildDeviceIdentifiers as h}from"./6232.js";import{INTERNAL_COMMANDS as g,BATCH_COMMAND_NAMES as y,PUBLIC_COMMANDS as v}from"./5792.js";import{assertResolvedAppsFilter as S}from"./1393.js";import{request as w,selectorSnapshotOptionsFromFlags as A,direct as b,requiredString as I,commonInputFromFlags as _,optionalString as N,readJsonObject as R,optionalNumber as M,optionalCliNumber as x,selectionOptionsFromFlags as k,commandNameSet as D,captureDaemonWriters as L,requiredDaemonString as C,splitRequiredSelector as P}from"./6085.js";import{isPerfAction as q,PERF_AREA_ERROR_MESSAGE as V,PERF_ACTION_ERROR_MESSAGE as G,isPerfArea as E}from"./8020.js";import{parseDeviceRotation as U}from"./1998.js";import{compactRecord as $}from"./9404.js";import{interactionDaemonWriters as z}from"./8502.js";function K(e,t){let a=f(e,"bundleId"),n=f(e,"package");return{app:r(e,"app"),appPath:r(e,"appPath"),platform:i(e,"platform"),appId:a??n,bundleId:a,package:n,identifiers:m({session:t,bundleId:a,packageName:n})}}function T(e,r){let i=f(e,"bundleId"),a=f(e,"packageName"),n=i??a??f(e,"appId"),o=f(e,"launchTarget")??a??i??n;if(!o)throw new t("COMMAND_FAILED",'Daemon response is missing "launchTarget".',{response:e});return{appName:f(e,"appName"),appId:n,bundleId:i,packageName:a,launchTarget:o,installablePath:f(e,"installablePath"),archivePath:f(e,"archivePath"),materializationId:f(e,"materializationId"),materializationExpiresAt:f(e,"materializationExpiresAt"),identifiers:m({session:r,bundleId:i,packageName:a,appId:n})}}function F(e){return{released:!0===e.released,materializationId:r(e,"materializationId"),identifiers:{}}}function B(e){let{record:t,platform:r,id:i,name:n,target:o}=H(e,"name");return{platform:r,target:o,kind:a(t,"kind"),id:i,name:n,booted:"boolean"==typeof t.booted?t.booted:void 0,identifiers:h(r,i,n),...j(r,i)}}function O(e){let{record:t,platform:i,id:a,name:o,target:s}=H(e,"name"),l=r(t,"device"),u={session:o,...h(i,a,l)};return{name:o,createdAt:d(t,"createdAt"),sessionStateDir:f(t,"sessionStateDir"),runnerLogPath:f(t,"runnerLogPath"),device:{platform:i,target:s,id:a,name:l,identifiers:u,...j(i,a,n(t,"ios_simulator_device_set"))},identifiers:u}}function H(e,t){let a=l(e);return{record:a,platform:i(a,"platform"),id:r(a,"id"),name:r(a,t),target:o(a,"target")}}function j(e,t,r){return{ios:"ios"===e?{udid:t,...void 0!==r?{simulatorSetPath:r}:{}}:void 0,android:"android"===e?{serial:t}:void 0}}function J(e){if(!c(e))return;let t=e.platform,r=f(e,"metroHost"),i="number"==typeof e.metroPort?e.metroPort:void 0;return{platform:"ios"===t||"android"===t?t:void 0,metroHost:r,metroPort:i,bundleUrl:f(e,"bundleUrl"),launchUrl:f(e,"launchUrl")}}function W(e){let t=e.platform,r=f(e,"id"),i=f(e,"device");if("ios"!==t&&"macos"!==t&&"android"!==t&&"linux"!==t||!r||!i)return;let a=o(e,"target"),s=h(t,r,i);return{platform:t,target:a,id:r,name:i,identifiers:s,ios:"ios"===t?{udid:f(e,"device_udid")??r,simulatorSetPath:n(e,"ios_simulator_device_set")}:void 0,android:"android"===t?{serial:f(e,"serial")??r}:void 0}}function Q(e){if(c(e)&&"number"==typeof e.durationMs&&"string"==typeof e.measuredAt&&"string"==typeof e.method)return{durationMs:e.durationMs,measuredAt:e.measuredAt,method:e.method,appTarget:f(e,"appTarget"),appBundleId:f(e,"appBundleId")}}function X(e){return Array.isArray(e)?e:[]}function Y(e){let t=e.overlayRefs;if(!Array.isArray(t))return;let r=[];for(let e of t){if(!c(e))continue;let t=f(e,"ref"),i=s(e,"rect"),a=s(e,"overlayRect"),n=p(e,"center");t&&i&&a&&n&&r.push({ref:t,label:f(e,"label"),rect:i,overlayRect:a,center:n})}return r}function Z(t){return u({stateDir:t.stateDir,daemonBaseUrl:t.daemonBaseUrl,daemonAuthToken:t.daemonAuthToken,daemonTransport:t.daemonTransport,daemonServerMode:t.daemonServerMode,tenant:t.tenant,sessionIsolation:t.sessionIsolation,runId:t.runId,leaseId:t.leaseId,leaseBackend:t.leaseBackend,platform:t.platform,target:t.target,device:t.device,udid:t.udid,serial:t.serial,iosSimulatorDeviceSet:t.iosSimulatorDeviceSet,androidDeviceAllowlist:t.androidDeviceAllowlist,surface:t.surface,activity:t.activity,launchConsole:t.launchConsole,launchArgs:t.launchArgs,relaunch:t.relaunch,shutdown:t.shutdown,saveScript:t.saveScript,noRecord:t.noRecord,backMode:t.backMode,metroHost:t.metroHost,metroPort:t.metroPort,bundleUrl:t.bundleUrl,launchUrl:t.launchUrl,snapshotInteractiveOnly:t.interactiveOnly,snapshotCompact:t.compact,snapshotDepth:t.depth,snapshotScope:t.scope,snapshotRaw:t.raw,snapshotForceFull:t.forceFull,...e(t),appsFilter:t.appsFilter,out:t.out,count:t.count,fps:t.fps,quality:t.quality,hideTouches:t.hideTouches,intervalMs:t.intervalMs,delayMs:t.delayMs,holdMs:t.holdMs,jitterPx:t.jitterPx,pixels:t.pixels,doubleTap:t.doubleTap,clickButton:t.clickButton,pauseMs:t.pauseMs,pattern:t.pattern,headless:t.headless,restart:t.restart,replayUpdate:t.replayUpdate,replayBackend:t.replayBackend,replayEnv:t.replayEnv,replayShellEnv:t.replayShellEnv,failFast:t.failFast,timeoutMs:t.timeoutMs,retries:t.retries,artifactsDir:t.artifactsDir,reportJunit:t.reportJunit,shardAll:t.shardAll,shardSplit:t.shardSplit,findFirst:t.findFirst,findLast:t.findLast,networkInclude:t.networkInclude,batchOnError:t.batchOnError,batchMaxSteps:t.batchMaxSteps,batchSteps:t.batchSteps,verbose:t.debug})}function ee(e){return u({requestId:e.requestId,cwd:e.cwd,sessionExplicit:void 0!==e.session,debug:e.debug,lockPolicy:e.lockPolicy,lockPlatform:e.lockPlatform,tenantId:e.tenant,runId:e.runId,leaseId:e.leaseId,leaseBackend:e.leaseBackend,leaseTtlMs:e.leaseTtlMs,sessionIsolation:e.sessionIsolation,installSource:e.installSource,retainMaterializedPaths:e.retainMaterializedPaths,materializedPathRetentionMs:e.materializedPathRetentionMs,materializationId:e.materializationId})}function et(e){return e??"default"}function er(e,r){if(!e||"object"!=typeof e||Array.isArray(e))throw new t("INVALID_ARGS",`${r} installSource must be an object.`);if("github-actions-artifact"!==en(e.type,`${r} installSource.type`))throw new t("INVALID_ARGS",`${r} installSource.type must be "github-actions-artifact".`);let{owner:i,repo:a}=ea(en(e.repo,`${r} installSource.repo`),`${r} installSource.repo`);return ei(i,a,e.artifact,`${r} installSource.artifact`)}function ei(e,r,i,a){var n;return"number"==typeof i||"string"==typeof(n=i)&&/^\d+$/.test(n.trim())?{kind:"github-actions-artifact",owner:e,repo:r,artifactId:function(e,r){let i="number"==typeof e?e:"string"==typeof e?Number(e):NaN;if(!Number.isInteger(i))throw new t("INVALID_ARGS",`${r} must be an integer.`);return i}(i,a)}:{kind:"github-actions-artifact",owner:e,repo:r,artifactName:en(i,a)}}function ea(e,r){let i=e.indexOf("/");if(i<=0||i===e.length-1||-1!==e.indexOf("/",i+1))throw new t("INVALID_ARGS",`${r} must use owner/repo.`);let a={owner:e.slice(0,i).trim(),repo:e.slice(i+1).trim()};if(!a.owner||!a.repo)throw new t("INVALID_ARGS",`${r} must use owner/repo.`);return a}function en(e,r){let i="string"==typeof e&&e.trim().length>0?e.trim():void 0;if(!i)throw new t("INVALID_ARGS",`${r} must be a non-empty string.`);return i}let eo={devices:(e,t)=>_(t),apps:(e,t)=>({..._(t),appsFilter:S(t.appsFilter)}),session:(e,r)=>({..._(r),action:function(e){let r=e??"list";if("list"===r)return r;throw new t("INVALID_ARGS","session only supports list")}(e[0])}),boot:(e,t)=>({..._(t),headless:t.headless}),prepare:(e,t)=>({..._(t),action:I(e[0],"prepare requires subcommand"),timeoutMs:t.timeoutMs}),open:(e,t)=>({..._(t),app:e[0],url:e[1],surface:t.surface,activity:t.activity,launchConsole:t.launchConsole,launchArgs:t.launchArgs,relaunch:t.relaunch,saveScript:t.saveScript,noRecord:t.noRecord}),close:(e,t)=>({..._(t),app:e[0],shutdown:t.shutdown,saveScript:t.saveScript}),install:el,reinstall:el,"install-from-source":(e,r)=>({..._(r),source:function(e,r){let i=e[0]?.trim();if(e.length>1)throw new t("INVALID_ARGS","install-from-source accepts either one <url> positional or --github-actions-artifact");let a=r.githubActionsArtifact?function(e,r="--github-actions-artifact"){let i=e.indexOf(":");if(i<=0||i===e.length-1)throw new t("INVALID_ARGS",`${r} must use owner/repo:artifact, for example thymikee/RNCLI83:6635342232`);let{owner:a,repo:n}=ea(e.slice(0,i),r);return ei(a,n,e.slice(i+1),`${r} artifact`)}(r.githubActionsArtifact):void 0,n=r.installSource;if(1!=+!!i+ +!!a+ +!!n)throw new t("INVALID_ARGS","install-from-source requires exactly one source: <url>, --github-actions-artifact, or config installSource");if(!i&&r.header&&r.header.length>0)throw new t("INVALID_ARGS","install-from-source --header is only supported for URL sources");return a||n||{kind:"url",url:i,headers:function(e){if(!e||0===e.length)return;let r={};for(let i of e){let e=i.indexOf(":");if(e<=0)throw new t("INVALID_ARGS",`Invalid --header value "${i}". Expected "name:value".`);let a=i.slice(0,e).trim(),n=i.slice(e+1).trim();if(!a)throw new t("INVALID_ARGS",`Invalid --header value "${i}". Header name cannot be empty.`);r[a]=n}return r}(r.header)}}(e,r),retainPaths:r.retainPaths,retentionMs:r.retentionMs}),push:(e,t)=>({..._(t),app:I(e[0],"push requires bundleOrPackage"),payload:I(e[1],"push requires payloadOrJson")}),"trigger-app-event":(e,t)=>({..._(t),event:I(e[0],"trigger-app-event requires event"),payload:e[1]?R(e[1],"trigger-app-event payload"):void 0})},es={devices:b(v.devices),boot:b(v.boot),prepare:b(v.prepare,e=>[C(e.action,"prepare requires subcommand")]),apps:b(v.apps),open:b(v.open,function(e){return e.app?e.url?[e.app,e.url]:[e.app]:[]}),close:b(v.close,e=>N(e.app)),install:b(v.install,e=>eu(e.app,e.appPath)),reinstall:b(v.reinstall,e=>eu(e.app,e.appPath)),"install-from-source":e=>w(g.installSource,[],{...e,installSource:e.source,retainMaterializedPaths:e.retainPaths,materializedPathRetentionMs:e.retentionMs}),push:b(v.push,e=>{var t;return[(t=e).app,"string"==typeof t.payload?t.payload:JSON.stringify(t.payload)]}),"trigger-app-event":b(v.triggerAppEvent,e=>{var t;return[(t=e).event,...t.payload?[JSON.stringify(t.payload)]:[]]})};function el(e,t,r="install"){return{..._(t),app:I(e[0],`${r} requires app`),appPath:I(e[1],`${r} requires path`)}}function eu(e,t){return[C(e,"missing first positional"),C(t,"missing second positional")]}let ec={gesture:function(e,r){let i=e[0],a=e.slice(1),n=_(r);switch(i){case"pan":return{...n,kind:i,origin:{x:Number(a[0]),y:Number(a[1])},delta:{x:Number(a[2]),y:Number(a[3])},durationMs:x(a[4])};case"fling":return{...n,kind:i,direction:a[0],origin:{x:Number(a[1]),y:Number(a[2])},distance:x(a[3]),durationMs:x(a[4])};case"swipe":return{...n,kind:i,preset:a[0],durationMs:x(a[1])};case"pinch":return{...n,kind:i,scale:Number(a[0]),origin:void 0===a[1]||void 0===a[2]?void 0:{x:Number(a[1]),y:Number(a[2])}};case"rotate":return{...n,kind:i,degrees:Number(a[0]),origin:void 0===a[1]||void 0===a[2]?void 0:{x:Number(a[1]),y:Number(a[2])},velocity:x(a[3])};case"transform":return{...n,kind:i,origin:{x:Number(a[0]),y:Number(a[1])},delta:{x:Number(a[2]),y:Number(a[3])},scale:Number(a[4]),degrees:Number(a[5]),durationMs:x(a[6])};default:throw new t("INVALID_ARGS","gesture requires pan, fling, swipe, pinch, rotate, or transform")}}},ed={gesture:b(v.gesture,function(e){switch(e.kind){case"pan":return["pan",String(e.origin?.x),String(e.origin?.y),String(e.delta?.x),String(e.delta?.y),...M(e.durationMs)];case"fling":return["fling",C(e.direction,"gesture fling requires direction"),String(e.origin?.x),String(e.origin?.y),...M(e.distance),...M(e.durationMs)];case"swipe":return ep(e);case"pinch":return["pinch",String(e.scale),...M(e.origin?.x),...M(e.origin?.y)];case"rotate":return["rotate",String(e.degrees),...M(e.origin?.x),...M(e.origin?.y),...M(e.velocity)];case"transform":return["transform",String(e.origin?.x),String(e.origin?.y),String(e.delta?.x),String(e.delta?.y),String(e.scale),String(e.degrees),...M(e.durationMs)];default:throw new t("INVALID_ARGS","gesture requires pan, fling, swipe, pinch, rotate, or transform")}}),"gesture-pan":b(v.gesture,function(e){return["pan",String(e.x),String(e.y),String(e.dx),String(e.dy),...M(e.durationMs)]}),"gesture-fling":b(v.gesture,e=>{var t;let r;return r=void 0!==(t=e).durationMs?t.distance??180:t.distance,["fling",t.direction,String(t.x),String(t.y),...M(r),...M(t.durationMs)]}),"gesture-swipe":b(v.gesture,ep),"gesture-pinch":b(v.gesture,function(e){return["pinch",String(e.scale),...M(e.x),...M(e.y)]}),"gesture-rotate":b(v.gesture,e=>(function(e){var r=e;if(void 0===r.x&&void 0!==r.y||void 0!==r.x&&void 0===r.y)throw new t("INVALID_ARGS","gesture rotate center requires both x and y");let i=void 0===e.x||void 0===e.y?[]:[String(e.x),String(e.y)];return["rotate",String(e.degrees),...i,...M(e.velocity)]})(e)),"gesture-transform":b(v.gesture,function(e){return["transform",String(e.x),String(e.y),String(e.dx),String(e.dy),String(e.scale),String(e.degrees),...M(e.durationMs)]})};function ep(e){return["swipe",C(e.preset,"gesture swipe requires preset"),...M(e.durationMs)]}let ef={perf:(e,r)=>({..._(r),...function(e){if(void 0!==e[0]&&void 0===e[1]){let t=ey(e[0],{allowUndefined:!0});if(t)return{action:t}}return{area:function(e){if(void 0===e)return;let r=e.toLowerCase();if(E(r))return r;throw new t("INVALID_ARGS",V)}(e[0]),action:ey(e[1])}}(e)}),logs:(e,r)=>({..._(r),action:function(e){if(void 0!==e){if("path"===e||"start"===e||"stop"===e||"doctor"===e||"mark"===e||"clear"===e)return e;throw new t("INVALID_ARGS","logs requires path, start, stop, doctor, mark, or clear")}}(e[0]),message:e.slice(1).join(" ")||void 0,restart:r.restart}),network:(e,r)=>({..._(r),action:function(e){if(void 0!==e){if("dump"===e||"log"===e)return e;throw new t("INVALID_ARGS","network requires dump or log")}}(e[0]),limit:x(e[1]),include:r.networkInclude??function(e){if(void 0!==e){if("summary"===e||"headers"===e||"body"===e||"all"===e)return e;throw new t("INVALID_ARGS","network include mode must be summary, headers, body, or all")}}(e[2])}),record:(e,t)=>({..._(t),action:eg(e[0],"record"),path:e[1],fps:t.fps,quality:t.quality,hideTouches:t.hideTouches}),trace:(e,t)=>({..._(t),action:eg(e[0],"trace"),path:e[1]})},em={perf:b(v.perf,e=>{var t;return[...N((t=e).area??(t.action?"metrics":void 0)),...N(t.action)]}),logs:b(v.logs,e=>{var t;return[(t=e).action??"path",...N(t.message)]}),network:e=>{var t;return w(v.network,[...(t=e).action?[t.action]:[],...M(t.limit)],{...e,networkInclude:e.include})},record:b(v.record,e=>eh(e)),trace:b(v.trace,e=>eh(e))};function eh(e){return[e.action,...N(e.path)]}function eg(e,r){if("start"===e||"stop"===e)return e;throw new t("INVALID_ARGS",`${r} requires start|stop`)}function ey(e,r={}){if(void 0===e)return;let i=e.toLowerCase();if(q(i))return i;if(!r.allowUndefined)throw new t("INVALID_ARGS",G)}let ev={replay:(e,t)=>({..._(t),path:I(e[0],"replay requires path"),update:t.replayUpdate,backend:t.replayMaestro?"maestro":void 0,env:t.replayEnv}),test:(e,t)=>({..._(t),paths:e,update:t.replayUpdate,backend:t.replayMaestro?"maestro":void 0,env:t.replayEnv,failFast:t.failFast,timeoutMs:t.timeoutMs,retries:t.retries,artifactsDir:t.artifactsDir,reportJunit:t.reportJunit,shardAll:t.shardAll,shardSplit:t.shardSplit})};function eS(e){return e.backend??(!0===e.maestro?"maestro":void 0)}function ew(e){let t={};for(let[r,i]of Object.entries(e))"string"==typeof i&&r.startsWith("AD_VAR_")&&(t[r]=i);return t}let eA={find:(e,r)=>(function(e,r){var i;let a={...{depth:(i=r).snapshotDepth,raw:i.snapshotRaw},...k(r),first:r.findFirst,last:r.findLast},n=function(e){if("text"===e||"label"===e||"value"===e||"role"===e||"id"===e)return e}(e[0]),o=void 0!==n,s=o?e[1]:e[0],l=o?2:1,u=e[l];if(void 0===u)return{...a,locator:n,query:eI(s)};if("get"===u){let r=e[l+1];if("text"===r)return{...a,locator:n,query:eI(s),action:"getText"};if("attrs"===r)return{...a,locator:n,query:eI(s),action:"getAttrs"};throw new t("INVALID_ARGS","find get only supports text or attrs")}if("wait"===u)return{...a,locator:n,query:eI(s),action:"wait",timeoutMs:x(e[l+1])};if("fill"===u||"type"===u)return{...a,locator:n,query:eI(s),action:u,value:e.slice(l+1).join(" ")};if("click"===u||"focus"===u||"exists"===u)return{...a,locator:n,query:eI(s),action:u};throw new t("INVALID_ARGS",`Unsupported find action: ${u}`)})(e,r),is:(e,r)=>(function(e,r){let i={...A(r),...k(r)},a=e[0],n=P(e.slice(1),{preferTrailingValue:"text"===a});if("text"===a)return{...i,predicate:a,selector:n.selectorExpression,value:n.rest.join(" ")};if("visible"===a||"hidden"===a||"exists"===a||"editable"===a||"selected"===a)return{...i,predicate:a,selector:n.selectorExpression};throw new t("INVALID_ARGS","is requires predicate: visible|hidden|exists|editable|selected|text")})(e,r)},eb={is:b(v.is,e=>{var t;return[(t=e).predicate,t.selector,..."text"===t.predicate?[t.value]:[]]}),find:e=>w(v.find,function(e){let t=e.locator&&"any"!==e.locator?[e.locator,e.query]:[e.query];switch(e.action){case void 0:case"click":case"focus":case"exists":return e.action?[...t,e.action]:t;case"getText":return[...t,"get","text"];case"getAttrs":return[...t,"get","attrs"];case"wait":return[...t,"wait",...M(e.timeoutMs)];case"fill":case"type":return[...t,e.action,e.value]}}(e),{...e,findFirst:e.first,findLast:e.last})};function eI(e){if(void 0===e||""===e)throw new t("INVALID_ARGS","find requires query");return e}let e_={appstate:(e,t)=>_(t),home:(e,t)=>_(t),"app-switcher":(e,t)=>_(t),back:(e,t)=>({..._(t),mode:t.backMode}),rotate:(e,t)=>({..._(t),orientation:U(e[0])}),keyboard:(e,r)=>({..._(r),...function(e){if(e.length>1)throw new t("INVALID_ARGS","keyboard accepts at most one action argument.");return $({action:function(e){let r=e?.toLowerCase();if("get"===r)return"status";if(void 0===r||"status"===r||"dismiss"===r||"enter"===r||"return"===r)return r;throw new t("INVALID_ARGS","keyboard action must be status, get, dismiss, enter, or return.")}(e[0])})}(e)}),clipboard:(e,r)=>({..._(r),...function(e){let r=e[0]?.toLowerCase();if("read"!==r&&"write"!==r)throw new t("INVALID_ARGS","clipboard requires a subcommand: read or write.");if("read"===r){if(1!==e.length)throw new t("INVALID_ARGS","clipboard read does not accept additional arguments.");return{action:r}}if(e.length<2)throw new t("INVALID_ARGS","clipboard write requires text.");return{action:r,text:e.slice(1).join(" ")}}(e)}),"react-native":(e,r)=>({..._(r),action:function(e){if("dismiss-overlay"===e)return e;throw new t("INVALID_ARGS","react-native supports only: dismiss-overlay")}(e[0])})},eN={appstate:b(v.appState),back:e=>{var t;return w(v.back,[],{...e,backMode:"in-app"===(t=e.mode)||"system"===t?t:void 0})},home:b(v.home),rotate:b(v.rotate,e=>[C(e.orientation,"rotate requires orientation")]),"app-switcher":b(v.appSwitcher),keyboard:b(v.keyboard,e=>N(e.action)),clipboard:b(v.clipboard,e=>{var t;return"read"===(t=e).action?["read"]:["write",t.text]}),"react-native":b(v.reactNative,e=>[C(e.action,"react-native requires action")])},eR={...es,...L,...z,...ed,...eb,...em,replay:e=>w(v.replay,[C(e.path,"replay requires path")],{...e,replayUpdate:e.update,replayBackend:eS(e),replayEnv:e.env,replayShellEnv:ew(process.env)}),test:e=>w(v.test,e.paths??[],{...e,replayUpdate:e.update,replayBackend:eS(e),replayEnv:e.env,replayShellEnv:ew(process.env)}),...eN,batch:e=>w(v.batch,[],{...e,batchSteps:function(e){if(!Array.isArray(e)||0===e.length)throw new t("INVALID_ARGS","batch requires a non-empty steps array.");return e.map((e,r)=>{var i;let a,n,o,s,l,u;return o=function(e,r){let i="string"==typeof e.command?e.command.trim().toLowerCase():"";if(ex.has(i))return i;throw new t("INVALID_ARGS",`Batch step ${r} command is not available through command batch: ${String(e.command)}`)}(n=function(e,r){if(!e||"object"!=typeof e||Array.isArray(e))throw new t("INVALID_ARGS",`Invalid batch step ${r}.`);return e}(e,i=r+1),i),s=function(e,r){let i=e.input;if(!i||"object"!=typeof i||Array.isArray(i))throw new t("INVALID_ARGS",`Batch step ${r} input must be an object.`);return i}(n,i),l=function(e,r){let i=e.runtime;if(void 0!==i&&(!i||"object"!=typeof i||Array.isArray(i)))throw new t("INVALID_ARGS",`Batch step ${r} runtime must be an object.`);return i}(n,i),{...u={command:(a=ek(o,s)).command,positionals:a.positionals,flags:Z(a.options),runtime:a.options.runtime},runtime:l??u.runtime}})}(e.steps),batchOnError:e.onError,batchMaxSteps:e.maxSteps})},eM=y,ex=D(eM);function ek(e,t){return eR[e](t)}export{eo as appCliReaders,eM as batchCommandNames,Z as buildFlags,ee as buildMeta,ec as gestureCliReaders,K as normalizeDeployResult,B as normalizeDevice,T as normalizeInstallFromSourceResult,F as normalizeMaterializationReleaseResult,W as normalizeOpenDevice,J as normalizeRuntimeHints,O as normalizeSession,Q as normalizeStartupSample,ef as observabilityCliReaders,er as parseInstallSourceConfig,ek as prepareDaemonCommandRequest,Y as readScreenshotOverlayRefs,X as readSnapshotNodes,ev as replayCliReaders,et as resolveSessionName,eA as selectorCliReaders,e_ as systemCliReaders};
|
|
1
|
+
import{screenshotFlagsFromOptions as e,screenshotOptionsFromFlags as t}from"./695.js";import{AppError as r}from"./9152.js";import{readRequiredString as i,readRequiredPlatform as n,readRequiredDeviceKind as o,readNullableString as a,readDeviceTarget as s,readRect as u,asRecord as l,stripUndefined as c,isRecord as d,readRequiredNumber as p,readPoint as f,readOptionalString as m}from"./7455.js";import{buildAppIdentifiers as h,isPerfAction as g,PERF_AREA_ERROR_MESSAGE as v,LOG_ACTION_VALUES as w,PERF_ACTION_ERROR_MESSAGE as y,buildDeviceIdentifiers as S,isPerfArea as A}from"./2672.js";import{splitSelectorFromArgs as b,tryParseSelectorChain as I}from"./8407.js";import{compactRecord as _}from"./9974.js";import{INTERNAL_COMMANDS as N,parseStringMember as M,PUBLIC_COMMANDS as x,BATCH_COMMAND_NAMES as R}from"./5898.js";import{readLocationCoordinate as D}from"./9673.js";import{parseWaitPositionals as k}from"./2284.js";import{readInteractionTargetFromPositionals as L,readFillTargetFromPositionals as V}from"./3393.js";import{NETWORK_INCLUDE_MODES as G}from"./9616.js";import{parseDeviceRotation as q}from"./1534.js";import{assertResolvedAppsFilter as C}from"./3675.js";function P(e,t){let r=m(e,"bundleId"),o=m(e,"package");return{app:i(e,"app"),appPath:i(e,"appPath"),platform:n(e,"platform"),appId:r??o,bundleId:r,package:o,identifiers:h({session:t,bundleId:r,packageName:o})}}function E(e,t){let i=m(e,"bundleId"),n=m(e,"packageName"),o=i??n??m(e,"appId"),a=m(e,"launchTarget")??n??i??o;if(!a)throw new r("COMMAND_FAILED",'Daemon response is missing "launchTarget".',{response:e});return{appName:m(e,"appName"),appId:o,bundleId:i,packageName:n,launchTarget:a,installablePath:m(e,"installablePath"),archivePath:m(e,"archivePath"),materializationId:m(e,"materializationId"),materializationExpiresAt:m(e,"materializationExpiresAt"),identifiers:h({session:t,bundleId:i,packageName:n,appId:o})}}function U(e){return{released:!0===e.released,materializationId:i(e,"materializationId"),identifiers:{}}}function $(e){let{record:t,platform:r,id:i,name:n,target:a}=K(e,"name");return{platform:r,target:a,kind:o(t,"kind"),id:i,name:n,booted:"boolean"==typeof t.booted?t.booted:void 0,identifiers:S(r,i,n),...j(r,i)}}function F(e){let{record:t,platform:r,id:n,name:o,target:s}=K(e,"name"),u=i(t,"device"),l={session:o,...S(r,n,u)};return{name:o,createdAt:p(t,"createdAt"),sessionStateDir:m(t,"sessionStateDir"),runnerLogPath:m(t,"runnerLogPath"),device:{platform:r,target:s,id:n,name:u,identifiers:l,...j(r,n,a(t,"ios_simulator_device_set"))},identifiers:l}}function K(e,t){let r=l(e);return{record:r,platform:n(r,"platform"),id:i(r,"id"),name:i(r,t),target:s(r,"target")}}function j(e,t,r){return{ios:"ios"===e?{udid:t,...void 0!==r?{simulatorSetPath:r}:{}}:void 0,android:"android"===e?{serial:t}:void 0}}function O(e){if(!d(e))return;let t=e.platform,r=m(e,"metroHost"),i="number"==typeof e.metroPort?e.metroPort:void 0;return{platform:"ios"===t||"android"===t?t:void 0,metroHost:r,metroPort:i,bundleUrl:m(e,"bundleUrl"),launchUrl:m(e,"launchUrl")}}function T(e){let t=e.platform,r=m(e,"id"),i=m(e,"device");if("ios"!==t&&"macos"!==t&&"android"!==t&&"linux"!==t||!r||!i)return;let n=s(e,"target"),o=S(t,r,i);return{platform:t,target:n,id:r,name:i,identifiers:o,ios:"ios"===t?{udid:m(e,"device_udid")??r,simulatorSetPath:a(e,"ios_simulator_device_set")}:void 0,android:"android"===t?{serial:m(e,"serial")??r}:void 0}}function z(e){if(d(e)&&"number"==typeof e.durationMs&&"string"==typeof e.measuredAt&&"string"==typeof e.method)return{durationMs:e.durationMs,measuredAt:e.measuredAt,method:e.method,appTarget:m(e,"appTarget"),appBundleId:m(e,"appBundleId")}}function H(e){return Array.isArray(e)?e:[]}function B(e){let t=e.overlayRefs;if(!Array.isArray(t))return;let r=[];for(let e of t){if(!d(e))continue;let t=m(e,"ref"),i=u(e,"rect"),n=u(e,"overlayRect"),o=f(e,"center");t&&i&&n&&o&&r.push({ref:t,label:m(e,"label"),rect:i,overlayRect:n,center:o})}return r}function J(t){return c({stateDir:t.stateDir,daemonBaseUrl:t.daemonBaseUrl,daemonAuthToken:t.daemonAuthToken,daemonTransport:t.daemonTransport,daemonServerMode:t.daemonServerMode,tenant:t.tenant,sessionIsolation:t.sessionIsolation,runId:t.runId,leaseId:t.leaseId,leaseBackend:t.leaseBackend,platform:t.platform,target:t.target,device:t.device,udid:t.udid,serial:t.serial,iosSimulatorDeviceSet:t.iosSimulatorDeviceSet,androidDeviceAllowlist:t.androidDeviceAllowlist,surface:t.surface,activity:t.activity,launchConsole:t.launchConsole,launchArgs:t.launchArgs,relaunch:t.relaunch,shutdown:t.shutdown,saveScript:t.saveScript,noDeviceHub:t.noDeviceHub,noRecord:t.noRecord,backMode:t.backMode,metroHost:t.metroHost,metroPort:t.metroPort,bundleUrl:t.bundleUrl,launchUrl:t.launchUrl,snapshotInteractiveOnly:t.interactiveOnly,snapshotCompact:t.compact,snapshotDepth:t.depth,snapshotScope:t.scope,snapshotRaw:t.raw,snapshotForceFull:t.forceFull,...e(t),appsFilter:t.appsFilter,out:t.out,count:t.count,fps:t.fps,quality:t.quality,hideTouches:t.hideTouches,intervalMs:t.intervalMs,delayMs:t.delayMs,holdMs:t.holdMs,jitterPx:t.jitterPx,pixels:t.pixels,doubleTap:t.doubleTap,clickButton:t.clickButton,pauseMs:t.pauseMs,pattern:t.pattern,headless:t.headless,restart:t.restart,replayUpdate:t.replayUpdate,replayBackend:t.replayBackend,replayEnv:t.replayEnv,replayShellEnv:t.replayShellEnv,failFast:t.failFast,timeoutMs:t.timeoutMs,retries:t.retries,recordVideo:t.recordVideo,artifactsDir:t.artifactsDir,reportJunit:t.reportJunit,shardAll:t.shardAll,shardSplit:t.shardSplit,findFirst:t.findFirst,findLast:t.findLast,networkInclude:t.networkInclude,batchOnError:t.batchOnError,batchMaxSteps:t.batchMaxSteps,batchSteps:t.batchSteps,verbose:t.debug})}function W(e){return c({requestId:e.requestId,cwd:e.cwd,sessionExplicit:void 0!==e.session,debug:e.debug,lockPolicy:e.lockPolicy,lockPlatform:e.lockPlatform,tenantId:e.tenant,runId:e.runId,leaseId:e.leaseId,leaseBackend:e.leaseBackend,leaseTtlMs:e.leaseTtlMs,sessionIsolation:e.sessionIsolation,installSource:e.installSource,retainMaterializedPaths:e.retainMaterializedPaths,materializedPathRetentionMs:e.materializedPathRetentionMs,materializationId:e.materializationId})}function Q(e){return e??"default"}function X(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw new r("INVALID_ARGS",`${t} installSource must be an object.`);if("github-actions-artifact"!==ee(e.type,`${t} installSource.type`))throw new r("INVALID_ARGS",`${t} installSource.type must be "github-actions-artifact".`);let{owner:i,repo:n}=Z(ee(e.repo,`${t} installSource.repo`),`${t} installSource.repo`);return Y(i,n,e.artifact,`${t} installSource.artifact`)}function Y(e,t,i,n){var o;return"number"==typeof i||"string"==typeof(o=i)&&/^\d+$/.test(o.trim())?{kind:"github-actions-artifact",owner:e,repo:t,artifactId:function(e,t){let i="number"==typeof e?e:"string"==typeof e?Number(e):NaN;if(!Number.isInteger(i))throw new r("INVALID_ARGS",`${t} must be an integer.`);return i}(i,n)}:{kind:"github-actions-artifact",owner:e,repo:t,artifactName:ee(i,n)}}function Z(e,t){let i=e.indexOf("/");if(i<=0||i===e.length-1||-1!==e.indexOf("/",i+1))throw new r("INVALID_ARGS",`${t} must use owner/repo.`);let n={owner:e.slice(0,i).trim(),repo:e.slice(i+1).trim()};if(!n.owner||!n.repo)throw new r("INVALID_ARGS",`${t} must use owner/repo.`);return n}function ee(e,t){let i="string"==typeof e&&e.trim().length>0?e.trim():void 0;if(!i)throw new r("INVALID_ARGS",`${t} must be a non-empty string.`);return i}function et(e,t){return r=>er(e,t?t(r):[],r)}function er(e,t,r){return{command:e,positionals:t,options:function(e){var t;let r="mobile"===(t=e.deviceTarget??e.target)||"tv"===t||"desktop"===t?t:void 0;if(void 0===r&&void 0===e.target)return e;let{target:i,...n}=e;return void 0===r?n:{...n,target:r}}(r)}}function ei(e){return _({session:e.session,platform:e.platform,deviceTarget:e.target,device:e.device,udid:e.udid,serial:e.serial,iosSimulatorDeviceSet:e.iosSimulatorDeviceSet,androidDeviceAllowlist:e.androidDeviceAllowlist})}function en(e){return{platform:e.platform,target:e.target,device:e.device,udid:e.udid,serial:e.serial,iosSimulatorDeviceSet:e.iosSimulatorDeviceSet,androidDeviceAllowlist:e.androidDeviceAllowlist}}function eo(e){return _({depth:e.snapshotDepth,scope:e.snapshotScope,raw:e.snapshotRaw})}function ea(e){return{depth:e.snapshotDepth,scope:e.snapshotScope,raw:e.snapshotRaw}}function es(e){return _({count:e.count,intervalMs:e.intervalMs,holdMs:e.holdMs,jitterPx:e.jitterPx,doubleTap:e.doubleTap})}function eu(e){return"ref"in e&&void 0!==e.ref?_({kind:"ref",ref:e.ref,label:e.label}):"selector"in e&&void 0!==e.selector?{kind:"selector",selector:e.selector}:{kind:"point",x:e.x,y:e.y}}function el(e){let t=ec(e);if("string"==typeof t.ref)return[t.ref,...ep(t.label)];if("string"==typeof t.selector)return[t.selector];if("point"===t.kind||void 0!==t.x||void 0!==t.y)return[String(ed(t.x,"x")),String(ed(t.y,"y"))];throw new r("INVALID_ARGS","interaction requires @ref, selector, or point target")}function ec(e){if(!e||"object"!=typeof e||Array.isArray(e))throw new r("INVALID_ARGS","Expected target object.");let t=e.target;return t&&"object"==typeof t&&!Array.isArray(t)?t:e}function ed(e,t){if("number"!=typeof e||!Number.isFinite(e))throw new r("INVALID_ARGS",`point target requires numeric ${t}.`);return e}function ep(e){return"string"==typeof e&&e.length>0?[e]:[]}function ef(...e){return new Set(e)}function em(e,t){return void 0!==e&&t.has(e)}function eh(e){return void 0!==e&&""!==e.trim()&&Number.isFinite(Number(e))}function eg(e){return void 0===e?void 0:Number(e)}function ev(e){return void 0===e?[]:[e]}function ew(e){return void 0===e?[]:[String(e)]}function ey(e,t){if(void 0===e||""===e)throw new r("INVALID_ARGS",t);return e}function eS(e,t){if("string"!=typeof e||0===e.length)throw new r("INVALID_ARGS",t);return e}let eA={devices:(e,t)=>ei(t),apps:(e,t)=>({...ei(t),appsFilter:C(t.appsFilter)}),session:(e,t)=>({...ei(t),action:function(e){let t=e??"list";if("list"===t||"state-dir"===t)return t;throw new r("INVALID_ARGS","session only supports list or state-dir")}(e[0])}),boot:(e,t)=>({...ei(t),headless:t.headless}),shutdown:(e,t)=>ei(t),prepare:(e,t)=>({...ei(t),action:ey(e[0],"prepare requires subcommand"),timeoutMs:t.timeoutMs}),open:(e,t)=>({...ei(t),app:e[0],url:e[1],surface:t.surface,activity:t.activity,launchConsole:t.launchConsole,launchArgs:t.launchArgs,relaunch:t.relaunch,saveScript:t.saveScript,noDeviceHub:t.noDeviceHub,noRecord:t.noRecord}),close:(e,t)=>({...ei(t),app:e[0],shutdown:t.shutdown,saveScript:t.saveScript}),install:eI,reinstall:eI,"install-from-source":(e,t)=>({...ei(t),source:function(e,t){let i=e[0]?.trim();if(e.length>1)throw new r("INVALID_ARGS","install-from-source accepts either one <url> positional or --github-actions-artifact");let n=t.githubActionsArtifact?function(e,t="--github-actions-artifact"){let i=e.indexOf(":");if(i<=0||i===e.length-1)throw new r("INVALID_ARGS",`${t} must use owner/repo:artifact, for example thymikee/RNCLI83:6635342232`);let{owner:n,repo:o}=Z(e.slice(0,i),t);return Y(n,o,e.slice(i+1),`${t} artifact`)}(t.githubActionsArtifact):void 0,o=t.installSource;if(1!=+!!i+ +!!n+ +!!o)throw new r("INVALID_ARGS","install-from-source requires exactly one source: <url>, --github-actions-artifact, or config installSource");if(!i&&t.header&&t.header.length>0)throw new r("INVALID_ARGS","install-from-source --header is only supported for URL sources");return n||o||{kind:"url",url:i,headers:function(e){if(!e||0===e.length)return;let t={};for(let i of e){let e=i.indexOf(":");if(e<=0)throw new r("INVALID_ARGS",`Invalid --header value "${i}". Expected "name:value".`);let n=i.slice(0,e).trim(),o=i.slice(e+1).trim();if(!n)throw new r("INVALID_ARGS",`Invalid --header value "${i}". Header name cannot be empty.`);t[n]=o}return t}(t.header)}}(e,t),retainPaths:t.retainPaths,retentionMs:t.retentionMs}),push:(e,t)=>({...ei(t),app:ey(e[0],"push requires bundleOrPackage"),payload:ey(e[1],"push requires payloadOrJson")}),"trigger-app-event":(e,t)=>({...ei(t),event:ey(e[0],"trigger-app-event requires event"),payload:e[1]?function(e,t){try{let t=JSON.parse(e);if(t&&"object"==typeof t&&!Array.isArray(t))return t}catch{}throw new r("INVALID_ARGS",`${t} must be a JSON object`)}(e[1],"trigger-app-event payload"):void 0})},eb={devices:et(x.devices),boot:et(x.boot),shutdown:et(x.shutdown),prepare:et(x.prepare,e=>[eS(e.action,"prepare requires subcommand")]),apps:et(x.apps),open:et(x.open,function(e){return e.app?e.url?[e.app,e.url]:[e.app]:[]}),close:et(x.close,e=>ev(e.app)),install:et(x.install,e=>e_(e.app,e.appPath)),reinstall:et(x.reinstall,e=>e_(e.app,e.appPath)),"install-from-source":e=>er(N.installSource,[],{...e,installSource:e.source,retainMaterializedPaths:e.retainPaths,materializedPathRetentionMs:e.retentionMs}),push:et(x.push,e=>{var t;return[(t=e).app,"string"==typeof t.payload?t.payload:JSON.stringify(t.payload)]}),"trigger-app-event":et(x.triggerAppEvent,e=>{var t;return[(t=e).event,...t.payload?[JSON.stringify(t.payload)]:[]]})};function eI(e,t,r="install"){return{...ei(t),app:ey(e[0],`${r} requires app`),appPath:ey(e[1],`${r} requires path`)}}function e_(e,t){return[eS(e,"missing first positional"),eS(t,"missing second positional")]}let eN={snapshot:(e,t)=>({...ei(t),interactiveOnly:t.snapshotInteractiveOnly,compact:t.snapshotCompact,depth:t.snapshotDepth,scope:t.snapshotScope,raw:t.snapshotRaw,forceFull:t.snapshotForceFull,timeoutMs:t.timeoutMs}),screenshot:(e,r)=>({...ei(r),path:e[0]??r.out,...t(r)}),diff:(e,t)=>{if("snapshot"!==e[0])throw new r("INVALID_ARGS","Only diff snapshot is available through this parser.");return{...ei(t),kind:"snapshot",out:t.out,interactiveOnly:t.snapshotInteractiveOnly,compact:t.snapshotCompact,depth:t.snapshotDepth,scope:t.snapshotScope,raw:t.snapshotRaw}},wait:(e,t)=>(function(e,t){let i=k(e);if(!i)throw new r("INVALID_ARGS","wait requires <ms>, text <text>, @ref, or <selector> [timeoutMs].");let n={...en(t),...ea(t)};if("sleep"===i.kind)return{...n,durationMs:i.durationMs};if("text"===i.kind){if(!i.text)throw new r("INVALID_ARGS","wait requires text.");return{...n,text:i.text,...ex(i.timeoutMs)}}return"ref"===i.kind?{...n,ref:i.rawRef,...ex(i.timeoutMs)}:{...n,selector:i.selectorExpression,...ex(i.timeoutMs)}})(e,t),alert:(e,t)=>({...ei(t),...function(e){if(e.length>2)throw new r("INVALID_ARGS","alert accepts at most action and timeout arguments.");return _({action:function(e){let t=e?.toLowerCase();if(void 0===t||"get"===t||"accept"===t||"dismiss"===t||"wait"===t)return t;throw new r("INVALID_ARGS","alert action must be get, accept, dismiss, or wait.")}(e[0]),timeoutMs:function(e,t){if(void 0===e)return;let i=Number(e);if(Number.isFinite(i))return i;throw new r("INVALID_ARGS",`${t} must be a finite number.`)}(e[1],"alert timeout")})}(e)}),settings:(e,t)=>(function(e,t){let i=en(t),n=e[0],o=e[1];if(em(n,eR)&&em(o,eD))return{...i,setting:n,state:o};if("location"===n&&"set"===o)return{...i,setting:n,state:o,latitude:D(e[2],"latitude"),longitude:D(e[3],"longitude")};if("appearance"===n&&em(o,ek)||em(n,eL)&&em(o,eV)||"fingerprint"===n&&em(o,eG))return{...i,setting:n,state:o};if("permission"===n&&em(o,eq))return{...i,setting:n,state:o,permission:function(e){if(em(e,eC))return e;throw new r("INVALID_ARGS","settings permission requires a permission target.")}(e[2]),mode:function(e){if(void 0===e||"full"===e||"limited"===e)return e;throw new r("INVALID_ARGS","settings permission mode must be full or limited.")}(e[3])};if("clear-app-state"===n){let t="clear"===o?e[2]:o;return{...i,setting:n,state:"clear",app:t}}throw new r("INVALID_ARGS","Invalid settings arguments.")})(e,t)},eM={snapshot:et(x.snapshot),screenshot:t=>er(x.screenshot,ev(t.path),{...t,...e(t)}),diff:et(x.diff,e=>[eS(e.kind,"diff requires kind")]),wait:et(x.wait,e=>(function(e){if(1!==[void 0!==e.durationMs?"durationMs":void 0,void 0!==e.text?"text":void 0,void 0!==e.ref?"ref":void 0,void 0!==e.selector?"selector":void 0].filter(Boolean).length)throw new r("INVALID_ARGS","wait command requires exactly one of durationMs, text, ref, or selector.");if(void 0!==e.durationMs)return[String(e.durationMs)];let t=ew(e.timeoutMs);if(void 0!==e.text)return["text",e.text,...t];if(void 0!==e.ref)return[e.ref,...t];let i=e.selector;if(!I(i))throw new r("INVALID_ARGS",`Invalid wait selector: ${i}`);return[i,...t]})(e)),alert:et(x.alert,e=>{var t;return[(t=e).action??"get",...ew(t.timeoutMs)]}),settings:et(x.settings,e=>{var t;return"clear-app-state"===(t=e).setting?[t.setting,...ev(t.app)]:"location"===t.setting&&"set"===t.state?[t.setting,t.state,String(t.latitude),String(t.longitude)]:"permission"===t.setting?[t.setting,t.state,t.permission,...ev(t.mode)]:[t.setting,t.state]})};function ex(e){return null===e?{}:{timeoutMs:e}}let eR=ef("wifi","airplane","location","animations"),eD=ef("on","off"),ek=ef("light","dark","toggle"),eL=ef("faceid","touchid"),eV=ef("match","nonmatch","enroll","unenroll"),eG=ef("match","nonmatch"),eq=ef("grant","deny","reset"),eC=ef("camera","microphone","photos","contacts","contacts-limited","notifications","calendar","location","location-always","media-library","motion","reminders","siri","accessibility","screen-recording","input-monitoring"),eP={gesture:function(e,t){let i=e[0],n=e.slice(1),o=ei(t);switch(i){case"pan":return{...o,kind:i,origin:{x:Number(n[0]),y:Number(n[1])},delta:{x:Number(n[2]),y:Number(n[3])},durationMs:eg(n[4])};case"fling":return{...o,kind:i,direction:n[0],origin:{x:Number(n[1]),y:Number(n[2])},distance:eg(n[3]),durationMs:eg(n[4])};case"swipe":return{...o,kind:i,preset:n[0],durationMs:eg(n[1])};case"pinch":return{...o,kind:i,scale:Number(n[0]),origin:void 0===n[1]||void 0===n[2]?void 0:{x:Number(n[1]),y:Number(n[2])}};case"rotate":return{...o,kind:i,degrees:Number(n[0]),origin:void 0===n[1]||void 0===n[2]?void 0:{x:Number(n[1]),y:Number(n[2])},velocity:eg(n[3])};case"transform":return{...o,kind:i,origin:{x:Number(n[0]),y:Number(n[1])},delta:{x:Number(n[2]),y:Number(n[3])},scale:Number(n[4]),degrees:Number(n[5]),durationMs:eg(n[6])};default:throw new r("INVALID_ARGS","gesture requires pan, fling, swipe, pinch, rotate, or transform")}}},eE={gesture:et(x.gesture,function(e){switch(e.kind){case"pan":return["pan",String(e.origin?.x),String(e.origin?.y),String(e.delta?.x),String(e.delta?.y),...ew(e.durationMs)];case"fling":return["fling",eS(e.direction,"gesture fling requires direction"),String(e.origin?.x),String(e.origin?.y),...ew(e.distance),...ew(e.durationMs)];case"swipe":return eU(e);case"pinch":return["pinch",String(e.scale),...ew(e.origin?.x),...ew(e.origin?.y)];case"rotate":return["rotate",String(e.degrees),...ew(e.origin?.x),...ew(e.origin?.y),...ew(e.velocity)];case"transform":return["transform",String(e.origin?.x),String(e.origin?.y),String(e.delta?.x),String(e.delta?.y),String(e.scale),String(e.degrees),...ew(e.durationMs)];default:throw new r("INVALID_ARGS","gesture requires pan, fling, swipe, pinch, rotate, or transform")}}),"gesture-pan":et(x.gesture,function(e){return["pan",String(e.x),String(e.y),String(e.dx),String(e.dy),...ew(e.durationMs)]}),"gesture-fling":et(x.gesture,e=>{var t;let r;return r=void 0!==(t=e).durationMs?t.distance??180:t.distance,["fling",t.direction,String(t.x),String(t.y),...ew(r),...ew(t.durationMs)]}),"gesture-swipe":et(x.gesture,eU),"gesture-pinch":et(x.gesture,function(e){return["pinch",String(e.scale),...ew(e.x),...ew(e.y)]}),"gesture-rotate":et(x.gesture,e=>(function(e){var t=e;if(void 0===t.x&&void 0!==t.y||void 0!==t.x&&void 0===t.y)throw new r("INVALID_ARGS","gesture rotate center requires both x and y");let i=void 0===e.x||void 0===e.y?[]:[String(e.x),String(e.y)];return["rotate",String(e.degrees),...i,...ew(e.velocity)]})(e)),"gesture-transform":et(x.gesture,function(e){return["transform",String(e.x),String(e.y),String(e.dx),String(e.dy),String(e.scale),String(e.degrees),...ew(e.durationMs)]})};function eU(e){return["swipe",eS(e.preset,"gesture swipe requires preset"),...ew(e.durationMs)]}let e$={click:(e,t)=>({...ei(t),...eo(t),...es(t),target:eu(L(e)),button:t.clickButton}),press:(e,t)=>({...ei(t),...eo(t),...es(t),target:eu(L(e))}),longpress:(e,t)=>{let r,i={...L((r=function(e){if(eh(e[0])&&eh(e[1]))return{target:e.slice(0,2),...void 0!==e[2]?{durationMs:Number(e[2])}:{}};let t=e.at(-1);return e.length>1&&eh(t)?{target:e.slice(0,-1),durationMs:Number(t)}:{target:e}}(e)).target),...void 0!==r.durationMs?{durationMs:r.durationMs}:{}};return{...ei(t),...eo(t),target:eu(i),durationMs:i.durationMs}},swipe:(e,t)=>({...ei(t),from:{x:Number(e[0]),y:Number(e[1])},to:{x:Number(e[2]),y:Number(e[3])},durationMs:eg(e[4]),count:t.count,pauseMs:t.pauseMs,pattern:t.pattern}),focus:(e,t)=>({...ei(t),x:Number(e[0]),y:Number(e[1])}),type:(e,t)=>({...ei(t),text:e.join(" "),delayMs:t.delayMs}),fill:(e,t)=>{let r=V(e);return{...ei(t),...eo(t),target:eu(r.target),text:r.text,delayMs:t.delayMs}},scroll:(e,t)=>({...ei(t),direction:function(e){if("up"===e||"down"===e||"left"===e||"right"===e||"top"===e||"bottom"===e)return e;throw new r("INVALID_ARGS",`Unknown direction: ${String(e)}`)}(e[0]),amount:eg(e[1]),pixels:t.pixels}),get:(e,t)=>({...ei(t),...eo(t),format:function(e){if("text"===e||"attrs"===e)return e;throw new r("INVALID_ARGS","get only supports text or attrs")}(e[0]),target:eu(function(e){if(e[0]?.startsWith("@"))return{ref:e[0],label:e.slice(1).join(" ").trim()||void 0};let t=e.join(" ").trim();if(!t)throw new r("INVALID_ARGS","get requires @ref or selector expression");return{selector:t}}(e.slice(1)))})},eF={click:e=>er(x.click,el(e),{...e,clickButton:e.button}),press:et(x.press,e=>el(e)),longpress:et(x.longPress,e=>{var t;return[...el(t=e),...ew(t.durationMs)]}),swipe:et(x.swipe,function(e){return[String(e.from?.x),String(e.from?.y),String(e.to?.x),String(e.to?.y),...ew(e.durationMs)]}),focus:et(x.focus,e=>[String(e.x),String(e.y)]),type:et(x.type,e=>[e.text]),fill:et(x.fill,e=>{var t;return[...el(t=e),t.text]}),scroll:et(x.scroll,e=>[eS(e.direction,"scroll requires direction"),...ew(e.amount)]),get:et(x.get,e=>[eS(e.format,"get requires format"),...function(e){let t=ec(e);if("string"==typeof t.ref)return[t.ref,...ep(t.label)];if("string"==typeof t.selector)return[t.selector];throw new r("INVALID_ARGS","element command requires @ref or selector target")}(e)])},eK={perf:(e,t)=>({...ei(t),...function(e){if(void 0!==e[0]&&void 0===e[1]){let t=ez(e[0],{allowUndefined:!0});if(t)return{action:t}}return{area:function(e){if(void 0===e)return;let t=e.toLowerCase();if(A(t))return t;throw new r("INVALID_ARGS",v)}(e[0]),action:ez(e[1])}}(e)}),logs:(e,t)=>({...ei(t),action:function(e){if(void 0!==e)return M(w,e,{message:"logs requires path, start, stop, doctor, mark, or clear"})}(e[0]),message:e.slice(1).join(" ")||void 0,restart:t.restart}),network:(e,t)=>({...ei(t),action:function(e){if(void 0!==e){if("dump"===e||"log"===e)return e;throw new r("INVALID_ARGS","network requires dump or log")}}(e[0]),limit:eg(e[1]),include:t.networkInclude??function(e){if(void 0!==e)return M(G,e,{message:"network include mode must be summary, headers, body, or all"})}(e[2])}),record:(e,t)=>({...ei(t),action:eT(e[0],"record"),path:e[1],fps:t.fps,quality:t.quality,hideTouches:t.hideTouches}),trace:(e,t)=>({...ei(t),action:eT(e[0],"trace"),path:e[1]})},ej={perf:et(x.perf,e=>{var t;return[...ev((t=e).area??(t.action?"metrics":void 0)),...ev(t.action)]}),logs:et(x.logs,e=>{var t;return[(t=e).action??"path",...ev(t.message)]}),network:e=>{var t;return er(x.network,[...(t=e).action?[t.action]:[],...ew(t.limit)],{...e,networkInclude:e.include})},record:et(x.record,e=>eO(e)),trace:et(x.trace,e=>eO(e))};function eO(e){return[e.action,...ev(e.path)]}function eT(e,t){if("start"===e||"stop"===e)return e;throw new r("INVALID_ARGS",`${t} requires start|stop`)}function ez(e,t={}){if(void 0===e)return;let i=e.toLowerCase();if(g(i))return i;if(!t.allowUndefined)throw new r("INVALID_ARGS",y)}let eH={replay:(e,t)=>({...ei(t),path:ey(e[0],"replay requires path"),update:t.replayUpdate,backend:t.replayMaestro?"maestro":void 0,env:t.replayEnv}),test:(e,t)=>({...ei(t),paths:e,update:t.replayUpdate,backend:t.replayMaestro?"maestro":void 0,env:t.replayEnv,failFast:t.failFast,timeoutMs:t.timeoutMs,retries:t.retries,recordVideo:t.recordVideo,artifactsDir:t.artifactsDir,reportJunit:t.reportJunit,shardAll:t.shardAll,shardSplit:t.shardSplit})};function eB(e){return e.backend??(!0===e.maestro?"maestro":void 0)}function eJ(e){let t={};for(let[r,i]of Object.entries(e))"string"==typeof i&&r.startsWith("AD_VAR_")&&(t[r]=i);return t}let eW={find:(e,t)=>(function(e,t){var i;let n={...{depth:(i=t).snapshotDepth,raw:i.snapshotRaw},...en(t),first:t.findFirst,last:t.findLast},o=function(e){if("text"===e||"label"===e||"value"===e||"role"===e||"id"===e)return e}(e[0]),a=void 0!==o,s=a?e[1]:e[0],u=a?2:1,l=e[u];if(void 0===l)return{...n,locator:o,query:eX(s)};if("get"===l){let t=e[u+1];if("text"===t)return{...n,locator:o,query:eX(s),action:"getText"};if("attrs"===t)return{...n,locator:o,query:eX(s),action:"getAttrs"};throw new r("INVALID_ARGS","find get only supports text or attrs")}if("wait"===l)return{...n,locator:o,query:eX(s),action:"wait",timeoutMs:eg(e[u+1])};if("fill"===l||"type"===l)return{...n,locator:o,query:eX(s),action:l,value:e.slice(u+1).join(" ")};if("click"===l||"focus"===l||"exists"===l)return{...n,locator:o,query:eX(s),action:l};throw new r("INVALID_ARGS",`Unsupported find action: ${l}`)})(e,t),is:(e,t)=>(function(e,t){let i={...ea(t),...en(t)},n=e[0],o=function(e,t={}){let i=b(e,t);if(!i)throw new r("INVALID_ARGS","is requires a selector expression");return i}(e.slice(1),{preferTrailingValue:"text"===n});if("text"===n)return{...i,predicate:n,selector:o.selectorExpression,value:o.rest.join(" ")};if("visible"===n||"hidden"===n||"exists"===n||"editable"===n||"selected"===n)return{...i,predicate:n,selector:o.selectorExpression};throw new r("INVALID_ARGS","is requires predicate: visible|hidden|exists|editable|selected|text")})(e,t)},eQ={is:et(x.is,e=>{var t;return[(t=e).predicate,t.selector,..."text"===t.predicate?[t.value]:[]]}),find:e=>er(x.find,function(e){let t=e.locator&&"any"!==e.locator?[e.locator,e.query]:[e.query];switch(e.action){case void 0:case"click":case"focus":case"exists":return e.action?[...t,e.action]:t;case"getText":return[...t,"get","text"];case"getAttrs":return[...t,"get","attrs"];case"wait":return[...t,"wait",...ew(e.timeoutMs)];case"fill":case"type":return[...t,e.action,e.value]}}(e),{...e,findFirst:e.first,findLast:e.last})};function eX(e){if(void 0===e||""===e)throw new r("INVALID_ARGS","find requires query");return e}let eY={appstate:(e,t)=>ei(t),home:(e,t)=>ei(t),"app-switcher":(e,t)=>ei(t),back:(e,t)=>({...ei(t),mode:t.backMode}),rotate:(e,t)=>({...ei(t),orientation:q(e[0])}),keyboard:(e,t)=>({...ei(t),...function(e){if(e.length>1)throw new r("INVALID_ARGS","keyboard accepts at most one action argument.");return _({action:function(e){let t=e?.toLowerCase();if("get"===t)return"status";if(void 0===t||"status"===t||"dismiss"===t||"enter"===t||"return"===t)return t;throw new r("INVALID_ARGS","keyboard action must be status, get, dismiss, enter, or return.")}(e[0])})}(e)}),clipboard:(e,t)=>({...ei(t),...function(e){let t=e[0]?.toLowerCase();if("read"!==t&&"write"!==t)throw new r("INVALID_ARGS","clipboard requires a subcommand: read or write.");if("read"===t){if(1!==e.length)throw new r("INVALID_ARGS","clipboard read does not accept additional arguments.");return{action:t}}if(e.length<2)throw new r("INVALID_ARGS","clipboard write requires text.");return{action:t,text:e.slice(1).join(" ")}}(e)}),"react-native":(e,t)=>({...ei(t),action:function(e){if("dismiss-overlay"===e)return e;throw new r("INVALID_ARGS","react-native supports only: dismiss-overlay")}(e[0])})},eZ={appstate:et(x.appState),back:e=>{var t;return er(x.back,[],{...e,backMode:"in-app"===(t=e.mode)||"system"===t?t:void 0})},home:et(x.home),rotate:et(x.rotate,e=>[eS(e.orientation,"rotate requires orientation")]),"app-switcher":et(x.appSwitcher),keyboard:et(x.keyboard,e=>ev(e.action)),clipboard:et(x.clipboard,e=>{var t;return"read"===(t=e).action?["read"]:["write",t.text]}),"react-native":et(x.reactNative,e=>[eS(e.action,"react-native requires action")])},e0={...eb,...eM,...eF,...eE,...eQ,...ej,replay:e=>er(x.replay,[eS(e.path,"replay requires path")],{...e,replayUpdate:e.update,replayBackend:eB(e),replayEnv:e.env,replayShellEnv:eJ(process.env)}),test:e=>er(x.test,e.paths??[],{...e,replayUpdate:e.update,replayBackend:eB(e),replayEnv:e.env,replayShellEnv:eJ(process.env)}),...eZ,batch:e=>er(x.batch,[],{...e,batchSteps:function(e){if(!Array.isArray(e)||0===e.length)throw new r("INVALID_ARGS","batch requires a non-empty steps array.");return e.map((e,t)=>{var i;let n,o,a,s,u,l;return a=function(e,t){let i="string"==typeof e.command?e.command.trim().toLowerCase():"";if(e2.has(i))return i;throw new r("INVALID_ARGS",`Batch step ${t} command is not available through command batch: ${String(e.command)}`)}(o=function(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw new r("INVALID_ARGS",`Invalid batch step ${t}.`);return e}(e,i=t+1),i),s=function(e,t){let i=e.input;if(!i||"object"!=typeof i||Array.isArray(i))throw new r("INVALID_ARGS",`Batch step ${t} input must be an object.`);return i}(o,i),u=function(e,t){let i=e.runtime;if(void 0!==i&&(!i||"object"!=typeof i||Array.isArray(i)))throw new r("INVALID_ARGS",`Batch step ${t} runtime must be an object.`);return i}(o,i),{...l={command:(n=e3(a,s)).command,positionals:n.positionals,flags:J(n.options),runtime:n.options.runtime},runtime:u??l.runtime}})}(e.steps),batchOnError:e.onError,batchMaxSteps:e.maxSteps})},e1=R,e2=new Set(e1);function e3(e,t){return e0[e](t)}export{eA as appCliReaders,e1 as batchCommandNames,J as buildFlags,W as buildMeta,eN as captureCliReaders,ei as commonInputFromFlags,eP as gestureCliReaders,e$ as interactionCliReaders,P as normalizeDeployResult,$ as normalizeDevice,E as normalizeInstallFromSourceResult,U as normalizeMaterializationReleaseResult,T as normalizeOpenDevice,O as normalizeRuntimeHints,F as normalizeSession,z as normalizeStartupSample,eK as observabilityCliReaders,X as parseInstallSourceConfig,e3 as prepareDaemonCommandRequest,B as readScreenshotOverlayRefs,H as readSnapshotNodes,eH as replayCliReaders,Q as resolveSessionName,eW as selectorCliReaders,eY as systemCliReaders};
|
package/dist/src/8806.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{promises as t}from"node:fs";import e from"node:os";import a from"node:path";import{asAppError as n,AppError as i}from"./9152.js";import{emitDiagnostic as r}from"./7599.js";import{runCmd as o,resolveFileOverridePath as s,whichCmd as l,runCmdDetached as d}from"./9818.js";import{ensureAndroidSdkPathConfigured as u,resolveAndroidArchivePackageName as c}from"./7651.js";import{sleep as p}from"./4829.js";import{createAndroidPortReverseManager as f,resolveAndroidAdbProvider as m,installAndroidAdbPackage as w,resolveAndroidAdbExecutor as h}from"./9639.js";import{materializeInstallablePath as A,isTrustedInstallSourceUrl as y}from"./989.js";let g=["mCurrentFocus=Window{","mFocusedApp=AppWindowToken{","mResumedActivity:","ResumedActivity:"],v=/\bApplication Not Responding:\s*([A-Za-z0-9_.]+)/i,_=/([^{}]*\bis(?:n't| not)\s+responding[^{}]*)/i,M=/\b([A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z0-9_]+)+)\b/;function b(t){let e=new Set;for(let a of t.split("\n")){let t=a.trim();if(!t)continue;let n=t.split(/\s+/)[0]??"";if(!n.includes("/"))continue;let i=n.split("/")[0]??"";i.includes(".")&&i&&e.add(i)}return Array.from(e)}function I(t){return t.split("\n").map(t=>{let e=t.trim();return e.startsWith("package:")?e.slice(8):e}).filter(Boolean)}function N(t){return O(t,t=>(function(t){for(let e of t.trim().split(/\s+/)){let t=e.indexOf("/");if(t<=0)continue;let a=D(e.slice(0,t),!1),n=D(e.slice(t+1),!0);if(a&&n&&a.length===t)return{package:a,activity:n}}return null})(t))}function O(t,e){let a=t.split("\n");for(let t of g)for(let n of a){let a=n.indexOf(t);if(-1===a)continue;let i=n.trim(),r=e(n.slice(a+t.length),i);if(r)return r}return null}function D(t,e){let a=0;for(;a<t.length&&function(t,e){if(!t)return!1;let a=t.charCodeAt(0);return a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||"_"===t||"."===t||e&&"$"===t}(t[a],e);)a+=1;return t.slice(0,a)}function
|
|
1
|
+
import{promises as t}from"node:fs";import e from"node:os";import a from"node:path";import{asAppError as n,AppError as i}from"./9152.js";import{emitDiagnostic as r}from"./7599.js";import{runCmd as o,resolveFileOverridePath as s,whichCmd as l,runCmdDetached as d}from"./9818.js";import{ensureAndroidSdkPathConfigured as u,resolveAndroidArchivePackageName as c}from"./7651.js";import{sleep as p}from"./4829.js";import{createAndroidPortReverseManager as f,resolveAndroidAdbProvider as m,installAndroidAdbPackage as w,resolveAndroidAdbExecutor as h}from"./9639.js";import{materializeInstallablePath as A,isTrustedInstallSourceUrl as y}from"./989.js";let g=["mCurrentFocus=Window{","mFocusedApp=AppWindowToken{","mResumedActivity:","ResumedActivity:"],v=/\bApplication Not Responding:\s*([A-Za-z0-9_.]+)/i,_=/([^{}]*\bis(?:n't| not)\s+responding[^{}]*)/i,M=/\b([A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z0-9_]+)+)\b/;function b(t){let e=new Set;for(let a of t.split("\n")){let t=a.trim();if(!t)continue;let n=t.split(/\s+/)[0]??"";if(!n.includes("/"))continue;let i=n.split("/")[0]??"";i.includes(".")&&i&&e.add(i)}return Array.from(e)}function I(t){return t.split("\n").map(t=>{let e=t.trim();return e.startsWith("package:")?e.slice(8):e}).filter(Boolean)}function N(t){return O(t,t=>(function(t){for(let e of t.trim().split(/\s+/)){let t=e.indexOf("/");if(t<=0)continue;let a=D(e.slice(0,t),!1),n=D(e.slice(t+1),!0);if(a&&n&&a.length===t)return{package:a,activity:n}}return null})(t))}function O(t,e){let a=t.split("\n");for(let t of g)for(let n of a){let a=n.indexOf(t);if(-1===a)continue;let i=n.trim(),r=e(n.slice(a+t.length),i);if(r)return r}return null}function D(t,e){let a=0;for(;a<t.length&&function(t,e){if(!t)return!1;let a=t.charCodeAt(0);return a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||"_"===t||"."===t||e&&"$"===t}(t[a],e);)a+=1;return t.slice(0,a)}function E(t){let e=t.trim();if(!e||/\s/.test(e))return!1;let a=/^([A-Za-z][A-Za-z0-9+.-]*):(.+)$/.exec(e);if(!a)return!1;let n=a[1]?.toLowerCase(),i=a[2]??"";return"http"!==n&&"https"!==n&&"ws"!==n&&"wss"!==n&&"ftp"!==n&&"ftps"!==n||i.startsWith("//")}function C(t){let e=t.trim().split(":")[0]?.toLowerCase();return"http"===e||"https"===e}function T(t,e){let a=t?.trim();return a||(C(e)?"com.apple.mobilesafari":void 0)}function L(t={}){let e=t.ttlMs??3e4,a=t.nowMs??Date.now,n=new Map,i=t=>{var e;let a=[(e=t).platform,e.deviceId,""].join("\0");for(let t of n.keys())t.startsWith(a)&&n.delete(t)};return{get(t,e){let i=k(t,e),r=n.get(i);if(r)return r.expiresAtMs<=a()?void n.delete(i):r.value},set:(t,i,r)=>(n.set(k(t,i),{value:r,expiresAtMs:a()+e}),r),clear(t){i(t)},async invalidateWhile(t,e){i(t);try{return await e()}finally{i(t)}}}}function k(t,e){return[t.platform,t.deviceId,t.variant??"",e.trim().toLowerCase()].join("\0")}function S(t){return["1","true","yes","on"].includes((t??"").trim().toLowerCase())}class R{startedAtMs;expiresAtMs;constructor(t,e){this.startedAtMs=t,this.expiresAtMs=t+Math.max(0,e)}static fromTimeoutMs(t,e=Date.now()){return new R(e,t)}remainingMs(t=Date.now()){return Math.max(0,this.expiresAtMs-t)}elapsedMs(t=Date.now()){return Math.max(0,t-this.startedAtMs)}isExpired(t=Date.now()){return 0>=this.remainingMs(t)}}async function x(t,e={},a={}){let n,r={maxAttempts:e.maxAttempts??3,baseDelayMs:e.baseDelayMs??200,maxDelayMs:e.maxDelayMs??2e3,jitter:e.jitter??.2,shouldRetry:e.shouldRetry};for(let e=1;e<=r.maxAttempts;e+=1){if(a.signal?.aborted)throw new i("COMMAND_FAILED","request canceled",{reason:"request_canceled"});if(a.deadline?.isExpired()&&e>1)break;try{let n=await t({attempt:e,maxAttempts:r.maxAttempts,deadline:a.deadline});return a.onEvent?.({phase:a.phase,event:"succeeded",attempt:e,maxAttempts:r.maxAttempts,elapsedMs:a.deadline?.elapsedMs(),remainingMs:a.deadline?.remainingMs()}),P({phase:a.phase,event:"succeeded",attempt:e,maxAttempts:r.maxAttempts,elapsedMs:a.deadline?.elapsedMs(),remainingMs:a.deadline?.remainingMs()}),n}catch(d){n=d;let t=a.classifyReason?.(d),i={phase:a.phase,event:"attempt_failed",attempt:e,maxAttempts:r.maxAttempts,elapsedMs:a.deadline?.elapsedMs(),remainingMs:a.deadline?.remainingMs(),reason:t};if(a.onEvent?.(i),P(i),e>=r.maxAttempts||r.shouldRetry&&!r.shouldRetry(d,e))break;let o=function(t,e,a,n){let i=Math.min(e,t*2**(n-1));return Math.max(0,i+i*a*(2*Math.random()-1))}(r.baseDelayMs,r.maxDelayMs,r.jitter,e),s=a.deadline?Math.min(o,a.deadline.remainingMs()):o;if(s<=0)break;let l={phase:a.phase,event:"retry_scheduled",attempt:e,maxAttempts:r.maxAttempts,delayMs:s,elapsedMs:a.deadline?.elapsedMs(),remainingMs:a.deadline?.remainingMs(),reason:t};a.onEvent?.(l),P(l),await function(t,e){return new Promise(a=>{if(e?.aborted)return void a();let n=!1,i=()=>{n||(n=!0,e&&e.removeEventListener("abort",o),a())},r=setTimeout(i,t);function o(){clearTimeout(r),i()}e&&e.addEventListener("abort",o,{once:!0})})}(s,a.signal)}}let o={phase:a.phase,event:"exhausted",attempt:r.maxAttempts,maxAttempts:r.maxAttempts,elapsedMs:a.deadline?.elapsedMs(),remainingMs:a.deadline?.remainingMs(),reason:a.classifyReason?.(n)};if(a.onEvent?.(o),P(o),n)throw n;throw new i("COMMAND_FAILED","retry failed")}async function U(t,e={}){return x(()=>t(),{maxAttempts:e.attempts,baseDelayMs:e.baseDelayMs,maxDelayMs:e.maxDelayMs,jitter:e.jitter,shouldRetry:e.shouldRetry})}function P(t){r({level:"attempt_failed"===t.event||"exhausted"===t.event?"warn":"debug",phase:"retry",data:{...t}})}function F(t){return t?.trim()||void 0}function B(t){return F(t)}function $(t){return new Set(t.split(/[\s,]+/).map(t=>t.trim()).filter(Boolean))}function V(t,e=process.env){let a=F(t)??F(e.AGENT_DEVICE_ANDROID_DEVICE_ALLOWLIST);if(a)return $(a)}let W=new Set(["IOS_BOOT_TIMEOUT","IOS_RUNNER_CONNECT_TIMEOUT","IOS_TOOL_MISSING","ANDROID_BOOT_TIMEOUT","ADB_TRANSPORT_UNAVAILABLE","CI_RESOURCE_STARVATION_SUSPECTED"]);function G(t){return W.has(t.toUpperCase())}function j(t){let e=t.error?n(t.error):null,a=t.context?.platform,i=t.context?.phase;if(e?.code==="TOOL_MISSING")return"android"===a?"ADB_TRANSPORT_UNAVAILABLE":"IOS_TOOL_MISSING";let r=e?.details??{},o="string"==typeof r.message?r.message:void 0,s="string"==typeof r.stdout?r.stdout:void 0,l="string"==typeof r.stderr?r.stderr:void 0,d=r.boot&&"object"==typeof r.boot?r.boot:null,u=r.bootstatus&&"object"==typeof r.bootstatus?r.bootstatus:null,c=[t.message,e?.message,t.stdout,t.stderr,o,s,l,"string"==typeof d?.stdout?d.stdout:void 0,"string"==typeof d?.stderr?d.stderr:void 0,"string"==typeof u?.stdout?u.stdout:void 0,"string"==typeof u?.stderr?u.stderr:void 0].filter(Boolean).join("\n").toLowerCase();return"ios"===a&&(c.includes("runner did not accept connection")||"connect"===i&&(c.includes("timed out")||c.includes("timeout")||c.includes("econnrefused")||c.includes("connection refused")||c.includes("fetch failed")||c.includes("socket hang up")))?"IOS_RUNNER_CONNECT_TIMEOUT":"ios"===a&&"boot"===i&&(c.includes("timed out")||c.includes("timeout"))?"IOS_BOOT_TIMEOUT":"android"===a&&"boot"===i&&(c.includes("timed out")||c.includes("timeout"))?"ANDROID_BOOT_TIMEOUT":c.includes("resource temporarily unavailable")||c.includes("killed: 9")||c.includes("cannot allocate memory")||c.includes("system is low on memory")?"CI_RESOURCE_STARVATION_SUSPECTED":"android"===a&&(c.includes("device not found")||c.includes("no devices")||c.includes("device offline")||c.includes("offline")||c.includes("unauthorized")||c.includes("not authorized")||c.includes("unable to locate device")||c.includes("invalid device"))?"ADB_TRANSPORT_UNAVAILABLE":e?.code==="COMMAND_FAILED"||c.length>0?"BOOT_COMMAND_FAILED":"UNKNOWN"}function H(t){switch(t){case"IOS_BOOT_TIMEOUT":return"Retry simulator boot and inspect simctl bootstatus logs; in CI reduce parallel jobs or use a larger runner.";case"IOS_RUNNER_CONNECT_TIMEOUT":return"Retry runner startup, inspect xcodebuild logs, and verify simulator responsiveness before command execution.";case"ANDROID_BOOT_TIMEOUT":return"Retry emulator startup and verify sys.boot_completed reaches 1; consider increasing startup budget in CI.";case"ADB_TRANSPORT_UNAVAILABLE":return"Check adb server/device transport (adb devices -l), restart adb, and ensure the target device is online and authorized.";case"CI_RESOURCE_STARVATION_SUSPECTED":return"CI machine may be resource constrained; reduce parallel jobs or use a larger runner.";case"IOS_TOOL_MISSING":return"Xcode command-line tools are missing or not in PATH; run xcode-select --install and verify xcrun works.";case"BOOT_COMMAND_FAILED":return"Inspect command stderr/stdout for the failing boot phase and retry after environment validation.";default:return"Retry once and inspect verbose logs for the failing phase."}}let K=["android.software.leanback","android.software.leanback_only","android.hardware.type.television"];async function z(t,e,a){let n=Array(t.length),i=0,r=Math.min(e,t.length);return await Promise.all(Array.from({length:r},async()=>{for(;i<t.length;){let e=i;i+=1,n[e]=await a(t[e])}})),n}function q(t){return`${t.stdout}
|
|
2
2
|
${t.stderr}`}function Z(t,e){return["-s",t,...e]}function J(t){return t.startsWith("emulator-")}function X(t){return t.toLowerCase().replace(/_/g," ").replace(/\s+/g," ").trim()}async function Q(t,e=1e4){return o("adb",Z(t,["shell","getprop","sys.boot_completed"]),{allowFailure:!0,timeoutMs:e})}async function Y(t,e){let a=e.replace(/_/g," ").trim();if(!J(t))return a||t;let n=await te(t);return n?n.replace(/_/g," "):a||t}async function tt(t,e,a){try{return await a("adb",Z(t,e),{allowFailure:!0,timeoutMs:1e4})}catch(t){var i;if("COMMAND_FAILED"===(i=n(t)).code&&"number"==typeof i.details?.timeoutMs)return;throw t}}async function te(t,e=o){for(let a of["ro.boot.qemu.avd_name","persist.sys.avd_name"]){let n=await tt(t,["shell","getprop",a],e);if(!n)continue;let i=n.stdout.trim();if(0===n.exitCode&&i.length>0)return i}let a=await tt(t,["emu","avd","name"],e);if(!a)return;let n=function(t){let e=t.split("\n").map(t=>t.trim()).filter(t=>t.length>0);if(0!==e.length)return"OK"===e.at(-1)&&e.pop(),e.join("\n").trim()||void 0}(a.stdout);if(0===a.exitCode&&n)return n}async function ta(t,e){let a=q(await o("adb",Z(t,["shell","cmd","package","has-feature",e]),{allowFailure:!0,timeoutMs:1e4})).toLowerCase();return!!a.includes("true")||!a.includes("false")&&null}async function tn(t){return(await z(K,2,async e=>await ta(t,e))).some(t=>!0===t)}async function ti(t){var e;let a;return"tv"===((a=q(await o("adb",Z(t,["shell","getprop","ro.build.characteristics"]),{allowFailure:!0,timeoutMs:1e4})).toLowerCase()).includes("tv")||a.includes("leanback")?"tv":null)||await tn(t)?"tv":(e=q(await o("adb",Z(t,["shell","pm","list","features"]),{allowFailure:!0,timeoutMs:1e4})),/feature:android\.(software\.leanback(_only)?|hardware\.type\.television)\b/i.test(e))?"tv":"mobile"}async function tr(t={}){if(await u(),!await l("adb"))throw new i("TOOL_MISSING","adb not found in PATH");let e=t.serialAllowlist??V(void 0),a=(await to()).filter(t=>!e||e.has(t.serial));return await z(a,3,async({serial:t,rawModel:e})=>{let[a,n,i]=await Promise.all([Y(t,e),tu(t),ti(t)]);return{platform:"android",id:t,name:a,kind:J(t)?"emulator":"device",target:i,booted:n}})}async function to(){return(await o("adb",["devices","-l"],{timeoutMs:1e4})).stdout.split("\n").map(t=>t.trim()).filter(t=>t.length>0&&!t.startsWith("List of devices")).map(t=>t.split(/\s+/)).flatMap(t=>{let e=t[0];return void 0===e||"device"!==t[1]?[]:[{serial:e,rawModel:(t.find(t=>t.startsWith("model:"))??"").replace("model:","")}]})}async function ts(){let t=await o("emulator",["-list-avds"],{allowFailure:!0,timeoutMs:1e4});if(0!==t.exitCode)throw new i("COMMAND_FAILED","Failed to list Android emulator AVDs",{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode,hint:"Verify Android emulator tooling is installed and available in PATH."});return t.stdout.split("\n").map(t=>t.trim()).filter(t=>t.length>0)}async function tl(t){let e=Date.now();for(;Date.now()-e<t.timeoutMs;){try{let e=await td(t.avdName,t.serial);if(e)return{platform:"android",id:e,name:t.avdName,kind:"emulator",target:"mobile",booted:!1}}catch{}await p(1e3)}throw new i("COMMAND_FAILED","Android emulator did not appear in time",{avdName:t.avdName,serial:t.serial,timeoutMs:t.timeoutMs,hint:"Check emulator logs and verify the AVD can start from command line."})}async function td(t,e){let a=X(t);for(let t of(await to()).filter(t=>(!e||t.serial===e)&&J(t.serial)))if(X(t.rawModel)===a||X(await Y(t.serial,t.rawModel))===a)return t.serial}async function tu(t){try{let e=await Q(t);return"1"===e.stdout.trim()}catch{return!1}}async function tc(t){var e,a;let n;await u();let r=t.avdName.trim();if(!r)throw new i("INVALID_ARGS","Android emulator boot requires a non-empty AVD name.");let o=t.timeoutMs??12e4;if(!await l("adb"))throw new i("TOOL_MISSING","adb not found in PATH");if(!await l("emulator"))throw new i("TOOL_MISSING","emulator not found in PATH");let s=await ts(),c=function(t,e){let a=t.find(t=>t===e);if(a)return a;let n=X(e);return t.find(t=>X(t)===n)}(s,r);if(!c)throw new i("DEVICE_NOT_FOUND",`No Android emulator AVD named ${t.avdName}`,{requestedAvdName:r,availableAvds:s,hint:"Run `emulator -list-avds` and pass an existing AVD name to --device."});let p=Date.now(),f=(e=await tr(),a=t.serial,n=X(c),e.find(t=>"android"===t.platform&&"emulator"===t.kind&&(!a||t.id===a)&&X(t.name)===n));if(!f){let e=["-avd",c];t.headless&&e.push("-no-window","-no-audio"),d("emulator",e)}let m=f??await tl({avdName:c,serial:t.serial,timeoutMs:o}),w=Math.max(1e3,o-(Date.now()-p));await tp(m.id,w);let h=(await tr()).find(t=>t.id===m.id);return h?{...h,name:c,booted:!0}:{...m,name:c,booted:!0}}async function tp(t,e=6e4){let a,r=R.fromTimeoutMs(e),o=Math.max(1,Math.ceil(e/1e3)),s=!1;try{await x(async({deadline:n})=>{if(n?.isExpired())throw s=!0,new i("COMMAND_FAILED","Android boot deadline exceeded",{serial:t,timeoutMs:e,elapsedMs:r.elapsedMs(),message:"timeout"});let o=Math.max(1e3,n?.remainingMs()??e),l=await Q(t,Math.min(o,1e4));if(a=l,"1"!==l.stdout.trim())throw new i("COMMAND_FAILED","Android device is still booting",{serial:t,stdout:l.stdout,stderr:l.stderr,exitCode:l.exitCode})},{maxAttempts:o,baseDelayMs:1e3,maxDelayMs:1e3,jitter:0,shouldRetry:t=>{let e=j({error:t,stdout:a?.stdout,stderr:a?.stderr,context:{platform:"android",phase:"boot"}});return"ADB_TRANSPORT_UNAVAILABLE"!==e&&"ANDROID_BOOT_TIMEOUT"!==e}},{deadline:r,phase:"boot",classifyReason:t=>j({error:t,stdout:a?.stdout,stderr:a?.stderr,context:{platform:"android",phase:"boot"}})})}catch(f){let o=n(f),l=a?.stdout,d=a?.stderr,u=a?.exitCode,c=j({error:f,stdout:l,stderr:d,context:{platform:"android",phase:"boot"}});"BOOT_COMMAND_FAILED"===c&&"Android device is still booting"===o.message&&(c="ANDROID_BOOT_TIMEOUT");let p={serial:t,timeoutMs:e,elapsedMs:r.elapsedMs(),reason:c,hint:H(c),stdout:l,stderr:d,exitCode:u};if(s||"ANDROID_BOOT_TIMEOUT"===c)throw new i("COMMAND_FAILED","Android device did not finish booting in time",p);if("TOOL_MISSING"===o.code)throw new i("TOOL_MISSING",o.message,{...p,...o.details??{}});if("ADB_TRANSPORT_UNAVAILABLE"===c)throw new i("COMMAND_FAILED",o.message,{...p,...o.details??{}});throw new i(o.code,o.message,{...p,...o.details??{}},o.cause)}}async function tf(t,e,a){return await h(t)(e,a)}function tm(t){return{platform:"android",id:t,name:t,kind:t.startsWith("emulator-")?"emulator":"device",booted:!0}}function tw(t,e){let a=`${t}
|
|
3
|
-
${e}`.toLowerCase();return a.includes("no shell command implementation")||a.includes("unknown command")}let th=/\.(?:apk|aab)$/i,tA=/^[A-Za-z_][\w]*(\.[A-Za-z_][\w]*)+$/;function ty(t){var e,a;let n=t.trim();return 0===n.length?"other":th.test(n)?n.includes("/")||n.includes("\\")||n.startsWith(".")||n.startsWith("~")||(e=n,!tA.test(e))?"binary":"package":(a=n,tA.test(a))?"package":"other"}function tg(t){return`Android runtime hints require an installed package name, not "${t}". Install or reinstall the app first, then relaunch by package.`}async function tv(t,e){let n="url"===t.kind&&y(t.url),i=await A({source:t,isInstallablePath:(t,e)=>{var n;let i;return e.isFile()&&(n=t,".apk"===(i=a.extname(n).toLowerCase())||".aab"===i)},installableLabel:"Android installable (.apk or .aab)",allowArchiveExtraction:"url"!==t.kind||n,signal:e?.signal});try{let t=e?.resolveIdentity===!1?{}:await t_(i.installablePath);return{archivePath:i.archivePath,installablePath:i.installablePath,packageName:t.packageName,cleanup:i.cleanup}}catch(t){throw await i.cleanup(),t}}async function t_(t){let e=a.extname(t).toLowerCase();return".apk"!==e&&".aab"!==e?{}:{packageName:await c(t)}}let tM={settings:{type:"intent",value:"android.settings.SETTINGS"}},tb="android.intent.category.LAUNCHER",tI="android.intent.category.LEANBACK_LAUNCHER",tN="android.intent.category.DEFAULT",tO="Run agent-device apps --platform android to discover the installed package name, then retry open with that exact package.",tD=new Set(["localhost","127.0.0.1","::1","[::1]"]),
|
|
3
|
+
${e}`.toLowerCase();return a.includes("no shell command implementation")||a.includes("unknown command")}let th=/\.(?:apk|aab)$/i,tA=/^[A-Za-z_][\w]*(\.[A-Za-z_][\w]*)+$/;function ty(t){var e,a;let n=t.trim();return 0===n.length?"other":th.test(n)?n.includes("/")||n.includes("\\")||n.startsWith(".")||n.startsWith("~")||(e=n,!tA.test(e))?"binary":"package":(a=n,tA.test(a))?"package":"other"}function tg(t){return`Android runtime hints require an installed package name, not "${t}". Install or reinstall the app first, then relaunch by package.`}async function tv(t,e){let n="url"===t.kind&&y(t.url),i=await A({source:t,isInstallablePath:(t,e)=>{var n;let i;return e.isFile()&&(n=t,".apk"===(i=a.extname(n).toLowerCase())||".aab"===i)},installableLabel:"Android installable (.apk or .aab)",allowArchiveExtraction:"url"!==t.kind||n,signal:e?.signal});try{let t=e?.resolveIdentity===!1?{}:await t_(i.installablePath);return{archivePath:i.archivePath,installablePath:i.installablePath,packageName:t.packageName,cleanup:i.cleanup}}catch(t){throw await i.cleanup(),t}}async function t_(t){let e=a.extname(t).toLowerCase();return".apk"!==e&&".aab"!==e?{}:{packageName:await c(t)}}let tM={settings:{type:"intent",value:"android.settings.SETTINGS"}},tb="android.intent.category.LAUNCHER",tI="android.intent.category.LEANBACK_LAUNCHER",tN="android.intent.category.DEFAULT",tO="Run agent-device apps --platform android to discover the installed package name, then retry open with that exact package.",tD=new Set(["localhost","127.0.0.1","::1","[::1]"]),tE=L();function tC(t){return{platform:"android",deviceId:t.id,variant:t.target??""}}async function tT(t,e){let a=e.trim();if("package"===ty(a))return{type:"package",value:a};let n=tM[a.toLowerCase()];if(n)return n;let r=tC(t),o=tE.get(r,a);if(o)return o;let s=(await tf(t,["shell","pm","list","packages"])).stdout.split("\n").map(t=>t.replace("package:","").trim()).filter(Boolean).filter(t=>t.toLowerCase().includes(a.toLowerCase())),l=s[0];if(void 0!==l&&1===s.length)return tE.set(r,a,{type:"package",value:l});if(s.length>1)throw new i("INVALID_ARGS",`Multiple packages matched "${e}"`,{matches:s,hint:"Run agent-device apps --platform android to see the exact installed package names before retrying open."});throw new i("APP_NOT_INSTALLED",`No package found matching "${e}"`,{hint:tO})}async function tL(t,e){let a=await tk(t);return("user-installed"===e?(await tR(t)).filter(t=>a.has(t)):Array.from(a)).sort((t,e)=>t.localeCompare(e)).map(t=>({package:t,name:tx(t)}))}async function tk(t){let e=new Set;for(let a of tS(t,{includeFallbackWhenUnknown:!0})){let n=await tf(t,["shell","cmd","package","query-activities","--brief","-a","android.intent.action.MAIN","-c",a],{allowFailure:!0});if(0===n.exitCode&&0!==n.stdout.trim().length)for(let t of b(n.stdout))e.add(t)}return e}function tS(t,e={}){return"tv"===t.target?[tI]:"mobile"===t.target?[tb]:e.includeFallbackWhenUnknown?[tb,tI]:[tb]}async function tR(t){return I((await tf(t,["shell","pm","list","packages","-3"])).stdout)}function tx(t){let e=new Set(["com","android","google","app","apps","service","services","mobile","client"]),a=t.split(".").flatMap(t=>t.split(/[_-]+/)).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0),n=a[a.length-1]??t;for(let t=a.length-1;t>=0;t-=1){let i=a[t];if(i&&!e.has(i)){n=i;break}}return n.split(/[^a-z0-9]+/i).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}async function tU(t){let e=await tF(t,[["shell","dumpsys","window","windows"],["shell","dumpsys","window"]]);if(e)return e;let a=await tF(t,[["shell","dumpsys","activity","activities"],["shell","dumpsys","activity"]]);return a||{}}async function tP(t){return await tB(t,[["shell","dumpsys","window","windows"],["shell","dumpsys","window"]])}async function tF(t,e){for(let a of e){let e=N((await tf(t,a,{allowFailure:!0})).stdout??"");if(e)return e}return null}async function tB(t,e){for(let a of e){let e=O((await tf(t,a,{allowFailure:!0})).stdout??"",(t,e)=>(function(t,e){let a=t.split("}")[0]?.trim()??t.trim(),n=v.exec(a);if(n){let t=n[1];return{package:t,focusedWindow:`Application Not Responding: ${t}`,raw:e}}let i=_.exec(a);if(!i)return null;let r=i[1];if(void 0===r)return null;let o=r.trim().replace(/\s+/g," "),s=M.exec(o)?.[1];return{...s?{package:s}:{},focusedWindow:o,raw:e}})(t,e));if(e)return e}return null}async function t$(t,e){let a=function(t){let e;try{e=new URL(t)}catch{return null}let a=e.hostname.toLowerCase();if(!tD.has(a)||!e.port)return null;let n=Number(e.port);return Number.isInteger(n)?`tcp:${n}`:null}(e);if(!a)return;let n=f(m(t));try{await n.ensure({local:a,remote:a})}catch(e){let t={localPort:a.replace("tcp:",""),operation:`adb reverse ${a} ${a}`};throw e instanceof i&&Object.assign(t,{hint:e.details?.hint,diagnosticId:e.details?.diagnosticId,logPath:e.details?.logPath}),new i("COMMAND_FAILED",`Failed to ensure Android port reverse ${a} before opening localhost URL`,t,e)}}function tV(t){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function tW(t){return(t.launchArgs??[]).map(tV)}async function tG(t,e,a){var n;t.booted||await tp(t.id);let i="string"==typeof(n=a)?{activity:n}:n??{},r=i.activity,o=e.trim();if(E(o))return void await tj(t,o,i);if(void 0!==i.url)return void await tH(t,e,i);let s=await tT(t,e),l=tS(t)[0]??tb;"intent"===s.type?await tK(t,s.value,i):r?await tz(t,s.value,r,l,i):await tq(t,s.value,l,i)}async function tj(t,e,a){var n;let r;if(a.activity)throw new i("INVALID_ARGS","Activity override is not supported when opening a deep link URL");await t$(t,e),await tf(t,["shell","am","start","-W","-a","android.intent.action.VIEW","-d",e,...(n=a.appBundleId,(r=n?.trim())?["-p",r]:[]),...tW(a)])}async function tH(t,e,a){if(a.activity)throw new i("INVALID_ARGS","Activity override is not supported when opening an app-bound deep link URL");let n=a.url?.trim()??"";if(!E(n))throw new i("INVALID_ARGS","Android app-bound open requires a valid URL target");let r=await tJ(t,e,"app-bound open");await tf(t,["shell","am","start","-W","-a","android.intent.action.VIEW","-d",n,"-p",r,...tW(a)])}async function tK(t,e,a){if(a.activity)throw new i("INVALID_ARGS","Activity override requires a package name, not an intent");await tf(t,["shell","am","start","-W","-a",e,...tW(a)])}async function tz(t,e,a,n,i){let r=a.includes("/")?a:`${e}/${a.startsWith(".")?a:`.${a}`}`;try{await tf(t,tZ(r,n,i))}catch(a){throw await tY(t,e,a),a}}async function tq(t,e,a,n){let r=await tf(t,["shell","am","start","-W","-a","android.intent.action.MAIN","-c",tN,"-c",a,"-p",e,...tW(n)],{allowFailure:!0});if(0===r.exitCode&&!t9(r.stdout,r.stderr))return;let o=await t1(t,e);if(!o){if(!await tQ(t,e))throw tX(e);throw new i("COMMAND_FAILED",`Failed to launch ${e}`,{stdout:r.stdout,stderr:r.stderr})}await tf(t,tZ(o,a,n))}function tZ(t,e,a){return["shell","am","start","-W","-a","android.intent.action.MAIN","-c",tN,"-c",e,"-n",t,...tW(a)]}async function tJ(t,e,a){let n=await tT(t,e);if("intent"===n.type)throw new i("INVALID_ARGS",`Android ${a} requires a package name, not an intent`);return n.value}function tX(t){return new i("APP_NOT_INSTALLED",`No package found matching "${t}"`,{package:t,hint:tO})}async function tQ(t,e){let a=await tf(t,["shell","pm","path",e],{allowFailure:!0}),n=`${a.stdout}
|
|
4
4
|
${a.stderr}`;return!!(0===a.exitCode&&/\bpackage:/i.test(n))||(t0(n),!1)}async function tY(t,e,a){if(t0(a instanceof i?`${String(a.details?.stdout??"")}
|
|
5
5
|
${String(a.details?.stderr??"")}`:"")||!await tQ(t,e))throw tX(e)}function t0(t){return/\bunknown package\b/i.test(t)||/\bpackage .* (?:was|is) not found\b/i.test(t)||/\bpackage .* does not exist\b/i.test(t)||/\bcould not find package\b/i.test(t)}async function t1(t,e){for(let a of Array.from(new Set(tS(t,{includeFallbackWhenUnknown:!0})))){let n=await tf(t,["shell","cmd","package","resolve-activity","--brief","-a","android.intent.action.MAIN","-c",a,e],{allowFailure:!0});if(0!==n.exitCode)continue;let i=t2(n.stdout);if(i)return i}return null}function t9(t,e){let a=`${t}
|
|
6
6
|
${e}`;return/Error:.*(?:Activity not started|unable to resolve Intent)/i.test(a)}function t2(t){let e=t.split("\n").map(t=>t.trim()).filter(Boolean);for(let t=e.length-1;t>=0;t-=1){let a=e[t];if(void 0===a||!a.includes("/"))continue;let n=a.split(/\s+/)[0];if(void 0!==n)return n}return null}async function t3(t){t.booted||await tp(t.id)}async function t4(t,e){if("settings"===e.trim().toLowerCase()){await tf(t,["shell","am","force-stop","com.android.settings"]),await t5(t,"com.android.settings");return}let a=await tT(t,e);if("intent"===a.type)throw new i("INVALID_ARGS","Close requires a package name, not an intent");await tf(t,["shell","am","force-stop",a.value]),await t5(t,a.value)}async function t5(t,e){await t8(t,e),await t6(t,e)}async function t8(t,e){let a=Date.now()+2e3;for(;Date.now()<a;){let a=await t7(t);if(a?.package!==e)return;await p(50)}}async function t7(t){for(let e of[["shell","dumpsys","window","windows"],["shell","dumpsys","window"],["shell","dumpsys","activity","activities"],["shell","dumpsys","activity"]]){let a=N((await tf(t,e,{allowFailure:!0})).stdout??"");if(a)return a}return null}async function t6(t,e){let a=Date.now()+2e3;for(;Date.now()<a;){if(!await et(t,e)&&(await p(150),!await et(t,e)))return;await p(50)}}async function et(t,e){return((await tf(t,["shell","pidof",e],{allowFailure:!0})).stdout??"").trim().length>0}async function ee(t,e){let a=await tT(t,e);if("intent"===a.type)throw new i("INVALID_ARGS","App uninstall requires a package name, not an intent");let n=await tf(t,["uninstall",a.value],{allowFailure:!0});if(0!==n.exitCode){let t=`${n.stdout}
|
|
7
|
-
${n.stderr}`.toLowerCase();if(!t.includes("unknown package")&&!t.includes("not installed"))throw new i("COMMAND_FAILED",`adb uninstall failed for ${a.value}`,{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode})}return{package:a.value}}let ea=null;async function en(){let t=`${process.env.PATH??""}::${process.env.AGENT_DEVICE_BUNDLETOOL_JAR??""}`;if(ea?.key===t)return ea.invocation;if(await l("bundletool")){let e={cmd:"bundletool",prefixArgs:[]};return ea={key:t,invocation:e},e}let e=await s(process.env.AGENT_DEVICE_BUNDLETOOL_JAR,"AGENT_DEVICE_BUNDLETOOL_JAR");if(!e)throw new i("TOOL_MISSING","bundletool not found in PATH. Install bundletool or set AGENT_DEVICE_BUNDLETOOL_JAR to a bundletool-all.jar path.");let a={cmd:"java",prefixArgs:["-jar",e]};return ea={key:t,invocation:a},a}async function ei(t){let e=await en();await o(e.cmd,[...e.prefixArgs,...t])}async function er(n,i){let r=m(n),o="universal";if(r.installBundle)return void await r.installBundle(i,{mode:o});let s=await t.mkdtemp(a.join(e.tmpdir(),"agent-device-aab-")),l=a.join(s,"bundle.apks");try{await ei(["build-apks","--bundle",i,"--output",l,"--mode",o]),await ei(["install-apks","--apks",l,"--device-id",n.id])}finally{await t.rm(s,{recursive:!0,force:!0})}}async function eo(t,e){".aab"===a.extname(e).toLowerCase()?await er(t,e):await w(e,{device:t,replace:!0})}async function es(t){return new Set((await tf(t,["shell","pm","list","packages"])).stdout.split("\n").map(t=>t.replace("package:","").trim()).filter(Boolean))}async function el(t,e){let a=Array.from(await es(t)).filter(t=>!e.has(t));if(1===a.length)return a[0]}async function ed(t,e){await
|
|
7
|
+
${n.stderr}`.toLowerCase();if(!t.includes("unknown package")&&!t.includes("not installed"))throw new i("COMMAND_FAILED",`adb uninstall failed for ${a.value}`,{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode})}return{package:a.value}}let ea=null;async function en(){let t=`${process.env.PATH??""}::${process.env.AGENT_DEVICE_BUNDLETOOL_JAR??""}`;if(ea?.key===t)return ea.invocation;if(await l("bundletool")){let e={cmd:"bundletool",prefixArgs:[]};return ea={key:t,invocation:e},e}let e=await s(process.env.AGENT_DEVICE_BUNDLETOOL_JAR,"AGENT_DEVICE_BUNDLETOOL_JAR");if(!e)throw new i("TOOL_MISSING","bundletool not found in PATH. Install bundletool or set AGENT_DEVICE_BUNDLETOOL_JAR to a bundletool-all.jar path.");let a={cmd:"java",prefixArgs:["-jar",e]};return ea={key:t,invocation:a},a}async function ei(t){let e=await en();await o(e.cmd,[...e.prefixArgs,...t])}async function er(n,i){let r=m(n),o="universal";if(r.installBundle)return void await r.installBundle(i,{mode:o});let s=await t.mkdtemp(a.join(e.tmpdir(),"agent-device-aab-")),l=a.join(s,"bundle.apks");try{await ei(["build-apks","--bundle",i,"--output",l,"--mode",o]),await ei(["install-apks","--apks",l,"--device-id",n.id])}finally{await t.rm(s,{recursive:!0,force:!0})}}async function eo(t,e){".aab"===a.extname(e).toLowerCase()?await er(t,e):await w(e,{device:t,replace:!0})}async function es(t){return new Set((await tf(t,["shell","pm","list","packages"])).stdout.split("\n").map(t=>t.replace("package:","").trim()).filter(Boolean))}async function el(t,e){let a=Array.from(await es(t)).filter(t=>!e.has(t));if(1===a.length)return a[0]}async function ed(t,e){await tE.invalidateWhile(tC(t),async()=>{t.booted||await tp(t.id),await eo(t,e)})}async function eu(t,e,a){let n=a?void 0:await es(t);return await ed(t,e),a??(n?await el(t,n):void 0)}async function ec(t,e){t.booted||await tp(t.id);let a=await tv({kind:"path",path:e});try{let e=await eu(t,a.installablePath,a.packageName),n=e?tx(e):void 0;return{archivePath:a.archivePath,installablePath:a.installablePath,packageName:e,appName:n,launchTarget:e}}finally{await a.cleanup()}}async function ep(t,e,a){return await tE.invalidateWhile(tC(t),async()=>{t.booted||await tp(t.id);let{package:n}=await ee(t,e),i=await tv({kind:"path",path:a},{resolveIdentity:!1});try{await ed(t,i.installablePath)}finally{await i.cleanup()}return{package:n}})}async function ef(t,e={}){let a=["logcat","-d","-v","time"];void 0!==e.lines&&a.push("-t",String(Math.max(1,Math.floor(e.lines))));let n=await t(a,{allowFailure:!0,timeoutMs:e.timeoutMs,signal:e.signal});if(0!==n.exitCode)throw new i("COMMAND_FAILED","Failed to capture Android logcat",{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode});return n.stdout}function em(t,e={}){if(!t.spawn)throw new i("UNSUPPORTED_OPERATION","Android ADB provider does not support streams",{capability:"adb.spawn"});let a=["logcat","-v","time"];e.pid&&a.push("--pid",e.pid);let n=t.spawn(a,{stdio:["ignore","pipe","pipe"],signal:e.signal});return e.output&&n.stdout&&n.stdout.pipe(e.output,{end:!1}),n}export{R as Deadline,tm as androidDeviceForSerial,H as bootFailureHint,ef as captureAndroidLogcatWithAdb,ty as classifyAndroidAppTarget,j as classifyBootFailure,t4 as closeAndroidApp,L as createAppResolutionCache,tc as ensureAndroidEmulatorBooted,tg as formatAndroidInstalledPackageRequiredMessage,tU as getAndroidAppState,tP as getAndroidBlockingDialogFocus,tx as inferAndroidAppName,ec as installAndroidApp,eu as installAndroidInstallablePathAndResolvePackageName,t9 as isAmStartError,tw as isClipboardShellUnsupported,E as isDeepLinkTarget,S as isEnvTruthy,G as isInfrastructureBootFailureReason,C as isWebUrl,tL as listAndroidApps,tr as listAndroidDevices,tG as openAndroidApp,t3 as openAndroidDevice,N as parseAndroidForegroundApp,t2 as parseAndroidLaunchComponent,b as parseAndroidLaunchablePackages,I as parseAndroidUserInstalledPackages,$ as parseSerialAllowlist,tv as prepareAndroidInstallArtifact,ep as reinstallAndroidApp,tT as resolveAndroidApp,V as resolveAndroidSerialAllowlist,T as resolveIosDeviceDeepLinkBundleId,B as resolveIosSimulatorDeviceSetPath,x as retryWithPolicy,tf as runAndroidAdb,em as streamAndroidLogcatWithAdb,tp as waitForAndroidBoot,U as withRetry};
|
package/dist/src/9010.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{deflateSync as t,inflateSync as e}from"node:zlib";import{AppError as r}from"./9152.js";let n=Buffer.from([137,80,78,71,13,10,26,10]),i=new Map([[0,1],[2,3],[3,1],[4,2],[6,4]]),o=new Map([[0,new Set([1,2,4,8,16])],[2,new Set([8,16])],[3,new Set([1,2,4,8])],[4,new Set([8,16])],[6,new Set([8,16])]]),f=[{x:0,y:0,dx:8,dy:8},{x:4,y:0,dx:8,dy:8},{x:0,y:4,dx:4,dy:8},{x:2,y:0,dx:4,dy:4},{x:0,y:2,dx:2,dy:4},{x:1,y:0,dx:2,dy:2},{x:0,y:1,dx:1,dy:2}];class a{width;height;data;static sync={read:h,write:l};constructor(t){this.width=E(t.width,"width"),this.height=E(t.height,"height");let e=this.width*this.height*4;if(this.data=t.data?Buffer.from(t.data):Buffer.alloc(e),this.data.length!==e)throw Error(`PNG data length must be ${e} bytes`)}}function h(t){var r;let{metadata:h,idatChunks:l}=function(t){let e,r=[];for(let f of function*(t){if(!t.subarray(0,n.length).equals(n))throw Error("Invalid PNG signature");let e=n.length;for(;e<t.length;){if(e+12>t.length)throw Error("Truncated PNG chunk");let r=t.readUInt32BE(e),n=t.toString("ascii",e+4,e+8),i=e+8,o=i+r;if(o+4>t.length)throw Error(`Truncated PNG ${n} chunk`);let f=t.subarray(i,o),a=t.readUInt32BE(o);if(g(t.subarray(e+4,o))!==a)throw Error(`Invalid PNG ${n} chunk CRC`);e=o+4,yield{type:n,data:f}}}(t))if("IHDR"===f.type?e=function(t){var e;if(13!==t.length)throw Error("Invalid PNG IHDR length");let r=t.readUInt32BE(0),n=t.readUInt32BE(4),f=t[8],a=t[9],h=t[10],l=t[11],u=t[12];if(e=a,!i.has(e))throw Error(`Unsupported PNG color type ${a}`);let c=o.get(a);if(!c?.has(f))throw Error(`Unsupported PNG color type ${a} with bit depth ${f}`);if(0!==h)throw Error(`Unsupported PNG compression method ${h}`);if(0!==l)throw Error(`Unsupported PNG filter method ${l}`);if(0!==u&&1!==u)throw Error(`Unsupported PNG interlace method ${u}`);return{width:E(r,"width"),height:E(n,"height"),bitDepth:f,colorType:a,interlace:u}}(f.data):"IDAT"===f.type?r.push(Buffer.from(f.data)):e=function(t,e){if("PLTE"===t.type){if(!e)throw Error("PNG PLTE appeared before IHDR");e.palette=Buffer.from(t.data)}else if("tRNS"===t.type){if(!e)throw Error("PNG tRNS appeared before IHDR");e.transparency=Buffer.from(t.data)}return e}(f,e),"IEND"===f.type)break;return{metadata:e,idatChunks:r}}(t);if(!h)throw Error("PNG is missing IHDR");if(0===l.length)throw Error("PNG is missing IDAT");let s=function(t,r){let n=function(t){if(0===t.interlace)return function(t,e){return(p(t)+1)*e}(t,t.height);let e=0;for(let r of f){let n=c(t.width,r.x,r.dx),i=c(t.height,r.y,r.dy);0!==n&&0!==i&&(e+=function(t,e){return(p(t)+1)*e}({...t,width:n,height:i},i))}return e}(r);try{let r=e(Buffer.concat(t),{maxOutputLength:n});if(r.length!==n)throw Error("PNG pixel data is truncated");return r}catch(t){var i;if((i=t)instanceof Error&&"code"in i&&"ERR_BUFFER_TOO_LARGE"===i.code)throw Error(`PNG pixel data exceeds expected length ${n}`);throw t}}(l,h);return new a({width:h.width,height:h.height,data:1===h.interlace?function(t,e){let r=Buffer.alloc(e.width*e.height*4),n=0;for(let i of f){let o=c(e.width,i.x,i.dx),f=c(e.height,i.y,i.dy);if(0===o||0===f)continue;let a={...e,width:o,height:f,interlace:0},h=u({inflated:t,offset:n,scanlineLength:p(a),height:f,bytesPerPixel:y(a)});n=h.offset;let l=p(a);for(let t=0;t<f;t+=1){let n=h.raw.subarray(t*l,(t+1)*l);for(let f=0;f<o;f+=1){let o=i.x+f*i.dx,h=((i.y+t*i.dy)*e.width+o)*4,[l,u,c,s]=d(n,f,a);r[h]=l,r[h+1]=u,r[h+2]=c,r[h+3]=s}}}return r}(s,h):function(t,e){let r=Buffer.alloc(e.width*e.height*4),n=p(e);for(let i=0;i<e.height;i+=1){let o=t.subarray(i*n,(i+1)*n);for(let t=0;t<e.width;t+=1){let n=(i*e.width+t)*4,[f,a,h,l]=d(o,t,e);r[n]=f,r[n+1]=a,r[n+2]=h,r[n+3]=l}}return r}(u({inflated:s,offset:0,scanlineLength:p(r=h),height:r.height,bytesPerPixel:y(r)}).raw,h)})}function l(e){let r=4*e.width,i=Buffer.alloc((r+1)*e.height);for(let t=0;t<e.height;t+=1){let n=t*(r+1);i[n]=0,e.data.copy(i,n+1,t*r,(t+1)*r)}let o=Buffer.alloc(13);return o.writeUInt32BE(e.width,0),o.writeUInt32BE(e.height,4),o[8]=8,o[9]=6,o[10]=0,o[11]=0,o[12]=0,Buffer.concat([n,w("IHDR",o),w("IDAT",t(i)),w("IEND",Buffer.alloc(0))])}function u(t){let{inflated:e,offset:r,scanlineLength:n,height:i,bytesPerPixel:o}=t,f=r+(n+1)*i;if(e.length<f)throw Error("PNG pixel data is truncated");let a=Buffer.alloc(n*i);for(let t=0;t<i;t+=1){let i=r+t*(n+1),f=t*n,h=e[i];for(let r=0;r<n;r+=1){let l=e[i+1+r],u=r>=o?a[f+r-o]:0,c=t>0?a[f+r-n]:0,d=t>0&&r>=o?a[f+r-n-o]:0;a[f+r]=function(t,e,r,n,i){if(0===t)return e;if(1===t)return e+r&255;if(2===t)return e+n&255;if(3===t)return e+Math.floor((r+n)/2)&255;if(4===t)return e+function(t,e,r){let n=t+e-r,i=Math.abs(n-t),o=Math.abs(n-e),f=Math.abs(n-r);return i<=o&&i<=f?t:o<=f?e:r}(r,n,i)&255;throw Error(`Unsupported PNG filter type ${t}`)}(h,l,u,c,d)}}return{raw:a,offset:f}}function c(t,e,r){return t<=e?0:Math.floor((t-e+r-1)/r)}function d(t,e,r){if(3===r.colorType){var n,o,f,a,h,l,u,c=t,d=e,p=r;if(!p.palette)throw Error("Indexed PNG is missing PLTE");let i=s(c,d,p.bitDepth),y=3*i;if(y+2>=p.palette.length)throw Error("Indexed PNG palette is invalid");return[p.palette[y],p.palette[y+1],p.palette[y+2],p.transparency?.[i]??255]}if(r.bitDepth<8){let i,o;return[o=Math.round((i=s(t,e,(n=r).bitDepth))/((1<<n.bitDepth)-1)*255),o,o,255*!(n.transparency&&n.transparency.length>=2&&i===n.transparency.readUInt16BE(0))]}let y=16===r.bitDepth?2:1,w=e*i.get(r.colorType)*y,g=e=>16===r.bitDepth?t.readUInt16BE(w+2*e):t[w+e*y],E=t=>{var e;return e=g(t),16===r.bitDepth?Math.round(e/65535*255):e};if(0===r.colorType){let t=E(0);return[t,t,t,255*(o=g(0),!(f=r).transparency||!!(f.transparency.length<2)||o!==f.transparency.readUInt16BE(0))]}if(2===r.colorType){return[E(0),E(1),E(2),255*(a=g(0),h=g(1),l=g(2),!(u=r).transparency||!!(u.transparency.length<6)||a!==u.transparency.readUInt16BE(0)||h!==u.transparency.readUInt16BE(2)||l!==u.transparency.readUInt16BE(4))]}if(4===r.colorType){let t=E(0);return[t,t,t,E(1)]}return[E(0),E(1),E(2),E(3)]}function s(t,e,r){let n=e*r;return t[Math.floor(n/8)]>>8-r-n%8&(1<<r)-1}function p(t){let e=i.get(t.colorType);return Math.ceil(t.width*e*t.bitDepth/8)}function y(t){return Math.max(1,Math.ceil(i.get(t.colorType)*t.bitDepth/8))}function w(t,e){let r=Buffer.from(t,"ascii"),n=Buffer.alloc(8+e.length+4);return n.writeUInt32BE(e.length,0),r.copy(n,4),e.copy(n,8),n.writeUInt32BE(g(Buffer.concat([r,e])),8+e.length),n}function g(t){let e=0xffffffff;for(let r of t){e^=r;for(let t=0;t<8;t+=1)e=1&e?0xedb88320^e>>>1:e>>>1}return(0xffffffff^e)>>>0}function E(t,e){if(!Number.isInteger(t)||t<1)throw Error(`PNG ${e} must be positive`);return t}function x(t,e){try{return a.sync.read(t)}catch(t){throw new r("COMMAND_FAILED",`Failed to decode ${e} as PNG`,{label:e,reason:t instanceof Error?t.message:String(t)})}}function B(t){let{baselineData:e,currentData:r,maxColorDistance:n}=t,i=t.width*t.height,o=Buffer.alloc(4*i),f=new Uint8Array(i),a=0;for(let t=0,i=0;t<e.length;t+=4,i+=1){if(Math.sqrt((e[t]-r[t])**2+(e[t+1]-r[t+1])**2+(e[t+2]-r[t+2])**2)>n){a+=1,f[i]=1;let e=P(r,t);o[t]=b(e,220,.78),o[t+1]=b(e,0,.78),o[t+2]=b(e,0,.78),o[t+3]=255;continue}let h=P(r,t);o[t]=h,o[t+1]=h,o[t+2]=h,o[t+3]=255}return{diffData:o,diffMask:f,differentPixels:a}}function P(t,e){return b(Math.round(.299*t[e]+.587*t[e+1]+.114*t[e+2]),255,.72)}function b(t,e,r){return Math.round(t*(1-r)+e*r)}function I(t){return Buffer.from(t.buffer,t.byteOffset,t.byteLength)}export{a as PNG,B as computeScreenshotDiffPixels,x as decodePng,I as toBuffer};
|
package/dist/src/9238.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import e from"node:
|
|
1
|
+
import e from"node:crypto";import t from"node:fs";import n from"node:path";import{resolveUserPath as r,expandUserHomePath as o}from"./3267.js";import{findProjectRoot as s}from"./9671.js";function i(l,a={}){var u,c;let f,p=(u=l,c=a,(f=(u??"").trim())?r(f,{env:c.env}):function(r={}){var i;let l,a,u,c=n.join(o("~",{env:r.env}),".agent-device"),f=r.projectRoot??s();return(i=f,t.existsSync(n.join(i,"package.json"))&&t.existsSync(n.join(i,"src","daemon.ts")))?n.join(c,"dev",(l=function(e){try{return t.realpathSync.native(e)}catch{return n.resolve(e)}}(f),a=n.basename(l).replaceAll(/[^a-zA-Z0-9._-]+/g,"-"),u=e.createHash("sha1").update(l).digest("hex").slice(0,12),`${a||"agent-device"}-${u}`)):c}(c));return{baseDir:p,infoPath:n.join(p,"daemon.json"),lockPath:n.join(p,"daemon.lock"),logPath:n.join(p,"daemon.log"),sessionsDir:n.join(p,"sessions")}}function l(e){let t=(e??"").trim().toLowerCase();return"http"===t?"http":"dual"===t?"dual":"socket"}function a(e){let t=(e??"").trim().toLowerCase();return"auto"===t?"auto":"socket"===t?"socket":"http"===t?"http":"auto"}function u(e){return"tenant"===(e??"").trim().toLowerCase()?"tenant":"none"}function c(e){if(!e)return;let t=e.trim();if(t&&/^[a-zA-Z0-9._-]{1,128}$/.test(t))return t}let f=/(?:^|[^\w$.])(?:import|export)\s+(?:type\s+)?(?:[^'"`]*?\s+from\s+)?['"]([^'"]+)['"]/gm,p=/import\(\s*['"]([^'"]+)['"]\s*\)/gm,m=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];function d(){let e=process.argv[1];return e?h(e):"unknown"}function h(r,o=s()){try{let s=n.resolve(o),i=[n.resolve(r)],l=new Set,a=[];for(;i.length>0;){let e=i.pop();if(!e||l.has(e))continue;l.add(e);let r=t.statSync(e);if(!r.isFile())continue;let o=n.relative(s,e)||e;a.push(`${o}:${r.size}:${Math.trunc(r.mtimeMs)}`);let u=t.readFileSync(e,"utf8");for(let t of function(e){let t=new Set;return v(e,f,t),v(e,p,t),[...t]}(u)){let r=function(e,t){let r=n.resolve(n.dirname(e),t),o=g(r);if(o)return o;for(let e of m){let t=g(`${r}${e}`);if(t)return t}for(let e of m){let t=g(n.join(r,`index${e}`));if(t)return t}return null}(e,t);r&&i.push(r)}}let u=a.sort().join("|"),c=e.createHash("sha1").update(u).digest("hex");return`graph:${a.length}:${c}`}catch{return"unknown"}}function v(e,t,n){t.lastIndex=0;let r=null;for(;null!==(r=t.exec(e));){let e=r[1]?.trim();e?.startsWith(".")&&n.add(e)}}function g(e){try{return t.statSync(e).isFile()?e:null}catch{return null}}let y=/^[A-Za-z0-9_@%+=:,./-]+$/;function S(e){return`'${e.replaceAll("'","'\\''")}'`}function j(e){return y.test(e)?e:S(e)}function $(e,t){let n=[],r=e+t.toString(),o=r.indexOf("\n");for(;-1!==o;){let e=r.slice(0,o).trim();r=r.slice(o+1),e&&n.push(e),o=r.indexOf("\n")}return{lines:n,buffer:r}}function x(e){return e.meta?.requestProgress==="replay-test"}function _(e){return!!e&&"object"==typeof e&&"progress"===e.type&&!!e.event}function D(e){return!!e&&"object"==typeof e&&"response"===e.type&&!!e.response}function P(e){return`${JSON.stringify({type:"progress",event:e})}
|
|
2
2
|
`}function C(e){return`${JSON.stringify({type:"response",response:e})}
|
|
3
|
-
`}function
|
|
4
|
-
`}
|
|
3
|
+
`}function k(e){return`${JSON.stringify({type:"response",response:e})}
|
|
4
|
+
`}export{h as computeDaemonCodeSignature,$ as consumeTextLines,_ as isDaemonProgressEnvelope,D as isDaemonResponseEnvelope,c as normalizeTenantId,d as resolveDaemonCodeSignature,i as resolveDaemonPaths,l as resolveDaemonServerMode,a as resolveDaemonTransportPreference,u as resolveSessionIsolationMode,P as serializeDaemonProgressEnvelope,C as serializeDaemonResponseEnvelope,k as serializeDaemonRpcResponseEnvelope,S as shellQuote,j as shellQuoteIfNeeded,x as shouldStreamRequestProgress};
|
package/dist/src/9471.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{setSessionSnapshot as e,captureSnapshot as r,isNavigationSensitiveAction as t,markPendingInteractionOutcome as n,markPostGestureStabilization as o,getSnapshotReferenceFrame as i,recordTouchVisualizationEvent as a,markAndroidSnapshotFreshness as c,stripInternalInteractionFlags as s}from"./2415.js";import{successText as d}from"./
|
|
1
|
+
import{setSessionSnapshot as e,captureSnapshot as r,isNavigationSensitiveAction as t,markPendingInteractionOutcome as n,markPostGestureStabilization as o,getSnapshotReferenceFrame as i,recordTouchVisualizationEvent as a,markAndroidSnapshotFreshness as c,stripInternalInteractionFlags as s}from"./2415.js";import{successText as d}from"./1534.js";import{getAndroidScreenSize as f}from"./input-actions.js";import{emitDiagnostic as u}from"./7599.js";async function l(t,n,o,i,a){let c={...n??{},snapshotInteractiveOnly:a.interactiveOnly,snapshotCompact:a.interactiveOnly},s=i(c,t.appBundleId,t.trace?.outPath),{snapshot:d}=await r({device:t.device,session:t,flags:c,outPath:c.out,logPath:s.logPath??"",androidFreshnessMode:a.androidFreshnessMode});return e(t,d),o.set(t.name,t),d}function p(e){var r,t,n;let o,i,a,{data:c,fallbackX:s,fallbackY:f,referenceFrame:u,extra:l}=e,p=(r=l,t=s,n=f,o="string"==typeof r?.ref?r.ref:void 0,i="string"==typeof r?.button?r.button:void 0,a="string"==typeof r?.gesture?r.gesture:void 0,("string"==typeof r?.text?`Filled ${Array.from(r.text).length} chars`:o?"longpress"===a?`Long pressed @${o} (${t}, ${n})`:i&&"primary"!==i?`Clicked ${i} @${o} (${t}, ${n})`:`Tapped @${o} (${t}, ${n})`:void 0)??("string"==typeof c?.message?c.message:void 0));return{x:s,y:f,...u??{},...l??{},...c??{},...d(p)}}function h(e){let{session:r,sessionStore:i,command:d,positionals:f,retryPositionals:u,flags:l,result:p,responseData:h,actionStartedAt:g,actionFinishedAt:m,androidFreshnessBaseline:_}=e,v=s(l);return i.recordAction(r,{command:d,positionals:f,flags:v??{},result:p}),n({session:r,command:d,positionals:u??f,flags:l,preSnapshot:r.snapshot}),t(d)&&c(r,d,_??r.snapshot),o(r,d,u??f,l),a(r,d,f,p,v??{},g,m),{ok:!0,data:h}}async function g(e){let{session:r,flags:t,sessionStore:n,contextFromFlags:o,captureSnapshotForSession:a}=e;if(!r.recording)return;if(r.recording.touchReferenceFrame)return r.recording.touchReferenceFrame;if("android"===r.device.platform){let e=await f(r.device),t={referenceWidth:e.width,referenceHeight:e.height};return r.recording&&(r.recording.touchReferenceFrame=t),t}let c=i(r.snapshot);if(c)return r.recording&&(r.recording.touchReferenceFrame=c),c;if(!r.recording)return;let s=i(await a(r,t,n,o,{interactiveOnly:!0}));return s&&r.recording&&(r.recording.touchReferenceFrame=s),s}async function m(e){try{return await g(e)}catch(r){u({level:"warn",phase:"touch_reference_frame_resolve_failed",data:{platform:e.session.device.platform,error:r instanceof Error?r.message:String(r)}});return}}function _(e){return i({nodes:e,createdAt:0})}export{p as buildTouchVisualizationResult,h as finalizeTouchInteraction,l as interaction_snapshot_captureSnapshotForSession,_ as readSnapshotNodesReferenceFrame,m as resolveDirectTouchReferenceFrameSafely};
|