agent-device 0.11.15 → 0.11.16
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/dist/src/152.js +1 -0
- package/dist/src/155.js +38 -0
- package/dist/src/164.js +1 -0
- package/dist/src/267.js +1 -0
- package/dist/src/556.js +1 -0
- package/dist/src/57.js +1 -0
- package/dist/src/818.js +1 -3
- package/dist/src/924.js +1 -1
- package/dist/src/940.js +1 -0
- package/dist/src/974.js +2 -2
- package/dist/src/artifacts.d.ts +3 -0
- package/dist/src/artifacts.js +1 -0
- package/dist/src/bin.js +23 -23
- package/dist/src/contracts.d.ts +59 -0
- package/dist/src/contracts.js +1 -1
- package/dist/src/daemon.js +15 -18
- package/dist/src/finders.d.ts +75 -0
- package/dist/src/finders.js +1 -0
- package/dist/src/index.d.ts +6 -4
- package/dist/src/index.js +3 -2
- package/dist/src/install-source.d.ts +40 -0
- package/dist/src/install-source.js +1 -0
- package/dist/src/metro.d.ts +6 -0
- package/dist/src/metro.js +1 -1
- package/dist/src/selectors.d.ts +110 -0
- package/dist/src/selectors.js +1 -0
- package/package.json +17 -1
- package/dist/src/760.js +0 -33
- package/dist/src/957.js +0 -2
package/dist/src/164.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"node:fs";import o from"node:os";import t from"node:path";function e(n=process.env){let r=n.ANDROID_SDK_ROOT?.trim(),i=n.ANDROID_HOME?.trim(),d=n.HOME?.trim()||o.homedir();return function(o){let t=new Set,e=[];for(let n of o){let o=n.trim();!o||t.has(o)||(t.add(o),e.push(o))}return e}([r??"",i??"",d?t.join(d,"Android","Sdk"):""])}t.join("cmdline-tools","latest","bin"),t.join("cmdline-tools","tools","bin");export{e as resolveAndroidSdkRoots};
|
package/dist/src/267.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import e from"node:os";import r from"node:path";function o(r){return r?.HOME?.trim()||e.homedir()}function t(e,n={}){return"~"===e?o(n.env):e.startsWith("~/")?r.join(o(n.env),e.slice(2)):e}function n(e,o={}){let s=t(e,o);return r.isAbsolute(s)?s:r.resolve(o.cwd??process.cwd(),s)}export{t as expandUserHomePath,n as resolveUserPath};
|
package/dist/src/556.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{AppError as e}from"./152.js";function t(e,l,o,u={}){let c=i(o);if(!c)return{matches:[],score:0};let a=0,s=[];for(let t of e){if(u.requireRect&&!t.rect)continue;let e=function(e,t,i){switch(t){case"role":return function(e,t){let r=n(e??"");return r?r===t?2:+!!r.includes(t):0}(e.type,i);case"label":return r(e.label,i);case"value":return r(e.value,i);case"id":return r(e.identifier,i);default:return Math.max(r(e.label,i),r(e.value,i),r(e.identifier,i))}}(t,l,c);if(!(e<=0)){if(e>a){a=e,s.length=0,s.push(t);continue}e===a&&s.push(t)}}return{matches:s,score:a}}function r(e,t){let r=i(e??"");return r?r===t?2:+!!r.includes(t):0}function i(e){return e.trim().toLowerCase().replace(/\s+/g," ")}function n(e){let t=e.trim();return t?t=(t.split(".").pop()??t).replace(/XCUIElementType/gi,"").toLowerCase():""}function l(t){let r="any",i=0;["text","label","value","role","id"].includes(t[0])&&(r=t[0],i=1);let n=t[i]??"",l=t.slice(i+1);if(0===l.length)return{locator:r,query:n,action:"click"};let o=l[0].toLowerCase();if("get"===o){let t=l[1]?.toLowerCase();if("text"===t)return{locator:r,query:n,action:"get_text"};if("attrs"===t)return{locator:r,query:n,action:"get_attrs"};throw new e("INVALID_ARGS","find get only supports text or attrs")}if("wait"===o)return{locator:r,query:n,action:"wait",timeoutMs:function(e){if(!e)return null;let t=Number(e);return Number.isFinite(t)?t:null}(l[1])??void 0};if("exists"===o)return{locator:r,query:n,action:"exists"};if("click"===o)return{locator:r,query:n,action:"click"};if("focus"===o)return{locator:r,query:n,action:"focus"};if("fill"===o)return{locator:r,query:n,action:"fill",value:l.slice(1).join(" ")};if("type"===o)return{locator:r,query:n,action:"type",value:l.slice(1).join(" ")};throw new e("INVALID_ARGS",`Unsupported find action: ${l[0]}`)}export{t as findBestMatchesByLocator,n as normalizeRole,i as normalizeText,l as parseFindArgs};
|
package/dist/src/57.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function t(t){return{x:Math.round(t.x+t.width/2),y:Math.round(t.y+t.height/2)}}export{t as centerOfRect};
|
package/dist/src/818.js
CHANGED
|
@@ -1,3 +1 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`;try{t.logPath&&r.appendFile(t.logPath,o,()=>{}),t.traceLogPath&&r.appendFile(t.traceLogPath,o,()=>{}),t.logPath||t.traceLogPath||process.stderr.write(o)}catch{}}async function w(e,t,r){let n=Date.now();try{let o=await t();return h({level:"info",phase:e,durationMs:Date.now()-n,data:r}),o}catch(t){throw h({level:"error",phase:e,durationMs:Date.now()-n,data:{...r??{},error:t instanceof Error?t.message:String(t)}}),t}}function E(e={}){let t=l.getStore();if(!t||!e.force&&!t.debug||0===t.events.length)return null;try{let e=(t.session??"default").replace(/[^a-zA-Z0-9._-]/g,"_"),n=new Date().toISOString().slice(0,10),s=i.join(o.homedir(),".agent-device","logs",e,n);r.mkdirSync(s,{recursive:!0});let a=new Date().toISOString().replace(/[:.]/g,"-"),d=i.join(s,`${a}-${t.diagnosticId}.ndjson`),u=t.events.map(e=>JSON.stringify(S(e)));return r.writeFileSync(d,`${u.join("\n")}
|
|
3
|
-
`),t.events=[],d}catch{return null}}function S(e){return function e(t,r,n){if(null==t)return t;if("string"==typeof t){var o=t,i=n;let e=o.trim();if(!e)return o;if(i&&c.test(i)||f.test(e))return"[REDACTED]";let r=function(e){try{let t=new URL(e);return t.search&&(t.search="?REDACTED"),(t.username||t.password)&&(t.username="REDACTED",t.password="REDACTED"),t.toString()}catch{return null}}(e);return r||(e.length>400?`${e.slice(0,200)}...<truncated>`:e)}if("object"!=typeof t)return t;if(r.has(t))return"[Circular]";if(r.add(t),Array.isArray(t))return t.map(t=>e(t,r));let s={};for(let[n,o]of Object.entries(t)){if(c.test(n)){s[n]="[REDACTED]";continue}s[n]=e(o,r,n)}return s}(e,new WeakSet)}class D extends Error{code;details;cause;constructor(e,t,r,n){super(t),this.code=e,this.details=r,this.cause=n}}function A(e){return e instanceof D?e:e instanceof Error?new D("UNKNOWN",e.message,void 0,e):new D("UNKNOWN","Unknown error",{err:e})}function I(e,t={}){let r=A(e),n=r.details?S(r.details):void 0,o=n&&"string"==typeof n.hint?n.hint:void 0,i=(n&&"string"==typeof n.diagnosticId?n.diagnosticId:void 0)??t.diagnosticId,s=(n&&"string"==typeof n.logPath?n.logPath:void 0)??t.logPath,a=o??function(e){switch(e){case"INVALID_ARGS":return"Check command arguments and run --help for usage examples.";case"SESSION_NOT_FOUND":return"Run open first or pass an explicit device selector.";case"TOOL_MISSING":return"Install required platform tooling and ensure it is available in PATH.";case"DEVICE_NOT_FOUND":return"Verify the target device is booted/connected and selectors match.";case"APP_NOT_INSTALLED":return"Run apps to discover the exact installed package or bundle id, or install the app before open.";case"UNSUPPORTED_OPERATION":return"This command is not available for the selected platform/device.";case"COMMAND_FAILED":default:return"Retry with --debug and inspect diagnostics log for details.";case"UNAUTHORIZED":return"Refresh daemon metadata and retry the command."}}(r.code),d=function(e){if(!e)return;let t={...e};return delete t.hint,delete t.diagnosticId,delete t.logPath,Object.keys(t).length>0?t:void 0}(n),u=function(e,t,r){if("COMMAND_FAILED"!==e||r?.processExitError!==!0)return t;let n=function(e){let t=[/^an error was encountered processing the command/i,/^underlying error\b/i,/^simulator device failed to complete the requested operation/i];for(let r of e.split("\n")){let e=r.trim();if(e&&!t.some(t=>t.test(e)))return e.length>200?`${e.slice(0,200)}...`:e}return null}("string"==typeof r?.stderr?r.stderr:"");return n||t}(r.code,r.message,n);return{code:r.code,message:u,hint:a,diagnosticId:i,logPath:s,details:d}}let v=/^[A-Za-z0-9][A-Za-z0-9._+-]*$/,O=[".com",".exe",".bat",".cmd"];async function y(e,t,r={}){let n=L(e);return new Promise((o,i)=>{let s=d(n,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],detached:r.detached,shell:!1}),a="",u=r.binaryStdout?Buffer.alloc(0):void 0,l="",c=!1,f=b(r.timeoutMs),p=f?setTimeout(()=>{c=!0,s.kill("SIGKILL")},f):null;r.binaryStdout||s.stdout.setEncoding("utf8"),s.stderr.setEncoding("utf8"),void 0!==r.stdin&&s.stdin.write(r.stdin),s.stdin.end(),s.stdout.on("data",e=>{r.binaryStdout?u=Buffer.concat([u??Buffer.alloc(0),Buffer.isBuffer(e)?e:Buffer.from(e)]):a+=e}),s.stderr.on("data",e=>{l+=e}),s.on("error",r=>{(p&&clearTimeout(p),"ENOENT"===r.code)?i(new D("TOOL_MISSING",`${n} not found in PATH`,{cmd:e},r)):i(new D("COMMAND_FAILED",`Failed to run ${n}`,{cmd:e,args:t},r))}),s.on("close",s=>{p&&clearTimeout(p);let d=s??1;c&&f?i(new D("COMMAND_FAILED",`${n} timed out after ${f}ms`,{cmd:e,args:t,stdout:a,stderr:l,exitCode:d,timeoutMs:f})):0===d||r.allowFailure?o({stdout:a,stderr:l,exitCode:d,stdoutBuffer:u}):i(new D("COMMAND_FAILED",`${n} exited with code ${d}`,{cmd:e,args:t,stdout:a,stderr:l,exitCode:d,processExitError:!0}))})})}async function N(e){let t=C(e,{allowRelativePath:!1});if(!t)return!1;if(i.isAbsolute(t))return F(t);let r=process.env.PATH;if(!r)return!1;let n=function(){if("win32"!==process.platform)return[""];let e=process.env.PATHEXT;if(!e)return O;let t=e.split(";").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0);return t.length>0?t:O}();for(let e of r.split(i.delimiter)){let r=e.trim();if(r){for(let e of function(e,t){if("win32"!==process.platform)return[e];let r=e.toLowerCase();return t.some(e=>r.endsWith(e))?[e]:t.map(t=>`${e}${t}`)}(t,n))if(await F(i.join(r,e)))return!0}}return!1}function M(e,t,r={}){let n=L(e),o=u(n,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],encoding:r.binaryStdout?void 0:"utf8",input:r.stdin,timeout:b(r.timeoutMs),shell:!1});if(o.error){let i=o.error.code;if("ETIMEDOUT"===i)throw new D("COMMAND_FAILED",`${n} timed out after ${b(r.timeoutMs)}ms`,{cmd:e,args:t,timeoutMs:b(r.timeoutMs)},o.error);if("ENOENT"===i)throw new D("TOOL_MISSING",`${n} not found in PATH`,{cmd:e},o.error);throw new D("COMMAND_FAILED",`Failed to run ${n}`,{cmd:e,args:t},o.error)}let i=r.binaryStdout?Buffer.isBuffer(o.stdout)?o.stdout:Buffer.from(o.stdout??""):void 0,s=r.binaryStdout?"":"string"==typeof o.stdout?o.stdout:(o.stdout??"").toString(),a="string"==typeof o.stderr?o.stderr:(o.stderr??"").toString(),d=o.status??1;if(0!==d&&!r.allowFailure)throw new D("COMMAND_FAILED",`${n} exited with code ${d}`,{cmd:e,args:t,stdout:s,stderr:a,exitCode:d,processExitError:!0});return{stdout:s,stderr:a,exitCode:d,stdoutBuffer:i}}function T(e,t,r={}){let n=d(L(e),t,{cwd:r.cwd,env:r.env,stdio:r.stdio??"ignore",detached:!0,shell:!1});return n.unref(),n.pid??0}async function _(e,t,r={}){let n=L(e);return new Promise((o,i)=>{let s=d(n,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],detached:r.detached,shell:!1});r.onSpawn?.(s);let a="",u="",l=r.binaryStdout?Buffer.alloc(0):void 0,c=!1,f=b(r.timeoutMs),p=f?setTimeout(()=>{c=!0,s.kill("SIGKILL")},f):null;r.binaryStdout||s.stdout.setEncoding("utf8"),s.stderr.setEncoding("utf8"),void 0!==r.stdin&&s.stdin.write(r.stdin),s.stdin.end(),s.stdout.on("data",e=>{if(r.binaryStdout){l=Buffer.concat([l??Buffer.alloc(0),Buffer.isBuffer(e)?e:Buffer.from(e)]);return}let t=String(e);a+=t,r.onStdoutChunk?.(t)}),s.stderr.on("data",e=>{let t=String(e);u+=t,r.onStderrChunk?.(t)}),s.on("error",r=>{(p&&clearTimeout(p),"ENOENT"===r.code)?i(new D("TOOL_MISSING",`${n} not found in PATH`,{cmd:e},r)):i(new D("COMMAND_FAILED",`Failed to run ${n}`,{cmd:e,args:t},r))}),s.on("close",s=>{p&&clearTimeout(p);let d=s??1;c&&f?i(new D("COMMAND_FAILED",`${n} timed out after ${f}ms`,{cmd:e,args:t,stdout:a,stderr:u,exitCode:d,timeoutMs:f})):0===d||r.allowFailure?o({stdout:a,stderr:u,exitCode:d,stdoutBuffer:l}):i(new D("COMMAND_FAILED",`${n} exited with code ${d}`,{cmd:e,args:t,stdout:a,stderr:u,exitCode:d,processExitError:!0}))})})}function $(e,t,r={}){let n=L(e),o=d(n,t,{cwd:r.cwd,env:r.env,stdio:["ignore","pipe","pipe"],detached:r.detached,shell:!1}),i="",s="";o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",e=>{i+=e}),o.stderr.on("data",e=>{s+=e});let a=new Promise((a,d)=>{o.on("error",r=>{"ENOENT"===r.code?d(new D("TOOL_MISSING",`${n} not found in PATH`,{cmd:e},r)):d(new D("COMMAND_FAILED",`Failed to run ${n}`,{cmd:e,args:t},r))}),o.on("close",o=>{let u=o??1;0===u||r.allowFailure?a({stdout:i,stderr:s,exitCode:u}):d(new D("COMMAND_FAILED",`${n} exited with code ${u}`,{cmd:e,args:t,stdout:i,stderr:s,exitCode:u,processExitError:!0}))})});return{child:o,wait:a}}function L(e){let t=C(e,{allowRelativePath:!0});if(!t)throw new D("INVALID_ARGS",`Invalid executable command: ${JSON.stringify(e)}`,{cmd:e});return t}function C(e,t){let r=e.trim();return!r||r.includes("\0")?null:i.isAbsolute(r)?r:r.includes("/")||r.includes("\\")?t.allowRelativePath?r:null:v.test(r)?r:null}async function F(e){try{if(!(await a(e)).isFile())return!1;return await s(e,"win32"===process.platform?n.F_OK:n.X_OK),!0}catch{return!1}}function b(e){if(!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t}export{D as AppError,A as asAppError,p as createRequestId,h as emitDiagnostic,E as flushDiagnosticsToSessionFile,g as getDiagnosticsMeta,I as normalizeError,y as runCmd,$ as runCmdBackground,T as runCmdDetached,_ as runCmdStreaming,M as runCmdSync,N as whichCmd,w as withDiagnosticTimer,m as withDiagnosticsScope};
|
|
1
|
+
import{constants as e}from"node:fs";import{access as t,stat as r}from"node:fs/promises";import n from"node:path";import{spawn as o,spawnSync as i}from"node:child_process";let s=/(token|secret|password|authorization|cookie|api[_-]?key|access[_-]?key|private[_-]?key)/i,d=/(bearer\s+[a-z0-9._-]+|(?:api[_-]?key|token|secret|password)\s*[=:]\s*\S+)/i;function a(e){return function e(t,r,n){if(null==t)return t;if("string"==typeof t){var o=t,i=n;let e=o.trim();if(!e)return o;if(i&&s.test(i)||d.test(e))return"[REDACTED]";let r=function(e){try{let t=new URL(e);return t.search&&(t.search="?REDACTED"),(t.username||t.password)&&(t.username="REDACTED",t.password="REDACTED"),t.toString()}catch{return null}}(e);return r||(e.length>400?`${e.slice(0,200)}...<truncated>`:e)}if("object"!=typeof t)return t;if(r.has(t))return"[Circular]";if(r.add(t),Array.isArray(t))return t.map(t=>e(t,r));let a={};for(let[n,o]of Object.entries(t)){if(s.test(n)){a[n]="[REDACTED]";continue}a[n]=e(o,r,n)}return a}(e,new WeakSet)}class u extends Error{code;details;cause;constructor(e,t,r,n){super(t),this.code=e,this.details=r,this.cause=n}}function l(e){return e instanceof u?e:e instanceof Error?new u("UNKNOWN",e.message,void 0,e):new u("UNKNOWN","Unknown error",{err:e})}function c(e,t={}){let r=l(e),n=r.details?a(r.details):void 0,o=n&&"string"==typeof n.hint?n.hint:void 0,i=(n&&"string"==typeof n.diagnosticId?n.diagnosticId:void 0)??t.diagnosticId,s=(n&&"string"==typeof n.logPath?n.logPath:void 0)??t.logPath,d=o??function(e){switch(e){case"INVALID_ARGS":return"Check command arguments and run --help for usage examples.";case"SESSION_NOT_FOUND":return"Run open first or pass an explicit device selector.";case"TOOL_MISSING":return"Install required platform tooling and ensure it is available in PATH.";case"DEVICE_NOT_FOUND":return"Verify the target device is booted/connected and selectors match.";case"APP_NOT_INSTALLED":return"Run apps to discover the exact installed package or bundle id, or install the app before open.";case"UNSUPPORTED_OPERATION":return"This command is not available for the selected platform/device.";case"COMMAND_FAILED":default:return"Retry with --debug and inspect diagnostics log for details.";case"UNAUTHORIZED":return"Refresh daemon metadata and retry the command."}}(r.code),u=function(e){if(!e)return;let t={...e};return delete t.hint,delete t.diagnosticId,delete t.logPath,Object.keys(t).length>0?t:void 0}(n),f=function(e,t,r){if("COMMAND_FAILED"!==e||r?.processExitError!==!0)return t;let n=function(e){let t=[/^an error was encountered processing the command/i,/^underlying error\b/i,/^simulator device failed to complete the requested operation/i];for(let r of e.split("\n")){let e=r.trim();if(e&&!t.some(t=>t.test(e)))return e.length>200?`${e.slice(0,200)}...`:e}return null}("string"==typeof r?.stderr?r.stderr:"");return n||t}(r.code,r.message,n);return{code:r.code,message:f,hint:d,diagnosticId:i,logPath:s,details:u}}let f=/^[A-Za-z0-9][A-Za-z0-9._+-]*$/,p=[".com",".exe",".bat",".cmd"];async function m(e,t,r={}){let n=D(e);return new Promise((i,s)=>{let d=o(n,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],detached:r.detached,shell:!1}),a="",l=r.binaryStdout?Buffer.alloc(0):void 0,c="",f=!1,p=I(r.timeoutMs),m=p?setTimeout(()=>{f=!0,d.kill("SIGKILL")},p):null;r.binaryStdout||d.stdout.setEncoding("utf8"),d.stderr.setEncoding("utf8"),void 0!==r.stdin&&d.stdin.write(r.stdin),d.stdin.end(),d.stdout.on("data",e=>{r.binaryStdout?l=Buffer.concat([l??Buffer.alloc(0),Buffer.isBuffer(e)?e:Buffer.from(e)]):a+=e}),d.stderr.on("data",e=>{c+=e}),d.on("error",r=>{(m&&clearTimeout(m),"ENOENT"===r.code)?s(new u("TOOL_MISSING",`${n} not found in PATH`,{cmd:e},r)):s(new u("COMMAND_FAILED",`Failed to run ${n}`,{cmd:e,args:t},r))}),d.on("close",o=>{m&&clearTimeout(m);let d=o??1;f&&p?s(new u("COMMAND_FAILED",`${n} timed out after ${p}ms`,{cmd:e,args:t,stdout:a,stderr:c,exitCode:d,timeoutMs:p})):0===d||r.allowFailure?i({stdout:a,stderr:c,exitCode:d,stdoutBuffer:l}):s(new u("COMMAND_FAILED",`${n} exited with code ${d}`,{cmd:e,args:t,stdout:a,stderr:c,exitCode:d,processExitError:!0}))})})}async function w(e){let t=N(e,{allowRelativePath:!1});if(!t)return!1;if(n.isAbsolute(t))return O(t);let r=process.env.PATH;if(!r)return!1;let o=function(){if("win32"!==process.platform)return[""];let e=process.env.PATHEXT;if(!e)return p;let t=e.split(";").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0);return t.length>0?t:p}();for(let e of r.split(n.delimiter)){let r=e.trim();if(r){for(let e of function(e,t){if("win32"!==process.platform)return[e];let r=e.toLowerCase();return t.some(e=>r.endsWith(e))?[e]:t.map(t=>`${e}${t}`)}(t,o))if(await O(n.join(r,e)))return!0}}return!1}function h(e,t,r={}){let n=D(e),o=i(n,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],encoding:r.binaryStdout?void 0:"utf8",input:r.stdin,timeout:I(r.timeoutMs),shell:!1});if(o.error){let i=o.error.code;if("ETIMEDOUT"===i)throw new u("COMMAND_FAILED",`${n} timed out after ${I(r.timeoutMs)}ms`,{cmd:e,args:t,timeoutMs:I(r.timeoutMs)},o.error);if("ENOENT"===i)throw new u("TOOL_MISSING",`${n} not found in PATH`,{cmd:e},o.error);throw new u("COMMAND_FAILED",`Failed to run ${n}`,{cmd:e,args:t},o.error)}let s=r.binaryStdout?Buffer.isBuffer(o.stdout)?o.stdout:Buffer.from(o.stdout??""):void 0,d=r.binaryStdout?"":"string"==typeof o.stdout?o.stdout:(o.stdout??"").toString(),a="string"==typeof o.stderr?o.stderr:(o.stderr??"").toString(),l=o.status??1;if(0!==l&&!r.allowFailure)throw new u("COMMAND_FAILED",`${n} exited with code ${l}`,{cmd:e,args:t,stdout:d,stderr:a,exitCode:l,processExitError:!0});return{stdout:d,stderr:a,exitCode:l,stdoutBuffer:s}}function E(e,t,r={}){let n=o(D(e),t,{cwd:r.cwd,env:r.env,stdio:r.stdio??"ignore",detached:!0,shell:!1});return n.unref(),n.pid??0}async function A(e,t,r={}){let n=D(e);return new Promise((i,s)=>{let d=o(n,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],detached:r.detached,shell:!1});r.onSpawn?.(d);let a="",l="",c=r.binaryStdout?Buffer.alloc(0):void 0,f=!1,p=I(r.timeoutMs),m=p?setTimeout(()=>{f=!0,d.kill("SIGKILL")},p):null;r.binaryStdout||d.stdout.setEncoding("utf8"),d.stderr.setEncoding("utf8"),void 0!==r.stdin&&d.stdin.write(r.stdin),d.stdin.end(),d.stdout.on("data",e=>{if(r.binaryStdout){c=Buffer.concat([c??Buffer.alloc(0),Buffer.isBuffer(e)?e:Buffer.from(e)]);return}let t=String(e);a+=t,r.onStdoutChunk?.(t)}),d.stderr.on("data",e=>{let t=String(e);l+=t,r.onStderrChunk?.(t)}),d.on("error",r=>{(m&&clearTimeout(m),"ENOENT"===r.code)?s(new u("TOOL_MISSING",`${n} not found in PATH`,{cmd:e},r)):s(new u("COMMAND_FAILED",`Failed to run ${n}`,{cmd:e,args:t},r))}),d.on("close",o=>{m&&clearTimeout(m);let d=o??1;f&&p?s(new u("COMMAND_FAILED",`${n} timed out after ${p}ms`,{cmd:e,args:t,stdout:a,stderr:l,exitCode:d,timeoutMs:p})):0===d||r.allowFailure?i({stdout:a,stderr:l,exitCode:d,stdoutBuffer:c}):s(new u("COMMAND_FAILED",`${n} exited with code ${d}`,{cmd:e,args:t,stdout:a,stderr:l,exitCode:d,processExitError:!0}))})})}function g(e,t,r={}){let n=D(e),i=o(n,t,{cwd:r.cwd,env:r.env,stdio:["ignore","pipe","pipe"],detached:r.detached,shell:!1}),s="",d="";i.stdout.setEncoding("utf8"),i.stderr.setEncoding("utf8"),i.stdout.on("data",e=>{s+=e}),i.stderr.on("data",e=>{d+=e});let a=new Promise((o,a)=>{i.on("error",r=>{"ENOENT"===r.code?a(new u("TOOL_MISSING",`${n} not found in PATH`,{cmd:e},r)):a(new u("COMMAND_FAILED",`Failed to run ${n}`,{cmd:e,args:t},r))}),i.on("close",i=>{let l=i??1;0===l||r.allowFailure?o({stdout:s,stderr:d,exitCode:l}):a(new u("COMMAND_FAILED",`${n} exited with code ${l}`,{cmd:e,args:t,stdout:s,stderr:d,exitCode:l,processExitError:!0}))})});return{child:i,wait:a}}function D(e){let t=N(e,{allowRelativePath:!0});if(!t)throw new u("INVALID_ARGS",`Invalid executable command: ${JSON.stringify(e)}`,{cmd:e});return t}function N(e,t){let r=e.trim();return!r||r.includes("\0")?null:n.isAbsolute(r)?r:r.includes("/")||r.includes("\\")?t.allowRelativePath?r:null:f.test(r)?r:null}async function O(n){try{if(!(await r(n)).isFile())return!1;return await t(n,"win32"===process.platform?e.F_OK:e.X_OK),!0}catch{return!1}}function I(e){if(!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t}export{u as AppError,l as asAppError,c as normalizeError,a as redactDiagnosticData,m as runCmd,g as runCmdBackground,E as runCmdDetached,A as runCmdStreaming,h as runCmdSync,w as whichCmd};
|
package/dist/src/924.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import e from"node:fs";import t from"node:path";import{
|
|
1
|
+
import e from"node:fs";import t from"node:path";import{AppError as r}from"./152.js";import{resolveUserPath as n}from"./267.js";let o=new Set(["1","true","yes","on"]),i=new Set(["0","false","no","off"]);function a(e,t,n,o){if(e.multiple)return(Array.isArray(t)?t:[t]).map(t=>a({...e,multiple:!1},t,n,o));if("boolean"===e.type){var i=t,l=n,m=o;if("boolean"==typeof i)return i;if("string"==typeof i){let e=s(i);if(void 0!==e)return e}throw new r("INVALID_ARGS",`Invalid value for "${m}" in ${l}. Expected boolean.`)}if("booleanOrString"===e.type){if("boolean"==typeof t)return t;if("string"==typeof t&&void 0!==s(t))return s(t);if("string"==typeof t&&t.trim().length>0)return t;throw new r("INVALID_ARGS",`Invalid value for "${o}" in ${n}. Expected boolean or non-empty string.`)}if("string"===e.type){if("string"==typeof t&&t.trim().length>0)return t;throw new r("INVALID_ARGS",`Invalid value for "${o}" in ${n}. Expected non-empty string.`)}if("enum"===e.type){if(void 0!==e.setValue){var u=e,f=t,p=n,y=o;let i=u.setValue;if(f===i)return i;if("string"==typeof f){let e=f.trim();if(""===e||"true"===e||"1"===e)return i;if("false"===e||"0"===e)return}if(!0===f)return i;if(!1!==f)throw new r("INVALID_ARGS",`Invalid value for "${y}" in ${p}. Expected boolean-like value for enum flag.`);return}if("string"!=typeof t||!e.enumValues?.includes(t))throw new r("INVALID_ARGS",`Invalid value for "${o}" in ${n}. Expected one of: ${e.enumValues?.join(", ")}.`);return t}let g="number"==typeof t?t:"string"==typeof t?Number(t):NaN;if(!Number.isFinite(g)||!Number.isInteger(g))throw new r("INVALID_ARGS",`Invalid value for "${o}" in ${n}. Expected integer.`);if("number"==typeof e.min&&g<e.min)throw new r("INVALID_ARGS",`Invalid value for "${o}" in ${n}. Must be >= ${e.min}.`);if("number"==typeof e.max&&g>e.max)throw new r("INVALID_ARGS",`Invalid value for "${o}" in ${n}. Must be <= ${e.max}.`);return g}function s(e){let t=e.trim().toLowerCase();return!!o.has(t)||!i.has(t)&&void 0}let l=[{key:"stateDir",type:"string",path:!0},{key:"daemonBaseUrl",type:"string"},{key:"daemonAuthToken",type:"string"},{key:"daemonTransport",type:"enum",enumValues:["auto","socket","http"]},{key:"daemonServerMode",type:"enum",enumValues:["socket","http","dual"]},{key:"tenant",type:"string"},{key:"sessionIsolation",type:"enum",enumValues:["none","tenant"]},{key:"runId",type:"string"},{key:"leaseId",type:"string"},{key:"platform",type:"enum",enumValues:["ios","macos","android","linux","apple"]},{key:"target",type:"enum",enumValues:["mobile","tv","desktop"]},{key:"device",type:"string"},{key:"udid",type:"string"},{key:"serial",type:"string"},{key:"iosSimulatorDeviceSet",type:"string",path:!0,legacyEnvNames:["IOS_SIMULATOR_DEVICE_SET"]},{key:"androidDeviceAllowlist",type:"string",legacyEnvNames:["ANDROID_DEVICE_ALLOWLIST"]},{key:"session",type:"string"},{key:"metroProjectRoot",type:"string",path:!0},{key:"metroKind",type:"enum",enumValues:["auto","react-native","expo"]},{key:"metroPublicBaseUrl",type:"string"},{key:"metroProxyBaseUrl",type:"string"},{key:"metroBearerToken",type:"string",legacyEnvNames:["AGENT_DEVICE_PROXY_TOKEN"]},{key:"metroPreparePort",type:"int",min:1,max:65535},{key:"metroListenHost",type:"string"},{key:"metroStatusHost",type:"string"},{key:"metroStartupTimeoutMs",type:"int",min:1},{key:"metroProbeTimeoutMs",type:"int",min:1},{key:"metroRuntimeFile",type:"string",path:!0},{key:"metroNoReuseExisting",type:"boolean"},{key:"metroNoInstallDeps",type:"boolean"}],m=["session","platform","daemonBaseUrl","daemonAuthToken","daemonTransport","metroProjectRoot","metroKind","metroPublicBaseUrl","metroProxyBaseUrl","metroBearerToken","metroPreparePort","metroListenHost","metroStatusHost","metroStartupTimeoutMs","metroProbeTimeoutMs","metroRuntimeFile","metroNoReuseExisting","metroNoInstallDeps"],u=new Map(l.map(e=>[e.key,e]));function f(e){let t=e.env??process.env;return n(e.configPath,{cwd:e.cwd,env:t})}function p(o){let i=function(o){let i,s,l=o.env??process.env,m=f(o);if(!e.existsSync(m))throw new r("INVALID_ARGS",`Remote config file not found: ${m}`);try{i=e.readFileSync(m,"utf8")}catch(e){throw new r("INVALID_ARGS",`Failed to read remote config file: ${m}`,{cause:e instanceof Error?e.message:String(e)})}try{s=JSON.parse(i)}catch(e){throw new r("INVALID_ARGS",`Invalid JSON in remote config file: ${m}`,{cause:e instanceof Error?e.message:String(e)})}if(!s||"object"!=typeof s||Array.isArray(s))throw new r("INVALID_ARGS",`Remote config file must contain a JSON object: ${m}`);let p={},y=s,g=t.dirname(m);for(let[e,t]of Object.entries(y)){let o=u.get(e);if(!o)throw new r("INVALID_ARGS",`Unsupported remote config key "${e}" in remote config file ${m}.`);let i=a(o,t,`remote config file ${m}`,e);p[o.key]="string"==typeof i&&"path"in o&&o.path?n(i,{cwd:g,env:l}):i}return{resolvedPath:m,profile:p}}(o);return{resolvedPath:i.resolvedPath,profile:function(...e){let t={};for(let r of e)if(r)for(let e of l){let n=r[e.key];void 0!==n&&(t[e.key]=n)}return t}(function(e=process.env){let t={};for(let r of l){let n=(function(e){let t=u.get(e);return[`AGENT_DEVICE_${e.replace(/([A-Z])/g,"_$1").replace(/[^A-Za-z0-9_]/g,"_").toUpperCase()}`,...t?.legacyEnvNames??[]]})(r.key).map(t=>({name:t,value:e[t]})).find(e=>"string"==typeof e.value&&e.value.trim().length>0);n&&(t[r.key]=a(r,n.value,`environment variable ${n.name}`,n.name))}return t}(o.env),i.profile)}}export{l as REMOTE_CONFIG_FIELD_SPECS,m as REMOTE_OPEN_PROFILE_KEYS,f as resolveRemoteConfigPath,p as resolveRemoteConfigProfile};
|
package/dist/src/940.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{AppError as e}from"./152.js";import{normalizeText as t}from"./556.js";let r=new Set(["id","role","text","label","value","appname","windowtitle"]),n=new Set(["visible","hidden","editable","selected","enabled","hittable"]),l=new Set([...r,...n]);function i(t){let r=t.trim();if(!r)throw new e("INVALID_ARGS","Selector expression cannot be empty");let n=function(t){let r=[],n="",l=null;for(let i=0;i<t.length;i+=1){let u=t[i];if(('"'===u||"'"===u)&&!f(t,i)){l=c(l,u),n+=u;continue}if(!l&&"|"===u&&"|"===t[i+1]){let l=n.trim();if(!l)throw new e("INVALID_ARGS",`Invalid selector fallback expression: ${t}`);r.push(l),n="",i+=1;continue}n+=u}let i=n.trim();if(!i)throw new e("INVALID_ARGS",`Invalid selector fallback expression: ${t}`);return r.push(i),r}(r);if(0===n.length)throw new e("INVALID_ARGS","Selector expression cannot be empty");return{raw:r,selectors:n.map(t=>(function(t){let r=t.trim();if(!r)throw new e("INVALID_ARGS","Selector segment cannot be empty");let n=function(t){let r=[],n="",l=null;for(let e=0;e<t.length;e+=1){let i=t[e];if(('"'===i||"'"===i)&&!f(t,e)){l=c(l,i),n+=i;continue}if(!l&&/\s/.test(i)){n.trim()&&r.push(n.trim()),n="";continue}n+=i}if(l)throw new e("INVALID_ARGS",`Unclosed quote in selector: ${t}`);return n.trim()&&r.push(n.trim()),r}(r);if(0===n.length)throw new e("INVALID_ARGS",`Invalid selector segment: ${t}`);return{raw:r,terms:n.map(a)}})(t))}}function u(e){try{return i(e)}catch{return null}}function o(e){let t=e.trim();if(!t)return!1;if("||"===t)return!0;let r=t.indexOf("=");if(-1!==r){let e=t.slice(0,r).trim().toLowerCase();return l.has(e)}return l.has(t.toLowerCase())}function a(t){let r=t.trim();if(!r)throw new e("INVALID_ARGS","Empty selector term");let i=r.indexOf("=");if(-1===i){let l=r.toLowerCase();if(!n.has(l))throw new e("INVALID_ARGS",`Invalid selector term "${t}", expected key=value`);return{key:l,value:!0}}let u=r.slice(0,i).trim().toLowerCase(),o=r.slice(i+1).trim();if(!l.has(u))throw new e("INVALID_ARGS",`Unknown selector key: ${u}`);if(!o)throw new e("INVALID_ARGS",`Missing selector value for key: ${u}`);if(n.has(u)){let t,r="true"===(t=s(o).toLowerCase())||"false"!==t&&null;if(null===r)throw new e("INVALID_ARGS",`Invalid boolean value for ${u}: ${o}`);return{key:u,value:r}}return{key:u,value:s(o)}}function c(e,t){return e?e===t?null:e:t}function s(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1).replace(/\\(["'])/g,"$1"):t}function f(e,t){let r=0;for(let n=t-1;n>=0&&"\\"===e[n];n-=1)r+=1;return r%2==1}function d(e){let t=e.trim().replace(/XCUIElementType/gi,"");t.startsWith("AX")&&(t=t.slice(2));let r=Math.max((t=t.toLowerCase()).lastIndexOf("."),t.lastIndexOf("/"));return -1!==r&&(t=t.slice(r+1)),t}function h(e,t,r){return t.terms.every(t=>(function(e,t,r){switch(t.key){case"id":return p(e.identifier,String(t.value));case"role":return p(d(e.type??""),String(t.value));case"label":return p(e.label,String(t.value));case"value":return p(e.value,String(t.value));case"text":return p([e.label,e.value,e.identifier].map(e=>"string"==typeof e?e.trim():"").filter(e=>e.length>0)[0]??"",String(t.value));case"appname":return p(e.appName,String(t.value));case"windowtitle":return p(e.windowTitle,String(t.value));case"visible":return m(e)===!!t.value;case"hidden":return!m(e)==!!t.value;case"editable":return w(e,r)===!!t.value;case"selected":return!0===e.selected==!!t.value;case"enabled":return!1!==e.enabled==!!t.value;case"hittable":return!0===e.hittable==!!t.value;default:return!1}})(e,t,r))}function m(e){return!0===e.hittable||!!e.rect&&e.rect.width>0&&e.rect.height>0}function w(e,t){var r;let n;return r=e.type??"",(!(n=d(r))||("android"===t?n.includes("edittext")||n.includes("autocompletetextview"):n.includes("textfield")||n.includes("securetextfield")||n.includes("searchfield")||n.includes("textview")||n.includes("textarea")||"search"===n))&&!1!==e.enabled}function p(e,r){return t(e??"")===t(r)}function S(e,t,r){let n=r.requireRect??!1,l=r.requireUnique??!0,i=[];for(let u=0;u<t.selectors.length;u+=1){let o=t.selectors[u],a=function(e,t,r,n){let l=0,i=null,u=null,o=!1;for(let a of e){if(n&&!a.rect||!h(a,t,r))continue;if(l+=1,i??=a,!u){u=a;continue}let e=function(e,t){let r=e.depth??0,n=t.depth??0;if(r!==n)return r>n?1:-1;let l=b(e),i=b(t);return l!==i?l<i?1:-1:0}(a,u);e>0?(u=a,o=!1):0===e&&(o=!0)}return{count:l,firstNode:i,disambiguated:o?null:u}}(e,o,r.platform,n);if(i.push({selector:o.raw,matches:a.count}),0!==a.count&&a.firstNode){if(l&&1!==a.count){if(!r.disambiguateAmbiguous||!a.disambiguated)continue;return{node:a.disambiguated,selector:o,selectorIndex:u,matches:a.count,diagnostics:i}}return{node:a.firstNode,selector:o,selectorIndex:u,matches:a.count,diagnostics:i}}}return null}function v(e,t,r){let n=r.requireRect??!1,l=[];for(let i=0;i<t.selectors.length;i+=1){let u=t.selectors[i],o=function(e,t,r,n){let l=0;for(let i of e)(!n||i.rect)&&h(i,t,r)&&(l+=1);return l}(e,u,r.platform,n);if(l.push({selector:u.raw,matches:o}),o>0)return{selectorIndex:i,selector:u,matches:o,diagnostics:l}}return null}function I(e,t,r){if(0===t.length)return`Selector did not match: ${e.raw}`;let n=t.map(e=>`${e.selector} -> ${e.matches}`).join(", ");return r.unique??!0?`Selector did not resolve uniquely (${n})`:`Selector did not match (${n})`}function b(e){return e.rect?e.rect.width*e.rect.height:1/0}export{v as findSelectorChainMatch,I as formatSelectorFailure,w as isNodeEditable,o as isSelectorToken,i as parseSelectorChain,S as resolveSelectorChain,m as isNodeVisible,u as tryParseSelectorChain};
|
package/dist/src/974.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e from"node:fs";import
|
|
2
|
-
`,"utf8")}function k(t){try{let r=e.readdirSync(t);0===r.length&&e.rmdirSync(t)}catch{}}function R(r){let n=t.dirname(r.statePath),o=t.dirname(r.logPath);var i=r.statePath;try{e.unlinkSync(i)}catch{}var a=r.logPath;try{e.unlinkSync(a)}catch{}k(n),o!==n&&k(o),t.basename(n)===U&&k(t.dirname(n))}function $(e){return e.includes(S)}function O(e){return v(e.consumerKey)??v(e.profileKey)??null}function C(e,t){return!t||e.consumers.includes(t)?e:{...e,consumers:[...e.consumers,t]}}async function D(e){if(!f(e.pid))return;let t=g(e.pid);if(t&&$(t)){try{process.kill(e.pid,"SIGTERM")}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return;throw t}if(!await w(e.pid,1e3)){try{process.kill(e.pid,"SIGKILL")}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return;throw t}await w(e.pid,1e3)}}}async function x(r){let n=O(r),o=N(r.projectRoot,r.profileKey),a=T(o.statePath);if(a&&function(e,t){if(!f(e.pid))return!1;if(e.startTime){let t=h(e.pid);if(!t||t!==e.startTime)return!1}let r=g(e.pid);return!!r&&!!$(r)&&e.serverBaseUrl===M(t.serverBaseUrl)&&e.localBaseUrl===M(t.localBaseUrl)&&e.launchUrl===v(t.launchUrl)&&e.tokenHash===A(t.bearerToken)}(a,r)){let e=C(a,n);return e!==a&&I(o.statePath,e),{pid:a.pid,spawned:!1,statePath:o.statePath,logPath:o.logPath}}a&&(await D(a),R(o));let s=function(r,n){let o=function(){let r=i(import.meta.url),n=t.extname(r)||".js",o=t.join(t.dirname(r),`metro-companion${n}`);if(!e.existsSync(o))throw Error(`Metro companion entrypoint not found at ${o}. Rebuild the package to include the companion worker entry.`);return o}(),a=o.endsWith(".ts")?["--experimental-strip-types"]:[];e.mkdirSync(t.dirname(n),{recursive:!0});let s=e.openSync(n,"a"),l=0;try{let e;l=c(process.execPath,[...a,o,S],{env:(e={...r.env??process.env,AGENT_DEVICE_METRO_COMPANION_SERVER_BASE_URL:M(r.serverBaseUrl),AGENT_DEVICE_METRO_COMPANION_BEARER_TOKEN:r.bearerToken,AGENT_DEVICE_METRO_COMPANION_LOCAL_BASE_URL:M(r.localBaseUrl),AGENT_DEVICE_METRO_COMPANION_STATE_PATH:N(r.projectRoot,r.profileKey).statePath},r.launchUrl?.trim()?e[_]=r.launchUrl.trim():delete e[_],e),stdio:["ignore",s,s]})}finally{e.closeSync(s)}if(!Number.isInteger(l)||l<=0)throw Error("Failed to start Metro companion process.");return{pid:l,startTime:h(l)??void 0,command:g(l)??void 0,serverBaseUrl:M(r.serverBaseUrl),localBaseUrl:M(r.localBaseUrl),launchUrl:v(r.launchUrl),tokenHash:A(r.bearerToken),consumers:[]}}(r,o.logPath);return I(o.statePath,C(s,n)),{pid:s.pid,spawned:!0,statePath:o.statePath,logPath:o.logPath}}async function B(e){let t=O(e),r=N(e.projectRoot,e.profileKey),n=T(r.statePath);if(!n)return R(r),{stopped:!1,statePath:r.statePath};let o=t?{...n,consumers:n.consumers.filter(e=>e!==t)}:{...n,consumers:[]};return o.consumers.length>0?(I(r.statePath,o),{stopped:!1,statePath:r.statePath}):(await D(n),R(r),{stopped:!0,statePath:r.statePath})}function j(e){return"string"==typeof e&&e.trim()?M(e.trim()):""}function L(e){return"string"==typeof e&&e.trim()?e.trim():void 0}function F(e,t,r){return a(e,{env:t,cwd:r})}function G(t){try{return e.accessSync(t,e.constants.F_OK),!0}catch{return!1}}function H(e,t,r){if(null==e||""===e)return t;let n=Number.parseInt(String(e),10);return Number.isInteger(n)?Math.max(n,r):t}function K(e,t){return{platform:t,bundleUrl:P(e,t)}}function V(e,t){return{platform:t,metroHost:L(e?.metro_host),metroPort:e?.metro_port,bundleUrl:L(e?.metro_bundle_url),launchUrl:L(e?.launch_url)}}async function J(e){await new Promise(t=>setTimeout(t,e))}async function q(e,t,r={}){try{let n=await fetch(e,{headers:r,signal:AbortSignal.timeout(t)});return{ok:n.ok,status:n.status,body:await n.text()}}catch(r){if(r instanceof Error&&"TimeoutError"===r.name)throw Error(`Timed out fetching ${e} after ${t}ms`);throw r}}async function z(e,t){try{let r=await q(e,t);return r.ok&&r.body.includes("packager-status:running")}catch{return!1}}function Z(e,t){let r=Error(e);return r.retryable=t,r}async function W(e){var t,r,n,o;let i;try{i=await fetch(`${e.baseUrl}/api/metro/bridge`,{method:"POST",headers:(t=e.baseUrl,r=e.bearerToken,{Authorization:`Bearer ${r}`,"Content-Type":"application/json",...t.includes("ngrok")?{"ngrok-skip-browser-warning":"1"}:{}}),body:JSON.stringify({ios_runtime:e.runtime,timeout_ms:e.timeoutMs}),signal:AbortSignal.timeout(e.timeoutMs)})}catch(t){if(t instanceof Error&&"TimeoutError"===t.name)throw Z(`/api/metro/bridge timed out after ${e.timeoutMs}ms calling ${e.baseUrl}/api/metro/bridge`,!0);throw Z(t instanceof Error?t.message:String(t),!0)}let a=await i.text(),s=a?JSON.parse(a):{};if(!i.ok)throw Z(`/api/metro/bridge failed (${i.status}): ${JSON.stringify(s)}`,(n=i.status,!!(n>=500||408===n||425===n||429===n||JSON.stringify(s).includes("Metro companion is not connected"))));return{enabled:(o=s.data??s).enabled,baseUrl:o.base_url,statusUrl:o.status_url??"",bundleUrl:o.bundle_url??"",iosRuntime:V(o.ios_runtime,"ios"),androidRuntime:V(o.android_runtime,"android"),upstream:{bundleUrl:o.upstream.bundle_url??"",host:o.upstream.host??"",port:o.upstream.port??0,statusUrl:o.upstream.status_url??""},probe:{reachable:o.probe.reachable,statusCode:o.probe.status_code,latencyMs:o.probe.latency_ms,detail:o.probe.detail}}}function X(e,t,r,n,o){let i=[`Metro bridge is required for this run but could not be configured via ${e}/api/metro/bridge.`];return t&&i.push(`bridgeError=${t}`),r?.probe.reachable===!1&&i.push(`bridgeProbe=${r.probe.detail||`unreachable (status ${r.probe.statusCode||0})`}`),n&&n!==t&&i.push(`initialBridgeError=${n}`),o&&i.push(`metroCompanionLog=${o}`),i.join(" ")}async function Y(e,t,r){let n=Date.now()+t;for(;Date.now()<n;){let t=Math.min(r,Math.max(n-Date.now(),1));if(await z(e,t))return!0;let o=Math.min(500,Math.max(n-Date.now(),0));o>0&&await J(o)}return!1}async function Q(e){let t=Date.now()+e.startupTimeoutMs,r=null,n=null;for(;Date.now()<t;){try{let t=await W({baseUrl:e.baseUrl,bearerToken:e.bearerToken,runtime:e.runtime,timeoutMs:e.probeTimeoutMs});if(!1!==t.probe.reachable)return t;r=t,n=null}catch(e){if(n=e instanceof Error?e.message:String(e),!(e&&"object"==typeof e&&"retryable"in e&&!0===e.retryable))break}let o=Math.min(1e3,Math.max(t-Date.now(),0));o>0&&await J(o)}throw Error(X(e.baseUrl,n,r,e.initialBridgeError,e.companionLogPath))}async function ee(r={}){let n=r.env??process.env,o=process.cwd(),i=F(r.projectRoot??o,n,o),a=function(r,n){if("auto"!==n)return n;let o=function(r){let n=t.join(r,"package.json");if(!G(n))throw new s("INVALID_ARGS",`package.json not found at ${n}`);return JSON.parse(e.readFileSync(n,"utf8"))}(r);return"string"==typeof({...o.dependencies??{},...o.devDependencies??{}}).expo?"expo":"react-native"}(i,r.kind??"auto"),l=function(e){if(null==e||""===e)return 8081;let t=Number.parseInt(String(e),10);if(!Number.isInteger(t)||t<1||t>65535)throw new s("INVALID_ARGS",`Invalid Metro port: ${String(e)}. Use 1-65535.`);return t}(r.metroPort??8081),m=L(r.listenHost)??"0.0.0.0",d=L(r.statusHost)??"127.0.0.1",p=j(r.publicBaseUrl),f=H(r.startupTimeoutMs,18e4,3e4),h=H(r.probeTimeoutMs,1e4,1e3),g=r.reuseExisting??!0,y=r.installDependenciesIfNeeded??!0,b=r.runtimeFilePath?F(r.runtimeFilePath,n,o):null,w=F(r.logPath??t.join(i,".agent-device","metro.log"),n,o);if(!p)throw new s("INVALID_ARGS","metro prepare requires --public-base-url <url>.");let{proxyEnabled:E,proxyBaseUrl:S,proxyBearerToken:_}=function(e,t){if(e&&!t)throw new s("INVALID_ARGS","metro prepare requires proxy auth when --proxy-base-url is provided. Pass --bearer-token or set AGENT_DEVICE_PROXY_TOKEN.");if(!e&&t)throw new s("INVALID_ARGS","metro prepare requires --proxy-base-url when proxy auth is provided.");return{proxyEnabled:!!(e&&t),proxyBaseUrl:e,proxyBearerToken:t}}(j(r.proxyBaseUrl),L(r.proxyBearerToken)??""),M=y?function(r,n){if(function(t){try{return e.statSync(t).isDirectory()}catch{return!1}}(t.join(r,"node_modules")))return{installed:!1};let o=G(t.join(r,"pnpm-lock.yaml"))?{command:"pnpm",installArgs:["install"]}:G(t.join(r,"yarn.lock"))?{command:"yarn",installArgs:["install"]}:{command:"npm",installArgs:["install"]};return u(o.command,o.installArgs,{cwd:r,env:n}),{installed:!0,packageManager:o.command}}(i,n):{installed:!1},P=`http://${d}:${l}/status`,U=!1,A=!1,v=0;if(g&&await z(P,h))A=!0;else if(U=!0,v=function(r,n,o,i,a,s){let l="expo"===n?{command:"npx",installArgs:["expo","start","--host","lan","--port",String(o)]}:{command:"npx",installArgs:["react-native","start","--host",i,"--port",String(o)]};e.mkdirSync(t.dirname(a),{recursive:!0});let u=e.openSync(a,"a"),m=0;try{m=c(l.command,l.installArgs,{cwd:r,env:s,stdio:["ignore",u,u]})}finally{e.closeSync(u)}if(!Number.isInteger(m)||m<=0)throw Error("Failed to start Metro. Expected a detached child PID.");return{pid:m}}(i,a,l,m,w,n).pid,!await Y(P,f,h))throw Error(`Metro did not become ready at ${P} within ${f}ms. Check ${w}.`);let N=K(p,"ios"),T=K(p,"android"),I=null,k=null;if(E)try{I=await W({baseUrl:S,bearerToken:_,runtime:{metro_bundle_url:N.bundleUrl},timeoutMs:h})}catch(e){k=e instanceof Error?e.message:String(e)}if(E&&(!I||!1===I.probe.reachable)){let e;try{e=(await x({projectRoot:i,serverBaseUrl:S,bearerToken:_,localBaseUrl:`http://${d}:${l}`,launchUrl:L(r.launchUrl),profileKey:L(r.companionProfileKey),consumerKey:L(r.companionConsumerKey),env:n})).logPath}catch(e){throw Error(X(S,e instanceof Error?e.message:String(e),I,k))}try{I=await Q({baseUrl:S,bearerToken:_,runtime:{metro_bundle_url:N.bundleUrl},probeTimeoutMs:h,startupTimeoutMs:f,initialBridgeError:k,companionLogPath:e})}catch(e){throw e instanceof Error?e:Error(String(e))}}let R=I?.iosRuntime??N,$=I?.androidRuntime??T,O={projectRoot:i,kind:a,dependenciesInstalled:M.installed,packageManager:M.packageManager??null,started:U,reused:A,pid:v,logPath:w,statusUrl:P,runtimeFilePath:b,iosRuntime:R,androidRuntime:$,bridge:I};return b&&(e.mkdirSync(t.dirname(b),{recursive:!0}),e.writeFileSync(b,JSON.stringify(O,null,2))),O}export{P as buildBundleUrl,K as buildMetroRuntimeHints,x as ensureMetroCompanion,y as isAgentDeviceDaemonProcess,M as normalizeBaseUrl,ee as prepareMetroRuntime,c as runCmdDetached,u as runCmdSync,B as stopMetroCompanion,E as stopProcessForTakeover};
|
|
1
|
+
import e from"node:fs";import t from"node:path";import{createHash as r}from"node:crypto";import{fileURLToPath as n}from"node:url";import{runCmdSync as o,runCmdDetached as a}from"./818.js";import{AppError as i}from"./152.js";import{resolveUserPath as s}from"./267.js";let l=[/(^|[/\s"'=])dist\/src\/daemon\.js($|[\s"'])/,/(^|[/\s"'=])src\/daemon\.ts($|[\s"'])/];function u(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(e){return"EPERM"===e.code}}function c(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=o("ps",["-p",String(e),"-o","lstart="],{allowFailure:!0,timeoutMs:1e3});if(0!==t.exitCode)return null;let r=t.stdout.trim();return r.length>0?r:null}catch{return null}}function m(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=o("ps",["-p",String(e),"-o","command="],{allowFailure:!0,timeoutMs:1e3});if(0!==t.exitCode)return null;let r=t.stdout.trim();return r.length>0?r:null}catch{return null}}function d(e,t){let r;if(!u(e))return!1;if(t){let r=c(e);if(!r||r!==t)return!1}let n=m(e);return!!n&&!!(r=n.toLowerCase().replaceAll("\\","/")).includes("agent-device")&&l.some(e=>e.test(r))}function p(e,t){try{return process.kill(e,t),!0}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return!1;throw t}}async function f(e,t){if(!u(e))return!0;let r=Date.now();for(;Date.now()-r<t;)if(await new Promise(e=>setTimeout(e,50)),!u(e))return!0;return!u(e)}async function h(e,t){!d(e,t.expectedStartTime)||!p(e,"SIGTERM")||await f(e,t.termTimeoutMs)||p(e,"SIGKILL")&&await f(e,t.killTimeoutMs)}let g="--agent-device-run-metro-companion",y="AGENT_DEVICE_METRO_COMPANION_LAUNCH_URL";function b(e){let t=e.length;for(;t>0&&47===e.charCodeAt(t-1);)t-=1;return t===e.length?e:e.slice(0,t)}function w(e,t){let r=new URL(`${b(e)}/index.bundle`);return r.searchParams.set("platform",t),r.searchParams.set("dev","true"),r.searchParams.set("minify","false"),r.toString()}let E="metro-companion";function _(e){return r("sha256").update(e).digest("hex")}function S(e){return e?.trim()?e.trim():void 0}function P(e,r){let n=t.join(e,".agent-device");if(!r)return{statePath:t.join(n,"metro-companion.json"),logPath:t.join(n,"metro-companion.log")};let o=_(r).slice(0,12),a=t.join(n,E);return{statePath:t.join(a,`metro-companion-${o}.json`),logPath:t.join(a,`metro-companion-${o}.log`)}}function U(t){try{let r=JSON.parse(e.readFileSync(t,"utf8"));if(!Number.isInteger(r.pid)||0>=Number(r.pid)||"string"!=typeof r.serverBaseUrl||"string"!=typeof r.localBaseUrl||"string"!=typeof r.tokenHash||0===r.tokenHash.length)return null;let n=Array.isArray(r.consumers)?r.consumers.filter(e=>"string"==typeof e&&e.length>0):[];return{pid:Number(r.pid),startTime:"string"==typeof r.startTime?r.startTime:void 0,command:"string"==typeof r.command?r.command:void 0,serverBaseUrl:r.serverBaseUrl,localBaseUrl:r.localBaseUrl,launchUrl:S("string"==typeof r.launchUrl?r.launchUrl:void 0),tokenHash:r.tokenHash,consumers:n}}catch{return null}}function M(r,n){e.mkdirSync(t.dirname(r),{recursive:!0}),e.writeFileSync(r,`${JSON.stringify(n,null,2)}
|
|
2
|
+
`,"utf8")}function k(t){try{let r=e.readdirSync(t);0===r.length&&e.rmdirSync(t)}catch{}}function T(r){let n=t.dirname(r.statePath),o=t.dirname(r.logPath);var a=r.statePath;try{e.unlinkSync(a)}catch{}var i=r.logPath;try{e.unlinkSync(i)}catch{}k(n),o!==n&&k(o),t.basename(n)===E&&k(t.dirname(n))}function N(e){return e.includes(g)}function A(e){return S(e.consumerKey)??S(e.profileKey)??null}function v(e,t){return!t||e.consumers.includes(t)?e:{...e,consumers:[...e.consumers,t]}}async function R(e){if(!u(e.pid))return;let t=m(e.pid);if(t&&N(t)){try{process.kill(e.pid,"SIGTERM")}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return;throw t}if(!await f(e.pid,1e3)){try{process.kill(e.pid,"SIGKILL")}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return;throw t}await f(e.pid,1e3)}}}async function I(r){let o=A(r),i=P(r.projectRoot,r.profileKey),s=U(i.statePath);if(s&&function(e,t){if(!u(e.pid))return!1;if(e.startTime){let t=c(e.pid);if(!t||t!==e.startTime)return!1}let r=m(e.pid);return!!r&&!!N(r)&&e.serverBaseUrl===b(t.serverBaseUrl)&&e.localBaseUrl===b(t.localBaseUrl)&&e.launchUrl===S(t.launchUrl)&&e.tokenHash===_(t.bearerToken)}(s,r)){let e=v(s,o);return e!==s&&M(i.statePath,e),{pid:s.pid,spawned:!1,statePath:i.statePath,logPath:i.logPath}}s&&(await R(s),T(i));let l=function(r,o){let i=function(){let r=n(import.meta.url),o=t.extname(r)||".js",a=t.join(t.dirname(r),`metro-companion${o}`);if(!e.existsSync(a))throw Error(`Metro companion entrypoint not found at ${a}. Rebuild the package to include the companion worker entry.`);return a}(),s=i.endsWith(".ts")?["--experimental-strip-types"]:[];e.mkdirSync(t.dirname(o),{recursive:!0});let l=e.openSync(o,"a"),u=0;try{let e;u=a(process.execPath,[...s,i,g],{env:(e={...r.env??process.env,AGENT_DEVICE_METRO_COMPANION_SERVER_BASE_URL:b(r.serverBaseUrl),AGENT_DEVICE_METRO_COMPANION_BEARER_TOKEN:r.bearerToken,AGENT_DEVICE_METRO_COMPANION_LOCAL_BASE_URL:b(r.localBaseUrl),AGENT_DEVICE_METRO_COMPANION_STATE_PATH:P(r.projectRoot,r.profileKey).statePath},r.launchUrl?.trim()?e[y]=r.launchUrl.trim():delete e[y],e),stdio:["ignore",l,l]})}finally{e.closeSync(l)}if(!Number.isInteger(u)||u<=0)throw Error("Failed to start Metro companion process.");return{pid:u,startTime:c(u)??void 0,command:m(u)??void 0,serverBaseUrl:b(r.serverBaseUrl),localBaseUrl:b(r.localBaseUrl),launchUrl:S(r.launchUrl),tokenHash:_(r.bearerToken),consumers:[]}}(r,i.logPath);return M(i.statePath,v(l,o)),{pid:l.pid,spawned:!0,statePath:i.statePath,logPath:i.logPath}}async function C(e){let t=A(e),r=P(e.projectRoot,e.profileKey),n=U(r.statePath);if(!n)return T(r),{stopped:!1,statePath:r.statePath};let o=t?{...n,consumers:n.consumers.filter(e=>e!==t)}:{...n,consumers:[]};return o.consumers.length>0?(M(r.statePath,o),{stopped:!1,statePath:r.statePath}):(await R(n),T(r),{stopped:!0,statePath:r.statePath})}function x(e){return"string"==typeof e&&e.trim()?b(e.trim()):""}function $(e){return"string"==typeof e&&e.trim()?e.trim():void 0}function B(e,t,r){return s(e,{env:t,cwd:r})}function O(t){try{return e.accessSync(t,e.constants.F_OK),!0}catch{return!1}}function D(e,t,r){if(null==e||""===e)return t;let n=Number.parseInt(String(e),10);return Number.isInteger(n)?Math.max(n,r):t}function j(e,t){return{platform:t,bundleUrl:w(e,t)}}function K(e,t){return{platform:t,metroHost:$(e?.metro_host),metroPort:e?.metro_port,bundleUrl:$(e?.metro_bundle_url),launchUrl:$(e?.launch_url)}}async function L(e){await new Promise(t=>setTimeout(t,e))}async function H(e,t,r={}){try{let n=await fetch(e,{headers:r,signal:AbortSignal.timeout(t)});return{ok:n.ok,status:n.status,body:await n.text()}}catch(r){if(r instanceof Error&&"TimeoutError"===r.name)throw Error(`Timed out fetching ${e} after ${t}ms`);throw r}}async function G(e,t){try{let r=await H(e,t);return r.ok&&r.body.includes("packager-status:running")}catch{return!1}}function F(e,t){let r=Error(e);return r.retryable=t,r}async function V(e){var t,r,n,o;let a;try{a=await fetch(`${e.baseUrl}/api/metro/bridge`,{method:"POST",headers:(t=e.baseUrl,r=e.bearerToken,{Authorization:`Bearer ${r}`,"Content-Type":"application/json",...t.includes("ngrok")?{"ngrok-skip-browser-warning":"1"}:{}}),body:JSON.stringify({ios_runtime:e.runtime,timeout_ms:e.timeoutMs}),signal:AbortSignal.timeout(e.timeoutMs)})}catch(t){if(t instanceof Error&&"TimeoutError"===t.name)throw F(`/api/metro/bridge timed out after ${e.timeoutMs}ms calling ${e.baseUrl}/api/metro/bridge`,!0);throw F(t instanceof Error?t.message:String(t),!0)}let i=await a.text(),s=i?JSON.parse(i):{};if(!a.ok)throw F(`/api/metro/bridge failed (${a.status}): ${JSON.stringify(s)}`,(n=a.status,!!(n>=500||408===n||425===n||429===n||JSON.stringify(s).includes("Metro companion is not connected"))));return{enabled:(o=s.data??s).enabled,baseUrl:o.base_url,statusUrl:o.status_url??"",bundleUrl:o.bundle_url??"",iosRuntime:K(o.ios_runtime,"ios"),androidRuntime:K(o.android_runtime,"android"),upstream:{bundleUrl:o.upstream.bundle_url??"",host:o.upstream.host??"",port:o.upstream.port??0,statusUrl:o.upstream.status_url??""},probe:{reachable:o.probe.reachable,statusCode:o.probe.status_code,latencyMs:o.probe.latency_ms,detail:o.probe.detail}}}function J(e,t,r,n,o){let a=[`Metro bridge is required for this run but could not be configured via ${e}/api/metro/bridge.`];return t&&a.push(`bridgeError=${t}`),r?.probe.reachable===!1&&a.push(`bridgeProbe=${r.probe.detail||`unreachable (status ${r.probe.statusCode||0})`}`),n&&n!==t&&a.push(`initialBridgeError=${n}`),o&&a.push(`metroCompanionLog=${o}`),a.join(" ")}async function q(e,t,r){let n=Date.now()+t;for(;Date.now()<n;){let t=Math.min(r,Math.max(n-Date.now(),1));if(await G(e,t))return!0;let o=Math.min(500,Math.max(n-Date.now(),0));o>0&&await L(o)}return!1}async function z(e){let t=Date.now()+e.startupTimeoutMs,r=null,n=null;for(;Date.now()<t;){try{let t=await V({baseUrl:e.baseUrl,bearerToken:e.bearerToken,runtime:e.runtime,timeoutMs:e.probeTimeoutMs});if(!1!==t.probe.reachable)return t;r=t,n=null}catch(e){if(n=e instanceof Error?e.message:String(e),!(e&&"object"==typeof e&&"retryable"in e&&!0===e.retryable))break}let o=Math.min(1e3,Math.max(t-Date.now(),0));o>0&&await L(o)}throw Error(J(e.baseUrl,n,r,e.initialBridgeError,e.companionLogPath))}async function W(r={}){let n=r.env??process.env,s=process.cwd(),l=B(r.projectRoot??s,n,s),u=function(r,n){if("auto"!==n)return n;let o=function(r){let n=t.join(r,"package.json");if(!O(n))throw new i("INVALID_ARGS",`package.json not found at ${n}`);return JSON.parse(e.readFileSync(n,"utf8"))}(r);return"string"==typeof({...o.dependencies??{},...o.devDependencies??{}}).expo?"expo":"react-native"}(l,r.kind??"auto"),c=function(e){if(null==e||""===e)return 8081;let t=Number.parseInt(String(e),10);if(!Number.isInteger(t)||t<1||t>65535)throw new i("INVALID_ARGS",`Invalid Metro port: ${String(e)}. Use 1-65535.`);return t}(r.metroPort??8081),m=$(r.listenHost)??"0.0.0.0",d=$(r.statusHost)??"127.0.0.1",p=x(r.publicBaseUrl),f=D(r.startupTimeoutMs,18e4,3e4),h=D(r.probeTimeoutMs,1e4,1e3),g=r.reuseExisting??!0,y=r.installDependenciesIfNeeded??!0,b=r.runtimeFilePath?B(r.runtimeFilePath,n,s):null,w=B(r.logPath??t.join(l,".agent-device","metro.log"),n,s);if(!p)throw new i("INVALID_ARGS","metro prepare requires --public-base-url <url>.");let{proxyEnabled:E,proxyBaseUrl:_,proxyBearerToken:S}=function(e,t){if(e&&!t)throw new i("INVALID_ARGS","metro prepare requires proxy auth when --proxy-base-url is provided. Pass --bearer-token or set AGENT_DEVICE_PROXY_TOKEN.");if(!e&&t)throw new i("INVALID_ARGS","metro prepare requires --proxy-base-url when proxy auth is provided.");return{proxyEnabled:!!(e&&t),proxyBaseUrl:e,proxyBearerToken:t}}(x(r.proxyBaseUrl),$(r.proxyBearerToken)??""),P=y?function(r,n){if(function(t){try{return e.statSync(t).isDirectory()}catch{return!1}}(t.join(r,"node_modules")))return{installed:!1};let a=O(t.join(r,"pnpm-lock.yaml"))?{command:"pnpm",installArgs:["install"]}:O(t.join(r,"yarn.lock"))?{command:"yarn",installArgs:["install"]}:{command:"npm",installArgs:["install"]};return o(a.command,a.installArgs,{cwd:r,env:n}),{installed:!0,packageManager:a.command}}(l,n):{installed:!1},U=`http://${d}:${c}/status`,M=!1,k=!1,T=0;if(g&&await G(U,h))k=!0;else if(M=!0,T=function(r,n,o,i,s,l){let u="expo"===n?{command:"npx",installArgs:["expo","start","--host","lan","--port",String(o)]}:{command:"npx",installArgs:["react-native","start","--host",i,"--port",String(o)]};e.mkdirSync(t.dirname(s),{recursive:!0});let c=e.openSync(s,"a"),m=0;try{m=a(u.command,u.installArgs,{cwd:r,env:l,stdio:["ignore",c,c]})}finally{e.closeSync(c)}if(!Number.isInteger(m)||m<=0)throw Error("Failed to start Metro. Expected a detached child PID.");return{pid:m}}(l,u,c,m,w,n).pid,!await q(U,f,h))throw Error(`Metro did not become ready at ${U} within ${f}ms. Check ${w}.`);let N=j(p,"ios"),A=j(p,"android"),v=null,R=null;if(E)try{v=await V({baseUrl:_,bearerToken:S,runtime:{metro_bundle_url:N.bundleUrl},timeoutMs:h})}catch(e){R=e instanceof Error?e.message:String(e)}if(E&&(!v||!1===v.probe.reachable)){let e;try{e=(await I({projectRoot:l,serverBaseUrl:_,bearerToken:S,localBaseUrl:`http://${d}:${c}`,launchUrl:$(r.launchUrl),profileKey:$(r.companionProfileKey),consumerKey:$(r.companionConsumerKey),env:n})).logPath}catch(e){throw Error(J(_,e instanceof Error?e.message:String(e),v,R))}try{v=await z({baseUrl:_,bearerToken:S,runtime:{metro_bundle_url:N.bundleUrl},probeTimeoutMs:h,startupTimeoutMs:f,initialBridgeError:R,companionLogPath:e})}catch(e){throw e instanceof Error?e:Error(String(e))}}let C=v?.iosRuntime??N,K=v?.androidRuntime??A,L={projectRoot:l,kind:u,dependenciesInstalled:P.installed,packageManager:P.packageManager??null,started:M,reused:k,pid:T,logPath:w,statusUrl:U,runtimeFilePath:b,iosRuntime:C,androidRuntime:K,bridge:v};return b&&(e.mkdirSync(t.dirname(b),{recursive:!0}),e.writeFileSync(b,JSON.stringify(L,null,2))),L}export{w as buildBundleUrl,j as buildMetroRuntimeHints,I as ensureMetroCompanion,d as isAgentDeviceDaemonProcess,b as normalizeBaseUrl,W as prepareMetroRuntime,C as stopMetroCompanion,h as stopProcessForTakeover};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
let t;import e from"node:fs/promises";import r from"node:path";import{TextDecoder as n}from"node:util";import{runCmd as a}from"./818.js";import{resolveAndroidSdkRoots as i}from"./164.js";let f=new n("utf-16le");async function o(t){for(let r of["AndroidManifest.xml","base/manifest/AndroidManifest.xml"]){var e;let n=await u(t,r);if(!n)continue;let a=(e=n).subarray(0,Math.min(e.length,128)).toString("utf8").trimStart().startsWith("<")?function(t){let e=t.match(/<manifest\b[^>]*\bpackage\s*=\s*["']([^"']+)["']/i);return e?.[1]}(e.toString("utf8")):function(t){let e;if(!(t.length<8)&&3===t.readUInt16LE(0))for(let r=t.readUInt16LE(2);r+8<=t.length;){let n=t.readUInt16LE(r),a=t.readUInt16LE(r+2),i=t.readUInt32LE(r+4);if(i<=0||r+i>t.length)break;if(1===n)e=function(t){if(t.length<28)return[];let e=t.readUInt32LE(8),r=t.readUInt32LE(16),n=t.readUInt32LE(20),a=(256&r)!=0,i=[];for(let r=0;r<e;r+=1){let e=28+4*r;if(e+4>t.length)break;let o=n+t.readUInt32LE(e);i.push(a?function(t,e){let[,r]=l(t,e),[n,a]=l(t,e+r),i=e+r+a;return t.subarray(i,i+n).toString("utf8")}(t,o):function(t,e){let[r,n]=function(t,e){let r=t.readUInt16LE(e);return(32768&r)==0?[r,2]:[(32767&r)<<16|t.readUInt16LE(e+2),4]}(t,e),a=e+n;return f.decode(t.subarray(a,a+2*r))}(t,o))}return i}(t.subarray(r,r+i));else if(258===n&&e){let n=function(t,e,r,n){if(r<36||e+r>t.length||"manifest"!==n[t.readUInt32LE(e+20)])return;let a=t.readUInt16LE(e+24),i=t.readUInt16LE(e+26),f=t.readUInt16LE(e+28),o=e+a;for(let e=0;e<f;e+=1){let r=o+e*i;if(r+20>t.length)break;if("package"!==n[t.readUInt32LE(r+4)])continue;let a=t.readUInt32LE(r+8);if(0xffffffff!==a)return n[a];let f=t.readUInt8(r+15),u=t.readUInt32LE(r+16);if(3===f)return n[u];break}}(t,r,a,e);if(n)return n}r+=i}}(e);if(a)return a}return await d(t)}async function u(t,e){try{let r=await a("unzip",["-p",t,e],{allowFailure:!0,binaryStdout:!0});if(0!==r.exitCode||!r.stdoutBuffer||0===r.stdoutBuffer.length)return;return r.stdoutBuffer}catch{return}}function l(t,e){let r=t.readUInt8(e);return(128&r)==0?[r,1]:[(127&r)<<8|t.readUInt8(e+1),2]}async function d(t){let e=await c();if(!e)return;let r=await a(e,["dump","badging",t],{allowFailure:!0});if(0!==r.exitCode)return;let n=r.stdout.match(/package:\s+name='([^']+)'/);return n?.[1]}async function c(){if(void 0!==t)return t??void 0;try{for(let n of i()){let a=r.join(n,"build-tools");try{for(let n of(await e.readdir(a)).sort((t,e)=>e.localeCompare(t,void 0,{numeric:!0}))){let i=r.join(a,n,"aapt");try{return await e.access(i),t=i,i}catch{}}}catch{}}}catch{}t=null}export{o as resolveAndroidArchivePackageName};
|