agent-device 0.17.10 → 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.17.10.apk → agent-device-android-multitouch-helper-0.18.0.apk} +0 -0
- package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.18.0.apk.sha256 +1 -0
- package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.17.10.manifest.json → agent-device-android-multitouch-helper-0.18.0.manifest.json} +4 -4
- package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.17.10.apk → agent-device-android-snapshot-helper-0.18.0.apk} +0 -0
- package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.18.0.apk.sha256 +1 -0
- package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.17.10.manifest.json → agent-device-android-snapshot-helper-0.18.0.manifest.json} +6 -6
- package/dist/src/1848.js +4 -0
- package/dist/src/2577.js +1 -1
- package/dist/src/2948.js +20 -20
- package/dist/src/4291.js +1 -1
- package/dist/src/4723.js +1 -1
- package/dist/src/5341.js +1 -0
- package/dist/src/5643.js +1 -0
- package/dist/src/6918.js +1 -1
- package/dist/src/8275.js +2 -2
- package/dist/src/8936.js +1 -0
- package/dist/src/9414.js +1 -0
- package/dist/src/9581.js +4 -4
- package/dist/src/9722.js +32 -37
- package/dist/src/9919.js +5 -5
- package/dist/src/apple.js +1 -1
- package/dist/src/apps.js +10 -10
- package/dist/src/batch.d.ts +20 -3
- package/dist/src/batch.js +1 -1
- package/dist/src/cli-help.js +49 -32
- package/dist/src/cli.js +22 -25
- package/dist/src/contracts.d.ts +14 -0
- package/dist/src/device-ready.js +2 -0
- package/dist/src/find.js +1 -1
- package/dist/src/index.d.ts +67 -16
- package/dist/src/interaction.js +1 -1
- package/dist/src/internal/bin.js +1 -1
- package/dist/src/lease.js +1 -1
- package/dist/src/metro.js +1 -1
- package/dist/src/react-native.js +1 -1
- package/dist/src/record-trace-recording.js +3 -3
- package/dist/src/remote-config.d.ts +17 -11
- package/dist/src/selector-runtime.js +1 -1
- package/dist/src/session.js +11 -8
- package/dist/src/simulator.js +2 -0
- package/dist/src/snapshot.js +1 -1
- package/package.json +1 -1
- package/server.json +2 -2
- package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.17.10.apk.sha256 +0 -1
- package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.17.10.apk.sha256 +0 -1
- package/dist/src/2133.js +0 -1
- package/dist/src/5628.js +0 -1
- package/dist/src/8358.js +0 -4
package/dist/src/9919.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import e from"node:fs";import t from"node:http";import a from"node:https";import r from"node:path";import{pipeline as n}from"node:stream/promises";import i from"node:os";import{createHash as o,randomUUID as s}from"node:crypto";import{Writable as l}from"node:stream";import c from"node:net";import d from"node:fs/promises";import{toAppErrorCode as u,AppError as f}from"./733.js";import{runCmdDetachedMonitored as p,runCmd as m,runCmdSync as h}from"./8875.js";import{createRequestId as y,withDiagnosticTimer as w,emitDiagnostic as g}from"./432.js";import{isAgentDeviceDaemonProcess as b,stopProcessForTakeover as v}from"./5628.js";import{readSnapshotDiagnosticsSummary as I,consumeTextLines as A,shellQuote as S,shouldStreamRequestProgress as M,isDaemonResponseEnvelope as _,isDaemonProgressEnvelope as D,resolveDaemonPaths as P,resolveDaemonServerMode as k,computeDaemonCodeSignature as E,resolveDaemonTransportPreference as N}from"./8358.js";import{listCommandFamilyDaemonWriters as x,normalizeSession as $,readSerializedSnapshotCaptureAnnotations as T,readRequiredString as C,findCommandMetadata as U,normalizeMaterializationReleaseResult as L,colorize as O,readSnapshotNodes as R,normalizeDeployResult as F,normalizeOpenDevice as B,buildMeta as j,readOptionalString as q,resolveSessionName as V,supportsColor as H,buildRequestFlags as G,createBatchDaemonWriter as K,readMetadataCommandFlags as z,normalizeDevice as Y,normalizeStartupSample as W,readScreenshotOverlayRefs as J,normalizeRuntimeHints as X,normalizeInstallFromSourceResult as Q}from"./2948.js";import{INTERNAL_COMMANDS as Z,PUBLIC_COMMANDS as ee}from"./2133.js";import{readVersion as et,findProjectRoot as ea}from"./1404.js";import{sleep as er}from"./5560.js";import{reloadMetro as en,prepareMetroRuntime as ei}from"./8275.js";let eo="/agent-device";function es(e){return el(e,eo)}function el(e,t){let a=e.endsWith("/")?e:`${e}/`;return new URL(t.replace(/^\/+/,""),a).toString()}function ec(e){let t=e?.trim();return t?{authorization:`Bearer ${t}`,"x-agent-device-token":t}:{}}function ed(e){return new Promise((t,a)=>{let r="";e.setEncoding("utf8"),e.on("data",e=>{r+=e}),e.on("end",()=>t(r)),e.on("error",a)})}let eu="sha256";async function ef(e){let t=await ep(e.localPath,e.platform),a=e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`;try{let r=await ew({normalizedBase:a,token:e.token,artifact:t});if(r?.kind==="cache-hit")return r.uploadId;if(r?.kind==="direct-upload")try{return await eg(t.payloadPath,r),await eA({normalizedBase:a,token:e.token,uploadId:r.uploadId})}catch{}return await ey({normalizedBase:a,token:e.token,artifact:t})}finally{t.cleanup()}}async function ep(t,a){var n,i,o;let s,l=e.statSync(t),c=r.basename(t),d=l.isDirectory(),u=("ios"===(n=a)||"android"===n?n:void 0)??(i=t,o=l,s=i.toLowerCase(),o.isDirectory()&&s.endsWith(".app")||s.endsWith(".ipa")?"ios":s.endsWith(".apk")||s.endsWith(".aab")?"android":void 0),f=[];try{let a=d?await em(t,f):t,r=e.statSync(a);return{payloadPath:a,fileName:c,artifactType:d?"app-bundle":"file",platform:u,contentType:d?"application/gzip":"application/octet-stream",sha256:await eS(a),sizeBytes:r.size,cleanup:()=>eh(f)}}catch(e){throw eh(f),e}}async function em(t,a){let n=e.mkdtempSync(r.join(i.tmpdir(),`agent-device-upload-${s()}-`));a.push(n);let o=r.join(n,`${r.basename(t)}.tar.gz`);return await m("tar",["czf",o,"-C",r.dirname(t),r.basename(t)],{env:{...process.env,COPYFILE_DISABLE:"1"}}),o}function eh(t){for(let a of t)e.rmSync(a,{recursive:!0,force:!0})}async function ey(e){let{normalizedBase:t,token:a,artifact:r}=e,n=new URL("upload",t),i={"content-type":r.contentType,"x-artifact-type":r.artifactType,"x-artifact-filename":r.fileName,"x-artifact-hash":r.sha256,"x-artifact-hash-algorithm":eu,"transfer-encoding":"chunked"};Object.assign(i,ec(a));let o=await eb({url:n,method:"POST",headers:i,payloadPath:r.payloadPath,timeoutMessage:"Artifact upload timed out",timeoutHint:"The upload to the remote daemon exceeded the 5-minute timeout.",errorMessage:"Failed to upload artifact to remote daemon",errorHint:"Verify the remote daemon is reachable and supports artifact uploads."});try{let e=JSON.parse(o.body);if(!e.ok||!e.uploadId)throw new f("COMMAND_FAILED",`Upload failed: ${o.body}`);return e.uploadId}catch(e){if(e instanceof f)throw e;throw new f("COMMAND_FAILED",`Invalid upload response: ${o.body}`)}}async function ew(e){let t=new URL("upload/preflight",e.normalizedBase),a={"content-type":"application/json"};Object.assign(a,ec(e.token));let r=await fetch(t,{method:"POST",headers:a,signal:AbortSignal.timeout(3e4),body:JSON.stringify({sha256:e.artifact.sha256,fileName:e.artifact.fileName,sizeBytes:e.artifact.sizeBytes,artifactType:e.artifact.artifactType,...e.artifact.platform?{platform:e.artifact.platform}:{},contentType:e.artifact.contentType})}).catch(()=>void 0);if(r?.ok)return function(e){var t;if(!e||"object"!=typeof e||!0!==e.ok||"string"!=typeof e.uploadId)return;if(!0===e.cacheHit)return{kind:"cache-hit",uploadId:e.uploadId};let a=e.upload;if(!a||"string"!=typeof a.url)return;let r=a.headers??{};if(!(!(t=r)||"object"!=typeof t||Array.isArray(t))&&Object.values(t).every(e=>"string"==typeof e))return{kind:"direct-upload",uploadId:e.uploadId,url:a.url,headers:r}}(await r.json().catch(()=>void 0))}async function eg(e,t){let a=await eb({url:new URL(t.url),method:"PUT",headers:t.headers,payloadPath:e,timeoutMessage:"Direct artifact upload timed out",timeoutHint:"The direct upload ticket did not accept the artifact within the timeout.",errorMessage:"Failed to upload artifact with direct upload ticket"});if(a.statusCode<200||a.statusCode>=300)throw new f("COMMAND_FAILED","Direct artifact upload failed",{statusCode:a.statusCode,statusMessage:a.statusMessage})}async function eb(e){return await ev({...e,url:e.url,redirectCount:0,startOffset:0})}async function ev(r){var i,o,s;let l="https:"===r.url.protocol?a:t,c=e.statSync(r.payloadPath).size,d=(i=r.headers,o=r.startOffset,s=c,o<=0?i:{...i,"content-length":Math.max(s-o,0),"content-range":`bytes ${o}-${s-1}/${s}`});return await new Promise((t,a)=>{let i=!1,o=l.request({protocol:r.url.protocol,host:r.url.hostname,port:r.url.port,method:r.method,path:r.url.pathname+r.url.search,headers:d},e=>{i=!0,ed(e).then(n=>{clearTimeout(s);let i=e.statusCode??500,o=e.headers.location;if(o&&[301,302,303,307,308].includes(i)){if(r.redirectCount>=5)return void a(new f("COMMAND_FAILED","Artifact upload exceeded redirect limit",{maxRedirects:5,url:r.url.toString()}));let e=new URL(o,r.url);return void ev({...r,url:e,redirectCount:r.redirectCount+1}).then(t,a)}let l=308===i?function(e,t){let a=function(e){let t=eI(e);if(void 0===t)return;let a=Number(t);return Number.isSafeInteger(a)&&a>=0?a:void 0}(e["x-upload-offset"]??e["upload-offset"]);if(void 0!==a)return Math.min(a,t);let r=eI(e.range),n=r?.match(/^bytes=0-(\d+)$/);if(!n)return;let i=Number(n[1]);if(Number.isSafeInteger(i)&&!(i<0))return Math.min(i+1,t)}(e.headers,c):void 0;void 0!==l?l>=c?t({statusCode:200,statusMessage:"Upload already complete",body:""}):l<=r.startOffset?a(new f("COMMAND_FAILED","Artifact upload resume did not advance",{offset:l,previousOffset:r.startOffset,url:r.url.toString()})):ev({...r,startOffset:l}).then(t,a):t({statusCode:i,statusMessage:e.statusMessage,body:n})}).catch(a)}),s=setTimeout(()=>{o.destroy(),a(new f("COMMAND_FAILED",r.timeoutMessage,{timeoutMs:3e5,...r.timeoutHint?{hint:r.timeoutHint}:{}}))},3e5);o.on("error",e=>{i||(clearTimeout(s),a(new f("COMMAND_FAILED",r.errorMessage,r.errorHint?{hint:r.errorHint}:{},e)))}),o.on("close",()=>clearTimeout(s)),n(e.createReadStream(r.payloadPath,{start:r.startOffset}),o).catch(e=>{i||(o.destroy(),a(new f("COMMAND_FAILED","Failed to read local artifact",{},e instanceof Error?e:Error(String(e)))))})})}function eI(e){return Array.isArray(e)?e[0]:e}async function eA(e){let t=new URL("upload/finalize",e.normalizedBase),a={"content-type":"application/json"};Object.assign(a,ec(e.token));let r=await fetch(t,{method:"POST",headers:a,signal:AbortSignal.timeout(3e4),body:JSON.stringify({uploadId:e.uploadId})}).catch(e=>{throw new f("COMMAND_FAILED","Failed to finalize direct artifact upload",{},e)});if(!r.ok)throw new f("COMMAND_FAILED","Direct artifact upload finalize failed",{status:r.status,statusText:r.statusText});let n=await r.json().catch(()=>void 0);if(!n?.ok||!n.uploadId)throw new f("COMMAND_FAILED","Invalid upload finalize response");return n.uploadId}async function eS(t){let a=o(eu),r=new l({write(e,t,r){a.update(e),r()}});return await n(e.createReadStream(t),r).catch(e=>{throw new f("COMMAND_FAILED","Failed to read local artifact",{},e instanceof Error?e:void 0)}),a.digest("hex")}async function eM(e,t){var a;let n,i=[...e.positionals??[]],o=e.flags?{...e.flags}:void 0,s=e.meta?.installSource,l={};if(!("string"==typeof(a=t).baseUrl&&a.baseUrl.length>0))return eD({positionals:i,flags:o,installSource:s,uploadedArtifactId:n,clientArtifactPaths:l});o=function(e,t,a,n){var i,o;let s=function(e,t){if("screenshot"===e.command){let a=ek(e,"path",".png");return t[0]?{field:"path",localPath:a,positionalIndex:0,positionalPath:eE("screenshot",".png")}:{field:"path",localPath:a,positionalIndex:0,flagPath:eE("screenshot",".png")}}if("record"===e.command&&"start"===(t[0]??"").toLowerCase()){let t=ek(e,"outPath",".mp4",1);return{field:"outPath",localPath:t,positionalIndex:1,positionalPath:eE("recording",r.extname(t)||".mp4")}}return null}(e,t);if(!s)return a;void 0!==s.positionalPath&&(t[s.positionalIndex]=s.positionalPath);let l=(i=a,void 0===(o=s.flagPath)?i:{...i??{},out:o});return n[s.field]=s.localPath,l}(e,i,o,l);let c=await eP(e,t);c&&(s=c.installSource,n=c.uploadedArtifactId??n);let d=()=>eD({positionals:i,flags:o,installSource:s,uploadedArtifactId:n,clientArtifactPaths:l});return"install"!==e.command&&"reinstall"!==e.command||(n=await e_(e,t,i)??n),d()}async function e_(t,a,n){var i,o;let s,l=n[1];if(void 0===l)return;if(l.startsWith("remote:")){n[1]=l.slice(7);return}let c=(i=l,o=t.meta?.cwd,s=r.isAbsolute(i)?i:r.resolve(o??process.cwd(),i),e.existsSync(s)?s:void 0);if(c)return await ef({localPath:c,baseUrl:a.baseUrl,token:a.token,platform:t.flags?.platform})}function eD(e){return{positionals:e.positionals,flags:e.flags,installSource:e.installSource,uploadedArtifactId:e.uploadedArtifactId,...Object.keys(e.clientArtifactPaths).length>0?{clientArtifactPaths:e.clientArtifactPaths}:{}}}async function eP(t,a){let n=t.meta?.installSource;if("install_source"!==t.command||!n||"path"!==n.kind)return null;let i=n.path.trim();if(!i)return{installSource:n};if(i.startsWith("remote:"))return{installSource:{...n,path:i.slice(7)}};let o=r.isAbsolute(i)?i:r.resolve(t.meta?.cwd??process.cwd(),i);if(!e.existsSync(o))return{installSource:{...n,path:o}};let s=await ef({localPath:o,baseUrl:a.baseUrl,token:a.token,platform:t.flags?.platform});return{installSource:{...n,path:o},uploadedArtifactId:s}}function ek(e,t,a,n=0){let i=e.positionals?.[n]??e.flags?.out,o=`${"path"===t?"screenshot":"recording"}-${Date.now()}${a}`,s=i&&i.trim().length>0?i:o;return r.isAbsolute(s)?s:r.resolve(e.meta?.cwd??process.cwd(),s)}function eE(e,t){let a=t.startsWith(".")?t:`.${t}`;return r.posix.join("/tmp",`agent-device-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}${a}`)}async function eN(e,t,a){let n=Array.isArray(a.data?.artifacts)?a.data.artifacts:[];if(0===n.length||!e.baseUrl)return a;let i=a.data?{...a.data}:{},o=[];for(let a of n){if(!a||"object"!=typeof a||"string"!=typeof a.artifactId){o.push(a);continue}let n=function(e,t){if(e.localPath&&e.localPath.trim().length>0)return e.localPath;let a=t.meta?.clientArtifactPaths?.[e.field];if(a&&a.trim().length>0)return a;let n=e.fileName?.trim()||`${e.field}-${Date.now()}`;return r.resolve(t.meta?.cwd??process.cwd(),n)}(a,t);await ex({baseUrl:e.baseUrl,token:e.token,artifactId:a.artifactId,destinationPath:n,requestId:t.meta?.requestId}),i[a.field]=n,o.push({...a,localPath:n})}return i.artifacts=o,{ok:!0,data:i}}async function ex(i){var o,s;let l,c=new URL((o=i.baseUrl,s=i.artifactId,l=o.endsWith("/")?o:`${o}/`,new URL(`artifacts/${encodeURIComponent(s)}`,l).toString())),d="https:"===c.protocol?a:t;await e.promises.mkdir(r.dirname(i.destinationPath),{recursive:!0}),await new Promise((t,a)=>{let r=!1,o=i.timeoutMs??9e4,s=n=>{if(!r){if(r=!0,clearTimeout(u),n)return void e.promises.rm(i.destinationPath,{force:!0}).finally(()=>a(n));t()}},l=d.request({protocol:c.protocol,host:c.hostname,port:c.port,method:"GET",path:c.pathname+c.search,headers:ec(i.token)},t=>{if((t.statusCode??500)>=400){let e="";t.setEncoding("utf8"),t.on("data",t=>{e+=t}),t.on("end",()=>{s(new f("COMMAND_FAILED","Failed to download remote artifact",{artifactId:i.artifactId,statusCode:t.statusCode,requestId:i.requestId,body:e}))});return}t.on("aborted",()=>{s(new f("COMMAND_FAILED","Remote artifact download was interrupted",{artifactId:i.artifactId,requestId:i.requestId}))}),n(t,e.createWriteStream(i.destinationPath)).then(()=>s(),e=>s(e instanceof Error?e:Error(String(e))))}),u=setTimeout(()=>{let e=new f("COMMAND_FAILED","Remote artifact download timed out",{artifactId:i.artifactId,requestId:i.requestId,timeoutMs:o});s(e),l.destroy(e)},o);l.on("error",e=>{e instanceof f?s(e):s(new f("COMMAND_FAILED","Failed to download remote artifact",{artifactId:i.artifactId,requestId:i.requestId,timeoutMs:o},e instanceof Error?e:void 0))}),l.end()})}function e$(e){var t,a,r;let n,i,o=ej(e);if(!o||"object"!=typeof o)return null;let s="string"==typeof(t=o).token&&t.token.length>0?t.token:null;if(!s)return null;let l=(n=eC((a=o).port),i=eC(a.httpPort),void 0===n&&void 0===i?null:{port:n,httpPort:i});return l?{token:s,...l,transport:"socket"===(r=o.transport)||"http"===r||"dual"===r?r:void 0,pid:eC(o.pid)??0,version:eT(o.version),codeSignature:eT(o.codeSignature),processStartTime:eT(o.processStartTime)}:null}function eT(e){return"string"==typeof e?e:void 0}function eC(e){return Number.isInteger(e)&&Number(e)>0?Number(e):void 0}function eU(e){let t=ej(e);return t&&"object"==typeof t&&Number.isInteger(t.pid)&&Number(t.pid)>0?{pid:Number(t.pid),processStartTime:"string"==typeof t.processStartTime?t.processStartTime:void 0,startedAt:"number"==typeof t.startedAt?t.startedAt:void 0}:null}async function eL(t,a,r={}){let n=r.stopLiveProcesses??!0,i={reason:a,removedInfo:!1,removedLock:!1,stoppedInfoProcess:!1,stoppedLockProcess:!1};try{var o,s,l,c;let a=e.existsSync(t.infoPath),r=e$(t.infoPath);if(r){let e=b(r.pid,r.processStartTime);e&&!n?i.retainedInfoProcess=!0:(e&&(await eF(r),i.stoppedInfoProcess=!0),o=t.infoPath,eq(o),i.removedInfo=!0)}else a&&(s=t.infoPath,eq(s),i.removedInfo=!0);let d=e.existsSync(t.lockPath),u=eU(t.lockPath);if(u){let e=b(u.pid,u.processStartTime);e&&!n?i.retainedLockProcess=!0:(e&&(await v(u.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:u.processStartTime}),i.stoppedLockProcess=!0),l=t.lockPath,eq(l),i.removedLock=!0)}else d&&(c=t.lockPath,eq(c),i.removedLock=!0)}catch(e){i.error=e instanceof Error?e.message:String(e)}return g({level:i.error?"warn":"info",phase:"daemon_startup_metadata_cleanup",data:i}),i}function eO(t){return{hasInfo:e.existsSync(t.infoPath),hasLock:e.existsSync(t.lockPath)}}async function eR(e){let t=eO(e);if(!t.hasLock||t.hasInfo)return!1;let a=eU(e.lockPath);return!(a&&b(a.pid,a.processStartTime))&&(eq(e.lockPath),!0)}async function eF(e){await v(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}function eB(e){return"string"==typeof e.baseUrl&&e.baseUrl.length>0}function ej(t){if(!e.existsSync(t))return null;try{return JSON.parse(e.readFileSync(t,"utf8"))}catch{return null}}function eq(t){try{e.existsSync(t)&&e.unlinkSync(t)}catch{}}function eV(e){let t=Math.max(0,e)/1e3;return t>=10?`${t.toFixed(1)}s`:t>=1?`${t.toFixed(2)}s`:`${t.toFixed(3).replace(/0+$/,"").replace(/\.$/,"")}s`}function eH(e){let t=eG(e),a=t.findIndex(({stop:e})=>!1===e.ok);if(a<0)return[];let r=t.slice(Math.max(0,a-2),a+1);return[e.attempts>1?`steps (attempt ${e.attempts}):`:"steps:",...r.map(({stop:e,start:t})=>eW(e,t))]}function eG(t){var a,n;let i=(a=t).artifactsDir?r.join(a.artifactsDir,`attempt-${a.attempts}`,"replay-timing.ndjson"):void 0;if(!i)return[];let o=function(t){try{return e.readFileSync(t,"utf8").split(/\r?\n/).filter(e=>e.trim().length>0).flatMap(e=>{try{let t=JSON.parse(e);return eX(t)?[t]:[]}catch{return[]}})}catch{return[]}}(i);if(0===o.length)return[];let s=[],l=[];for(let e of o){if("replay_action_start"===(n=e).type&&eK(n)&&ez(n,"line")&&eY(n,"command")&&(void 0===n.positionals||Array.isArray(n.positionals))){s.push(e);continue}(function(e){var t;return["replay_action_stop"===e.type&&eK(e)&&ez(e,"line")&&eY(e,"command"),void 0===(t=e).ok||"boolean"==typeof t.ok,ez(e,"durationMs"),eY(e,"errorCode"),void 0===e.resultTiming||eX(e.resultTiming)].every(Boolean)})(e)&&l.push({stop:e,start:function(e,t){let a=t.command,r=e.findIndex(e=>e.step===t.step&&(void 0===a||void 0===e.command||e.command===a));if(!(r<0))return e.splice(r,1)[0]}(s,e)})}return l}function eK(e){return"number"==typeof e.step}function ez(e,t){return void 0===e[t]||"number"==typeof e[t]}function eY(e,t){return void 0===e[t]||"string"==typeof e[t]}function eW(e,t){var a,r,n,i;let o,s,l=!1===e.ok?"[FAIL] ":!0===e.ok?"":"[info] ";return` ${l}${a=t,r=e,[function(e){if(!e)return"unknown";if(!e.startsWith("__maestro"))return e;let t=e.slice(9);return t.length>0?t[0].toLowerCase()+t.slice(1):e}(a?.command??r.command),...(a?.positionals??[]).map(eJ)].join(" ")}${n=e,i=t,(s=["number"==typeof(o=i?.line??n.line)?`line ${o}`:"","number"==typeof n.durationMs?eV(n.durationMs):"",n.errorCode??"",n.resultTiming?`timing ${JSON.stringify(n.resultTiming)}`:""].filter(Boolean)).length>0?` (${s.join(", ")})`:""}`}function eJ(e){return"string"==typeof e?JSON.stringify(e):"number"==typeof e||"boolean"==typeof e?String(e):JSON.stringify(e)}function eX(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function eQ(e,t){return O(e,t,{validateStream:!1})}function eZ(e){if("number"!=typeof e.shardIndex)return"";let t="number"==typeof e.shardCount?e.shardCount:"?",a="string"==typeof e.deviceId?` ${e.deviceId}`:"";return` [shard ${e.shardIndex+1}/${t}${a}]`}function e0(e){return`\r\x1b[2K${e}`}function e1(e){return"number"==typeof e&&Number.isFinite(e)&&e>0?Math.floor(e):80}function e3(e,t){let a=e1(t);return e.length<=a?e:a<=0?"":a<=3?".".repeat(a):`${e.slice(0,a-3)}...`}function e2(e){return{file:e.file,title:e.title,durationMs:e.durationMs??0,attempts:e.attempt??1,artifactsDir:e.artifactsDir,session:e.session??""}}function e5(e){return function(e={}){let t=new Set,a=!1;return{render(n){var i,o;if("replay-test-suite"===n.type){t.clear(),a=!1;return}if("replay-test"!==n.type)return;if("progress"===n.status){if(!e.liveProgress)return;return a=!0,{text:e0(function(e,t){let a=e.title?.trim(),n=r.basename(e.file),i=eZ(e),o=e.stepIndex??0,s=e.stepTotal??0,l=`${i} [${o}/${s}]`,c="⊙ ";if(!a)return e3(`${c}${n}${l}`,t.columns);let d=`${c}"`,u=`" in ${n}${l}`,f=e3(a,Math.max(0,e1(t.columns)-d.length-u.length));return e3(`${d}${f}${u}`,t.columns)}(n,e)),newline:!1}}if("pass"===(i=n).status||"skip"===i.status||"fail"===i.status&&!i.retrying){let e,a=(e="number"==typeof(o=n).shardIndex?o.shardIndex:"",[o.status,o.index,o.total,o.file,o.title??"",e].join("\0"));if(t.has(a))return;t.add(a)}let s=function(e,t={}){if("replay-test"===e.type)return function(e,t){var a,n,i,o;let s,l,c,d,u,f;if("start"===e.status||"progress"===e.status||"fail"===e.status&&e.retrying)return;let p=[(c=function(e){let t=H(process.stderr);if("pass"===e.status){let a=e.attempt&&e.attempt>1?"yellow":"green";return t?eQ("✓",a):"✓"}return"fail"===e.status?t?eQ("⨯","red"):"⨯":"progress"===e.status?"⊙":t?eQ("-","dim"):"-"}(a=e),d=(n=a,s=n.title?.trim(),l=r.basename(n.file),s?`${JSON.stringify(s)} in ${l}`:l),u=eZ(a),f=void 0!==a.durationMs?` (${eV(a.durationMs??0)})`:"",`${c} ${d}${u}${f}`)];return function(e,t,a){if(a.verbose&&"fail"===t.status)return;let r=t.message?.replace(/\s+/g," ").trim();r&&e.push(` ${"fail"===t.status?`failed at: ${r}`:r}`),"fail"===t.status&&!t.retrying&&(t.session&&e.push(` session: ${t.session}`),t.artifactsDir&&e.push(` artifacts: ${t.artifactsDir}`))}(p,e,t),t.verbose&&p.push(...("pass"===(i=e).status||"fail"===i.status)&&i.artifactsDir&&i.attempt?(function(e){if("skipped"===e.status)return[];let t=eG(e);return 0===t.length?[]:[e.attempts>1?`steps (attempt ${e.attempts}):`:"steps:",...t.map(({stop:e,start:t})=>eW(e,t))]})("pass"===i.status?{...e2(i),status:"passed",replayed:0,healed:0}:{...e2(o=i),status:"failed",error:{code:"COMMAND_FAILED",message:o.message??"Unknown test failure"}}).map(e=>` ${e}`):[]),p.join("\n")}(e,t)}(n,e);if(!s)return;let l=a?e0(s):s;return a=!1,{text:l,newline:!0}}}}({verbose:!!(e.flags?.verbose||e.meta?.debug),liveProgress:!0===process.stderr.isTTY&&!process.env.CI,columns:process.stderr.columns})}function e4(e,t){let a=t.render(e);a&&process.stderr.write(a.newline?`${a.text}
|
|
2
|
-
`:a.text)}function
|
|
3
|
-
`)}),d=!1,u="number"==typeof r?setTimeout(()=>{d=!0,l.destroy(),o(
|
|
4
|
-
`)}catch{}}(r,n,e.paths.baseDir),await eF(r),eq(e.paths.infoPath),null)}async function tb(e,t){try{return await ta(e,t)}catch(e){var a;if((a=e)instanceof f&&"COMMAND_FAILED"===a.code&&(a.message===te||a.message===tt))return!1;throw e}}async function tv(t){let a,r,n=0,i=[];for(let o=1;o<=2;o+=1){let s;try{r={pid:(s=function(t){let a=tM(),r=a.useSrc?["--experimental-strip-types",a.srcPath]:[a.distPath],n={...process.env,AGENT_DEVICE_STATE_DIR:t.paths.baseDir,AGENT_DEVICE_DAEMON_SERVER_MODE:t.serverMode};e.mkdirSync(t.paths.baseDir,{recursive:!0});let i=e.openSync(t.paths.logPath,"a"),o=e.openSync(t.paths.logPath,"a");try{return p(process.execPath,r,{env:n,stdio:["ignore",i,o]})}finally{e.closeSync(i),e.closeSync(o)}}(t)).pid}}catch(e){if(a=e instanceof Error?e.message:String(e),i.push(await eL(t.paths,"start_error")),o<2){await er(150);continue}break}let l=await tS(15e3,t,s);if("ready"===l.kind)return{info:l.info,startedByClient:!0};if("early_exit"===l.kind){if(r=l.exit,a=tD(l.exit),i.push(await eL(t.paths,"start_error")),o<2){await er(150);continue}break}if(await eR(t.paths)){n+=1;continue}let c=eO(t.paths),d=o<2,u=await eL(t.paths,"startup_timeout",{stopLiveProcesses:!1});if(i.push(u),u.retainedInfoProcess||u.retainedLockProcess){let e=await tS(15e3,t,s);if("ready"===e.kind)return{info:e.info,startedByClient:!0};"early_exit"===e.kind&&(r=e.exit,a=tD(e.exit));break}if(!d)break;c.hasInfo||c.hasLock||await er(150)}let o=eO(t.paths),s=function(t){try{if(!e.existsSync(t))return;let a=e.statSync(t);if(a.size<=0)return;let r=Math.min(a.size,64e3),n=e.openSync(t,"r");try{let t=Buffer.alloc(r);e.readSync(n,t,0,r,a.size-r);let i=t.toString("utf8").trim();return i.length>0?i:void 0}finally{e.closeSync(n)}}catch{return}}(t.paths.logPath);throw new f("COMMAND_FAILED","Failed to start daemon",{kind:"daemon_startup_failed",stateDir:t.paths.baseDir,infoPath:t.paths.infoPath,lockPath:t.paths.lockPath,logPath:t.paths.logPath,startupTimeoutMs:15e3,startupAttempts:2,lockRecoveryCount:n,cleanupResults:i,startError:a,daemonProcess:r,...s?{daemonLogTail:s}:{},metadataState:o,hint:function(e,t=P(process.env.AGENT_DEVICE_STATE_DIR)){var a;let r=(a=t,`rm -f ${S(a.infoPath)} ${S(a.lockPath)}`);return e.hasLock&&!e.hasInfo?`agent-device attempted to clean stale daemon metadata automatically, but ${t.lockPath} still exists without ${t.infoPath}. Retry with --debug; if this persists after confirming no agent-device daemon process is running, run: ${r}`:e.hasLock&&e.hasInfo?`agent-device attempted to clean stale daemon metadata automatically, but ${t.infoPath} and ${t.lockPath} still remain. Retry with --debug; if this persists after confirming no agent-device daemon process is running, run: ${r}`:e.hasInfo?`agent-device did not observe reachable daemon metadata after retrying, and ${t.infoPath} still remains. Stale metadata was cleaned automatically when safe; retry with --debug. If this persists after confirming no agent-device daemon process is running, run: ${r}`:`agent-device did not observe reachable daemon metadata after retrying. Stale metadata was cleaned automatically when safe; retry with --debug and check daemon diagnostics logs. If stale metadata returns after confirming no agent-device daemon process is running, run: ${r}`}(o,t.paths)})}async function tI(t,a,r){if(!tA(t.command)||!a.startedByClient&&!r.ownedStateDir||eB(a.info))return;let n={pid:a.info.pid,removedInfo:!1,removedLock:!1,removedStateDir:!1,error:void 0};try{await eF(a.info)}catch(e){n.error=e instanceof Error?e.message:String(e)}finally{let t=e.existsSync(r.paths.infoPath);eq(r.paths.infoPath),n.removedInfo=t&&!e.existsSync(r.paths.infoPath);let a=e.existsSync(r.paths.lockPath);eq(r.paths.lockPath),n.removedLock=a&&!e.existsSync(r.paths.lockPath),r.ownedStateDir&&(e.rmSync(r.paths.baseDir,{recursive:!0,force:!0}),n.removedStateDir=!e.existsSync(r.paths.baseDir))}g({level:n.error?"warn":"info",phase:"daemon_replay_cleanup",data:n})}function tA(e){return e===ee.replay||e===ee.test}async function tS(e,t,a){let r,n=Date.now();for(a.exited.then(e=>{r=e});Date.now()-n<e;){if(r)return{kind:"early_exit",exit:r};let e=e$(t.paths.infoPath);if(e&&await ta(e,t.transportPreference))return{kind:"ready",info:e};if(r)return{kind:"early_exit",exit:r};await er(100)}return{kind:"timeout"}}function tM(){let t=ea(),a=[r.join(t,"dist","src","internal","daemon.js"),r.join(t,"dist","src","daemon.js")],n=a[0];if(void 0===n)throw new f("COMMAND_FAILED","Daemon dist path list is empty");let i=a.find(t=>e.existsSync(t))??n,o=r.join(t,"src","daemon.ts"),s=a.some(t=>e.existsSync(t)),l=e.existsSync(o);if(!s&&!l)throw new f("COMMAND_FAILED","Daemon entry not found",{distPaths:a,srcPath:o});return{root:t,distPath:i,distPaths:a,srcPath:o,useSrc:process.execArgv.includes("--experimental-strip-types")?l:!s&&l}}function t_(){let e=tM();return E(e.useSrc?e.srcPath:e.distPath,e.root)}function tD(e){return e.error?`daemon process ${e.pid} failed to start: ${e.error}`:e.signal?`daemon process ${e.pid} exited before readiness with signal ${e.signal}`:`daemon process ${e.pid} exited before readiness with code ${e.exitCode??0}`}async function tP(e){let t=e.meta?.requestId??y(),a=!!(e.meta?.debug||e.flags?.verbose),r=th(e),n=function(e){if(e.command!==ee.test){var t;return"number"==typeof e.flags?.timeoutMs&&((t=e.command)===ee.prepare||t===ee.replay||t===ee.snapshot)?e.flags.timeoutMs:e.command===ee.prepare?24e4:9e4}}(e),i=await w("daemon_startup",async()=>await ty(r),{requestId:t,session:e.session}),o=i.info,s=await eM(e,o),l={...e,positionals:s.positionals,flags:s.flags,token:o.token,meta:{...e.meta??{},requestId:t,debug:a,cwd:e.meta?.cwd,sessionExplicit:e.meta?.sessionExplicit,tenantId:e.meta?.tenantId??e.flags?.tenant,runId:e.meta?.runId??e.flags?.runId,leaseId:e.meta?.leaseId??e.flags?.leaseId,sessionIsolation:e.meta?.sessionIsolation??e.flags?.sessionIsolation,lockPolicy:e.meta?.lockPolicy,lockPlatform:e.meta?.lockPlatform,...s.uploadedArtifactId?{uploadedArtifactId:s.uploadedArtifactId}:{},...s.clientArtifactPaths?{clientArtifactPaths:s.clientArtifactPaths}:{},...s.installSource?{installSource:s.installSource}:{}}};g({level:"info",phase:"daemon_request_prepare",data:{requestId:t,command:e.command,session:e.session}});try{return await w("daemon_request",async()=>await to(o,l,r.transportPreference,r.paths,n),{requestId:t,command:e.command})}finally{await tI(e,i,r)}}tm.addSubnet("127.0.0.0",8,"ipv4"),tm.addAddress("::1","ipv6"),tm.addSubnet("::ffff:127.0.0.0",104,"ipv6");let tk=/^[0-9a-fA-F-]{32,36}$/;function tE(e){if(e&&tk.test(e))return e.replaceAll("-","").toUpperCase()}function tN(e,t){return`${e.uuid}:${tx(t)}`}function tx(e){return`0x${e.toString(16)}`}function t$(e){return"string"==typeof e&&e.length>0?e:void 0}function tT(...e){for(let t of e){let e=t$(t);if(e)return e}}function tC(e){return"object"==typeof e&&null!==e}function tU(e){return tC(e)?e:void 0}function tL(e){try{let t=JSON.parse(e);return tC(t)?t:null}catch{return null}}function tO(e){if("number"==typeof e&&Number.isSafeInteger(e))return e;if("string"==typeof e){let t=e.startsWith("0x")?Number.parseInt(e,16):Number(e);return Number.isSafeInteger(t)?t:void 0}}function tR(e,t,a){var r;if(!Object.hasOwn(e,t))return;let n="bigint"==typeof(r=e[t])?r:"number"==typeof r&&Number.isSafeInteger(r)?BigInt(r):"string"!=typeof r?void 0:/^(?:0x[0-9a-fA-F]+|\d+)$/.test(r)?BigInt(r):void 0;if(void 0!==n)return n;tF(a,t)}function tF(e,t){throw new f("INVALID_ARGS",`Invalid ${e} numeric field: ${t}`,{hint:"Crash artifact numeric fields must be integer numbers or integer numeric strings."})}function tB(e){return[...new Set(e)]}let tj=/^(?:arm64e?|arm64_32|x86_64|armv7[sk]?|i386)$/;async function tq(e){return e.dsym&&e.searchPath?[tY(e.cwd,e.dsym),...await tV(tY(e.cwd,e.searchPath))]:e.dsym?[tY(e.cwd,e.dsym)]:e.searchPath?await tV(tY(e.cwd,e.searchPath)):[]}async function tV(e){let t=[],a=0;async function n(i){if(!(t.length>=200)){if((a+=1)>1e4)throw new f("COMMAND_FAILED","debug symbols search-path scan exceeded bounds.",{searchPath:e,maxEntries:1e4,hint:"Pass --dsym <App.dSYM> directly or narrow --search-path to the build products directory."});if(!(await tH(i,e)).isDirectory()){i===e&&function(e){throw new f("INVALID_ARGS",`debug symbols search path is not a directory: ${e}`,{hint:"Pass an existing build products directory to --search-path, or pass --dsym <App.dSYM> directly."})}(e);return}if(i.endsWith(".dSYM"))return void t.push(i);for(let e of(await d.readdir(i,{withFileTypes:!0})))e.isDirectory()&&await n(r.join(i,e.name))}}return await n(e),t}async function tH(e,t){try{return await d.stat(e)}catch{throw new f("INVALID_ARGS",`debug symbols search path does not exist: ${t}`,{hint:"Pass an existing build products directory to --search-path, or pass --dsym <App.dSYM> directly."})}}async function tG(e,t){let a=(await Promise.all(tB(e).map(e=>tK(e,t)))).flat();if(0===a.length)throw new f("COMMAND_FAILED","No UUIDs found in dSYM bundle.",{hint:"Verify the path points to a built .dSYM bundle with DWARF contents."});return a}async function tK(e,t){var a;await tz(e);let r=await m(t,["--uuid",e],{timeoutMs:15e3,allowFailure:!0});if(0!==r.exitCode)throw new f("COMMAND_FAILED",`Failed to inspect dSYM UUIDs: ${e}`,{stderr:r.stderr,hint:"Verify the dSYM bundle is valid and readable."});return a=e,r.stdout.split("\n").flatMap(e=>{let t=e.match(/^UUID:\s+([0-9a-fA-F-]{32,36})\s+\(([^)]+)\)\s+(.+)$/),r=tE(t?.[1]);return t&&r?[{dsymPath:a,uuid:r,arch:t[2],binaryPath:t[3].trim()}]:[]})}async function tz(e){let t=await d.stat(e).catch(()=>null);if(!(t?.isDirectory()&&e.endsWith(".dSYM")))throw new f("INVALID_ARGS",`Not a .dSYM bundle: ${e}`,{hint:"Pass the .dSYM bundle path, not the DWARF executable inside it."})}function tY(e,t){return r.resolve(e,t)}function tW(e,t){let a=`${t}:`,r=e.find(e=>e.trimStart().startsWith(a));return r&&r.slice(r.indexOf(":")+1).trim()||void 0}function tJ(e,t,a,r){return{index:e,image:t.name,address:tx(a),symbol:r.get(tN(t,a))?.text}}function tX(e){var t;let a;return[(a=(t=e).topFrames.find(e=>e.symbol))?`Start with ${a.symbol} in ${a.image}; it is the first symbolicated frame captured on the crashed thread.`:t.topFrames.length>0?"No symbolicated frame was found on the crashed thread; verify matching dSYMs for the top images.":void 0,e.exceptionType?`Exception: ${e.exceptionType}`:void 0,e.terminationReason?`Termination: ${e.terminationReason}`:void 0].filter(e=>!!e).slice(0,3)}async function tQ(e,t,a){let r=new Map;for(let n of(function(e,t){let a=new Map;for(let r of e){let e=t.get(r.image.uuid);if(!e)continue;let n=`${r.image.uuid}:${e.dsym.binaryPath}`,i=a.get(n)??{...e,addresses:[]};i.addresses.push(r.address),a.set(n,i)}return a})(e,t).values())for(let e of(await tZ(a,n)))r.set(tN(e.image,e.address),e);return r}async function tZ(e,t){var a,r,n,i;let o,s,l=tB(t.addresses.map(tx)),c=await m(e,(a=t,r=l,["-arch",a.image.arch??a.dsym.arch??"arm64","-o",a.dsym.binaryPath,"-l",tx(a.image.base),...r]),{timeoutMs:3e4,allowFailure:!0});return 0!==c.exitCode&&function(e){throw new f("COMMAND_FAILED","atos failed while symbolicating crash frames.",{stderr:e,hint:"Verify the crash artifact and dSYM were produced from the same build and architecture."})}(c.stderr),n=t.image,i=l,s=(""===(o=c.stdout.split(/\r?\n/)).at(-1)&&o.pop(),o),i.map((e,t)=>{let a=s[t]?.trim();return{image:n,address:BigInt(e),text:!function(e,t){if(!e)return!1;let a=e.trim().toLowerCase();return!!a&&"??"!==a&&a!==t.toLowerCase()&&!a.startsWith("0x")}(a,e)?void 0:a}})}async function t0(){return{dwarfdump:await t1("dwarfdump"),atos:await t1("atos")}}async function t1(e){try{let t=await m("xcrun",["--find",e],{timeoutMs:5e3,allowFailure:!0}),a=t.stdout.trim();if(0===t.exitCode&&a.length>0)return a}catch{}throw new f("TOOL_MISSING",`Apple symbolication tool not found: ${e}`,{hint:"Install Xcode Command Line Tools and verify xcrun --find dwarfdump and xcrun --find atos succeed."})}async function t3(e){var t,a,n,i,o,s,l,c,u,p,m,h,y,w,g,b,v,I,A,S,M,_,D,P,k,E,N;let x,$,T,C,U,L,O,R,F;if(void 0!==e.action&&"symbols"!==e.action)throw new f("INVALID_ARGS","debug supports only the symbols workflow.",{hint:"Use debug symbols --artifact <crash.ips|crash.log> --dsym <App.dSYM> or --search-path <dir> --out <path>."});let B=e.cwd??process.cwd(),j=t4(B,e.artifact),q=t4(B,e.out??(a=j,$=(x=r.extname(a))?a.slice(0,-x.length):a,`${$}-symbolicated${x||".log"}`)),V=function(e){var t;let a,n=function(e){let t=tL(e);if(t)return{payload:t};let a=e.indexOf("\n");if(-1===a)return null;let r=e.slice(0,a),n=tL(e.slice(a+1));return n?{header:r,payload:n}:null}(e);if(!n)return null;let i=(Array.isArray(n.payload.usedImages)?n.payload.usedImages:[]).flatMap((e,t)=>(function(e,t){if(!e||"object"!=typeof e)return[];let a=tE(t$(e.uuid)),n=tR(e,"base","IPS usedImages");if(!a||void 0===n)return[];let i=t$(e.path);return[{index:t,name:t$(e.name)??(i?r.basename(i):`image-${t}`),uuid:a,arch:t$(e.arch),base:n,path:i}]})(e,t));if(0===i.length)return null;let o=(t=Array.isArray(n.payload.threads)?n.payload.threads:[],a=new Map(i.map(e=>[e.index,e])),t.flatMap((e,t)=>(function(e){if(!e||"object"!=typeof e)return[];let t=e.frames;return Array.isArray(t)?t.filter(e=>tC(e)):[]})(e).flatMap((e,r)=>(function(e,t,a,r){let n=function(e,t,a){if(!Object.hasOwn(e,t))return;let r=tO(e[t]);if(void 0!==r)return r;tF(a,t)}(e,"imageIndex","IPS frame"),i=tR(e,"imageOffset","IPS frame");if(void 0===n||void 0===i)return[];let o=t.get(n);return o?[{frame:e,frameIndex:r,threadIndex:a,image:o,address:o.base+i}]:[]})(e,a,t,r))));return{format:"ips",images:i,addresses:o.map(({frame:e,...t})=>t),document:n,frameMatches:o,write:e=>(function(e,t,a){for(let e of t){let t=a.get(tN(e.image,e.address))?.text;t&&function(e,t){let a,r=(a=t.match(/^(.*) \+ (\d+)$/))?{symbol:a[1],location:Number(a[2])}:{symbol:t};e.symbol=r.symbol,void 0!==r.location&&(e.symbolLocation=r.location)}(e.frame,t)}e.payload.agentDeviceSymbolication={tool:"agent-device debug symbols",symbolicatedFrames:[...a.values()].filter(e=>e.text).length};let r=`${JSON.stringify(e.payload,null,2)}
|
|
1
|
+
import e from"node:fs";import t from"node:http";import a from"node:https";import r from"node:path";import{pipeline as n}from"node:stream/promises";import i from"node:os";import{createHash as o,randomUUID as s}from"node:crypto";import{Writable as l}from"node:stream";import c from"node:net";import d from"node:fs/promises";import{toAppErrorCode as u,AppError as f}from"./733.js";import{runCmdDetachedMonitored as p,runCmd as m,runCmdSync as h}from"./8875.js";import{recordingExtensionForPlatform as y,appendRecordingExtensionWhenMissing as w}from"./5643.js";import{createRequestId as g,withDiagnosticTimer as v,emitDiagnostic as b}from"./432.js";import{isAgentDeviceDaemonProcess as I,stopProcessForTakeover as A}from"./9414.js";import{readSnapshotDiagnosticsSummary as S,consumeTextLines as P,shellQuote as _,shouldStreamRequestProgress as D,isDaemonResponseEnvelope as M,isDaemonProgressEnvelope as k,resolveDaemonPaths as E,readScreenshotResultData as N,resolveDaemonServerMode as x,computeDaemonCodeSignature as $,resolveDaemonTransportPreference as C}from"./1848.js";import{listCommandFamilyDaemonWriters as T,normalizeSession as U,normalizeInstallFromSourceResult as L,readSerializedSnapshotCaptureAnnotations as O,findCommandMetadata as R,normalizeMaterializationReleaseResult as F,colorize as B,readSnapshotNodes as j,normalizeDeployResult as q,leaseScopeToLeaseRpcParams as V,normalizeOpenDevice as H,buildMeta as K,resolveSessionName as G,supportsColor as z,buildRequestFlags as Y,createBatchDaemonWriter as W,readMetadataCommandFlags as J,normalizeRuntimeHints as X,normalizeDevice as Q,normalizeTargetShutdownResult as Z,normalizeStartupSample as ee,leaseScopeFromRequest as et}from"./2948.js";import{readRequiredString as ea,INTERNAL_COMMANDS as er,PUBLIC_COMMANDS as en,readOptionalString as ei,isRecord as eo}from"./5341.js";import{readVersion as es,findProjectRoot as el}from"./1404.js";import{sleep as ec}from"./5560.js";import{reloadMetro as ed,prepareMetroRuntime as eu}from"./8275.js";let ef="/agent-device";function ep(e){return em(e,ef)}function em(e,t){let a=e.endsWith("/")?e:`${e}/`;return new URL(t.replace(/^\/+/,""),a).toString()}function eh(e){let t=e?.trim();return t?{authorization:`Bearer ${t}`,"x-agent-device-token":t}:{}}function ey(e){return new Promise((t,a)=>{let r="";e.setEncoding("utf8"),e.on("data",e=>{r+=e}),e.on("end",()=>t(r)),e.on("error",a)})}let ew="sha256";async function eg(e){let t=await ev(e.localPath,e.platform),a=e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`;try{let r=await eS({normalizedBase:a,token:e.token,artifact:t});if(r?.kind==="cache-hit")return r.uploadId;if(r?.kind==="direct-upload")try{return await eP(t.payloadPath,r),await ek({normalizedBase:a,token:e.token,uploadId:r.uploadId})}catch{}return await eA({normalizedBase:a,token:e.token,artifact:t})}finally{t.cleanup()}}async function ev(t,a){var n,i,o;let s,l=e.statSync(t),c=r.basename(t),d=l.isDirectory(),u=("ios"===(n=a)||"android"===n?n:void 0)??(i=t,o=l,s=i.toLowerCase(),o.isDirectory()&&s.endsWith(".app")||s.endsWith(".ipa")?"ios":s.endsWith(".apk")||s.endsWith(".aab")?"android":void 0),f=[];try{let a=d?await eb(t,f):t,r=e.statSync(a);return{payloadPath:a,fileName:c,artifactType:d?"app-bundle":"file",platform:u,contentType:d?"application/gzip":"application/octet-stream",sha256:await eE(a),sizeBytes:r.size,cleanup:()=>eI(f)}}catch(e){throw eI(f),e}}async function eb(t,a){let n=e.mkdtempSync(r.join(i.tmpdir(),`agent-device-upload-${s()}-`));a.push(n);let o=r.join(n,`${r.basename(t)}.tar.gz`);return await m("tar",["czf",o,"-C",r.dirname(t),r.basename(t)],{env:{...process.env,COPYFILE_DISABLE:"1"}}),o}function eI(t){for(let a of t)e.rmSync(a,{recursive:!0,force:!0})}async function eA(e){let{normalizedBase:t,token:a,artifact:r}=e,n=new URL("upload",t),i={"content-type":r.contentType,"x-artifact-type":r.artifactType,"x-artifact-filename":r.fileName,"x-artifact-hash":r.sha256,"x-artifact-hash-algorithm":ew,"transfer-encoding":"chunked"};Object.assign(i,eh(a));let o=await e_({url:n,method:"POST",headers:i,payloadPath:r.payloadPath,timeoutMessage:"Artifact upload timed out",timeoutHint:"The upload to the remote daemon exceeded the 5-minute timeout.",errorMessage:"Failed to upload artifact to remote daemon",errorHint:"Verify the remote daemon is reachable and supports artifact uploads."});try{let e=JSON.parse(o.body);if(!e.ok||!e.uploadId)throw new f("COMMAND_FAILED",`Upload failed: ${o.body}`);return e.uploadId}catch(e){if(e instanceof f)throw e;throw new f("COMMAND_FAILED",`Invalid upload response: ${o.body}`)}}async function eS(e){let t=new URL("upload/preflight",e.normalizedBase),a={"content-type":"application/json"};Object.assign(a,eh(e.token));let r=await fetch(t,{method:"POST",headers:a,signal:AbortSignal.timeout(3e4),body:JSON.stringify({sha256:e.artifact.sha256,fileName:e.artifact.fileName,sizeBytes:e.artifact.sizeBytes,artifactType:e.artifact.artifactType,...e.artifact.platform?{platform:e.artifact.platform}:{},contentType:e.artifact.contentType})}).catch(()=>void 0);if(r?.ok)return function(e){var t;if(!e||"object"!=typeof e||!0!==e.ok||"string"!=typeof e.uploadId)return;if(!0===e.cacheHit)return{kind:"cache-hit",uploadId:e.uploadId};let a=e.upload;if(!a||"string"!=typeof a.url)return;let r=a.headers??{};if(!(!(t=r)||"object"!=typeof t||Array.isArray(t))&&Object.values(t).every(e=>"string"==typeof e))return{kind:"direct-upload",uploadId:e.uploadId,url:a.url,headers:r}}(await r.json().catch(()=>void 0))}async function eP(e,t){let a=await e_({url:new URL(t.url),method:"PUT",headers:t.headers,payloadPath:e,timeoutMessage:"Direct artifact upload timed out",timeoutHint:"The direct upload ticket did not accept the artifact within the timeout.",errorMessage:"Failed to upload artifact with direct upload ticket"});if(a.statusCode<200||a.statusCode>=300)throw new f("COMMAND_FAILED","Direct artifact upload failed",{statusCode:a.statusCode,statusMessage:a.statusMessage})}async function e_(e){return await eD({...e,url:e.url,redirectCount:0,startOffset:0})}async function eD(r){var i,o,s;let l="https:"===r.url.protocol?a:t,c=e.statSync(r.payloadPath).size,d=(i=r.headers,o=r.startOffset,s=c,o<=0?i:{...i,"content-length":Math.max(s-o,0),"content-range":`bytes ${o}-${s-1}/${s}`});return await new Promise((t,a)=>{let i=!1,o=l.request({protocol:r.url.protocol,host:r.url.hostname,port:r.url.port,method:r.method,path:r.url.pathname+r.url.search,headers:d},e=>{i=!0,ey(e).then(n=>{clearTimeout(s);let i=e.statusCode??500,o=e.headers.location;if(o&&[301,302,303,307,308].includes(i)){if(r.redirectCount>=5)return void a(new f("COMMAND_FAILED","Artifact upload exceeded redirect limit",{maxRedirects:5,url:r.url.toString()}));let e=new URL(o,r.url);return void eD({...r,url:e,redirectCount:r.redirectCount+1}).then(t,a)}let l=308===i?function(e,t){let a=function(e){let t=eM(e);if(void 0===t)return;let a=Number(t);return Number.isSafeInteger(a)&&a>=0?a:void 0}(e["x-upload-offset"]??e["upload-offset"]);if(void 0!==a)return Math.min(a,t);let r=eM(e.range),n=r?.match(/^bytes=0-(\d+)$/);if(!n)return;let i=Number(n[1]);if(Number.isSafeInteger(i)&&!(i<0))return Math.min(i+1,t)}(e.headers,c):void 0;void 0!==l?l>=c?t({statusCode:200,statusMessage:"Upload already complete",body:""}):l<=r.startOffset?a(new f("COMMAND_FAILED","Artifact upload resume did not advance",{offset:l,previousOffset:r.startOffset,url:r.url.toString()})):eD({...r,startOffset:l}).then(t,a):t({statusCode:i,statusMessage:e.statusMessage,body:n})}).catch(a)}),s=setTimeout(()=>{o.destroy(),a(new f("COMMAND_FAILED",r.timeoutMessage,{timeoutMs:3e5,...r.timeoutHint?{hint:r.timeoutHint}:{}}))},3e5);o.on("error",e=>{i||(clearTimeout(s),a(new f("COMMAND_FAILED",r.errorMessage,r.errorHint?{hint:r.errorHint}:{},e)))}),o.on("close",()=>clearTimeout(s)),n(e.createReadStream(r.payloadPath,{start:r.startOffset}),o).catch(e=>{i||(o.destroy(),a(new f("COMMAND_FAILED","Failed to read local artifact",{},e instanceof Error?e:Error(String(e)))))})})}function eM(e){return Array.isArray(e)?e[0]:e}async function ek(e){let t=new URL("upload/finalize",e.normalizedBase),a={"content-type":"application/json"};Object.assign(a,eh(e.token));let r=await fetch(t,{method:"POST",headers:a,signal:AbortSignal.timeout(3e4),body:JSON.stringify({uploadId:e.uploadId})}).catch(e=>{throw new f("COMMAND_FAILED","Failed to finalize direct artifact upload",{},e)});if(!r.ok)throw new f("COMMAND_FAILED","Direct artifact upload finalize failed",{status:r.status,statusText:r.statusText});let n=await r.json().catch(()=>void 0);if(!n?.ok||!n.uploadId)throw new f("COMMAND_FAILED","Invalid upload finalize response");return n.uploadId}async function eE(t){let a=o(ew),r=new l({write(e,t,r){a.update(e),r()}});return await n(e.createReadStream(t),r).catch(e=>{throw new f("COMMAND_FAILED","Failed to read local artifact",{},e instanceof Error?e:void 0)}),a.digest("hex")}async function eN(e,t){var a;let n,i=[...e.positionals??[]],o=e.flags?{...e.flags}:void 0,s=e.meta?.installSource,l={};if(!("string"==typeof(a=t).baseUrl&&a.baseUrl.length>0))return e$({positionals:i,flags:o,installSource:s,uploadedArtifactId:n,clientArtifactPaths:l});o=function(e,t,a,n){var i,o;let s=function(e,t){if("screenshot"===e.command){let a=eU(e,"path",".png");return t[0]?{field:"path",localPath:a,positionalIndex:0,positionalPath:eO("screenshot",".png")}:{field:"path",localPath:a,positionalIndex:0,flagPath:eO("screenshot",".png")}}if("record"===e.command&&"start"===(t[0]??"").toLowerCase()){var a,n,i;if(a=e,!(eL(a.positionals?.[1])||eL(a.flags?.out))&&e.flags?.platform===void 0)return null;let t=eT(e),o=(n=eU(e,"outPath",t,1),i=e,i.flags?.platform!=="web"?n:w(n,eT(i)));return{field:"outPath",localPath:o,positionalIndex:1,positionalPath:eO("recording",r.extname(o)||t)}}return null}(e,t);if(!s)return a;void 0!==s.positionalPath&&(t[s.positionalIndex]=s.positionalPath);let l=(i=a,void 0===(o=s.flagPath)?i:{...i??{},out:o});return n[s.field]=s.localPath,l}(e,i,o,l);let c=await eC(e,t);c&&(s=c.installSource,n=c.uploadedArtifactId??n);let d=()=>e$({positionals:i,flags:o,installSource:s,uploadedArtifactId:n,clientArtifactPaths:l});return"install"!==e.command&&"reinstall"!==e.command||(n=await ex(e,t,i)??n),d()}async function ex(t,a,n){var i,o;let s,l=n[1];if(void 0===l)return;if(l.startsWith("remote:")){n[1]=l.slice(7);return}let c=(i=l,o=t.meta?.cwd,s=r.isAbsolute(i)?i:r.resolve(o??process.cwd(),i),e.existsSync(s)?s:void 0);if(c)return await eg({localPath:c,baseUrl:a.baseUrl,token:a.token,platform:t.flags?.platform})}function e$(e){return{positionals:e.positionals,flags:e.flags,installSource:e.installSource,uploadedArtifactId:e.uploadedArtifactId,...Object.keys(e.clientArtifactPaths).length>0?{clientArtifactPaths:e.clientArtifactPaths}:{}}}async function eC(t,a){let n=t.meta?.installSource;if("install_source"!==t.command||!n||"path"!==n.kind)return null;let i=n.path.trim();if(!i)return{installSource:n};if(i.startsWith("remote:"))return{installSource:{...n,path:i.slice(7)}};let o=r.isAbsolute(i)?i:r.resolve(t.meta?.cwd??process.cwd(),i);if(!e.existsSync(o))return{installSource:{...n,path:o}};let s=await eg({localPath:o,baseUrl:a.baseUrl,token:a.token,platform:t.flags?.platform});return{installSource:{...n,path:o},uploadedArtifactId:s}}function eT(e){return y(e.flags?.platform)}function eU(e,t,a,n=0){let i=e.positionals?.[n]??e.flags?.out,o=`${"path"===t?"screenshot":"recording"}-${Date.now()}${a}`,s=eL(i)?i:o;return r.isAbsolute(s)?s:r.resolve(e.meta?.cwd??process.cwd(),s)}function eL(e){return"string"==typeof e&&e.trim().length>0}function eO(e,t){let a=t.startsWith(".")?t:`.${t}`;return r.posix.join("/tmp",`agent-device-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}${a}`)}async function eR(e,t,a){let n=Array.isArray(a.data?.artifacts)?a.data.artifacts:[];if(0===n.length||!e.baseUrl)return a;let i=a.data?{...a.data}:{},o=[];for(let a of n){if(!a||"object"!=typeof a||"string"!=typeof a.artifactId){o.push(a);continue}let n=function(e,t){if(e.localPath&&e.localPath.trim().length>0)return e.localPath;let a=t.meta?.clientArtifactPaths?.[e.field];if(a&&a.trim().length>0)return a;let n=e.fileName?.trim()||`${e.field}-${Date.now()}`;return r.resolve(t.meta?.cwd??process.cwd(),n)}(a,t);await eF({baseUrl:e.baseUrl,token:e.token,artifactId:a.artifactId,destinationPath:n,requestId:t.meta?.requestId}),i[a.field]=n,o.push({...a,localPath:n})}return i.artifacts=o,{ok:!0,data:i}}async function eF(i){var o,s;let l,c=new URL((o=i.baseUrl,s=i.artifactId,l=o.endsWith("/")?o:`${o}/`,new URL(`artifacts/${encodeURIComponent(s)}`,l).toString())),d="https:"===c.protocol?a:t;await e.promises.mkdir(r.dirname(i.destinationPath),{recursive:!0}),await new Promise((t,a)=>{let r=!1,o=i.timeoutMs??9e4,s=n=>{if(!r){if(r=!0,clearTimeout(u),n)return void e.promises.rm(i.destinationPath,{force:!0}).finally(()=>a(n));t()}},l=d.request({protocol:c.protocol,host:c.hostname,port:c.port,method:"GET",path:c.pathname+c.search,headers:eh(i.token)},t=>{if((t.statusCode??500)>=400){let e="";t.setEncoding("utf8"),t.on("data",t=>{e+=t}),t.on("end",()=>{s(new f("COMMAND_FAILED","Failed to download remote artifact",{artifactId:i.artifactId,statusCode:t.statusCode,requestId:i.requestId,body:e}))});return}t.on("aborted",()=>{s(new f("COMMAND_FAILED","Remote artifact download was interrupted",{artifactId:i.artifactId,requestId:i.requestId}))}),n(t,e.createWriteStream(i.destinationPath)).then(()=>s(),e=>s(e instanceof Error?e:Error(String(e))))}),u=setTimeout(()=>{let e=new f("COMMAND_FAILED","Remote artifact download timed out",{artifactId:i.artifactId,requestId:i.requestId,timeoutMs:o});s(e),l.destroy(e)},o);l.on("error",e=>{e instanceof f?s(e):s(new f("COMMAND_FAILED","Failed to download remote artifact",{artifactId:i.artifactId,requestId:i.requestId,timeoutMs:o},e instanceof Error?e:void 0))}),l.end()})}function eB(e){var t,a,r;let n,i,o=eW(e);if(!o||"object"!=typeof o)return null;let s="string"==typeof(t=o).token&&t.token.length>0?t.token:null;if(!s)return null;let l=(n=eq((a=o).port),i=eq(a.httpPort),void 0===n&&void 0===i?null:{port:n,httpPort:i});return l?{token:s,...l,transport:"socket"===(r=o.transport)||"http"===r||"dual"===r?r:void 0,pid:eq(o.pid)??0,version:ej(o.version),codeSignature:ej(o.codeSignature),processStartTime:ej(o.processStartTime)}:null}function ej(e){return"string"==typeof e?e:void 0}function eq(e){return Number.isInteger(e)&&Number(e)>0?Number(e):void 0}function eV(e){let t=eW(e);return t&&"object"==typeof t&&Number.isInteger(t.pid)&&Number(t.pid)>0?{pid:Number(t.pid),processStartTime:"string"==typeof t.processStartTime?t.processStartTime:void 0,startedAt:"number"==typeof t.startedAt?t.startedAt:void 0}:null}async function eH(t,a,r={}){let n=r.stopLiveProcesses??!0,i={reason:a,removedInfo:!1,removedLock:!1,stoppedInfoProcess:!1,stoppedLockProcess:!1};try{var o,s,l,c;let a=e.existsSync(t.infoPath),r=eB(t.infoPath);if(r){let e=I(r.pid,r.processStartTime);e&&!n?i.retainedInfoProcess=!0:(e&&(await ez(r),i.stoppedInfoProcess=!0),o=t.infoPath,eJ(o),i.removedInfo=!0)}else a&&(s=t.infoPath,eJ(s),i.removedInfo=!0);let d=e.existsSync(t.lockPath),u=eV(t.lockPath);if(u){let e=I(u.pid,u.processStartTime);e&&!n?i.retainedLockProcess=!0:(e&&(await A(u.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:u.processStartTime}),i.stoppedLockProcess=!0),l=t.lockPath,eJ(l),i.removedLock=!0)}else d&&(c=t.lockPath,eJ(c),i.removedLock=!0)}catch(e){i.error=e instanceof Error?e.message:String(e)}return b({level:i.error?"warn":"info",phase:"daemon_startup_metadata_cleanup",data:i}),i}function eK(t){return{hasInfo:e.existsSync(t.infoPath),hasLock:e.existsSync(t.lockPath)}}async function eG(e){let t=eK(e);if(!t.hasLock||t.hasInfo)return!1;let a=eV(e.lockPath);return!(a&&I(a.pid,a.processStartTime))&&(eJ(e.lockPath),!0)}async function ez(e){await A(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}function eY(e){return"string"==typeof e.baseUrl&&e.baseUrl.length>0}function eW(t){if(!e.existsSync(t))return null;try{return JSON.parse(e.readFileSync(t,"utf8"))}catch{return null}}function eJ(t){try{e.existsSync(t)&&e.unlinkSync(t)}catch{}}function eX(e){let t=Math.max(0,e)/1e3;return t>=10?`${t.toFixed(1)}s`:t>=1?`${t.toFixed(2)}s`:`${t.toFixed(3).replace(/0+$/,"").replace(/\.$/,"")}s`}function eQ(e){let t=eZ(e),a=t.findIndex(({stop:e})=>!1===e.ok);if(a<0)return[];let r=t.slice(Math.max(0,a-2),a+1);return[e.attempts>1?`steps (attempt ${e.attempts}):`:"steps:",...r.map(({stop:e,start:t})=>e2(e,t))]}function eZ(t){var a,n;let i=(a=t).artifactsDir?r.join(a.artifactsDir,`attempt-${a.attempts}`,"replay-timing.ndjson"):void 0;if(!i)return[];let o=function(t){try{return e.readFileSync(t,"utf8").split(/\r?\n/).filter(e=>e.trim().length>0).flatMap(e=>{try{let t=JSON.parse(e);return e4(t)?[t]:[]}catch{return[]}})}catch{return[]}}(i);if(0===o.length)return[];let s=[],l=[];for(let e of o){if("replay_action_start"===(n=e).type&&e0(n)&&e1(n,"line")&&e3(n,"command")&&(void 0===n.positionals||Array.isArray(n.positionals))){s.push(e);continue}(function(e){var t;return["replay_action_stop"===e.type&&e0(e)&&e1(e,"line")&&e3(e,"command"),void 0===(t=e).ok||"boolean"==typeof t.ok,e1(e,"durationMs"),e3(e,"errorCode"),void 0===e.resultTiming||e4(e.resultTiming)].every(Boolean)})(e)&&l.push({stop:e,start:function(e,t){let a=t.command,r=e.findIndex(e=>e.step===t.step&&(void 0===a||void 0===e.command||e.command===a));if(!(r<0))return e.splice(r,1)[0]}(s,e)})}return l}function e0(e){return"number"==typeof e.step}function e1(e,t){return void 0===e[t]||"number"==typeof e[t]}function e3(e,t){return void 0===e[t]||"string"==typeof e[t]}function e2(e,t){var a,r,n,i;let o,s,l=!1===e.ok?"[FAIL] ":!0===e.ok?"":"[info] ";return` ${l}${a=t,r=e,[function(e){if(!e)return"unknown";if(!e.startsWith("__maestro"))return e;let t=e.slice(9);return t.length>0?t[0].toLowerCase()+t.slice(1):e}(a?.command??r.command),...(a?.positionals??[]).map(e5)].join(" ")}${n=e,i=t,(s=["number"==typeof(o=i?.line??n.line)?`line ${o}`:"","number"==typeof n.durationMs?eX(n.durationMs):"",n.errorCode??"",n.resultTiming?`timing ${JSON.stringify(n.resultTiming)}`:""].filter(Boolean)).length>0?` (${s.join(", ")})`:""}`}function e5(e){return"string"==typeof e?JSON.stringify(e):"number"==typeof e||"boolean"==typeof e?String(e):JSON.stringify(e)}function e4(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function e6(e,t){return B(e,t,{validateStream:!1})}function e8(e){if("number"!=typeof e.shardIndex)return"";let t="number"==typeof e.shardCount?e.shardCount:"?",a="string"==typeof e.deviceId?` ${e.deviceId}`:"";return` [shard ${e.shardIndex+1}/${t}${a}]`}function e7(e){return`\r\x1b[2K${e}`}function e9(e){return"number"==typeof e&&Number.isFinite(e)&&e>0?Math.floor(e):80}function te(e,t){let a=e9(t);return e.length<=a?e:a<=0?"":a<=3?".".repeat(a):`${e.slice(0,a-3)}...`}function tt(e){return{file:e.file,title:e.title,durationMs:e.durationMs??0,attempts:e.attempt??1,artifactsDir:e.artifactsDir,session:e.session??""}}function ta(e){return function(e={}){let t=new Set,a=!1;return{render(n){var i,o;if("replay-test-suite"===n.type){t.clear(),a=!1;return}if("replay-test"!==n.type)return;if("progress"===n.status){if(!e.liveProgress)return;return a=!0,{text:e7(function(e,t){let a=e.title?.trim(),n=r.basename(e.file),i=e8(e),o=e.stepIndex??0,s=e.stepTotal??0,l=`${i} [${o}/${s}]`,c="⊙ ";if(!a)return te(`${c}${n}${l}`,t.columns);let d=`${c}"`,u=`" in ${n}${l}`,f=te(a,Math.max(0,e9(t.columns)-d.length-u.length));return te(`${d}${f}${u}`,t.columns)}(n,e)),newline:!1}}if("pass"===(i=n).status||"skip"===i.status||"fail"===i.status&&!i.retrying){let e,a=(e="number"==typeof(o=n).shardIndex?o.shardIndex:"",[o.status,o.index,o.total,o.file,o.title??"",e].join("\0"));if(t.has(a))return;t.add(a)}let s=function(e,t={}){if("replay-test"===e.type)return function(e,t){var a,n,i,o;let s,l,c,d,u,f;if("start"===e.status||"progress"===e.status||"fail"===e.status&&e.retrying)return;let p=[(c=function(e){let t=z(process.stderr);if("pass"===e.status){let a=e.attempt&&e.attempt>1?"yellow":"green";return t?e6("✓",a):"✓"}return"fail"===e.status?t?e6("⨯","red"):"⨯":"progress"===e.status?"⊙":t?e6("-","dim"):"-"}(a=e),d=(n=a,s=n.title?.trim(),l=r.basename(n.file),s?`${JSON.stringify(s)} in ${l}`:l),u=e8(a),f=void 0!==a.durationMs?` (${eX(a.durationMs??0)})`:"",`${c} ${d}${u}${f}`)];return function(e,t,a){if(a.verbose&&"fail"===t.status)return;let r=t.message?.replace(/\s+/g," ").trim();r&&e.push(` ${"fail"===t.status?`failed at: ${r}`:r}`),"fail"===t.status&&!t.retrying&&(t.session&&e.push(` session: ${t.session}`),t.artifactsDir&&e.push(` artifacts: ${t.artifactsDir}`))}(p,e,t),t.verbose&&p.push(...("pass"===(i=e).status||"fail"===i.status)&&i.artifactsDir&&i.attempt?(function(e){if("skipped"===e.status)return[];let t=eZ(e);return 0===t.length?[]:[e.attempts>1?`steps (attempt ${e.attempts}):`:"steps:",...t.map(({stop:e,start:t})=>e2(e,t))]})("pass"===i.status?{...tt(i),status:"passed",replayed:0,healed:0}:{...tt(o=i),status:"failed",error:{code:"COMMAND_FAILED",message:o.message??"Unknown test failure"}}).map(e=>` ${e}`):[]),p.join("\n")}(e,t)}(n,e);if(!s)return;let l=a?e7(s):s;return a=!1,{text:l,newline:!0}}}}({verbose:!!(e.flags?.verbose||e.meta?.debug),liveProgress:!0===process.stderr.isTTY&&!process.env.CI,columns:process.stderr.columns})}function tr(e,t){let a=t.render(e);a&&process.stderr.write(a.newline?`${a.text}
|
|
2
|
+
`:a.text)}function tn(e,t){let{info:a,req:r,resolve:n,reject:i}=t;try{var o,s,l;let t=(o=e,JSON.parse(o));if(t.error){let e;return void i((s=t.error,l=r.meta?.requestId,e=s.data??{},new f(u(null!=e.code?String(e.code):void 0,"COMMAND_FAILED"),String(e.message??s.message??"Daemon RPC request failed"),{..."object"==typeof e.details&&e.details?e.details:{},hint:"string"==typeof e.hint?e.hint:void 0,diagnosticId:"string"==typeof e.diagnosticId?e.diagnosticId:void 0,logPath:"string"==typeof e.logPath?e.logPath:void 0,requestId:l})))}if(!t.result||"object"!=typeof t.result)return void i(new f("COMMAND_FAILED","Invalid daemon RPC response",{requestId:r.meta?.requestId}));ti(a,r,t.result,n,i)}catch(t){i(new f("COMMAND_FAILED","Invalid daemon response",{requestId:r.meta?.requestId,line:e},t instanceof Error?t:void 0))}}async function ti(e,t,a,r,n){try{r(e.baseUrl&&a.ok?await eR(e,t,a):a)}catch(e){n(e)}}let to=["xcodebuild .*AgentDeviceRunnerUITests/RunnerTests/testCommand","xcodebuild .*AgentDeviceRunner\\.env\\.session-","xcodebuild build-for-testing .*ios-runner/AgentDeviceRunner/AgentDeviceRunner\\.xcodeproj"];function ts(e,t,a,r,n,i){let o=n?{terminated:0}:function(){let e=0;try{for(let t of to){let a=h("pkill",["-f",t],{allowFailure:!0});0===a.exitCode&&(e+=1)}return{terminated:e}}catch(t){return{terminated:e,error:t instanceof Error?t.message:String(t)}}}(),s=!n&&"snapshot"!==r,l=s?function(e,t){let a=!1;try{I(e.pid,e.processStartTime)&&(process.kill(e.pid,"SIGKILL"),a=!0)}catch{ez(e)}finally{eJ(t.infoPath),eJ(t.lockPath)}return{forcedKill:a}}(e,t):{forcedKill:!1};return b({level:"error",phase:"daemon_request_timeout",data:{timeoutMs:i,requestId:a,command:r,timedOutRunnerPidsTerminated:o.terminated,timedOutRunnerCleanupError:o.error,daemonPidReset:s?e.pid:void 0,daemonPidForceKilled:s?l.forcedKill:void 0,daemonPreservedAfterTimeout:!n&&!s,daemonBaseUrl:e.baseUrl}}),new f("COMMAND_FAILED","Daemon request timed out",{timeoutMs:i,requestId:a,hint:function(e){let{remote:t,resetDaemon:a,command:r}=e;if(t)return"Retry with --debug and verify the remote daemon URL, auth token, and remote host logs.";if(!a){let e=r===en.snapshot?" If this was the first Apple-platform snapshot on the device, run agent-device prepare ios-runner with the same --platform before snapshot/test so runner startup is handled explicitly.":"";return`Retry with --debug and check daemon diagnostics logs. The timed-out ${r??"request"} request was canceled and Apple runner work was aborted when detected; the daemon was kept alive so the session can still be closed or inspected.${e}`}return"Retry with --debug and check daemon diagnostics logs. Timed-out Apple runner xcodebuild processes were terminated when detected."}({remote:n,resetDaemon:s,command:r})})}let tl="Daemon HTTP endpoint is unavailable",tc="Daemon socket endpoint is unavailable";async function td(e,t){let a=ty(e,t);if(await tu(e,a))return!0;let r=tg(e,t,a);return!!r&&await tu(e,r)}async function tu(e,t){var a;return"http"===t?await tp(e).then(e=>e.reachable):await ((a=e.port)?new Promise(e=>{let t=!1,r=c.createConnection({host:"127.0.0.1",port:a},()=>{n(!0)}),n=a=>{t||(t=!0,r.destroy(),e(a))};r.setTimeout(500),r.on("timeout",()=>{n(!1)}),r.on("error",()=>{n(!1)})}):Promise.resolve(!1))}async function tf(e){let t=await tp(e);if(!e.baseUrl||!t.reachable)return t;if("number"==typeof t.rpcProtocolVersion&&1!==t.rpcProtocolVersion)throw new f("COMMAND_FAILED","Remote daemon RPC protocol is incompatible",{daemonBaseUrl:e.baseUrl,clientVersion:es(),remoteVersion:t.version,remoteService:t.service,supportedRpcProtocolVersion:1,remoteRpcProtocolVersion:t.rpcProtocolVersion,hint:"Upgrade agent-device on the client or remote host so both support the same daemon RPC protocol."});return t}function tp(e){let r=e.baseUrl?em(e.baseUrl,"health"):e.httpPort?`http://127.0.0.1:${e.httpPort}/health`:null;if(!r)return Promise.resolve({reachable:!1});let n=new URL(r),i="https:"===n.protocol?a:t,o=e.baseUrl?3e3:500;return new Promise(t=>{let a=e.baseUrl?eh(e.token):{},r=i.request({protocol:n.protocol,host:n.hostname,port:n.port,path:n.pathname+n.search,method:"GET",timeout:o,headers:a},e=>{let a="";e.setEncoding("utf8"),e.on("data",e=>{a+=e}),e.on("end",()=>{let r=e.statusCode??500;t({reachable:r<500,statusCode:r,...function(e){try{let t=JSON.parse(e);return{service:"string"==typeof t.service?t.service:void 0,version:"string"==typeof t.version?t.version:void 0,rpcProtocolVersion:"number"==typeof t.rpcProtocolVersion?t.rpcProtocolVersion:void 0}}catch{return{}}}(a)})})});r.on("timeout",()=>{r.destroy(),t({reachable:!1})}),r.on("error",()=>{t({reachable:!1})}),r.end()})}async function tm(e,t,a,r,n){let i=ty(e,a);try{return await th(e,t,r,n,i)}catch(l){var o;let s=tg(e,a,i);if(!s||(o=l,"socket"!==i||!(o instanceof f)||"COMMAND_FAILED"!==o.code||"Failed to communicate with daemon"!==o.message||o.details?.daemonSocketRequestWritten!==!1))throw l;return await th(e,t,r,n,s)}}async function th(e,t,a,r,n){return"http"===n?await tI(e,t,a,r):await tb(e,t,a,r)}function ty(e,t){if(e.baseUrl){if("socket"===t)throw new f("COMMAND_FAILED","Remote daemon endpoint only supports HTTP transport",{daemonBaseUrl:e.baseUrl});return"http"}if("http"===t||"socket"===t){var a=e,r=t;if(tw(a,r))return r;throw new f("COMMAND_FAILED","http"===r?tl:tc)}let n=("socket"===e.transport||"dual"===e.transport?["socket","http"]:["http","socket"]).find(t=>tw(e,t));if(n)return n;throw new f("COMMAND_FAILED","Daemon metadata has no reachable transport")}function tw(e,t){return"http"===t?!!e.httpPort:!!e.port}function tg(e,t,a){if("auto"!==t||e.baseUrl)return null;let r="socket"===a?"http":"socket";return tw(e,r)?r:null}function tv(e,t,a,r={}){return b({level:"error",phase:"daemon_request_socket_error",data:{requestId:t,message:e instanceof Error?e.message:String(e)}}),new f("COMMAND_FAILED","Failed to communicate with daemon",{...r,requestId:t,hint:a?"Retry command. If this persists, verify the remote daemon URL, auth token, and remote host reachability.":"Retry command. If this persists, clean stale daemon metadata and start a fresh session."},e instanceof Error?e:void 0)}async function tb(e,t,a,r){let n=e.port;if(!n)throw new f("COMMAND_FAILED",tc);return new Promise((i,o)=>{let s=!1,l=c.createConnection({host:"127.0.0.1",port:n},()=>{s=!0,l.write(`${JSON.stringify(t)}
|
|
3
|
+
`)}),d=!1,u="number"==typeof r?setTimeout(()=>{d=!0,l.destroy(),o(ts(e,a,t.meta?.requestId,t.command,!1,r))},r):void 0;!function(e,t){let{req:a,isSettled:r,resolve:n,reject:i,clearTimeout:o}=t,s="",l=ta(a),c=(e,t)=>{o(),i(new f("COMMAND_FAILED","Invalid daemon response",{requestId:a.meta?.requestId,line:e},t instanceof Error?t:void 0))};e.setEncoding("utf8"),e.on("data",t=>{if(r())return;let a=P(s,t);for(let t of(s=a.buffer,a.lines))try{let a=JSON.parse(t);if(k(a)){tr(a.event,l);continue}let r=M(a)?a.response:a;o(),n(r),e.end();return}catch(e){c(t,e);return}})}(l,{req:t,isSettled:()=>d,clearTimeout:()=>{u&&clearTimeout(u)},resolve:e=>{d=!0,i(e)},reject:e=>{d=!0,o(e)}}),l.on("error",e=>{d||(d=!0,u&&clearTimeout(u),o(tv(e,t.meta?.requestId,!1,{daemonSocketRequestWritten:s})))})})}async function tI(e,r,n,i){var o,s,l,c,d;let u,p=e.baseUrl?new URL(em(e.baseUrl,"rpc")):e.httpPort?new URL(`http://127.0.0.1:${e.httpPort}/rpc`):null;if(!p)throw new f("COMMAND_FAILED",tl);let m=JSON.stringify((o={includeTokenParam:!e.baseUrl},u=r.meta?.requestId??g(),"lease_allocate"!==(s=r.command)&&"lease_heartbeat"!==s&&"lease_release"!==s?{jsonrpc:"2.0",id:u,method:"agent_device.command",params:r}:{jsonrpc:"2.0",id:u,method:function(e){switch(e){case"lease_allocate":return"agent_device.lease.allocate";case"lease_heartbeat":return"agent_device.lease.heartbeat";case"lease_release":return"agent_device.lease.release"}}(r.command),params:(l=r,c=r.command,d=o,V(et(l),c,{includeTokenParam:d.includeTokenParam,token:l.token,session:l.session}))})),h={"content-type":"application/json","content-length":Buffer.byteLength(m)};return e.baseUrl&&Object.assign(h,eh(e.token)),await new Promise((o,s)=>{let l=("https:"===p.protocol?a:t).request({protocol:p.protocol,host:p.hostname,port:p.port,method:"POST",path:p.pathname+p.search,headers:h},t=>{var a;(a=t.headers?.["content-type"],D(r)&&String(Array.isArray(a)?a.join(","):a??"").includes("application/x-ndjson"))?function(e,t){let{req:a,handleResponseBody:r,reject:n,clearTimeout:i}=t,o="",s=!1,l=ta(a),c=e=>{try{let t=JSON.parse(e);if(k(t))return tr(t.event,l),!1;if(M(t))return s=!0,i(),r(JSON.stringify(t.response)),!0;throw Error("Missing daemon progress response envelope")}catch(t){return s=!0,i(),n(new f("COMMAND_FAILED","Invalid daemon response",{requestId:a.meta?.requestId,line:e},t instanceof Error?t:void 0)),!0}};e.setEncoding("utf8"),e.on("data",e=>{if(s)return;let t=P(o,e);for(let e of(o=t.buffer,t.lines))if(e&&c(e))return}),e.on("end",()=>{if(s)return;let e=o.trim();e&&c(e)||(s=!0,i(),n(new f("COMMAND_FAILED","Invalid daemon response",{requestId:a.meta?.requestId,line:e})))}),e.on("error",e=>{s||(s=!0,i(),n(new f("COMMAND_FAILED","Failed to read daemon response",{requestId:a.meta?.requestId},e instanceof Error?e:void 0)))})}(t,{req:r,reject:s,clearTimeout:()=>{d&&clearTimeout(d)},handleResponseBody:t=>tn(t,{info:e,req:r,resolve:o,reject:s})}):ey(t).then(t=>{d&&clearTimeout(d),tn(t,{info:e,req:r,resolve:o,reject:s})}).catch(e=>{d&&clearTimeout(d),s(new f("COMMAND_FAILED","Failed to read daemon response",{requestId:r.meta?.requestId},e instanceof Error?e:void 0))})}),c=eY(e),d="number"==typeof i?setTimeout(()=>{l.destroy(),s(ts(e,n,r.meta?.requestId,r.command,c,i))},i):void 0;l.on("error",e=>{d&&clearTimeout(d),s(tv(e,r.meta?.requestId,c))}),l.write(m),l.end()})}let tA=new c.BlockList;function tS(t){var a,n,o,s,l;let d,u,p,m=(a=t,a.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR),h=(n=t,u=function(e){let t;if(e){try{t=new URL(e)}catch(t){throw new f("INVALID_ARGS","Invalid daemon base URL",{daemonBaseUrl:e},t instanceof Error?t:void 0)}if("http:"!==t.protocol&&"https:"!==t.protocol)throw new f("INVALID_ARGS","Daemon base URL must use http or https",{daemonBaseUrl:e});return t.toString().replace(/\/+$/,"")}}(d=n.flags?.daemonBaseUrl??process.env.AGENT_DEVICE_DAEMON_BASE_URL),function(e,t){let a;if(!(!e||"localhost"===(a=new URL(e).hostname.trim().toLowerCase().replace(/^\[(.*)\]$/,"$1"))||(c.isIPv4(a)?tA.check(a,"ipv4"):!!c.isIPv6(a)&&tA.check(a,"ipv6")))&&("string"!=typeof t||!(t.trim().length>0)))throw new f("INVALID_ARGS","Remote daemon base URL for non-loopback hosts requires daemon authentication",{daemonBaseUrl:e,hint:"Provide --daemon-auth-token or AGENT_DEVICE_DAEMON_AUTH_TOKEN when using a non-loopback remote daemon URL."})}(u,p=n.flags?.daemonAuthToken??process.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN),{rawBaseUrl:d,remoteBaseUrl:u,authToken:p}),y=function(e,t){let a=e.flags?.daemonTransport??process.env.AGENT_DEVICE_DAEMON_TRANSPORT,r=C(a);if(t&&"socket"===r)throw new f("INVALID_ARGS","Remote daemon base URL only supports HTTP transport. Remove --daemon-transport socket.",{daemonBaseUrl:t});return{preference:r,serverMode:x(e.flags?.daemonServerMode??process.env.AGENT_DEVICE_DAEMON_SERVER_MODE??("dual"===a?"dual":void 0))}}(t,h.remoteBaseUrl),w=(o=t,s=m,l=h.rawBaseUrl,tN(o.command)&&!s&&!l);return{paths:E(w?e.mkdtempSync(r.join(i.tmpdir(),"agent-device-replay-daemon-")):m),transportPreference:y.preference,serverMode:y.serverMode,ownedStateDir:w,remoteBaseUrl:h.remoteBaseUrl,remoteAuthToken:h.authToken}}async function tP(e){if(e.remoteBaseUrl)return await t_(e);let t=await tD(e);return t?{info:t,startedByClient:!1}:(!function(e){let t=eK(e);if(!t.hasLock||t.hasInfo)return;let a=eV(e.lockPath);if(!a)return eJ(e.lockPath);I(a.pid,a.processStartTime)||eJ(e.lockPath)}(e.paths),await tk(e))}async function t_(e){let t={transport:"http",token:e.remoteAuthToken??"",pid:0,baseUrl:e.remoteBaseUrl};if((await tf(t)).reachable)return{info:t,startedByClient:!1};throw new f("COMMAND_FAILED","Remote daemon is unavailable",{daemonBaseUrl:e.remoteBaseUrl,hint:"Verify AGENT_DEVICE_DAEMON_BASE_URL points to a reachable daemon with GET /health and POST /rpc."})}async function tD(e){var t,a;let r=eB(e.paths.infoPath);if(!r)return null;let n=await tM(r,e.transportPreference);return(t=r,a=n,t.version===es()&&t.codeSignature===tC()&&a)?r:(function(e,t,a){try{var r,n;let i=e.version?`pid ${e.pid}, v${e.version}`:`pid ${e.pid}`,o=(r=e,n=t,r.version!==es()?`version mismatch (client v${es()})`:r.codeSignature!==tC()?"code-signature mismatch":n?"not reusable":"unreachable");process.stderr.write(`Replacing daemon (${i}) in ${a}: ${o}
|
|
4
|
+
`)}catch{}}(r,n,e.paths.baseDir),await ez(r),eJ(e.paths.infoPath),null)}async function tM(e,t){try{return await td(e,t)}catch(e){var a;if((a=e)instanceof f&&"COMMAND_FAILED"===a.code&&(a.message===tl||a.message===tc))return!1;throw e}}async function tk(t){let a,r,n=0,i=[];for(let o=1;o<=2;o+=1){let s;try{r={pid:(s=function(t){let a=t$(),r=a.useSrc?["--experimental-strip-types",a.srcPath]:[a.distPath],n={...process.env,AGENT_DEVICE_STATE_DIR:t.paths.baseDir,AGENT_DEVICE_DAEMON_SERVER_MODE:t.serverMode};e.mkdirSync(t.paths.baseDir,{recursive:!0});let i=e.openSync(t.paths.logPath,"a"),o=e.openSync(t.paths.logPath,"a");try{return p(process.execPath,r,{env:n,stdio:["ignore",i,o]})}finally{e.closeSync(i),e.closeSync(o)}}(t)).pid}}catch(e){if(a=e instanceof Error?e.message:String(e),i.push(await eH(t.paths,"start_error")),o<2){await ec(150);continue}break}let l=await tx(15e3,t,s);if("ready"===l.kind)return{info:l.info,startedByClient:!0};if("early_exit"===l.kind){if(r=l.exit,a=tT(l.exit),i.push(await eH(t.paths,"start_error")),o<2){await ec(150);continue}break}if(await eG(t.paths)){n+=1;continue}let c=eK(t.paths),d=o<2,u=await eH(t.paths,"startup_timeout",{stopLiveProcesses:!1});if(i.push(u),u.retainedInfoProcess||u.retainedLockProcess){let e=await tx(15e3,t,s);if("ready"===e.kind)return{info:e.info,startedByClient:!0};"early_exit"===e.kind&&(r=e.exit,a=tT(e.exit));break}if(!d)break;c.hasInfo||c.hasLock||await ec(150)}let o=eK(t.paths),s=function(t){try{if(!e.existsSync(t))return;let a=e.statSync(t);if(a.size<=0)return;let r=Math.min(a.size,64e3),n=e.openSync(t,"r");try{let t=Buffer.alloc(r);e.readSync(n,t,0,r,a.size-r);let i=t.toString("utf8").trim();return i.length>0?i:void 0}finally{e.closeSync(n)}}catch{return}}(t.paths.logPath);throw new f("COMMAND_FAILED","Failed to start daemon",{kind:"daemon_startup_failed",stateDir:t.paths.baseDir,infoPath:t.paths.infoPath,lockPath:t.paths.lockPath,logPath:t.paths.logPath,startupTimeoutMs:15e3,startupAttempts:2,lockRecoveryCount:n,cleanupResults:i,startError:a,daemonProcess:r,...s?{daemonLogTail:s}:{},metadataState:o,hint:function(e,t=E(process.env.AGENT_DEVICE_STATE_DIR)){var a;let r=(a=t,`rm -f ${_(a.infoPath)} ${_(a.lockPath)}`);return e.hasLock&&!e.hasInfo?`agent-device attempted to clean stale daemon metadata automatically, but ${t.lockPath} still exists without ${t.infoPath}. Retry with --debug; if this persists after confirming no agent-device daemon process is running, run: ${r}`:e.hasLock&&e.hasInfo?`agent-device attempted to clean stale daemon metadata automatically, but ${t.infoPath} and ${t.lockPath} still remain. Retry with --debug; if this persists after confirming no agent-device daemon process is running, run: ${r}`:e.hasInfo?`agent-device did not observe reachable daemon metadata after retrying, and ${t.infoPath} still remains. Stale metadata was cleaned automatically when safe; retry with --debug. If this persists after confirming no agent-device daemon process is running, run: ${r}`:`agent-device did not observe reachable daemon metadata after retrying. Stale metadata was cleaned automatically when safe; retry with --debug and check daemon diagnostics logs. If stale metadata returns after confirming no agent-device daemon process is running, run: ${r}`}(o,t.paths)})}async function tE(t,a,r){if(!tN(t.command)||!a.startedByClient&&!r.ownedStateDir||eY(a.info))return;let n={pid:a.info.pid,removedInfo:!1,removedLock:!1,removedStateDir:!1,error:void 0};try{await ez(a.info)}catch(e){n.error=e instanceof Error?e.message:String(e)}finally{let t=e.existsSync(r.paths.infoPath);eJ(r.paths.infoPath),n.removedInfo=t&&!e.existsSync(r.paths.infoPath);let a=e.existsSync(r.paths.lockPath);eJ(r.paths.lockPath),n.removedLock=a&&!e.existsSync(r.paths.lockPath),r.ownedStateDir&&(e.rmSync(r.paths.baseDir,{recursive:!0,force:!0}),n.removedStateDir=!e.existsSync(r.paths.baseDir))}b({level:n.error?"warn":"info",phase:"daemon_replay_cleanup",data:n})}function tN(e){return e===en.replay||e===en.test}async function tx(e,t,a){let r,n=Date.now();for(a.exited.then(e=>{r=e});Date.now()-n<e;){if(r)return{kind:"early_exit",exit:r};let e=eB(t.paths.infoPath);if(e&&await td(e,t.transportPreference))return{kind:"ready",info:e};if(r)return{kind:"early_exit",exit:r};await ec(100)}return{kind:"timeout"}}function t$(){let t=el(),a=[r.join(t,"dist","src","internal","daemon.js"),r.join(t,"dist","src","daemon.js")],n=a[0];if(void 0===n)throw new f("COMMAND_FAILED","Daemon dist path list is empty");let i=a.find(t=>e.existsSync(t))??n,o=r.join(t,"src","daemon.ts"),s=a.some(t=>e.existsSync(t)),l=e.existsSync(o);if(!s&&!l)throw new f("COMMAND_FAILED","Daemon entry not found",{distPaths:a,srcPath:o});return{root:t,distPath:i,distPaths:a,srcPath:o,useSrc:process.execArgv.includes("--experimental-strip-types")?l:!s&&l}}function tC(){let e=t$();return $(e.useSrc?e.srcPath:e.distPath,e.root)}function tT(e){return e.error?`daemon process ${e.pid} failed to start: ${e.error}`:e.signal?`daemon process ${e.pid} exited before readiness with signal ${e.signal}`:`daemon process ${e.pid} exited before readiness with code ${e.exitCode??0}`}async function tU(e){let t=e.meta?.requestId??g(),a=!!(e.meta?.debug||e.flags?.verbose),r=tS(e),n=function(e){if(e.command!==en.test){var t;return"number"==typeof e.flags?.timeoutMs&&((t=e.command)===en.prepare||t===en.replay||t===en.snapshot)?e.flags.timeoutMs:e.command===en.prepare?24e4:9e4}}(e),i=await v("daemon_startup",async()=>await tP(r),{requestId:t,session:e.session}),o=i.info,s=await eN(e,o),l={...e,positionals:s.positionals,flags:s.flags,token:o.token,meta:{...e.meta??{},requestId:t,debug:a,cwd:e.meta?.cwd,sessionExplicit:e.meta?.sessionExplicit,tenantId:e.meta?.tenantId??e.flags?.tenant,runId:e.meta?.runId??e.flags?.runId,leaseId:e.meta?.leaseId??e.flags?.leaseId,sessionIsolation:e.meta?.sessionIsolation??e.flags?.sessionIsolation,lockPolicy:e.meta?.lockPolicy,lockPlatform:e.meta?.lockPlatform,...s.uploadedArtifactId?{uploadedArtifactId:s.uploadedArtifactId}:{},...s.clientArtifactPaths?{clientArtifactPaths:s.clientArtifactPaths}:{},...s.installSource?{installSource:s.installSource}:{}}};b({level:"info",phase:"daemon_request_prepare",data:{requestId:t,command:e.command,session:e.session}});try{return await v("daemon_request",async()=>await tm(o,l,r.transportPreference,r.paths,n),{requestId:t,command:e.command})}finally{await tE(e,i,r)}}tA.addSubnet("127.0.0.0",8,"ipv4"),tA.addAddress("::1","ipv6"),tA.addSubnet("::ffff:127.0.0.0",104,"ipv6");let tL=/^[0-9a-fA-F-]{32,36}$/;function tO(e){if(e&&tL.test(e))return e.replaceAll("-","").toUpperCase()}function tR(e,t){return`${e.uuid}:${tF(t)}`}function tF(e){return`0x${e.toString(16)}`}function tB(e){return"string"==typeof e&&e.length>0?e:void 0}function tj(...e){for(let t of e){let e=tB(t);if(e)return e}}function tq(e){try{let t=JSON.parse(e);return eo(t)?t:null}catch{return null}}function tV(e){if("number"==typeof e&&Number.isSafeInteger(e))return e;if("string"==typeof e){let t=e.startsWith("0x")?Number.parseInt(e,16):Number(e);return Number.isSafeInteger(t)?t:void 0}}function tH(e,t,a){var r;if(!Object.hasOwn(e,t))return;let n="bigint"==typeof(r=e[t])?r:"number"==typeof r&&Number.isSafeInteger(r)?BigInt(r):"string"!=typeof r?void 0:/^(?:0x[0-9a-fA-F]+|\d+)$/.test(r)?BigInt(r):void 0;if(void 0!==n)return n;tK(a,t)}function tK(e,t){throw new f("INVALID_ARGS",`Invalid ${e} numeric field: ${t}`,{hint:"Crash artifact numeric fields must be integer numbers or integer numeric strings."})}function tG(e){return[...new Set(e)]}let tz=/^(?:arm64e?|arm64_32|x86_64|armv7[sk]?|i386)$/;async function tY(e){return e.dsym&&e.searchPath?[t0(e.cwd,e.dsym),...await tW(t0(e.cwd,e.searchPath))]:e.dsym?[t0(e.cwd,e.dsym)]:e.searchPath?await tW(t0(e.cwd,e.searchPath)):[]}async function tW(e){let t=[],a=0;async function n(i){if(!(t.length>=200)){if((a+=1)>1e4)throw new f("COMMAND_FAILED","debug symbols search-path scan exceeded bounds.",{searchPath:e,maxEntries:1e4,hint:"Pass --dsym <App.dSYM> directly or narrow --search-path to the build products directory."});if(!(await tJ(i,e)).isDirectory()){i===e&&function(e){throw new f("INVALID_ARGS",`debug symbols search path is not a directory: ${e}`,{hint:"Pass an existing build products directory to --search-path, or pass --dsym <App.dSYM> directly."})}(e);return}if(i.endsWith(".dSYM"))return void t.push(i);for(let e of(await d.readdir(i,{withFileTypes:!0})))e.isDirectory()&&await n(r.join(i,e.name))}}return await n(e),t}async function tJ(e,t){try{return await d.stat(e)}catch{throw new f("INVALID_ARGS",`debug symbols search path does not exist: ${t}`,{hint:"Pass an existing build products directory to --search-path, or pass --dsym <App.dSYM> directly."})}}async function tX(e,t){let a=(await Promise.all(tG(e).map(e=>tQ(e,t)))).flat();if(0===a.length)throw new f("COMMAND_FAILED","No UUIDs found in dSYM bundle.",{hint:"Verify the path points to a built .dSYM bundle with DWARF contents."});return a}async function tQ(e,t){var a;await tZ(e);let r=await m(t,["--uuid",e],{timeoutMs:15e3,allowFailure:!0});if(0!==r.exitCode)throw new f("COMMAND_FAILED",`Failed to inspect dSYM UUIDs: ${e}`,{stderr:r.stderr,hint:"Verify the dSYM bundle is valid and readable."});return a=e,r.stdout.split("\n").flatMap(e=>{let t=e.match(/^UUID:\s+([0-9a-fA-F-]{32,36})\s+\(([^)]+)\)\s+(.+)$/),r=tO(t?.[1]);return t&&r?[{dsymPath:a,uuid:r,arch:t[2],binaryPath:t[3].trim()}]:[]})}async function tZ(e){let t=await d.stat(e).catch(()=>null);if(!(t?.isDirectory()&&e.endsWith(".dSYM")))throw new f("INVALID_ARGS",`Not a .dSYM bundle: ${e}`,{hint:"Pass the .dSYM bundle path, not the DWARF executable inside it."})}function t0(e,t){return r.resolve(e,t)}function t1(e,t){let a=`${t}:`,r=e.find(e=>e.trimStart().startsWith(a));return r&&r.slice(r.indexOf(":")+1).trim()||void 0}function t3(e,t,a,r){return{index:e,image:t.name,address:tF(a),symbol:r.get(tR(t,a))?.text}}function t2(e){var t;let a;return[(a=(t=e).topFrames.find(e=>e.symbol))?`Start with ${a.symbol} in ${a.image}; it is the first symbolicated frame captured on the crashed thread.`:t.topFrames.length>0?"No symbolicated frame was found on the crashed thread; verify matching dSYMs for the top images.":void 0,e.exceptionType?`Exception: ${e.exceptionType}`:void 0,e.terminationReason?`Termination: ${e.terminationReason}`:void 0].filter(e=>!!e).slice(0,3)}async function t5(e,t,a){let r=new Map;for(let n of(function(e,t){let a=new Map;for(let r of e){let e=t.get(r.image.uuid);if(!e)continue;let n=`${r.image.uuid}:${e.dsym.binaryPath}`,i=a.get(n)??{...e,addresses:[]};i.addresses.push(r.address),a.set(n,i)}return a})(e,t).values())for(let e of(await t4(a,n)))r.set(tR(e.image,e.address),e);return r}async function t4(e,t){var a,r,n,i;let o,s,l=tG(t.addresses.map(tF)),c=await m(e,(a=t,r=l,["-arch",a.image.arch??a.dsym.arch??"arm64","-o",a.dsym.binaryPath,"-l",tF(a.image.base),...r]),{timeoutMs:3e4,allowFailure:!0});return 0!==c.exitCode&&function(e){throw new f("COMMAND_FAILED","atos failed while symbolicating crash frames.",{stderr:e,hint:"Verify the crash artifact and dSYM were produced from the same build and architecture."})}(c.stderr),n=t.image,i=l,s=(""===(o=c.stdout.split(/\r?\n/)).at(-1)&&o.pop(),o),i.map((e,t)=>{let a=s[t]?.trim();return{image:n,address:BigInt(e),text:!function(e,t){if(!e)return!1;let a=e.trim().toLowerCase();return!!a&&"??"!==a&&a!==t.toLowerCase()&&!a.startsWith("0x")}(a,e)?void 0:a}})}async function t6(){return{dwarfdump:await t8("dwarfdump"),atos:await t8("atos")}}async function t8(e){try{let t=await m("xcrun",["--find",e],{timeoutMs:5e3,allowFailure:!0}),a=t.stdout.trim();if(0===t.exitCode&&a.length>0)return a}catch{}throw new f("TOOL_MISSING",`Apple symbolication tool not found: ${e}`,{hint:"Install Xcode Command Line Tools and verify xcrun --find dwarfdump and xcrun --find atos succeed."})}async function t7(e){var t,a,n,i,o,s,l,c,u,p,m,h,y,w,g,v,b,I,A,S,P,_,D,M,k,E,N,x;let $,C,T,U,L,O,R,F,B,j,q;if(void 0!==e.action&&"symbols"!==e.action)throw new f("INVALID_ARGS","debug supports only the symbols workflow.",{hint:"Use debug symbols --artifact <crash.ips|crash.log> --dsym <App.dSYM> or --search-path <dir> --out <path>."});let V=e.cwd??process.cwd(),H=at(V,e.artifact),K=at(V,e.out??(a=H,C=($=r.extname(a))?a.slice(0,-$.length):a,`${C}-symbolicated${$||".log"}`)),G=function(e){var t;let a,n=function(e){let t=tq(e);if(t)return{payload:t};let a=e.indexOf("\n");if(-1===a)return null;let r=e.slice(0,a),n=tq(e.slice(a+1));return n?{header:r,payload:n}:null}(e);if(!n)return null;let i=(Array.isArray(n.payload.usedImages)?n.payload.usedImages:[]).flatMap((e,t)=>(function(e,t){if(!eo(e))return[];let a=tO(tB(e.uuid)),n=tH(e,"base","IPS usedImages");if(!a||void 0===n)return[];let i=tB(e.path);return[{index:t,name:tB(e.name)??(i?r.basename(i):`image-${t}`),uuid:a,arch:tB(e.arch),base:n,path:i}]})(e,t));if(0===i.length)return null;let o=(t=Array.isArray(n.payload.threads)?n.payload.threads:[],a=new Map(i.map(e=>[e.index,e])),t.flatMap((e,t)=>{var r;return(eo(r=e)&&Array.isArray(r.frames)?r.frames.filter(eo):[]).flatMap((e,r)=>(function(e,t,a,r){let n=function(e,t,a){if(!Object.hasOwn(e,t))return;let r=tV(e[t]);if(void 0!==r)return r;tK(a,t)}(e,"imageIndex","IPS frame"),i=tH(e,"imageOffset","IPS frame");if(void 0===n||void 0===i)return[];let o=t.get(n);return o?[{frame:e,frameIndex:r,threadIndex:a,image:o,address:o.base+i}]:[]})(e,a,t,r))}));return{format:"ips",images:i,addresses:o.map(({frame:e,...t})=>t),document:n,frameMatches:o,write:e=>(function(e,t,a){for(let e of t){let t=a.get(tR(e.image,e.address))?.text;t&&function(e,t){let a,r=(a=t.match(/^(.*) \+ (\d+)$/))?{symbol:a[1],location:Number(a[2])}:{symbol:t};e.symbol=r.symbol,void 0!==r.location&&(e.symbolLocation=r.location)}(e.frame,t)}e.payload.agentDeviceSymbolication={tool:"agent-device debug symbols",symbolicatedFrames:[...a.values()].filter(e=>e.text).length};let r=`${JSON.stringify(e.payload,null,2)}
|
|
5
5
|
`;return e.header?`${e.header}
|
|
6
|
-
${r}`:r})(n,o,e)}}(t=await t2(j,"crash artifact"))??function(e){let t=e.split("\n"),a=function(e){let t=[],a=e.findIndex(e=>/^Binary Images:/i.test(e.trim()));if(-1===a)return t;for(let n of e.slice(a+1)){let e=function(e){let t=e.match(/^\s*(0x[0-9a-fA-F]+)\s*-\s*(0x[0-9a-fA-F]+)\s+\+?(.+?)\s+<([0-9a-fA-F-]{32,36})>\s+(.+)$/);if(!t)return null;let a=tE(t[4]);if(!a)return null;let n=function(e,t){let a=e.split(/\s+/),n=a.at(-1);if(n&&tj.test(n))return{name:a.slice(0,-1).join(" ").trim(),arch:n};let i=r.basename(t);return{name:e.startsWith(i)?i:e}}(t[3].trim(),t[5].trim());return{name:n.name,arch:n.arch,uuid:a,base:BigInt(t[1]),end:BigInt(t[2]),path:t[5].trim()}}(n);e&&t.push(e)}return t}(t);if(0===a.length)return null;let n=function(e,t){let a,r=[];for(let[n,i]of e.entries()){let e=i.match(/^Thread\s+(\d+)\s+Crashed:/);e?a=Number(e[1]):(0===i.trim().length||/^Thread\s+\d+/.test(i))&&(a=void 0);let o=function(e,t){let a=e.match(/^\s*\d+\s+(.+?)\s+(0x[0-9a-fA-F]+)\b/);if(!a)return null;let r=a[1].trim(),n=BigInt(a[2]),i=function(e,t,a){let r=e.filter(e=>e.name===t);return r.find(e=>{var t,r;return t=e,r=a,void 0!==t.end&&t.base<=r&&r<=t.end})??(1===r.length?r[0]:void 0)}(t,r,n);return i?{image:i,address:n}:null}(i,t),s=i.match(/^\s*(\d+)/);o&&s&&r.push({...o,frameIndex:Number(s[1]),lineIndex:n,threadIndex:a})}return r}(t,a);return{format:"text",images:a,addresses:n,lines:t,frameMatches:n,write(e){let a=new Map(n.map(e=>[e.lineIndex,e]));return t.map((t,r)=>{let n=a.get(r);if(!n)return t;let i=e.get(tN(n.image,n.address))?.text;return!i||t.includes(i)?t:`${t} // ${i}`}).join("\n")}}}(t);V||function(){throw new f("UNSUPPORTED_OPERATION","debug symbols currently supports Apple crash artifacts with Binary Images or IPS usedImages.",{hint:"For Android Java/R8 crashes, use retrace with mapping.txt. For Android native crashes, use ndk-stack or addr2line with unstripped .so symbols. Capture the crash with logs, then symbolicate externally until Android support is added."})}();let H=await tq({cwd:B,dsym:e.dsym,searchPath:e.searchPath});if(0===H.length)throw new f("INVALID_ARGS","debug symbols requires --dsym or --search-path.",{hint:"Pass a matching .dSYM bundle directly, or pass --search-path <dir> so agent-device can match crash image UUIDs to local dSYMs."});let G=await t0(),K=await tG(H,G.dwarfdump),z=function(e,t,a){let r=new Map;for(let a of e){let e=t.find(e=>e.uuid===a.uuid&&(void 0===a.arch||void 0===e.arch||e.arch===a.arch));e&&r.set(a.uuid,{image:a,dsym:e})}if(r.size>0)return r;let n=tB(e.map(e=>e.uuid)),i=tB(t.map(e=>e.uuid));throw new f("COMMAND_FAILED",a?"dSYM UUID does not match any Apple image in the crash artifact.":"No matching dSYM UUID found under search path.",{artifactUuidCount:n.length,artifactUuidSample:n.slice(0,5),dsymUuidCount:i.length,dsymUuidSample:i.slice(0,5),hint:"Use dwarfdump --uuid <App.dSYM> and compare it with the crash Binary Images or usedImages UUID, then pass the matching dSYM/search path."})}(V.images,K,!!e.dsym),Y=await tQ(V.addresses,z,G.atos),W=V.write(Y);await d.mkdir(r.dirname(q),{recursive:!0}),await d.writeFile(q,W,"utf8");let J=[...z.values()].map(({image:e,dsym:t})=>({name:e.name,uuid:e.uuid,arch:e.arch??t.arch,dsymPath:t.dsymPath,binaryPath:t.binaryPath})),X=[...Y.values()].filter(e=>e.text).length,Q=V.images.length-J.length,Z=Q>0?[`${Q} Apple image${1===Q?"":"s"} had no matching dSYM and were left unchanged.`]:void 0;return{kind:"debugSymbols",platform:"apple",artifactPath:j,outPath:q,crash:"ips"===V.format?(n=V.document,i=V.frameMatches,o=Y,U=function(e){let t=tO(e.faultingThread);if(void 0!==t)return t;let a=(Array.isArray(e.threads)?e.threads:[]).findIndex(e=>tU(e)?.triggered===!0);return -1===a?void 0:a}(n.payload),{...L={format:"ips",...(T=(s=n).payload,C=(l=s.header)?tL(l):null,{appName:(c=T,u=C,tT(c.procName,u?.app_name,u?.name)),bundleId:(p=T,m=C,tT(tU(p.bundleInfo)?.CFBundleIdentifier,m?.bundleID)),version:(h=T,y=C,tT(tU(h.bundleInfo)?.CFBundleShortVersionString,y?.app_version)),incident:(w=T,g=C,tT(w.incident,g?.incident_id)),timestamp:(b=T,v=C,tT(b.captureTime,v?.timestamp)),exceptionType:(I=T.exception,t$(tU(I)?.type)),exceptionCodes:function(e){let t=tU(e);if(t)return tT(t.codes,t.rawCodes)}(T.exception),terminationReason:function(e){let t=tU(e);if(t){let e;return(e=[t$(t.namespace),t$(t.code),t$(t.reason)].filter(e=>!!e)).length>0?e.join(" "):void 0}}(T.termination)}),crashedThread:U,topFrames:(A=i,S=U,M=o,A.filter(e=>void 0===S||e.threadIndex===S).slice(0,5).map(e=>tJ(e.frameIndex,e.image,e.address,M))),findings:[]},findings:tX(L)}):(_=V.lines,D=V.frameMatches,P=Y,R=function(e){let t=tW(e,"Triggered by Thread"),a=t?Number.parseInt(t,10):NaN;if(Number.isSafeInteger(a))return a;for(let t of e){let e=t.match(/^Thread\s+(\d+)\s+Crashed:/);if(e)return Number(e[1])}}(_),{...F={format:"text",appName:(O=tW(_,"Process"),O?.replace(/\s+\[\d+\]$/,"")),bundleId:tW(_,"Identifier"),version:tW(_,"Version"),incident:tW(_,"Incident Identifier"),timestamp:tW(_,"Date/Time"),exceptionType:tW(_,"Exception Type"),exceptionCodes:tW(_,"Exception Codes"),terminationReason:tW(_,"Termination Reason"),crashedThread:R,topFrames:(k=D,E=R,N=P,void 0===E?[]:k.filter(e=>e.threadIndex===E).slice(0,5).map(e=>tJ(e.frameIndex,e.image,e.address,N))),findings:[]},findings:tX(F)}),matchedImages:J,symbolicatedFrames:X,skippedImages:Q,warnings:Z,message:`Symbolicated ${X} frame${1===X?"":"s"} -> ${q}`}}async function t2(e,t){await t5(e,t);try{return await d.readFile(e,"utf8")}catch(a){throw new f("INVALID_ARGS",`Failed to read ${t}: ${e}`,{message:a instanceof Error?a.message:String(a)})}}async function t5(e,t){try{let a=await d.stat(e);if(a.size<=0x4000000)return;throw new f("INVALID_ARGS",`${t} is too large: ${e}`,{actualBytes:a.size,maxBytes:0x4000000,hint:"Pass a bounded Apple .ips/.crash artifact. For very large logs, first narrow the log to the crash report, or use logs grep/tail for lead-up context."})}catch(a){if(a instanceof f)throw a;throw new f("INVALID_ARGS",`Failed to read ${t}: ${e}`,{message:a instanceof Error?a.message:String(a)})}}function t4(e,t){return r.resolve(e,t)}let t8={...x(),batch:K(function(e,t,a){let r=t8[e];if(!r)throw Error(`Missing daemon writer for batch command: ${e}`);let n=U(e);if(!n)throw Error(`Missing command metadata for batch command: ${e}`);try{return t6(r,n,n.readInput(t))}catch(r){let t=r instanceof Error?r.message:String(r);throw new f("INVALID_ARGS",`Batch step ${a} ${e} input is invalid: ${t}`,void 0,r)}})};function t6(e,t,a){let r=e(a);return{...r,...t?{metadataFlags:z(t,r.options)}:{}}}function t7(e={},t={}){let a=t.transport??tP,r=async(t,r=[],n={},i)=>{let o=ae(e,n),s=await a({session:V(o.session),command:t,positionals:r,flags:G(o,i),runtime:o.runtime,meta:j(o)});return s.ok||function(e){throw new f(u(e.code),e.message,{...e.details??{},hint:e.hint,diagnosticId:e.diagnosticId,logPath:e.logPath})}(s.error),s.data??{}},n=async(e={})=>{let t=await r(Z.sessionList,[],e);return(Array.isArray(t.sessions)?t.sessions:[]).map($)},i=async(e,t={})=>{let a=function(e,t){let a=t8[e];if(!a)throw Error(`Missing daemon writer for command: ${e}`);return t6(a,U(e),t)}(e,t);return await r(a.command,a.positionals,a.options,a.metadataFlags)},o=(t={})=>V(ae(e,t).session);return{command:{wait:async e=>await i("wait",e),alert:async(e={})=>await i("alert",e),appState:async(e={})=>await i("appstate",e),back:async(e={})=>await i("back",e),home:async(e={})=>await i("home",e),rotate:async e=>await i("rotate",e),appSwitcher:async(e={})=>await i("app-switcher",e),keyboard:async(e={})=>await i("keyboard",e),clipboard:async e=>await i("clipboard",e),reactNative:async e=>await i("react-native",e),prepare:async e=>await i("prepare",e),viewport:async e=>await i("viewport",e)},devices:{list:async(e={})=>{let t=await i("devices",e);return(Array.isArray(t.devices)?t.devices:[]).map(Y)},boot:async(e={})=>await i("boot",e),shutdown:async(e={})=>await i("shutdown",e)},sessions:{list:async(e={})=>await n(e),stateDir:async(t={})=>P(ae(e,t).stateDir??process.env.AGENT_DEVICE_STATE_DIR).baseDir,close:async(e={})=>{let t=o(e),a=(await i("close",e)).shutdown;return{session:t,shutdown:"object"==typeof a&&null!==a?a:void 0,identifiers:{session:t}}}},apps:{install:async e=>F(await i("install",e),o(e)),reinstall:async e=>F(await i("reinstall",e),o(e)),installFromSource:async e=>Q(await i("install-from-source",e),o(e)),list:async(e={})=>{let t=await i("apps",e);return Array.isArray(t.apps)?t.apps.filter(e=>"string"==typeof e):[]},open:async e=>{let t=o(e),a=await i("open",e),r=B(a),n=q(a,"appBundleId");return{session:t,sessionStateDir:q(a,"sessionStateDir"),appName:q(a,"appName"),appBundleId:n,appId:n,startup:W(a.startup),runtime:X(a.runtime),device:r,identifiers:{session:t,deviceId:r?.id,deviceName:r?.name,udid:r?.ios?.udid,serial:r?.android?.serial,appId:n,appBundleId:n}}},close:async(e={})=>{let t=o(e),a=(await i("close",e)).shutdown;return{session:t,closedApp:e.app,shutdown:"object"==typeof a&&null!==a?a:void 0,identifiers:{session:t}}},push:async e=>await i("push",e),triggerEvent:async e=>await i("trigger-app-event",e)},materializations:{release:async e=>L(await r(Z.releaseMaterializedPaths,[],{...e,materializationId:e.materializationId}))},leases:{allocate:async e=>at(await r(Z.leaseAllocate,[],{...e,leaseId:void 0,leaseTtlMs:e.ttlMs})),heartbeat:async e=>at(await r(Z.leaseHeartbeat,[],{...e,leaseTtlMs:e.ttlMs})),release:async e=>({released:!0===(await r(Z.leaseRelease,[],e)).released})},metro:{prepare:async t=>await ei({projectRoot:t.projectRoot??e.cwd,kind:t.kind,publicBaseUrl:t.publicBaseUrl,proxyBaseUrl:t.proxyBaseUrl,proxyBearerToken:t.bearerToken,bridgeScope:t.bridgeScope,launchUrl:t.launchUrl,companionProfileKey:t.companionProfileKey,companionConsumerKey:t.companionConsumerKey,metroPort:t.port,listenHost:t.listenHost,statusHost:t.statusHost,startupTimeoutMs:t.startupTimeoutMs,probeTimeoutMs:t.probeTimeoutMs,reuseExisting:t.reuseExisting,installDependenciesIfNeeded:t.installDependenciesIfNeeded,runtimeFilePath:t.runtimeFilePath,logPath:t.logPath}),reload:async(t={})=>await en({metroHost:t.metroHost,metroPort:t.metroPort,bundleUrl:t.bundleUrl,runtime:e.runtime,timeoutMs:t.timeoutMs})},capture:{snapshot:async(e={})=>{var t,a,r;let n,s,l,c,d=o(e);return t=await i("snapshot",e),a=d,n=q(t,"appBundleId"),{nodes:R(t.nodes),truncated:!0===t.truncated,appName:q(t,"appName"),appBundleId:n,...(s=t9((r=t).visibility),l=t9(r.unchanged),c=I(r.snapshotDiagnostics),{...s?{visibility:s}:{},...T(r),...l?{unchanged:l}:{},...c?{snapshotDiagnostics:c}:{}}),identifiers:{session:a,appId:n,appBundleId:n}}},screenshot:async(e={})=>{let t=o(e),a=await i("screenshot",e);return{path:C(a,"path"),overlayRefs:J(a),identifiers:{session:t}}},diff:async e=>await i("diff",e)},interactions:{click:async e=>await i("click",e),press:async e=>await i("press",e),longPress:async e=>await i("longpress",e),swipe:async e=>await i("swipe",e),pan:async e=>await i("gesture-pan",e),fling:async e=>await i("gesture-fling",e),swipeGesture:async e=>await i("gesture-swipe",e),focus:async e=>await i("focus",e),type:async e=>await i("type",e),fill:async e=>await i("fill",e),scroll:async e=>await i("scroll",e),pinch:async e=>await i("gesture-pinch",e),rotateGesture:async e=>await i("gesture-rotate",e),transformGesture:async e=>await i("gesture-transform",e),get:async e=>await i("get",e),is:async e=>await i("is",e),find:async e=>await i("find",e)},replay:{run:async e=>await i("replay",e),test:async e=>await i("test",e)},batch:{run:async e=>await i("batch",e)},observability:{perf:async(e={})=>await i("perf",e),logs:async(e={})=>await i("logs",e),network:async(e={})=>await i("network",e)},debug:{symbols:async t=>await t3({cwd:t.cwd??e.cwd,...t})},recording:{record:async e=>await i("record",e),trace:async e=>await i("trace",e)},settings:{update:async e=>await i("settings",e)}}}function t9(e){return"object"==typeof e&&null!==e?e:void 0}function ae(e,t){return{...e,...t}}function at(e){let t=e.lease;if(!t||"object"!=typeof t||Array.isArray(t))throw Error("Invalid lease response from daemon");return{leaseId:C(t,"leaseId"),tenantId:C(t,"tenantId"),runId:C(t,"runId"),backend:C(t,"backend"),createdAt:"number"==typeof t.createdAt?t.createdAt:void 0,heartbeatAt:"number"==typeof t.heartbeatAt?t.heartbeatAt:void 0,expiresAt:"number"==typeof t.expiresAt?t.expiresAt:void 0}}export{eo as DAEMON_HTTP_BASE_PATH,ec as buildDaemonHttpAuthHeaders,es as buildDaemonHttpBaseUrl,el as buildDaemonHttpUrl,t7 as createAgentDeviceClient,ty as ensureDaemon,eV as formatDurationSeconds,eH as replayTestFailureStepLines,th as resolveClientSettings,tP as sendToDaemon};
|
|
6
|
+
${r}`:r})(n,o,e)}}(t=await t9(H,"crash artifact"))??function(e){let t=e.split("\n"),a=function(e){let t=[],a=e.findIndex(e=>/^Binary Images:/i.test(e.trim()));if(-1===a)return t;for(let n of e.slice(a+1)){let e=function(e){let t=e.match(/^\s*(0x[0-9a-fA-F]+)\s*-\s*(0x[0-9a-fA-F]+)\s+\+?(.+?)\s+<([0-9a-fA-F-]{32,36})>\s+(.+)$/);if(!t)return null;let a=tO(t[4]);if(!a)return null;let n=function(e,t){let a=e.split(/\s+/),n=a.at(-1);if(n&&tz.test(n))return{name:a.slice(0,-1).join(" ").trim(),arch:n};let i=r.basename(t);return{name:e.startsWith(i)?i:e}}(t[3].trim(),t[5].trim());return{name:n.name,arch:n.arch,uuid:a,base:BigInt(t[1]),end:BigInt(t[2]),path:t[5].trim()}}(n);e&&t.push(e)}return t}(t);if(0===a.length)return null;let n=function(e,t){let a,r=[];for(let[n,i]of e.entries()){let e=i.match(/^Thread\s+(\d+)\s+Crashed:/);e?a=Number(e[1]):(0===i.trim().length||/^Thread\s+\d+/.test(i))&&(a=void 0);let o=function(e,t){let a=e.match(/^\s*\d+\s+(.+?)\s+(0x[0-9a-fA-F]+)\b/);if(!a)return null;let r=a[1].trim(),n=BigInt(a[2]),i=function(e,t,a){let r=e.filter(e=>e.name===t);return r.find(e=>{var t,r;return t=e,r=a,void 0!==t.end&&t.base<=r&&r<=t.end})??(1===r.length?r[0]:void 0)}(t,r,n);return i?{image:i,address:n}:null}(i,t),s=i.match(/^\s*(\d+)/);o&&s&&r.push({...o,frameIndex:Number(s[1]),lineIndex:n,threadIndex:a})}return r}(t,a);return{format:"text",images:a,addresses:n,lines:t,frameMatches:n,write(e){let a=new Map(n.map(e=>[e.lineIndex,e]));return t.map((t,r)=>{let n=a.get(r);if(!n)return t;let i=e.get(tR(n.image,n.address))?.text;return!i||t.includes(i)?t:`${t} // ${i}`}).join("\n")}}}(t);G||function(){throw new f("UNSUPPORTED_OPERATION","debug symbols currently supports Apple crash artifacts with Binary Images or IPS usedImages.",{hint:"For Android Java/R8 crashes, use retrace with mapping.txt. For Android native crashes, use ndk-stack or addr2line with unstripped .so symbols. Capture the crash with logs, then symbolicate externally until Android support is added."})}();let z=await tY({cwd:V,dsym:e.dsym,searchPath:e.searchPath});if(0===z.length)throw new f("INVALID_ARGS","debug symbols requires --dsym or --search-path.",{hint:"Pass a matching .dSYM bundle directly, or pass --search-path <dir> so agent-device can match crash image UUIDs to local dSYMs."});let Y=await t6(),W=await tX(z,Y.dwarfdump),J=function(e,t,a){let r=new Map;for(let a of e){let e=t.find(e=>e.uuid===a.uuid&&(void 0===a.arch||void 0===e.arch||e.arch===a.arch));e&&r.set(a.uuid,{image:a,dsym:e})}if(r.size>0)return r;let n=tG(e.map(e=>e.uuid)),i=tG(t.map(e=>e.uuid));throw new f("COMMAND_FAILED",a?"dSYM UUID does not match any Apple image in the crash artifact.":"No matching dSYM UUID found under search path.",{artifactUuidCount:n.length,artifactUuidSample:n.slice(0,5),dsymUuidCount:i.length,dsymUuidSample:i.slice(0,5),hint:"Use dwarfdump --uuid <App.dSYM> and compare it with the crash Binary Images or usedImages UUID, then pass the matching dSYM/search path."})}(G.images,W,!!e.dsym),X=await t5(G.addresses,J,Y.atos),Q=G.write(X);await d.mkdir(r.dirname(K),{recursive:!0}),await d.writeFile(K,Q,"utf8");let Z=[...J.values()].map(({image:e,dsym:t})=>({name:e.name,uuid:e.uuid,arch:e.arch??t.arch,dsymPath:t.dsymPath,binaryPath:t.binaryPath})),ee=[...X.values()].filter(e=>e.text).length,et=G.images.length-Z.length,ea=et>0?[`${et} Apple image${1===et?"":"s"} had no matching dSYM and were left unchanged.`]:void 0;return{kind:"debugSymbols",platform:"apple",artifactPath:H,outPath:K,crash:"ips"===G.format?(n=G.document,i=G.frameMatches,o=X,R=function(e){let t=tV(e.faultingThread);if(void 0!==t)return t;let a=(Array.isArray(e.threads)?e.threads:[]).findIndex(e=>eo(e)&&!0===e.triggered);return -1===a?void 0:a}(n.payload),{...F={format:"ips",...(T=(s=n).payload,U=(l=s.header)?tq(l):null,{appName:(c=T,u=U,tj(c.procName,u?.app_name,u?.name)),bundleId:(p=T,m=U,L=eo(p.bundleInfo)?p.bundleInfo:void 0,tj(L?.CFBundleIdentifier,m?.bundleID)),version:(h=T,y=U,O=eo(h.bundleInfo)?h.bundleInfo:void 0,tj(O?.CFBundleShortVersionString,y?.app_version)),incident:(w=T,g=U,tj(w.incident,g?.incident_id)),timestamp:(v=T,b=U,tj(v.captureTime,b?.timestamp)),exceptionType:eo(I=T.exception)?tB(I.type):void 0,exceptionCodes:eo(A=T.exception)?tj(A.codes,A.rawCodes):void 0,terminationReason:function(e){if(eo(e)){let t;return(t=[tB(e.namespace),tB(e.code),tB(e.reason)].filter(e=>!!e)).length>0?t.join(" "):void 0}}(T.termination)}),crashedThread:R,topFrames:(S=i,P=R,_=o,S.filter(e=>void 0===P||e.threadIndex===P).slice(0,5).map(e=>t3(e.frameIndex,e.image,e.address,_))),findings:[]},findings:t2(F)}):(D=G.lines,M=G.frameMatches,k=X,j=function(e){let t=t1(e,"Triggered by Thread"),a=t?Number.parseInt(t,10):NaN;if(Number.isSafeInteger(a))return a;for(let t of e){let e=t.match(/^Thread\s+(\d+)\s+Crashed:/);if(e)return Number(e[1])}}(D),{...q={format:"text",appName:(B=t1(D,"Process"),B?.replace(/\s+\[\d+\]$/,"")),bundleId:t1(D,"Identifier"),version:t1(D,"Version"),incident:t1(D,"Incident Identifier"),timestamp:t1(D,"Date/Time"),exceptionType:t1(D,"Exception Type"),exceptionCodes:t1(D,"Exception Codes"),terminationReason:t1(D,"Termination Reason"),crashedThread:j,topFrames:(E=M,N=j,x=k,void 0===N?[]:E.filter(e=>e.threadIndex===N).slice(0,5).map(e=>t3(e.frameIndex,e.image,e.address,x))),findings:[]},findings:t2(q)}),matchedImages:Z,symbolicatedFrames:ee,skippedImages:et,warnings:ea,message:`Symbolicated ${ee} frame${1===ee?"":"s"} -> ${K}`}}async function t9(e,t){await ae(e,t);try{return await d.readFile(e,"utf8")}catch(a){throw new f("INVALID_ARGS",`Failed to read ${t}: ${e}`,{message:a instanceof Error?a.message:String(a)})}}async function ae(e,t){try{let a=await d.stat(e);if(a.size<=0x4000000)return;throw new f("INVALID_ARGS",`${t} is too large: ${e}`,{actualBytes:a.size,maxBytes:0x4000000,hint:"Pass a bounded Apple .ips/.crash artifact. For very large logs, first narrow the log to the crash report, or use logs grep/tail for lead-up context."})}catch(a){if(a instanceof f)throw a;throw new f("INVALID_ARGS",`Failed to read ${t}: ${e}`,{message:a instanceof Error?a.message:String(a)})}}function at(e,t){return r.resolve(e,t)}let aa={...T(),batch:W(function(e,t,a){let r=aa[e];if(!r)throw Error(`Missing daemon writer for batch command: ${e}`);let n=R(e);if(!n)throw Error(`Missing command metadata for batch command: ${e}`);try{return ar(r,n,n.readInput(t))}catch(r){let t=r instanceof Error?r.message:String(r);throw new f("INVALID_ARGS",`Batch step ${a} ${e} input is invalid: ${t}`,void 0,r)}})};function ar(e,t,a){let r=e(a);return{...r,...t?{metadataFlags:J(t,r.options)}:{}}}function an(e={},t={}){let a=t.transport??tU,r=async(t,r=[],n={},i)=>{let o=ao(e,n),s=await a({session:G(o.session),command:t,positionals:r,flags:Y(o,i),runtime:o.runtime,meta:K(o)});return s.ok||function(e){throw new f(u(e.code),e.message,{...e.details??{},hint:e.hint,diagnosticId:e.diagnosticId,logPath:e.logPath})}(s.error),s.data??{}},n=async(e={})=>{let t=await r(er.sessionList,[],e);return(Array.isArray(t.sessions)?t.sessions:[]).map(U)},i=async(e,t={})=>{let a=function(e,t){let a=aa[e];if(!a)throw Error(`Missing daemon writer for command: ${e}`);return ar(a,R(e),t)}(e,t);return await r(a.command,a.positionals,a.options,a.metadataFlags)},o=(t={})=>G(ao(e,t).session);return{command:{wait:async e=>await i("wait",e),alert:async(e={})=>await i("alert",e),appState:async(e={})=>await i("appstate",e),back:async(e={})=>await i("back",e),home:async(e={})=>await i("home",e),rotate:async e=>await i("rotate",e),appSwitcher:async(e={})=>await i("app-switcher",e),keyboard:async(e={})=>await i("keyboard",e),clipboard:async e=>await i("clipboard",e),reactNative:async e=>await i("react-native",e),prepare:async e=>await i("prepare",e),viewport:async e=>await i("viewport",e)},devices:{list:async(e={})=>{let t=await i("devices",e);return(Array.isArray(t.devices)?t.devices:[]).map(Q)},boot:async(e={})=>await i("boot",e),shutdown:async(e={})=>await i("shutdown",e)},sessions:{list:async(e={})=>await n(e),stateDir:async(t={})=>E(ao(e,t).stateDir??process.env.AGENT_DEVICE_STATE_DIR).baseDir,close:async(e={})=>{let t=o(e);return{session:t,shutdown:Z((await i("close",e)).shutdown),identifiers:{session:t}}}},apps:{install:async e=>q(await i("install",e),o(e)),reinstall:async e=>q(await i("reinstall",e),o(e)),installFromSource:async e=>L(await i("install-from-source",e),o(e)),list:async(e={})=>{let t=await i("apps",e);return Array.isArray(t.apps)?t.apps.filter(e=>"string"==typeof e):[]},open:async e=>{let t=o(e),a=await i("open",e),r=H(a),n=ei(a,"appBundleId");return{session:t,sessionStateDir:ei(a,"sessionStateDir"),appName:ei(a,"appName"),appBundleId:n,appId:n,startup:ee(a.startup),runtime:X(a.runtime),device:r,identifiers:{session:t,deviceId:r?.id,deviceName:r?.name,udid:r?.ios?.udid,serial:r?.android?.serial,appId:n,appBundleId:n}}},close:async(e={})=>{let t=o(e),a=await i("close",e);return{session:t,closedApp:e.app,shutdown:Z(a.shutdown),identifiers:{session:t}}},push:async e=>await i("push",e),triggerEvent:async e=>await i("trigger-app-event",e)},materializations:{release:async e=>F(await r(er.releaseMaterializedPaths,[],{...e,materializationId:e.materializationId}))},leases:{allocate:async e=>as(await r(er.leaseAllocate,[],{...e,leaseId:void 0})),heartbeat:async e=>as(await r(er.leaseHeartbeat,[],e)),release:async e=>({released:!0===(await r(er.leaseRelease,[],e)).released})},metro:{prepare:async t=>await eu({projectRoot:t.projectRoot??e.cwd,kind:t.kind,publicBaseUrl:t.publicBaseUrl,proxyBaseUrl:t.proxyBaseUrl,proxyBearerToken:t.bearerToken,bridgeScope:t.bridgeScope,launchUrl:t.launchUrl,companionProfileKey:t.companionProfileKey,companionConsumerKey:t.companionConsumerKey,metroPort:t.port,listenHost:t.listenHost,statusHost:t.statusHost,startupTimeoutMs:t.startupTimeoutMs,probeTimeoutMs:t.probeTimeoutMs,reuseExisting:t.reuseExisting,installDependenciesIfNeeded:t.installDependenciesIfNeeded,runtimeFilePath:t.runtimeFilePath,logPath:t.logPath}),reload:async(t={})=>await ed({metroHost:t.metroHost,metroPort:t.metroPort,bundleUrl:t.bundleUrl,runtime:e.runtime,timeoutMs:t.timeoutMs})},capture:{snapshot:async(e={})=>{var t,a,r;let n,s,l,c,d=o(e);return t=await i("snapshot",e),a=d,n=ei(t,"appBundleId"),{nodes:j(t.nodes),truncated:!0===t.truncated,appName:ei(t,"appName"),appBundleId:n,...(s=ai((r=t).visibility),l=ai(r.unchanged),c=S(r.snapshotDiagnostics),{...s?{visibility:s}:{},...O(r),...l?{unchanged:l}:{},...c?{snapshotDiagnostics:c}:{}}),identifiers:{session:a,appId:n,appBundleId:n}}},screenshot:async(e={})=>{let t=o(e),a=await i("screenshot",e),r=N(a);return{path:ea(a,"path"),overlayRefs:r?.overlayRefs,identifiers:{session:t}}},diff:async e=>await i("diff",e)},interactions:{click:async e=>await i("click",e),press:async e=>await i("press",e),longPress:async e=>await i("longpress",e),swipe:async e=>await i("swipe",e),pan:async e=>await i("gesture-pan",e),fling:async e=>await i("gesture-fling",e),swipeGesture:async e=>await i("gesture-swipe",e),focus:async e=>await i("focus",e),type:async e=>await i("type",e),fill:async e=>await i("fill",e),scroll:async e=>await i("scroll",e),pinch:async e=>await i("gesture-pinch",e),rotateGesture:async e=>await i("gesture-rotate",e),transformGesture:async e=>await i("gesture-transform",e),get:async e=>await i("get",e),is:async e=>await i("is",e),find:async e=>await i("find",e)},replay:{run:async e=>await i("replay",e),test:async e=>await i("test",e)},batch:{run:async e=>await i("batch",e)},observability:{perf:async(e={})=>await i("perf",e),logs:async(e={})=>await i("logs",e),network:async(e={})=>await i("network",e)},debug:{symbols:async t=>await t7({cwd:t.cwd??e.cwd,...t})},recording:{record:async e=>await i("record",e),trace:async e=>await i("trace",e)},settings:{update:async e=>await i("settings",e)}}}function ai(e){return eo(e)?e:void 0}function ao(e,t){return{...e,...t}}function as(e){let t=e.lease;if(!eo(t))throw Error("Invalid lease response from daemon");return{leaseId:ea(t,"leaseId"),tenantId:ea(t,"tenantId"),runId:ea(t,"runId"),backend:ea(t,"backend"),leaseProvider:ei(t,"leaseProvider"),clientId:ei(t,"clientId"),deviceKey:ei(t,"deviceKey"),createdAt:"number"==typeof t.createdAt?t.createdAt:void 0,heartbeatAt:"number"==typeof t.heartbeatAt?t.heartbeatAt:void 0,expiresAt:"number"==typeof t.expiresAt?t.expiresAt:void 0}}export{ef as DAEMON_HTTP_BASE_PATH,eh as buildDaemonHttpAuthHeaders,ep as buildDaemonHttpBaseUrl,em as buildDaemonHttpUrl,an as createAgentDeviceClient,tP as ensureDaemon,eX as formatDurationSeconds,eQ as replayTestFailureStepLines,tS as resolveClientSettings,tU as sendToDaemon};
|
package/dist/src/apple.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readSnapshotQualityVerdict as a,normalizeScrollDurationMs as e,buildScrollGesturePlan as t,assertScrollGestureInput as n}from"./2948.js";import{parseRunnerSequenceResult as o,buildRunnerSequenceCommand as d,runMacOsScreenshotAction as i,runIosRunnerCommand as r}from"./9722.js";import{writeIosClipboardText as s,openIosApp as u,openIosDevice as l,screenshotIos as p,closeIosApp as c,setIosSetting as m,readIosClipboardText as y}from"./apps.js";import{withDiagnosticTimer as v}from"./432.js";import{AppError as f}from"./733.js";function I(a,e,n,o={includeDuration:!0}){let d=w(a.referenceWidth),i=w(a.referenceHeight);if(void 0===d||void 0===i)return B(a,{amount:n?.amount});let r=t({direction:e,amount:n?.amount,pixels:n?.pixels,referenceWidth:d,referenceHeight:i});return B(a,{amount:n?.amount,pixels:r.pixels,durationMs:o?.includeDuration?n?.durationMs:void 0,preferProvidedPixels:!0})}function h(a,e={includeDuration:!0}){return{...a?.amount!==void 0?{amount:a.amount}:{},...a?.pixels!==void 0?{pixels:a.pixels}:{},...e?.includeDuration&&a?.durationMs!==void 0?{durationMs:a.durationMs}:{}}}function w(a){return"number"==typeof a&&Number.isFinite(a)?a:void 0}function B(a,e){var t,n,o,d;let i,r,s,u,{x1:l,y1:p,x2:c,y2:m}=(i=w((t=a).x),r=w(t.y),s=w(t.x2),u=w(t.y2),{...void 0!==i?{x1:i}:{},...void 0!==r?{y1:r}:{},...void 0!==s?{x2:s}:{},...void 0!==u?{y2:u}:{}}),y=w(a.referenceWidth),v=w(a.referenceHeight),f=(n=e,o=void 0!==l&&void 0!==c?Math.round(Math.abs(c-l)):void 0,d=void 0!==p&&void 0!==m?Math.round(Math.abs(m-p)):void 0,n?.preferProvidedPixels&&void 0!==n.pixels?n.pixels:void 0!==o&&o>0?o:void 0!==d&&d>0?d:void 0);return{...void 0!==l?{x1:l}:{},...void 0!==p?{y1:p}:{},...void 0!==c?{x2:c}:{},...void 0!==m?{y2:m}:{},...void 0!==y?{referenceWidth:y}:{},...void 0!==v?{referenceHeight:v}:{},...e?.amount!==void 0?{amount:e.amount}:{},...void 0!==f?{pixels:f}:{},...e?.durationMs!==void 0?{durationMs:e.durationMs}:{}}}async function M(a,e,t,n,o,d){return I(await a(e,{command:"desktopScroll",direction:o,...h(d,{includeDuration:!0}),appBundleId:t.appBundleId},n),o,d,{includeDuration:!0})}function g(a,e,t,n){return{command:"tap",x:t,y:n,...
|
|
1
|
+
import{readSnapshotQualityVerdict as a,normalizeScrollDurationMs as e,buildScrollGesturePlan as t,assertScrollGestureInput as n}from"./2948.js";import{parseRunnerSequenceResult as o,buildRunnerSequenceCommand as d,runMacOsScreenshotAction as i,runIosRunnerCommand as r}from"./9722.js";import{writeIosClipboardText as s,openIosApp as u,openIosDevice as l,screenshotIos as p,closeIosApp as c,setIosSetting as m,readIosClipboardText as y}from"./apps.js";import{withDiagnosticTimer as v}from"./432.js";import{AppError as f}from"./733.js";function I(a,e,n,o={includeDuration:!0}){let d=w(a.referenceWidth),i=w(a.referenceHeight);if(void 0===d||void 0===i)return B(a,{amount:n?.amount});let r=t({direction:e,amount:n?.amount,pixels:n?.pixels,referenceWidth:d,referenceHeight:i});return B(a,{amount:n?.amount,pixels:r.pixels,durationMs:o?.includeDuration?n?.durationMs:void 0,preferProvidedPixels:!0})}function h(a,e={includeDuration:!0}){return{...a?.amount!==void 0?{amount:a.amount}:{},...a?.pixels!==void 0?{pixels:a.pixels}:{},...e?.includeDuration&&a?.durationMs!==void 0?{durationMs:a.durationMs}:{}}}function w(a){return"number"==typeof a&&Number.isFinite(a)?a:void 0}function B(a,e){var t,n,o,d;let i,r,s,u,{x1:l,y1:p,x2:c,y2:m}=(i=w((t=a).x),r=w(t.y),s=w(t.x2),u=w(t.y2),{...void 0!==i?{x1:i}:{},...void 0!==r?{y1:r}:{},...void 0!==s?{x2:s}:{},...void 0!==u?{y2:u}:{}}),y=w(a.referenceWidth),v=w(a.referenceHeight),f=(n=e,o=void 0!==l&&void 0!==c?Math.round(Math.abs(c-l)):void 0,d=void 0!==p&&void 0!==m?Math.round(Math.abs(m-p)):void 0,n?.preferProvidedPixels&&void 0!==n.pixels?n.pixels:void 0!==o&&o>0?o:void 0!==d&&d>0?d:void 0);return{...void 0!==l?{x1:l}:{},...void 0!==p?{y1:p}:{},...void 0!==c?{x2:c}:{},...void 0!==m?{y2:m}:{},...void 0!==y?{referenceWidth:y}:{},...void 0!==v?{referenceHeight:v}:{},...e?.amount!==void 0?{amount:e.amount}:{},...void 0!==f?{pixels:f}:{},...e?.durationMs!==void 0?{durationMs:e.durationMs}:{}}}async function M(a,e,t,n,o,d){return I(await a(e,{command:"desktopScroll",direction:o,...h(d,{includeDuration:!0}),appBundleId:t.appBundleId},n),o,d,{includeDuration:!0})}function g(a,e,t,n){return{command:"tap",x:t,y:n,...x(a)?{synthesized:!0}:{},appBundleId:e.appBundleId}}function x(a){return"ios"===a.platform&&"tv"!==a.target}function _(a,e,t,n,o,d,i,r){var s,u;let l="ios"===a.platform&&"tv"!==a.target?(s=i,u=r.defaultDurationMs,void 0===s?u:Math.min(1e4,Math.max(16,Math.round(s)))):i??r.legacyDefaultDurationMs;return{command:"drag",x:t,y:n,x2:o,y2:d,...void 0!==l?{durationMs:l}:{},...!0===r.synthesized?{synthesized:!0}:{},appBundleId:e.appBundleId}}function b(a,e,t){return{command:"remotePress",remoteButton:a,...void 0!==t?{durationMs:t}:{},...void 0!==e?{appBundleId:e}:{}}}async function D(a,t,o,d,i,r){return(e(r?.durationMs,{invalidMessage:"scroll durationMs must be a non-negative integer at most 10000"}),"tv"===t.target)?B(await a(t,b(i,o.appBundleId,r?.durationMs),d),{amount:r?.amount,durationMs:r?.durationMs}):(n(r??{}),"macos"===t.platform)?await M(a,t,o,d,i,r):I(await a(t,{command:"scroll",direction:i,...h(r),appBundleId:o.appBundleId},d),i,r)}function C(e,t){let n,{overrides:I,runnerOpts:h}={runnerOpts:n={verbose:t.verbose,logPath:t.logPath,traceLogPath:t.traceLogPath,requestId:t.requestId,iosXctestrunFile:t.iosXctestrunFile,iosXctestDerivedDataPath:t.iosXctestDerivedDataPath,iosXctestEnvDir:t.iosXctestEnvDir,runnerLeaseContext:t.runnerLeaseContext},overrides:{tap:async(a,o)=>await r(e,g(e,t,a,o),n),tapElementSelector:async a=>await r(e,{command:"tap",selectorKey:a.key,selectorValue:a.value,allowNonHittableCoordinateFallback:a.allowNonHittableCoordinateFallback,appBundleId:t.appBundleId},n),doubleTap:async(a,i)=>{let s=await r(e,d([{kind:"doubleTap",x:a,y:i}],t.appBundleId),n);return o(s),s},swipe:async(a,o,d,i,s)=>await r(e,_(e,t,a,o,d,i,s,{defaultDurationMs:250,synthesized:x(e)}),n),pan:async(a,o,d,i,s)=>await r(e,_(e,t,a,o,d,i,s,{defaultDurationMs:500,legacyDefaultDurationMs:500,synthesized:x(e)}),n),fling:async(a,o,d,i,s)=>await r(e,_(e,t,a,o,d,i,s,{defaultDurationMs:16,legacyDefaultDurationMs:16,synthesized:x(e)}),n),longPress:async(a,o,d)=>await r(e,{command:"longPress",x:a,y:o,durationMs:d,appBundleId:t.appBundleId},n),focus:async(a,o)=>await r(e,g(e,t,a,o),n),type:async(a,o)=>{await r(e,{command:"type",text:a,delayMs:o,textEntryMode:"\n"===a?void 0:"append",appBundleId:t.appBundleId},n)},fillElementSelector:async(a,o,d)=>await r(e,{command:"type",selectorKey:a.key,selectorValue:a.value,allowNonHittableCoordinateFallback:a.allowNonHittableCoordinateFallback,text:o,delayMs:d,textEntryMode:"replace",appBundleId:t.appBundleId},n),fill:async(a,o,d,i)=>await r(e,{command:"type",x:a,y:o,text:d,delayMs:i,textEntryMode:"replace",appBundleId:t.appBundleId},n),scroll:async(a,o)=>await D(r,e,t,n,a,o),pinch:async(a,o,d)=>{await r(e,{command:"pinch",scale:a,x:o,y:d,appBundleId:t.appBundleId},n)},rotateGesture:async(a,o,d,i)=>{await r(e,{command:"rotateGesture",degrees:a,x:o,y:d,velocity:i,appBundleId:t.appBundleId},n)},transformGesture:async a=>await r(e,{command:"transformGesture",x:a.x,y:a.y,dx:a.dx,dy:a.dy,scale:a.scale,degrees:a.degrees,durationMs:a.durationMs,appBundleId:t.appBundleId},n)}};return{open:(a,t)=>u(e,a,{appBundleId:t?.appBundleId,launchConsole:t?.launchConsole,launchArgs:t?.launchArgs,url:t?.url}),openDevice:()=>l(e),close:a=>c(e,a),screenshot:async(a,t)=>{"macos"===e.platform&&t?.surface&&"app"!==t.surface?await i(a,{surface:t.surface,fullscreen:t.fullscreen}):await p(e,a,t?.appBundleId,t?.fullscreen,h)},snapshot:async t=>{var n;let o={nodes:Array.isArray((n=await v("snapshot_capture",async()=>await r(e,{command:"snapshot",appBundleId:t?.appBundleId,interactiveOnly:t?.interactiveOnly,depth:t?.depth,scope:t?.scope,raw:t?.raw},h),{backend:"xctest"})).nodes)?n.nodes:void 0,truncated:"boolean"==typeof n.truncated?n.truncated:void 0,quality:a(n.snapshotQuality),message:"string"==typeof n.message&&n.message.trim().length>0?n.message:void 0},d=o.nodes??[];if(0===d.length&&"simulator"===e.kind)throw new f("COMMAND_FAILED","XCTest snapshot returned 0 nodes on iOS simulator.");return{nodes:d,truncated:o.truncated??!1,backend:"xctest",...o.quality?{quality:o.quality}:{},...!o.quality&&o.message?{warnings:[o.message]}:{}}},back:async a=>{"tv"===e.target?await r(e,b("menu",t.appBundleId),h):await r(e,{command:"system"===a?"backSystem":"backInApp",appBundleId:t.appBundleId},h)},home:async()=>{"tv"===e.target?await r(e,b("home",t.appBundleId),h):await r(e,{command:"home",appBundleId:t.appBundleId},h)},rotate:async a=>{await r(e,{command:"rotate",orientation:a,appBundleId:t.appBundleId},h)},appSwitcher:async()=>{await r(e,{command:"appSwitcher",appBundleId:t.appBundleId},h)},readClipboard:()=>y(e),writeClipboard:a=>s(e,a),setSetting:(a,t,n,o)=>m(e,a,t,n,o),...I}}export{C as createAppleInteractor};
|
package/dist/src/apps.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
let e;import{promises as t}from"node:fs";import i from"node:os";import a from"node:path";import{fileURLToPath as r}from"node:url";import{AppError as n}from"./733.js";import{runXcrun as o,IOS_RUNNER_CONTAINER_BUNDLE_IDS as l,resolveIosDevicectlHint as s,LAUNCH_CONSOLE_DIRECT_APP_ONLY_MESSAGE as d,runIosRunnerCommand as u,resolveAppleToolProvider as c,runSimctlForDevice as p,IOS_DEVICECTL_DEFAULT_HINT as f,readInfoPlistString as w,requireSimulatorDevice as m,buildSimctlArgsForDevice as h,runMacOsPermissionAction as y,runIosDevicectl as A,filterAppleAppsByBundlePrefix as I,runAppleToolCommand as v,listIosDeviceApps as g,quitMacOsApp as _,ensureBootedSimulator as C,LAUNCH_CONSOLE_IOS_SIMULATOR_ONLY_MESSAGE as b,getSimulatorState as N}from"./9722.js";import{runCmd as S}from"./8875.js";import{materializeInstallablePath as L,isTrustedInstallSourceUrl as D}from"./5484.js";import{parseAppearanceAction as M,summarizeCommandAttemptFailures as O,parseSettingState as P,parsePermissionTarget as F,parsePermissionAction as x}from"./8225.js";import{isWebUrl as R,createAppResolutionCache as $,isDeepLinkTarget as E,resolveIosSimulatorDeviceSetPath as k,resolveIosDeviceDeepLinkBundleId as T,retryWithPolicy as U,Deadline as B}from"./3340.js";import{emitDiagnostic as G}from"./432.js";import{getUnsupportedMacOsSettingMessage as V,requireLocationCoordinates as j}from"./2948.js";function W(e){if(!(e instanceof n)||"COMMAND_FAILED"!==e.code)return!1;let t=e.details??{};if(4!==t.exitCode)return!1;let i=String(t.stderr??"").toLowerCase();return i.includes("fbsopenapplicationserviceerrordomain")&&i.includes("the request to open")}async function H(e,t){let i=await o(h(e,["get_app_container",e.id,t]),{allowFailure:!0});if(0!==i.exitCode)return{installed:!1};let a=i.stdout.trim();if(!a)return{installed:!1};let r=await v("plutil",["-extract","CFBundleExecutable","raw","-o","-",`${a}/Info.plist`],{allowFailure:!0});if(0!==r.exitCode||!r.stdout.trim())return{installed:!0};let n=r.stdout.trim(),l=`${a}/${n}`,s=await v("otool",["-l",l],{allowFailure:!0});if(0!==s.exitCode)return{installed:!0};let d=s.stdout.toLowerCase();return{installed:!0,simulatorCompatible:d.includes("iossimulator")||d.includes("platform 7")}}async function K(e,t){let i;if("url"===e.kind&&!D(e.url))throw new n("INVALID_ARGS","iOS install_from_source URL sources are only supported for trusted artifact services such as GitHub Actions and EAS. Use a path source for other hosts.");let a=await L({source:e,isInstallablePath:(e,t)=>t.isDirectory()&&e.toLowerCase().endsWith(".app")||t.isFile()&&e.toLowerCase().endsWith(".ipa"),installableLabel:"iOS installable (.app or .ipa)",allowArchiveExtraction:"url"!==e.kind||D(e.url),signal:t?.signal});try{let e=i=await q(a.installablePath,t),r=await z(e.installPath);return{archivePath:a.archivePath??(a.installablePath.toLowerCase().endsWith(".ipa")?a.installablePath:void 0),installablePath:e.installPath,bundleId:r.bundleId,appName:r.appName,cleanup:async()=>{await e.cleanup(),await a.cleanup()}}}catch(e){try{await i?.cleanup()}finally{await a.cleanup()}throw e}}async function z(e){let t=a.join(e,"Info.plist"),[i,r,n]=await Promise.all([w(t,"CFBundleIdentifier"),w(t,"CFBundleDisplayName"),w(t,"CFBundleName")]);return{bundleId:i,appName:r??n}}async function q(e,r){if(!e.toLowerCase().endsWith(".ipa"))return{installPath:e,cleanup:async()=>{}};let o=await t.mkdtemp(a.join(i.tmpdir(),"agent-device-ios-ipa-")),l=async()=>{await t.rm(o,{recursive:!0,force:!0})};try{await S("unzip",["-q",e,"-d",o]);let i=a.join(o,"Payload"),s=(await t.readdir(i,{withFileTypes:!0}).catch(()=>{throw new n("INVALID_ARGS","Invalid IPA: missing Payload directory")})).filter(e=>e.isDirectory()&&e.name.toLowerCase().endsWith(".app")).map(e=>({installPath:a.join(i,e.name),bundleName:e.name.replace(/\.app$/i,"")})),d=s[0];if(void 0!==d&&1===s.length)return{installPath:d.installPath,cleanup:l};if(0===s.length)throw new n("INVALID_ARGS","Invalid IPA: expected at least one .app under Payload, found 0");await J(s);let u=r?.appIdentifierHint?.trim();if(u){let e=function(e,t){let i=t.toLowerCase(),a=e.filter(e=>e.bundleName.toLowerCase()===i);if(1===a.length)return a[0];if(a.length>1)throw new n("INVALID_ARGS",`Invalid IPA: multiple app bundles matched "${t}" by name. Use a bundle id hint instead.`);if(t.includes(".")){let t=e.filter(e=>e.bundleId?.toLowerCase()===i);if(1===t.length)return t[0]}}(s,u);if(e)return{installPath:e.installPath,cleanup:l};throw new n("INVALID_ARGS",`Invalid IPA: found ${s.length} .app bundles under Payload and none matched "${u}". Available bundles: ${s.map(Z).join(", ")}`)}throw new n("INVALID_ARGS",`Invalid IPA: found ${s.length} .app bundles under Payload. Pass an app identifier or bundle name matching one of: ${s.map(Z).join(", ")}`)}catch(e){throw await l(),e}}async function J(e){await Promise.all(e.map(async e=>{if(e.bundleId&&e.appName)return;let t=await z(e.installPath);e.bundleId=e.bundleId??t.bundleId,e.appName=e.appName??t.appName}))}function Z(e){let t=e.bundleId??e.appName;return t?`${e.bundleName}.app (${t})`:`${e.bundleName}.app`}let Q={settings:"com.apple.systempreferences"},X=/^[a-z0-9-]+(?:\.[a-z0-9-]+)+$/,Y={platform:"macos",deviceId:"host",variant:"all"},ee=$();async function et(e){let t=e.trim(),i=Q[t.toLowerCase()];if(i)return i;if(X.test(t))return t;let a=ee.get(Y,t);if(a)return a;let r=(await es("all")).filter(e=>e.name.toLowerCase()===t.toLowerCase()),o=r[0];if(void 0!==o&&1===r.length)return ee.set(Y,t,o.bundleId);if(r.length>1)throw new n("INVALID_ARGS",`Multiple apps matched "${e}"`,{matches:r});throw new n("APP_NOT_INSTALLED",`No app found matching "${e}"`)}async function ei(e,t,i){let a=i?.url?.trim();if(a){if(!E(a))throw new n("INVALID_ARGS","open <app> <url> requires a valid URL target");let e=i?.appBundleId??await et(t);await ed().openBundle(e,a);return}let r=t.trim();if(E(r))return void await ed().openTarget(r);let o=i?.appBundleId??await et(r);await ed().openBundle(o)}async function ea(e,t){let i=await et(t),a=await _(i);if(a.running&&!a.terminated&&!a.forceTerminated)throw new n("COMMAND_FAILED",`Failed to close macOS app ${t}`,{bundleId:i,running:a.running,terminated:a.terminated,forceTerminated:a.forceTerminated})}async function er(){return await ed().readClipboard()}async function en(e){await ed().writeClipboard(e)}async function eo(){return await ed().readDarkMode()}async function el(e){let t=M(e),i="toggle"===t?!await eo():"dark"===t;await ed().setDarkMode(i)}async function es(e){return await ed().listApps(e)}function ed(){let e=c().macosHost;if(!e)throw new n("UNSUPPORTED_OPERATION","macOS host provider is not available");return e}function eu(e){if(!(e instanceof n))return{reason:e instanceof Error?e.message:String(e)};let t=e.details??{},i=Array.isArray(t.args)?t.args.filter(e=>"string"==typeof e).join(" "):void 0;return{errorCode:e.code,reason:e.message,timeoutMs:"number"==typeof t.timeoutMs?t.timeoutMs:void 0,exitCode:"number"==typeof t.exitCode?t.exitCode:void 0,stderr:"string"==typeof t.stderr&&t.stderr.trim()?t.stderr:void 0,stdout:"string"==typeof t.stdout&&t.stdout.trim()?t.stdout:void 0,commandArgs:i}}let ec=["--time","9:41","--dataNetwork","wifi","--wifiMode","active","--wifiBars","3","--batteryState","charged","--batteryLevel","100"],ep={0:"hide",1:"wifi",6:"3g",7:"4g",8:"lte",9:"lte-a",10:"lte+",11:"5g",12:"5g+",13:"5g-uwb",14:"5g-uc"},ef={1:"searching",2:"failed",3:"active"},ew={0:"notSupported",1:"searching",2:"failed",3:"active"};async function em(e){let t=null,i=!1;try{t=await ey(e),i=!0}catch(t){ev(e,"snapshot_failed",t)}try{await eA(e),await eI(e,ec)}catch(t){ev(e,"prepare_failed",t)}return async()=>{await eh(e,i?t:null)}}async function eh(e,t){var i,a;let r;await eA(e),t&&await eI(e,(r=[],(i=t).dataNetwork&&r.push("--dataNetwork",i.dataNetwork),i.wifiMode&&r.push("--wifiMode",i.wifiMode),void 0!==i.wifiBars&&("wifi"===i.dataNetwork||i.wifiMode)&&r.push("--wifiBars",i.wifiBars),i.cellularMode&&r.push("--cellularMode",i.cellularMode),void 0!==i.cellularBars&&(i.cellularMode||(a=i.dataNetwork)&&"hide"!==a&&"wifi"!==a||void 0!==i.operatorName)&&r.push("--cellularBars",i.cellularBars),void 0!==i.operatorName&&r.push("--operatorName",i.operatorName),r))}async function ey(e){var t;let i=await (t=["status_bar",e.id,"list"],p(e,t,{allowFailure:!0}));if(0!==i.exitCode)throw new n("COMMAND_FAILED","Failed to read simulator status bar overrides",{exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr});return function(e){let t={};for(let i of e.split("\n").map(e=>e.trim()).filter(e=>e.length>0&&"Current Status Bar Overrides:"!==e&&!/^=+$/.test(e))){let e=/^DataNetworkType:\s+(\d+)$/.exec(i);if(e){let i=Number(e[1]),a=ep[i];if(!a)throw new n("COMMAND_FAILED",`Unsupported simulator data network type: ${i}`);t.dataNetwork=a;continue}let a=/^WiFi Mode:\s+(\d+),\s+WiFi Bars:\s+(\d+)$/.exec(i);if(a){let e=ef[Number(a[1])];e&&(t.wifiMode=e),t.wifiBars=a[2];continue}let r=/^Cell Mode:\s+(\d+),\s+Cell Bars:\s+(\d+)$/.exec(i);if(r){let e=Number(r[1]),i=ew[e];if(!i)throw new n("COMMAND_FAILED",`Unsupported simulator cellular mode: ${e}`);t.cellularMode=i,t.cellularBars=r[2];continue}let o=/^Operator Name:\s*(.*)$/.exec(i);if(o){t.operatorName=o[1]??"";continue}}return 0===Object.keys(t).length?null:t}(i.stdout)}async function eA(e){await p(e,["status_bar",e.id,"clear"],void 0)}async function eI(e,t){0!==t.length&&await p(e,["status_bar",e.id,"override",...t],void 0)}function ev(e,t,i){G({level:"warn",phase:`ios_screenshot_status_bar_${t}`,data:{platform:e.platform,deviceKind:e.kind,deviceId:e.id,...eu(i)}})}let eg={ensureBooted:C,prepareStatusBarForScreenshot:em,captureWithRetry:eb,captureWithRunner:eN,shouldFallbackToRunner:eP};async function e_(e,t,i,a,r){if("macos"===e.platform)return void await eN(e,t,i,a,r);if("simulator"===e.kind)return void await eC(e,t,i,a,void 0,r);try{await A(["device","screenshot","--device",e.id,t],{action:"capture iOS screenshot",deviceId:e.id});return}catch(t){if(!function(e){if(!(e instanceof n)||"COMMAND_FAILED"!==e.code)return!1;let t=e.details??{},i="string"==typeof t.stdout?t.stdout:"",a="string"==typeof t.stderr?t.stderr:"",r=`${e.message}
|
|
1
|
+
let e;import{promises as t}from"node:fs";import i from"node:os";import a from"node:path";import{fileURLToPath as r}from"node:url";import{AppError as n}from"./733.js";import{runXcrun as o,resolveIosDevicectlHint as l,LAUNCH_CONSOLE_DIRECT_APP_ONLY_MESSAGE as s,runIosRunnerCommand as d,resolveAppleToolProvider as u,runSimctlForDevice as c,IOS_DEVICECTL_DEFAULT_HINT as p,readInfoPlistString as f,buildSimctlArgsForDevice as w,runMacOsPermissionAction as m,runIosDevicectl as h,filterAppleAppsByBundlePrefix as y,runAppleToolCommand as A,listIosDeviceApps as I,quitMacOsApp as _,LAUNCH_CONSOLE_IOS_SIMULATOR_ONLY_MESSAGE as v,IOS_RUNNER_CONTAINER_BUNDLE_IDS as g}from"./9722.js";import{runCmd as C}from"./8875.js";import{materializeInstallablePath as b,isTrustedInstallSourceUrl as N}from"./5484.js";import{parseAppearanceAction as S,summarizeCommandAttemptFailures as L,parseSettingState as D,parsePermissionTarget as M,parsePermissionAction as O}from"./8225.js";import{isWebUrl as P,createAppResolutionCache as F,isDeepLinkTarget as R,resolveIosSimulatorDeviceSetPath as x,resolveIosDeviceDeepLinkBundleId as $,retryWithPolicy as E,Deadline as k}from"./3340.js";import{emitDiagnostic as T}from"./432.js";import{requireSimulatorDevice as U,ensureBootedSimulator as B,getSimulatorState as G}from"./simulator.js";import{getUnsupportedMacOsSettingMessage as V,requireLocationCoordinates as j}from"./2948.js";function W(e){if(!(e instanceof n)||"COMMAND_FAILED"!==e.code)return!1;let t=e.details??{};if(4!==t.exitCode)return!1;let i=String(t.stderr??"").toLowerCase();return i.includes("fbsopenapplicationserviceerrordomain")&&i.includes("the request to open")}async function K(e,t){let i=await o(w(e,["get_app_container",e.id,t]),{allowFailure:!0});if(0!==i.exitCode)return{installed:!1};let a=i.stdout.trim();if(!a)return{installed:!1};let r=await A("plutil",["-extract","CFBundleExecutable","raw","-o","-",`${a}/Info.plist`],{allowFailure:!0});if(0!==r.exitCode||!r.stdout.trim())return{installed:!0};let n=r.stdout.trim(),l=`${a}/${n}`,s=await A("otool",["-l",l],{allowFailure:!0});if(0!==s.exitCode)return{installed:!0};let d=s.stdout.toLowerCase();return{installed:!0,simulatorCompatible:d.includes("iossimulator")||d.includes("platform 7")}}async function H(e,t){let i;if("url"===e.kind&&!N(e.url))throw new n("INVALID_ARGS","iOS install_from_source URL sources are only supported for trusted artifact services such as GitHub Actions and EAS. Use a path source for other hosts.");let a=await b({source:e,isInstallablePath:(e,t)=>t.isDirectory()&&e.toLowerCase().endsWith(".app")||t.isFile()&&e.toLowerCase().endsWith(".ipa"),installableLabel:"iOS installable (.app or .ipa)",allowArchiveExtraction:"url"!==e.kind||N(e.url),signal:t?.signal});try{let e=i=await q(a.installablePath,t),r=await z(e.installPath);return{archivePath:a.archivePath??(a.installablePath.toLowerCase().endsWith(".ipa")?a.installablePath:void 0),installablePath:e.installPath,bundleId:r.bundleId,appName:r.appName,cleanup:async()=>{await e.cleanup(),await a.cleanup()}}}catch(e){try{await i?.cleanup()}finally{await a.cleanup()}throw e}}async function z(e){let t=a.join(e,"Info.plist"),[i,r,n]=await Promise.all([f(t,"CFBundleIdentifier"),f(t,"CFBundleDisplayName"),f(t,"CFBundleName")]);return{bundleId:i,appName:r??n}}async function q(e,r){if(!e.toLowerCase().endsWith(".ipa"))return{installPath:e,cleanup:async()=>{}};let o=await t.mkdtemp(a.join(i.tmpdir(),"agent-device-ios-ipa-")),l=async()=>{await t.rm(o,{recursive:!0,force:!0})};try{await C("unzip",["-q",e,"-d",o]);let i=a.join(o,"Payload"),s=(await t.readdir(i,{withFileTypes:!0}).catch(()=>{throw new n("INVALID_ARGS","Invalid IPA: missing Payload directory")})).filter(e=>e.isDirectory()&&e.name.toLowerCase().endsWith(".app")).map(e=>({installPath:a.join(i,e.name),bundleName:e.name.replace(/\.app$/i,"")})),d=s[0];if(void 0!==d&&1===s.length)return{installPath:d.installPath,cleanup:l};if(0===s.length)throw new n("INVALID_ARGS","Invalid IPA: expected at least one .app under Payload, found 0");await J(s);let u=r?.appIdentifierHint?.trim();if(u){let e=function(e,t){let i=t.toLowerCase(),a=e.filter(e=>e.bundleName.toLowerCase()===i);if(1===a.length)return a[0];if(a.length>1)throw new n("INVALID_ARGS",`Invalid IPA: multiple app bundles matched "${t}" by name. Use a bundle id hint instead.`);if(t.includes(".")){let t=e.filter(e=>e.bundleId?.toLowerCase()===i);if(1===t.length)return t[0]}}(s,u);if(e)return{installPath:e.installPath,cleanup:l};throw new n("INVALID_ARGS",`Invalid IPA: found ${s.length} .app bundles under Payload and none matched "${u}". Available bundles: ${s.map(Z).join(", ")}`)}throw new n("INVALID_ARGS",`Invalid IPA: found ${s.length} .app bundles under Payload. Pass an app identifier or bundle name matching one of: ${s.map(Z).join(", ")}`)}catch(e){throw await l(),e}}async function J(e){await Promise.all(e.map(async e=>{if(e.bundleId&&e.appName)return;let t=await z(e.installPath);e.bundleId=e.bundleId??t.bundleId,e.appName=e.appName??t.appName}))}function Z(e){let t=e.bundleId??e.appName;return t?`${e.bundleName}.app (${t})`:`${e.bundleName}.app`}let Q={settings:"com.apple.systempreferences"},X=/^[a-z0-9-]+(?:\.[a-z0-9-]+)+$/,Y={platform:"macos",deviceId:"host",variant:"all"},ee=F();async function et(e){let t=e.trim(),i=Q[t.toLowerCase()];if(i)return i;if(X.test(t))return t;let a=ee.get(Y,t);if(a)return a;let r=(await es("all")).filter(e=>e.name.toLowerCase()===t.toLowerCase()),o=r[0];if(void 0!==o&&1===r.length)return ee.set(Y,t,o.bundleId);if(r.length>1)throw new n("INVALID_ARGS",`Multiple apps matched "${e}"`,{matches:r});throw new n("APP_NOT_INSTALLED",`No app found matching "${e}"`)}async function ei(e,t,i){let a=i?.url?.trim();if(a){if(!R(a))throw new n("INVALID_ARGS","open <app> <url> requires a valid URL target");let e=i?.appBundleId??await et(t);await ed().openBundle(e,a);return}let r=t.trim();if(R(r))return void await ed().openTarget(r);let o=i?.appBundleId??await et(r);await ed().openBundle(o)}async function ea(e,t){let i=await et(t),a=await _(i);if(a.running&&!a.terminated&&!a.forceTerminated)throw new n("COMMAND_FAILED",`Failed to close macOS app ${t}`,{bundleId:i,running:a.running,terminated:a.terminated,forceTerminated:a.forceTerminated})}async function er(){return await ed().readClipboard()}async function en(e){await ed().writeClipboard(e)}async function eo(){return await ed().readDarkMode()}async function el(e){let t=S(e),i="toggle"===t?!await eo():"dark"===t;await ed().setDarkMode(i)}async function es(e){return await ed().listApps(e)}function ed(){let e=u().macosHost;if(!e)throw new n("UNSUPPORTED_OPERATION","macOS host provider is not available");return e}function eu(e){if(!(e instanceof n))return{reason:e instanceof Error?e.message:String(e)};let t=e.details??{},i=Array.isArray(t.args)?t.args.filter(e=>"string"==typeof e).join(" "):void 0;return{errorCode:e.code,reason:e.message,timeoutMs:"number"==typeof t.timeoutMs?t.timeoutMs:void 0,exitCode:"number"==typeof t.exitCode?t.exitCode:void 0,stderr:"string"==typeof t.stderr&&t.stderr.trim()?t.stderr:void 0,stdout:"string"==typeof t.stdout&&t.stdout.trim()?t.stdout:void 0,commandArgs:i}}let ec=["--time","9:41","--dataNetwork","wifi","--wifiMode","active","--wifiBars","3","--batteryState","charged","--batteryLevel","100"],ep={0:"hide",1:"wifi",6:"3g",7:"4g",8:"lte",9:"lte-a",10:"lte+",11:"5g",12:"5g+",13:"5g-uwb",14:"5g-uc"},ef={1:"searching",2:"failed",3:"active"},ew={0:"notSupported",1:"searching",2:"failed",3:"active"};async function em(e){let t=null,i=!1;try{t=await ey(e),i=!0}catch(t){e_(e,"snapshot_failed",t)}try{await eA(e),await eI(e,ec)}catch(t){e_(e,"prepare_failed",t)}return async()=>{await eh(e,i?t:null)}}async function eh(e,t){var i,a;let r;await eA(e),t&&await eI(e,(r=[],(i=t).dataNetwork&&r.push("--dataNetwork",i.dataNetwork),i.wifiMode&&r.push("--wifiMode",i.wifiMode),void 0!==i.wifiBars&&("wifi"===i.dataNetwork||i.wifiMode)&&r.push("--wifiBars",i.wifiBars),i.cellularMode&&r.push("--cellularMode",i.cellularMode),void 0!==i.cellularBars&&(i.cellularMode||(a=i.dataNetwork)&&"hide"!==a&&"wifi"!==a||void 0!==i.operatorName)&&r.push("--cellularBars",i.cellularBars),void 0!==i.operatorName&&r.push("--operatorName",i.operatorName),r))}async function ey(e){var t;let i=await (t=["status_bar",e.id,"list"],c(e,t,{allowFailure:!0}));if(0!==i.exitCode)throw new n("COMMAND_FAILED","Failed to read simulator status bar overrides",{exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr});return function(e){let t={};for(let i of e.split("\n").map(e=>e.trim()).filter(e=>e.length>0&&"Current Status Bar Overrides:"!==e&&!/^=+$/.test(e))){let e=/^DataNetworkType:\s+(\d+)$/.exec(i);if(e){let i=Number(e[1]),a=ep[i];if(!a)throw new n("COMMAND_FAILED",`Unsupported simulator data network type: ${i}`);t.dataNetwork=a;continue}let a=/^WiFi Mode:\s+(\d+),\s+WiFi Bars:\s+(\d+)$/.exec(i);if(a){let e=ef[Number(a[1])];e&&(t.wifiMode=e),t.wifiBars=a[2];continue}let r=/^Cell Mode:\s+(\d+),\s+Cell Bars:\s+(\d+)$/.exec(i);if(r){let e=Number(r[1]),i=ew[e];if(!i)throw new n("COMMAND_FAILED",`Unsupported simulator cellular mode: ${e}`);t.cellularMode=i,t.cellularBars=r[2];continue}let o=/^Operator Name:\s*(.*)$/.exec(i);if(o){t.operatorName=o[1]??"";continue}}return 0===Object.keys(t).length?null:t}(i.stdout)}async function eA(e){await c(e,["status_bar",e.id,"clear"],void 0)}async function eI(e,t){0!==t.length&&await c(e,["status_bar",e.id,"override",...t],void 0)}function e_(e,t,i){T({level:"warn",phase:`ios_screenshot_status_bar_${t}`,data:{platform:e.platform,deviceKind:e.kind,deviceId:e.id,...eu(i)}})}let ev={ensureBooted:B,prepareStatusBarForScreenshot:em,captureWithRetry:eb,captureWithRunner:eN,shouldFallbackToRunner:eP};async function eg(e,t,i,a,r){if("macos"===e.platform)return void await eN(e,t,i,a,r);if("simulator"===e.kind)return void await eC(e,t,i,a,void 0,r);try{await h(["device","screenshot","--device",e.id,t],{action:"capture iOS screenshot",deviceId:e.id});return}catch(t){if(!function(e){if(!(e instanceof n)||"COMMAND_FAILED"!==e.code)return!1;let t=e.details??{},i="string"==typeof t.stdout?t.stdout:"",a="string"==typeof t.stderr?t.stderr:"",r=`${e.message}
|
|
2
2
|
${i}
|
|
3
|
-
${a}`.toLowerCase();return r.includes("unknown option '--device'")||r.includes("unknown subcommand")&&r.includes("screenshot")||r.includes("unrecognized subcommand")&&r.includes("screenshot")}(t))throw t;eM(e,"devicectl_screenshot",t)}await eN(e,t,i,a,r)}async function eC(e,t,i,a,r=
|
|
3
|
+
${a}`.toLowerCase();return r.includes("unknown option '--device'")||r.includes("unknown subcommand")&&r.includes("screenshot")||r.includes("unrecognized subcommand")&&r.includes("screenshot")}(t))throw t;eM(e,"devicectl_screenshot",t)}await eN(e,t,i,a,r)}async function eC(e,t,i,a,r=ev,o){if("simulator"!==e.kind)throw new n("UNSUPPORTED_OPERATION","Simulator screenshot fallback flow supports only iOS simulators");let l="object"==typeof a&&null!==a?a:r;await l.ensureBooted(e);let s=async()=>{};try{s=await l.prepareStatusBarForScreenshot(e)}catch(t){eO(e,"prepare_failed",t)}try{try{await l.captureWithRetry(e,t);return}catch(t){if(!l.shouldFallbackToRunner(t))throw t;eM(e,"simctl_screenshot",t)}await l.captureWithRunner(e,t,i,"boolean"==typeof a?a:void 0,o)}finally{await s().catch(t=>eO(e,"restore_failed",t))}}async function eb(e,t){let i=k.fromTimeoutMs(2e4);await E(async({deadline:i})=>{var a;await (a=["io",e.id,"screenshot",t],c(e,a,{timeoutMs:Math.max(1e3,i?.remainingMs()??2e4)}))},{maxAttempts:5,baseDelayMs:1e3,maxDelayMs:5e3,jitter:.2,shouldRetry:e=>eP(e)},{deadline:i,phase:"ios_simulator_screenshot"})}async function eN(e,i,a,r,o){let l=(await d(e,{command:"screenshot",appBundleId:a,fullscreen:r},o)).message;if(!l)throw new n("COMMAND_FAILED","Failed to capture iOS screenshot: runner returned no file path");"macos"===e.platform?await t.copyFile(l,i):"simulator"===e.kind?await eL(e,l,i):await eS(e,l,i)}async function eS(e,t,i){let a=k.fromTimeoutMs(2e4),r={exitCode:1,stdout:"",stderr:""};for(let n of g)if(0===(r=await o(["devicectl","device","copy","from","--device",e.id,"--source",t,"--destination",i,"--domain-type","appDataContainer","--domain-identifier",n],{allowFailure:!0,timeoutMs:eD(a,2e4,"runner screenshot copy")})).exitCode)return;let l=r.stderr.trim()||r.stdout.trim()||`devicectl exited with code ${r.exitCode}`;throw new n("COMMAND_FAILED",`Failed to capture iOS screenshot: ${l}`)}async function eL(e,i,r){let o=k.fromTimeoutMs(2e4),l="Unable to locate runner container for simulator screenshot";for(let n of g){var s;let d=await (s=["get_app_container",e.id,n,"data"],c(e,s,{allowFailure:!0,timeoutMs:eD(o,2e4,"runner screenshot container lookup")}));if(0!==d.exitCode){let e=d.stderr.trim();e&&(l=e);continue}let u=d.stdout.trim();if(!u){l="simctl get_app_container returned empty output";continue}for(let e of function(e,t){let i=a.resolve(e),r=t.trim();if(!r)return[];let n=[],o=new Set,l=e=>{let t=a.normalize(e);o.has(t)||(o.add(t),n.push(t))},s=r.replace(/^\/+/,""),d=s.replace(/\\/g,"/");if(s&&l(a.join(i,s)),a.isAbsolute(r)&&l(a.normalize(r)),d.startsWith("tmp/"))l(a.join(i,d));else{let e=d.lastIndexOf("/tmp/");if(e>=0){let t=d.slice(e+1);l(a.join(i,t))}}let u=a.basename(r);return u&&l(a.join(i,"tmp",u)),n}(u,i))try{await t.copyFile(e,r);return}catch(e){l=e instanceof Error?e.message:String(e)}}throw new n("COMMAND_FAILED",`Failed to capture iOS screenshot: ${l}`)}function eD(e,t,i){let a=e.remainingMs();if(a>0)return a;throw new n("COMMAND_FAILED",`iOS ${i} timed out after ${t}ms`,{timeoutMs:t,step:i})}function eM(e,t,i){let a=eu(i);T({level:"warn",phase:"ios_screenshot_fallback",data:{platform:e.platform,deviceKind:e.kind,deviceId:e.id,from:t,to:"runner",...a}})}function eO(e,t,i){T({level:"warn",phase:`ios_screenshot_status_bar_${t}`,data:{platform:e.platform,deviceKind:e.kind,deviceId:e.id,...eu(i)}})}function eP(e){if(!(e instanceof n)||"COMMAND_FAILED"!==e.code)return!1;let t=e.details??{},i="string"==typeof t.stdout?t.stdout:"",a="string"==typeof t.stderr?t.stderr:"",r=Array.isArray(t.args)?t.args.filter(e=>"string"==typeof e).join(" "):"",o=`${e.message}
|
|
4
4
|
${i}
|
|
5
5
|
${a}
|
|
6
|
-
${r}`.toLowerCase();return o.includes("timeout waiting for screen surfaces")||o.includes("nsposixerrordomain")&&o.includes("code=60")&&o.includes("screenshot")||o.includes("timed out")&&o.includes("screenshot")}let eF={settings:"com.apple.Preferences"},
|
|
7
|
-
${o}`.toLowerCase()))throw new n("COMMAND_FAILED",`Failed to uninstall iOS app ${i}`,{cmd:"xcrun",args:t,exitCode:a.exitCode,stdout:r,stderr:o,deviceId:e.id,hint:
|
|
8
|
-
${a.stderr}`.toLowerCase()))throw new n("COMMAND_FAILED",`simctl uninstall failed for ${i}`,{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode});return{bundleId:i}})}async function
|
|
9
|
-
`,"utf8"),await eE(e,["push",e.id,r,l])}finally{await t.rm(o,{recursive:!0,force:!0})}}async function eX(e,t,i,a,r){if("macos"===e.platform){let e=t.toLowerCase();if("appearance"===e)return void await el(i);if("permission"===e){let e=
|
|
10
|
-
${t}`);if(!i)return null;let a=i[1]?.toLowerCase();return"dark"===a?"dark":"light"===a?"light":null}(a.stdout,a.stderr);if(!r)throw new n("COMMAND_FAILED","Unable to determine current iOS appearance for toggle",{stdout:a.stdout,stderr:a.stderr});return"dark"===r?"light":"dark"}let e4={faceid:{label:"Face ID",modalityAliases:["face"]},touchid:{label:"Touch ID",modalityAliases:["finger","touch"]}};async function e5(e,t,i,a){let r=await e9(e);if(!r.has(i))throw new n("UNSUPPORTED_OPERATION",`iOS simctl privacy does not support service "${i}" on this runtime.`,{deviceId:e.id,appBundleId:a,hint:`Supported services: ${Array.from(r).sort().join(", ")}`});let o=["privacy",e.id,t,i,a],l="notifications"===i;if(!("reset"===t&&l))try{await eE(e,o);return}catch(t){if(!(l&&e8(t)))throw t;throw new n("UNSUPPORTED_OPERATION","iOS simulator does not support setting notifications permission via simctl privacy on this runtime.",{deviceId:e.id,appBundleId:a,hint:"Use reset notifications for reprompt behavior, or toggle notifications manually in Settings."})}try{await eE(e,o);return}catch(e){if(!e8(e))throw e}try{await eE(e,["privacy",e.id,"reset","all",a])}catch(t){throw new n("COMMAND_FAILED","iOS simulator blocked direct notifications reset. Fallback reset-all also failed.",{deviceId:e.id,appBundleId:a,hint:"Use reinstall to force a fresh notifications prompt, or reset simulator content and settings."},t instanceof Error?t:void 0)}}function e8(e){if(!(e instanceof n)||"COMMAND_FAILED"!==e.code)return!1;let t=String(e.details?.stderr??"").toLowerCase();return(t.includes("failed to grant access")||t.includes("failed to revoke access")||t.includes("failed to reset access"))&&t.includes("operation not permitted")}async function e9(t){let i=
|
|
11
|
-
${r.stderr}`);if(0===o.size)throw new n("COMMAND_FAILED","Unable to determine supported simctl privacy services",{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode,hint:"Run `xcrun simctl privacy help` manually to verify available services for this runtime."});return
|
|
12
|
-
${i}`.toLowerCase()).includes("unrecognized subcommand")||a.includes("unknown subcommand")||a.includes("not supported")||a.includes("unavailable")||a.includes("biometric")&&a.includes("invalid")}))throw new n("UNSUPPORTED_OPERATION",`${i.label} simulation is not supported on this simulator runtime.`,{deviceId:e.id,action:t,setting:i.settingName,attempts:l});throw new n("COMMAND_FAILED",`Failed to simulate ${i.settingName}.`,{deviceId:e.id,action:t,setting:i.settingName,attempts:l})}async function e6(e,t,i){await
|
|
13
|
-
${n}`),"utf8")}async function ti(e,t,i){let a=["device","process","launch","--device",e.id,t];i?.payloadUrl&&a.push("--payload-url",i.payloadUrl),i?.launchArgs&&i.launchArgs.length>0&&a.push("--",...i.launchArgs),await
|
|
6
|
+
${r}`.toLowerCase();return o.includes("timeout waiting for screen surfaces")||o.includes("nsposixerrordomain")&&o.includes("code=60")&&o.includes("screenshot")||o.includes("timed out")&&o.includes("screenshot")}let eF={settings:"com.apple.Preferences"},eR=F(),ex=null;function e$(e){return{platform:"ios",deviceId:e.id,variant:e.kind}}function eE(e,t,i){return o(w(e,t),i)}function ek(e){return e.includes("not installed")||e.includes("not found")||e.includes("no such file")}async function eT(e,t){if("macos"===e.platform)return await et(t);let i=t.trim();if(i.includes("."))return i;let a=eF[i.toLowerCase()];if(a)return a;let r=e$(e),o=eR.get(r,i);if(o)return o;let l=("simulator"===e.kind?await e0(e):await I(e,"all")).filter(e=>e.name.toLowerCase()===i.toLowerCase()),s=l[0];if(void 0!==s&&1===l.length)return eR.set(r,i,s.bundleId);if(l.length>1)throw new n("INVALID_ARGS",`Multiple apps matched "${t}"`,{matches:l});throw new n("APP_NOT_INSTALLED",`No app found matching "${t}"`)}async function eU(e,t){var i;let r;if("ios"!==e.platform||"simulator"!==e.kind)return;let n=(i=t,r=/^([A-Za-z][A-Za-z0-9+.-]*):/.exec(i.trim()),r?.[1]?.toLowerCase());if(!n)return;let o=await e1(e),l=[];for(let e of o)!e.bundleId.startsWith("com.callstack.agentdevice.runner")&&e.path&&(await e2(a.join(e.path,"Info.plist"))).has(n)&&l.push(e);let s=l.filter(e=>"User"===e.applicationType);return 1===s.length?s[0]?.bundleId:s.length>1?void 0:1===l.length?l[0]?.bundleId:void 0}async function eB(e,t,i){let a=i?.launchConsole?.trim(),r=i?.launchArgs;if(a&&("ios"!==e.platform||"simulator"!==e.kind))throw new n("UNSUPPORTED_OPERATION",v);if("macos"===e.platform){if(r&&r.length>0)throw new n("UNSUPPORTED_OPERATION","--launch-args is not supported on macOS; launch arguments are currently iOS-only.");await ei(e,t,i);return}let o=i?.url?.trim();if(o){if(a)throw new n("INVALID_ARGS",s);if(!R(o))throw new n("INVALID_ARGS","open <app> <url> requires a valid URL target");if("simulator"===e.kind){if(r||P(o)){let a=i?.appBundleId??await eT(e,t);await e6(e,a,{...r?{launchArgs:r}:{}})}await eG(e,o,void 0);return}let l=$(i?.appBundleId??await eT(e,t),o);if(!l)throw new n("INVALID_ARGS","Deep link open on iOS devices requires an active app bundle ID. Open the app first, then open the URL.");await ti(e,l,{payloadUrl:o,launchArgs:r});return}let l=t.trim();if(R(l)){if(a)throw new n("INVALID_ARGS",s);if("simulator"===e.kind)return void await eG(e,l,r);let t=$(i?.appBundleId,l);if(!t)throw new n("INVALID_ARGS","Deep link open on iOS devices requires an active app bundle ID. Open the app first, then open the URL.");return void await ti(e,t,{payloadUrl:l,launchArgs:r})}let d=i?.appBundleId??await eT(e,t);"simulator"===e.kind?await e6(e,d,{...a?{launchConsole:a}:{},...r?{launchArgs:r}:{}}):await ti(e,d,{launchArgs:r})}async function eG(e,t,i){if(i&&i.length>0)throw new n("INVALID_ARGS","--launch-args is not supported with iOS simulator URL opens (simctl openurl ignores launch args). Launch the app first with --launch-args, then issue the URL open in a separate call.");await B(e),await eE(e,["openurl",e.id,t])}async function eV(e){"macos"===e.platform||"simulator"!==e.kind||"Booted"!==await G(e)&&await B(e)}async function ej(e,t){if("macos"===e.platform)return void await ea(e,t);let i=await eT(e,t);if("simulator"===e.kind){await B(e);let t=w(e,["terminate",e.id,i]),a=await o(t,{allowFailure:!0,timeoutMs:15e3});if(0!==a.exitCode){if(a.stderr.toLowerCase().includes("found nothing to terminate"))return;throw new n("COMMAND_FAILED",`xcrun exited with code ${a.exitCode}`,{cmd:"xcrun",args:t,stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode})}return}await h(["device","process","terminate","--device",e.id,i],{action:"terminate iOS app",deviceId:e.id})}async function eW(e,i){if("ios"!==e.platform||"simulator"!==e.kind)throw new n("UNSUPPORTED_OPERATION","Clearing app state is currently supported only on iOS simulators.");let r=await eT(e,i);await B(e),await ej(e,r);let o=await eE(e,["get_app_container",e.id,r,"data"],{allowFailure:!0});if(0!==o.exitCode)throw new n("COMMAND_FAILED",`simctl get_app_container failed for ${r}`,{stdout:o.stdout,stderr:o.stderr,exitCode:o.exitCode});let l=o.stdout.trim();if(!l)throw new n("COMMAND_FAILED",`simctl get_app_container returned an empty data container path for ${r}`);let s=await t.readdir(l);return await Promise.all(s.map(e=>t.rm(a.join(l,e),{recursive:!0,force:!0}))),{bundleId:r,containerPath:l}}async function eK(e,t){return await eR.invalidateWhile(e$(e),async()=>{let i=await eT(e,t);if("simulator"!==e.kind){let t=["devicectl","device","uninstall","app","--device",e.id,i],a=await o(t,{allowFailure:!0,timeoutMs:2e4});if(0!==a.exitCode){let r=String(a.stdout??""),o=String(a.stderr??"");if(!ek(`${r}
|
|
7
|
+
${o}`.toLowerCase()))throw new n("COMMAND_FAILED",`Failed to uninstall iOS app ${i}`,{cmd:"xcrun",args:t,exitCode:a.exitCode,stdout:r,stderr:o,deviceId:e.id,hint:l(r,o)??p})}return{bundleId:i}}await B(e);let a=await eE(e,["uninstall",e.id,i],{allowFailure:!0});if(0!==a.exitCode&&!ek(`${a.stdout}
|
|
8
|
+
${a.stderr}`.toLowerCase()))throw new n("COMMAND_FAILED",`simctl uninstall failed for ${i}`,{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode});return{bundleId:i}})}async function eH(e,t,i){let a=await H({kind:"path",path:t},i);try{return await eq(e,a.installablePath),{archivePath:a.archivePath,installablePath:a.installablePath,bundleId:a.bundleId,appName:a.appName,launchTarget:a.bundleId}}finally{await a.cleanup()}}async function ez(e,t,i){return await eR.invalidateWhile(e$(e),async()=>{let{bundleId:a}=await eK(e,t);return await eH(e,i,{appIdentifierHint:t}),{bundleId:a}})}async function eq(e,t){await eR.invalidateWhile(e$(e),async()=>{"simulator"!==e.kind?await h(["device","install","app","--device",e.id,t],{action:"install iOS app",deviceId:e.id}):(await B(e),await eE(e,["install",e.id,t]))})}async function eJ(e){if("macos"===e.platform)return await er();U(e,"clipboard"),await B(e);let t=await eE(e,["pbpaste",e.id],{allowFailure:!0});if(0!==t.exitCode)throw new n("COMMAND_FAILED","Failed to read iOS simulator clipboard",{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode});return t.stdout.replace(/\r\n/g,"\n").replace(/\n$/,"")}async function eZ(e,t){if("macos"===e.platform)return void await en(t);U(e,"clipboard"),await B(e);let i=await eE(e,["pbcopy",e.id],{allowFailure:!0,stdin:t});if(0!==i.exitCode)throw new n("COMMAND_FAILED","Failed to write iOS simulator clipboard",{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode})}async function eQ(e,r,n){U(e,"push"),await B(e);let o=await t.mkdtemp(a.join(i.tmpdir(),"agent-device-ios-push-")),l=a.join(o,"payload.apns");try{await t.writeFile(l,`${JSON.stringify(n)}
|
|
9
|
+
`,"utf8"),await eE(e,["push",e.id,r,l])}finally{await t.rm(o,{recursive:!0,force:!0})}}async function eX(e,t,i,a,r){if("macos"===e.platform){let e=t.toLowerCase();if("appearance"===e)return void await el(i);if("permission"===e){let e=O(i);if("deny"===e)throw new n("INVALID_ARGS",V("permission"));let t=function(e){let t=e?.trim().toLowerCase();if("accessibility"===t||"screen-recording"===t||"input-monitoring"===t)return t;throw new n("INVALID_ARGS","Unsupported macOS permission target. Use accessibility|screen-recording|input-monitoring.")}(r?.permissionTarget);return await m(e,t)}throw new n("INVALID_ARGS",V(t))}U(e,"settings"),await B(e);let o=t.toLowerCase();switch(o){case"clear-app-state":{if("clear"!==i.toLowerCase())throw new n("INVALID_ARGS","settings clear-app-state only supports clear.");if(!a)throw new n("INVALID_ARGS","settings clear-app-state requires an app id or an active app session.");let t=await eW(e,a);return{bundleId:t.bundleId,containerPath:t.containerPath,cleared:!0}}case"wifi":{let t=D(i);await eE(e,["status_bar",e.id,"override","--wifiMode",t?"active":"failed"]);return}case"airplane":return void(D(i)?await eE(e,["status_bar",e.id,"override","--dataNetwork","hide","--wifiMode","failed","--wifiBars","0","--cellularMode","failed","--cellularBars","0","--operatorName",""]):await eE(e,["status_bar",e.id,"clear"]));case"location":{if("set"===i.toLowerCase()){let{latitude:t,longitude:i}=j(r);return await eE(e,["location",e.id,"set",`${t},${i}`]),{latitude:t,longitude:i}}let t=D(i);if(!a)throw new n("INVALID_ARGS","location setting requires an active app in session");await eE(e,["privacy",e.id,t?"grant":"revoke","location",a]);return}case"faceid":case"touchid":{let t=e4[o],a=function(e,t){let i=e.trim().toLowerCase();if("match"===i)return"match";if("nonmatch"===i)return"nonmatch";if("enroll"===i)return"enroll";if("unenroll"===i)return"unenroll";throw new n("INVALID_ARGS",`Invalid ${t} state: ${e}. Use match|nonmatch|enroll|unenroll.`)}(i,o);await e7(e,a,{settingName:o,label:t.label,modalityAliases:t.modalityAliases});return}case"appearance":{let t=await e3(e,i);await eE(e,["ui",e.id,"appearance",t]);return}case"permission":{var l;if(!a)throw new n("INVALID_ARGS","permission setting requires an active app in session");let t="deny"===(l=O(i))?"revoke":l,o=function(e,t){let i=M(e);if("photos"!==i&&t?.trim())throw new n("INVALID_ARGS",`Permission mode is only supported for photos. Received: ${t}.`);if("camera"===i)return"camera";if("microphone"===i)return"microphone";if("contacts"===i)return"contacts";if("contacts-limited"===i)return"contacts-limited";if("notifications"===i)return"notifications";if("calendar"===i)return"calendar";if("location"===i)return"location";if("location-always"===i)return"location-always";if("media-library"===i)return"media-library";if("motion"===i)return"motion";if("reminders"===i)return"reminders";if("siri"===i)return"siri";if("photos"===i){let e=t?.trim().toLowerCase();if(!e||"full"===e)return"photos";if("limited"===e)return"photos-add";throw new n("INVALID_ARGS",`Invalid photos mode: ${t}. Use full|limited.`)}throw new n("INVALID_ARGS",`Unsupported permission target: ${e}. Use camera|microphone|photos|contacts|contacts-limited|notifications|calendar|location|location-always|media-library|motion|reminders|siri.`)}(r?.permissionTarget,r?.permissionMode);await e5(e,t,o,a);return}default:throw new n("INVALID_ARGS",`Unsupported setting: ${t}`)}}async function eY(e,t){return"macos"===e.platform?await es(t):"simulator"===e.kind?y(await e0(e),t):await I(e,t)}async function e0(e){return(await e1(e)).map(e=>({bundleId:e.bundleId,name:e.name}))}async function e1(e){let t=(await eE(e,["listapps",e.id],{allowFailure:!0})).stdout.trim();if(!t)return[];let i=null;if(t.startsWith("{"))try{i=JSON.parse(t)}catch{i=null}if(!i&&t.startsWith("{"))try{let e=await A("plutil",["-convert","json","-o","-","-"],{allowFailure:!0,stdin:t});0===e.exitCode&&e.stdout.trim().startsWith("{")&&(i=JSON.parse(e.stdout))}catch{i=null}return i?Object.entries(i).map(([e,t])=>{let i=function(e){if(e.Path)return e.Path;if(e.Bundle)try{return r(e.Bundle)}catch{return}}(t);return{bundleId:e,name:t.CFBundleDisplayName??t.CFBundleName??e,...i?{path:i}:{},...t.ApplicationType?{applicationType:t.ApplicationType}:{}}}):[]}async function e2(e){let t=await A("plutil",["-convert","json","-o","-",e],{allowFailure:!0});if(0!==t.exitCode)return new Set;try{let e=JSON.parse(t.stdout),i=new Set;for(let t of e.CFBundleURLTypes??[])if(Array.isArray(t.CFBundleURLSchemes))for(let e of t.CFBundleURLSchemes)"string"==typeof e&&e.trim()&&i.add(e.trim().toLowerCase());return i}catch{return new Set}}async function e3(e,t){let i=S(t);if("toggle"!==i)return i;let a=await eE(e,["ui",e.id,"appearance"],{allowFailure:!0});if(0!==a.exitCode)throw new n("COMMAND_FAILED","Failed to read current iOS appearance",{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode});let r=function(e,t){let i=/\b(light|dark|unsupported|unknown)\b/i.exec(`${e}
|
|
10
|
+
${t}`);if(!i)return null;let a=i[1]?.toLowerCase();return"dark"===a?"dark":"light"===a?"light":null}(a.stdout,a.stderr);if(!r)throw new n("COMMAND_FAILED","Unable to determine current iOS appearance for toggle",{stdout:a.stdout,stderr:a.stderr});return"dark"===r?"light":"dark"}let e4={faceid:{label:"Face ID",modalityAliases:["face"]},touchid:{label:"Touch ID",modalityAliases:["finger","touch"]}};async function e5(e,t,i,a){let r=await e9(e);if(!r.has(i))throw new n("UNSUPPORTED_OPERATION",`iOS simctl privacy does not support service "${i}" on this runtime.`,{deviceId:e.id,appBundleId:a,hint:`Supported services: ${Array.from(r).sort().join(", ")}`});let o=["privacy",e.id,t,i,a],l="notifications"===i;if(!("reset"===t&&l))try{await eE(e,o);return}catch(t){if(!(l&&e8(t)))throw t;throw new n("UNSUPPORTED_OPERATION","iOS simulator does not support setting notifications permission via simctl privacy on this runtime.",{deviceId:e.id,appBundleId:a,hint:"Use reset notifications for reprompt behavior, or toggle notifications manually in Settings."})}try{await eE(e,o);return}catch(e){if(!e8(e))throw e}try{await eE(e,["privacy",e.id,"reset","all",a])}catch(t){throw new n("COMMAND_FAILED","iOS simulator blocked direct notifications reset. Fallback reset-all also failed.",{deviceId:e.id,appBundleId:a,hint:"Use reinstall to force a fresh notifications prompt, or reset simulator content and settings."},t instanceof Error?t:void 0)}}function e8(e){if(!(e instanceof n)||"COMMAND_FAILED"!==e.code)return!1;let t=String(e.details?.stderr??"").toLowerCase();return(t.includes("failed to grant access")||t.includes("failed to revoke access")||t.includes("failed to reset access"))&&t.includes("operation not permitted")}async function e9(t){let i=x(t.simulatorSetPath),a=`${process.env.PATH??""}::${i??""}`;if(ex&&e===a)return ex;let r=await eE(t,["privacy","help"],{allowFailure:!0}),o=function(e){let t=new Set,i=!1;for(let a of e.split("\n")){let e=a.trim();if(!e)continue;if("service"===e){i=!0;continue}if(!i)continue;if(e.startsWith("bundle identifier"))break;let r=/^([a-z-]+)\s+-\s+/.exec(e),n=r?.[1];void 0!==n&&t.add(n)}return t}(`${r.stdout}
|
|
11
|
+
${r.stderr}`);if(0===o.size)throw new n("COMMAND_FAILED","Unable to determine supported simctl privacy services",{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode,hint:"Run `xcrun simctl privacy help` manually to verify available services for this runtime."});return ex=o,e=a,o}async function e7(e,t,i){let a=function(e,t,i){let a=i.length>0?i:["face"];switch(t){case"match":return a.flatMap(t=>[["biometric",e,"match",t],["biometric","match",e,t]]);case"nonmatch":return a.flatMap(t=>[["biometric",e,"nonmatch",t],["biometric",e,"nomatch",t],["biometric","nonmatch",e,t],["biometric","nomatch",e,t]]);case"enroll":return[["biometric",e,"enroll","yes"],["biometric",e,"enroll","1"],["biometric","enroll",e,"yes"],["biometric","enroll",e,"1"]];case"unenroll":return[["biometric",e,"enroll","no"],["biometric",e,"enroll","0"],["biometric","enroll",e,"no"],["biometric","enroll",e,"0"]]}}(e.id,t,i.modalityAliases),r=[];for(let t of a){let i=w(e,t),a=await o(i,{allowFailure:!0});if(0===a.exitCode)return;r.push({args:i,stderr:a.stderr,stdout:a.stdout,exitCode:a.exitCode})}let l=L(r);if(r.length>0&&r.every(e=>{var t,i;let a;return t=e.stdout,i=e.stderr,(a=`${t}
|
|
12
|
+
${i}`.toLowerCase()).includes("unrecognized subcommand")||a.includes("unknown subcommand")||a.includes("not supported")||a.includes("unavailable")||a.includes("biometric")&&a.includes("invalid")}))throw new n("UNSUPPORTED_OPERATION",`${i.label} simulation is not supported on this simulator runtime.`,{deviceId:e.id,action:t,setting:i.settingName,attempts:l});throw new n("COMMAND_FAILED",`Failed to simulate ${i.settingName}.`,{deviceId:e.id,action:t,setting:i.settingName,attempts:l})}async function e6(e,t,i){await B(e);let a=0,r=k.fromTimeoutMs(6e4);try{await E(async({deadline:a})=>{var r,l,s,d;let u;if(a?.isExpired())throw new n("COMMAND_FAILED","App launch deadline exceeded",{timeoutMs:6e4});let c=(l=e.id,s=t,d=i,u=["launch"],d?.launchConsole&&u.push("--console-pty"),u.push(l,s),d?.launchArgs&&d.launchArgs.length>0&&u.push(...d.launchArgs),r=u,w(e,r)),p=i?.launchConsole?await te(c,i.launchConsole):await o(c,{allowFailure:!0});if(0!==p.exitCode)throw new n("COMMAND_FAILED",`xcrun exited with code ${p.exitCode}`,{cmd:"xcrun",args:c,stdout:p.stdout,stderr:p.stderr,exitCode:p.exitCode})},{maxAttempts:10,baseDelayMs:1e3,maxDelayMs:5e3,jitter:.2,shouldRetry:e=>!!W(e)&&(a+=1)<3},{deadline:r})}catch(i){if(W(i)){var l;let a=(l=await K(e,t)).installed?!1===l.simulatorCompatible?"ARCH_MISMATCH":"PERSISTENT_LAUNCH_FAIL":"APP_NOT_INSTALLED";i.details={...i.details,hint:function(e){switch(e){case"ARCH_MISMATCH":return"The app binary was not built for the simulator platform. Rebuild with a simulator destination or use a physical device.";case"APP_NOT_INSTALLED":return"The app bundle is not installed on this simulator. Run install before open.";case"PERSISTENT_LAUNCH_FAIL":return"The simulator repeatedly refused to launch the app. Inspect crash logs in Console.app or ~/Library/Logs/DiagnosticReports/ and consider reinstalling the app.";default:return"The simulator failed to launch the app. Retry with --debug and inspect diagnostics log for details."}}(a)}}throw i}}async function te(e,i){await t.mkdir(a.dirname(i),{recursive:!0});try{let t=await o(e,{allowFailure:!0,timeoutMs:25e3});return await tt(i,t.stdout,t.stderr),t}catch(t){let e=(t instanceof n?t:void 0)?.details;if(e?.timeoutMs===25e3){let t="string"==typeof e.stdout?e.stdout:"",a="string"==typeof e.stderr?e.stderr:"";return await tt(i,t,a),T({level:"warn",phase:"ios_simulator_launch_console_capture_timeout",data:{timeoutMs:25e3,logPath:i,stdoutBytes:Buffer.byteLength(t),stderrBytes:Buffer.byteLength(a)}}),{stdout:t,stderr:a,exitCode:0}}throw t}}async function tt(e,i,a){var r,n;await t.writeFile(e,(r=i,n=a,!r||!n||r.endsWith("\n")||r.endsWith("\r")?`${r}${n}`:`${r}
|
|
13
|
+
${n}`),"utf8")}async function ti(e,t,i){let a=["device","process","launch","--device",e.id,t];i?.payloadUrl&&a.push("--payload-url",i.payloadUrl),i?.launchArgs&&i.launchArgs.length>0&&a.push("--",...i.launchArgs),await h(a,{action:"launch iOS app",deviceId:e.id})}export{ej as closeIosApp,eH as installIosApp,eq as installIosInstallablePath,eY as listIosApps,eB as openIosApp,eV as openIosDevice,H as prepareIosInstallArtifact,eQ as pushIosNotification,eJ as readIosClipboardText,ez as reinstallIosApp,eT as resolveIosApp,eU as resolveIosSimulatorDeepLinkBundleId,eg as screenshotIos,eX as setIosSetting,eZ as writeIosClipboardText};
|