agent-device 0.12.6 → 0.12.8
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/113.js +1 -1
- package/dist/src/1974.js +2 -0
- package/dist/src/3883.js +1 -0
- package/dist/src/3918.js +32 -0
- package/dist/src/4057.js +1 -0
- package/dist/src/7556.js +1 -0
- package/dist/src/7651.js +1 -0
- package/dist/src/7847.js +1 -0
- package/dist/src/8164.js +1 -0
- package/dist/src/8564.js +3 -0
- package/dist/src/9076.js +1 -0
- package/dist/src/9323.js +5 -0
- package/dist/src/9366.js +1 -0
- package/dist/src/9542.js +2 -0
- package/dist/src/9818.js +1 -0
- package/dist/src/989.js +1 -0
- package/dist/src/android-apps.js +1 -1
- package/dist/src/artifacts.js +1 -1
- package/dist/src/bin.d.ts +1 -0
- package/dist/src/bin.js +68 -70
- package/dist/src/commands/index.js +1 -1
- package/dist/src/contracts.js +1 -1
- package/dist/src/daemon.d.ts +1 -0
- package/dist/src/daemon.js +15 -15
- package/dist/src/finders.js +1 -1
- package/dist/src/index.js +1 -3
- package/dist/src/install-source.js +1 -1
- package/dist/src/io.js +1 -1
- package/dist/src/metro-companion.d.ts +1 -0
- package/dist/src/metro.js +1 -1
- package/dist/src/remote-config.js +1 -1
- package/dist/src/selectors.js +1 -1
- package/dist/src/testing/conformance.js +1 -1
- package/dist/src/update-check-entry.d.ts +1 -0
- package/package.json +1 -1
- package/skills/agent-device/references/bootstrap-install.md +5 -3
- package/skills/agent-device/references/remote-tenancy.md +53 -13
- package/dist/src/164.js +0 -1
- package/dist/src/556.js +0 -1
- package/dist/src/57.js +0 -1
- package/dist/src/641.js +0 -38
- package/dist/src/818.js +0 -1
- package/dist/src/974.js +0 -2
- /package/dist/src/{267.js → 3267.js} +0 -0
- /package/dist/src/{152.js → 9152.js} +0 -0
- /package/dist/src/{1~rslib-runtime.js → rslib-runtime.js} +0 -0
package/dist/src/818.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
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,a=/(bearer\s+[a-z0-9._-]+|(?:api[_-]?key|token|secret|password)\s*[=:]\s*\S+)/i;function d(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)||a.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 d={};for(let[n,o]of Object.entries(t)){if(s.test(n)){d[n]="[REDACTED]";continue}d[n]=e(o,r,n)}return d}(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?d(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"NOT_IMPLEMENTED":return"This command is part of the planned API but is not implemented yet.";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:a,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=I(e);return new Promise((i,s)=>{let a=o(n,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],detached:r.detached,shell:!1}),d="",l=r.binaryStdout?Buffer.alloc(0):void 0,c="",f=!1,p=y(r.timeoutMs),m=p?setTimeout(()=>{f=!0,a.kill("SIGKILL")},p):null;r.binaryStdout||a.stdout.setEncoding("utf8"),a.stderr.setEncoding("utf8"),void 0!==r.stdin&&a.stdin.write(r.stdin),a.stdin.end(),a.stdout.on("data",e=>{r.binaryStdout?l=Buffer.concat([l??Buffer.alloc(0),Buffer.isBuffer(e)?e:Buffer.from(e)]):d+=e}),a.stderr.on("data",e=>{c+=e}),a.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))}),a.on("close",o=>{m&&clearTimeout(m);let a=o??1;f&&p?s(new u("COMMAND_FAILED",`${n} timed out after ${p}ms`,{cmd:e,args:t,stdout:d,stderr:c,exitCode:a,timeoutMs:p})):0===a||r.allowFailure?i({stdout:d,stderr:c,exitCode:a,stdoutBuffer:l}):s(new u("COMMAND_FAILED",`${n} exited with code ${a}`,{cmd:e,args:t,stdout:d,stderr:c,exitCode:a,processExitError:!0}))})})}async function h(e){let t=S(e);if(!t)return!1;if(n.isAbsolute(t))return T(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 T(n.join(r,e)))return!0}}return!1}async function w(e,t){let r=D(e,t,"executable");if(r){if(!await T(r))throw new u("TOOL_MISSING",`${t} points to a missing or non-executable file: ${r}`,{envName:t,path:r});return r}}async function E(e,t){let r=D(e,t,"file");if(r){if(!await M(r))throw new u("TOOL_MISSING",`${t} points to a missing or non-file path: ${r}`,{envName:t,path:r});return r}}function A(e,t,r={}){let n=I(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:y(r.timeoutMs),shell:!1});if(o.error){let i=o.error.code;if("ETIMEDOUT"===i)throw new u("COMMAND_FAILED",`${n} timed out after ${y(r.timeoutMs)}ms`,{cmd:e,args:t,timeoutMs:y(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,a=r.binaryStdout?"":"string"==typeof o.stdout?o.stdout:(o.stdout??"").toString(),d="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:a,stderr:d,exitCode:l,processExitError:!0});return{stdout:a,stderr:d,exitCode:l,stdoutBuffer:s}}function g(e,t,r={}){let n=o(I(e),t,{cwd:r.cwd,env:r.env,stdio:r.stdio??"ignore",detached:!0,shell:!1});return n.unref(),n.pid??0}async function O(e,t,r={}){let n=I(e);return new Promise((i,s)=>{let a=o(n,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],detached:r.detached,shell:!1});r.onSpawn?.(a);let d="",l="",c=r.binaryStdout?Buffer.alloc(0):void 0,f=!1,p=y(r.timeoutMs),m=p?setTimeout(()=>{f=!0,a.kill("SIGKILL")},p):null;r.binaryStdout||a.stdout.setEncoding("utf8"),a.stderr.setEncoding("utf8"),void 0!==r.stdin&&a.stdin.write(r.stdin),a.stdin.end(),a.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);d+=t,r.onStdoutChunk?.(t)}),a.stderr.on("data",e=>{let t=String(e);l+=t,r.onStderrChunk?.(t)}),a.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))}),a.on("close",o=>{m&&clearTimeout(m);let a=o??1;f&&p?s(new u("COMMAND_FAILED",`${n} timed out after ${p}ms`,{cmd:e,args:t,stdout:d,stderr:l,exitCode:a,timeoutMs:p})):0===a||r.allowFailure?i({stdout:d,stderr:l,exitCode:a,stdoutBuffer:c}):s(new u("COMMAND_FAILED",`${n} exited with code ${a}`,{cmd:e,args:t,stdout:d,stderr:l,exitCode:a,processExitError:!0}))})})}function N(e,t,r={}){let n=I(e),i=o(n,t,{cwd:r.cwd,env:r.env,stdio:["ignore","pipe","pipe"],detached:r.detached,shell:!1}),s="",a="";i.stdout.setEncoding("utf8"),i.stderr.setEncoding("utf8"),i.stdout.on("data",e=>{s+=e}),i.stderr.on("data",e=>{a+=e});let d=new Promise((o,d)=>{i.on("error",r=>{"ENOENT"===r.code?d(new u("TOOL_MISSING",`${n} not found in PATH`,{cmd:e},r)):d(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:a,exitCode:l}):d(new u("COMMAND_FAILED",`${n} exited with code ${l}`,{cmd:e,args:t,stdout:s,stderr:a,exitCode:l,processExitError:!0}))})});return{child:i,wait:d}}function I(e){let t=S(e);if(!t)throw new u("INVALID_ARGS",`Invalid executable command: ${JSON.stringify(e)}`,{cmd:e,hint:"Use a bare command name from PATH or an absolute executable path."});return t}function D(e,t,r){let o=e?.trim();if(o){if(!n.isAbsolute(o)||o.includes("\0"))throw new u("INVALID_ARGS",`${t} must be an absolute ${r} path, not ${JSON.stringify(e)}`,{envName:t,path:e});return o}}function S(e){let t=e.trim();return!t||t.includes("\0")?null:n.isAbsolute(t)?t:t.includes("/")||t.includes("\\")?null:f.test(t)?t:null}async function T(r){try{if(!await M(r))return!1;return await t(r,"win32"===process.platform?e.F_OK:e.X_OK),!0}catch{return!1}}async function M(e){try{return(await r(e)).isFile()}catch{return!1}}function y(e){if(!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t}export{u as AppError,l as asAppError,T as isExecutablePath,c as normalizeError,d as redactDiagnosticData,w as resolveExecutableOverridePath,E as resolveFileOverridePath,m as runCmd,N as runCmdBackground,g as runCmdDetached,O as runCmdStreaming,A as runCmdSync,h as whichCmd};
|
package/dist/src/974.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import e from"node:fs";import r from"node:path";import{createHash as t}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 r=o("ps",["-p",String(e),"-o","lstart="],{allowFailure:!0,timeoutMs:1e3});if(0!==r.exitCode)return null;let t=r.stdout.trim();return t.length>0?t:null}catch{return null}}function d(e){if(!Number.isInteger(e)||e<=0)return null;try{let r=o("ps",["-p",String(e),"-o","command="],{allowFailure:!0,timeoutMs:1e3});if(0!==r.exitCode)return null;let t=r.stdout.trim();return t.length>0?t:null}catch{return null}}function m(e,r){let t;if(!u(e))return!1;if(r){let t=c(e);if(!t||t!==r)return!1}let n=d(e);return!!n&&!!(t=n.toLowerCase().replaceAll("\\","/")).includes("agent-device")&&l.some(e=>e.test(t))}function p(e,r){try{return process.kill(e,r),!0}catch(r){let e=r.code;if("ESRCH"===e||"EPERM"===e)return!1;throw r}}async function f(e,r){if(!u(e))return!0;let t=Date.now();for(;Date.now()-t<r;)if(await new Promise(e=>setTimeout(e,50)),!u(e))return!0;return!u(e)}async function h(e,r){!m(e,r.expectedStartTime)||!p(e,"SIGTERM")||await f(e,r.termTimeoutMs)||p(e,"SIGKILL")&&await f(e,r.killTimeoutMs)}let g="--agent-device-run-metro-companion",y="AGENT_DEVICE_METRO_COMPANION_LAUNCH_URL";function b(e){let r=e.length;for(;r>0&&47===e.charCodeAt(r-1);)r-=1;return r===e.length?e:e.slice(0,r)}function E(e,r){let t=new URL(`${b(e)}/index.bundle`);return t.searchParams.set("platform",r),t.searchParams.set("dev","true"),t.searchParams.set("minify","false"),t.toString()}let S="metro-companion";function _(e){return t("sha256").update(e).digest("hex")}function w(e){return e?.trim()?e.trim():void 0}function I(e,t){let n=r.join(e,".agent-device");if(!t)return{statePath:r.join(n,"metro-companion.json"),logPath:r.join(n,"metro-companion.log")};let o=_(t).slice(0,12),a=r.join(n,S);return{statePath:r.join(a,`metro-companion-${o}.json`),logPath:r.join(a,`metro-companion-${o}.log`)}}function P(r){try{let t=JSON.parse(e.readFileSync(r,"utf8"));if(!Number.isInteger(t.pid)||0>=Number(t.pid)||"string"!=typeof t.serverBaseUrl||"string"!=typeof t.localBaseUrl||"string"!=typeof t.tokenHash||0===t.tokenHash.length)return null;let n=Array.isArray(t.consumers)?t.consumers.filter(e=>"string"==typeof e&&e.length>0):[];return{pid:Number(t.pid),startTime:"string"==typeof t.startTime?t.startTime:void 0,command:"string"==typeof t.command?t.command:void 0,serverBaseUrl:t.serverBaseUrl,localBaseUrl:t.localBaseUrl,launchUrl:w("string"==typeof t.launchUrl?t.launchUrl:void 0),bridgeScope:function(e){if(!(!e||"object"!=typeof e||Array.isArray(e))&&"string"==typeof e.tenantId&&"string"==typeof e.runId&&"string"==typeof e.leaseId)return{tenantId:e.tenantId,runId:e.runId,leaseId:e.leaseId}}(t.bridgeScope),tokenHash:t.tokenHash,consumers:n}}catch{return null}}function N(t,n){e.mkdirSync(r.dirname(t),{recursive:!0}),e.writeFileSync(t,`${JSON.stringify(n,null,2)}
|
|
2
|
-
`,"utf8")}function M(r){try{let t=e.readdirSync(r);0===t.length&&e.rmdirSync(r)}catch{}}function A(t){let n=r.dirname(t.statePath),o=r.dirname(t.logPath);var a=t.statePath;try{e.unlinkSync(a)}catch{}var i=t.logPath;try{e.unlinkSync(i)}catch{}M(n),o!==n&&M(o),r.basename(n)===S&&M(r.dirname(n))}function U(e){return e.includes(g)}function T(e){return w(e.consumerKey)??w(e.profileKey)??null}function R(e,r){return!r||e.consumers.includes(r)?e:{...e,consumers:[...e.consumers,r]}}async function k(e){if(!u(e.pid))return;let r=d(e.pid);if(r&&U(r)){try{process.kill(e.pid,"SIGTERM")}catch(r){let e=r.code;if("ESRCH"===e||"EPERM"===e)return;throw r}if(!await f(e.pid,1e3)){try{process.kill(e.pid,"SIGKILL")}catch(r){let e=r.code;if("ESRCH"===e||"EPERM"===e)return;throw r}await f(e.pid,1e3)}}}async function v(t){let o=T(t),i=I(t.projectRoot,t.profileKey),s=P(i.statePath);if(s&&function(e,r){var t,n;if(!u(e.pid))return!1;if(e.startTime){let r=c(e.pid);if(!r||r!==e.startTime)return!1}let o=d(e.pid);return!!o&&!!U(o)&&!!e.bridgeScope&&e.serverBaseUrl===b(r.serverBaseUrl)&&e.localBaseUrl===b(r.localBaseUrl)&&e.launchUrl===w(r.launchUrl)&&(t=e.bridgeScope,n=r.bridgeScope,t.tenantId===n.tenantId&&t.runId===n.runId&&t.leaseId===n.leaseId)&&e.tokenHash===_(r.bearerToken)}(s,t)){let e=R(s,o);return e!==s&&N(i.statePath,e),{pid:s.pid,spawned:!1,statePath:i.statePath,logPath:i.logPath}}s&&(await k(s),A(i));let l=function(t,o){let i=function(){let t=n(import.meta.url),o=r.extname(t)||".js",a=r.join(r.dirname(t),`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(r.dirname(o),{recursive:!0});let l=e.openSync(o,"a"),u=0;try{let e;u=a(process.execPath,[...s,i,g],{env:((e={...t.env??process.env,AGENT_DEVICE_METRO_COMPANION_SERVER_BASE_URL:b(t.serverBaseUrl),AGENT_DEVICE_METRO_COMPANION_BEARER_TOKEN:t.bearerToken,AGENT_DEVICE_METRO_COMPANION_LOCAL_BASE_URL:b(t.localBaseUrl),AGENT_DEVICE_METRO_COMPANION_STATE_PATH:I(t.projectRoot,t.profileKey).statePath}).AGENT_DEVICE_METRO_COMPANION_SCOPE_TENANT_ID=t.bridgeScope.tenantId,e.AGENT_DEVICE_METRO_COMPANION_SCOPE_RUN_ID=t.bridgeScope.runId,e.AGENT_DEVICE_METRO_COMPANION_SCOPE_LEASE_ID=t.bridgeScope.leaseId,t.launchUrl?.trim()?e[y]=t.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:d(u)??void 0,serverBaseUrl:b(t.serverBaseUrl),localBaseUrl:b(t.localBaseUrl),launchUrl:w(t.launchUrl),bridgeScope:t.bridgeScope,tokenHash:_(t.bearerToken),consumers:[]}}(t,i.logPath);return N(i.statePath,R(l,o)),{pid:l.pid,spawned:!0,statePath:i.statePath,logPath:i.logPath}}async function C(e){let r=T(e),t=I(e.projectRoot,e.profileKey),n=P(t.statePath);if(!n)return A(t),{stopped:!1,statePath:t.statePath};let o=r?{...n,consumers:n.consumers.filter(e=>e!==r)}:{...n,consumers:[]};return o.consumers.length>0?(N(t.statePath,o),{stopped:!1,statePath:t.statePath}):(await k(n),A(t),{stopped:!0,statePath:t.statePath})}function O(e){return"string"==typeof e&&e.trim()?b(e.trim()):""}function $(e){return"string"==typeof e&&e.trim()?e.trim():void 0}function x(e,r,t){return s(e,{env:r,cwd:t})}function D(r){try{return e.accessSync(r,e.constants.F_OK),!0}catch{return!1}}function j(e,r,t){if(null==e||""===e)return r;let n=Number.parseInt(String(e),10);return Number.isInteger(n)?Math.max(n,t):r}function B(e,r){return{platform:r,bundleUrl:E(e,r)}}function L(e,r){return{platform:r,metroHost:$(e?.metro_host),metroPort:e?.metro_port,bundleUrl:$(e?.metro_bundle_url),launchUrl:$(e?.launch_url)}}async function G(e){await new Promise(r=>setTimeout(r,e))}async function K(e,r,t={}){try{let n=await fetch(e,{headers:t,signal:AbortSignal.timeout(r)});return{ok:n.ok,status:n.status,body:await n.text()}}catch(t){if(t instanceof Error&&"TimeoutError"===t.name)throw Error(`Timed out fetching ${e} after ${r}ms`);throw t}}async function H(e,r){try{let t=await K(e,r);return t.ok&&t.body.includes("packager-status:running")}catch{return!1}}async function V(e){if(Number.isInteger(e)&&!(e<=0)){try{process.kill(e,"SIGTERM")}catch(r){let e=r.code;if("ESRCH"===e||"EPERM"===e)return;throw r}if(!await f(e,1e3)){try{process.kill(e,"SIGKILL")}catch(r){let e=r.code;if("ESRCH"===e||"EPERM"===e)return;throw r}await f(e,1e3)}}}function F(e,r){let t=Error(e);return t.retryable=r,t}function J(e,r){return!!(e>=500||408===e||425===e||429===e||JSON.stringify(r).includes("Metro companion is not connected"))}function q(e){return!!(e&&"object"==typeof e&&"retryable"in e&&!0===e.retryable)}async function z(e){let r;try{var t,n;r=await fetch(`${e.baseUrl}/api/metro/bridge`,{method:"POST",headers:(t=e.baseUrl,n=e.bearerToken,{Authorization:`Bearer ${n}`,"Content-Type":"application/json",...t.includes("ngrok")?{"ngrok-skip-browser-warning":"1"}:{}}),body:JSON.stringify({...e.scope,ios_runtime:e.runtime,timeout_ms:e.timeoutMs}),signal:AbortSignal.timeout(e.timeoutMs)})}catch(r){if(r instanceof Error&&"TimeoutError"===r.name)throw F(`/api/metro/bridge timed out after ${e.timeoutMs}ms calling ${e.baseUrl}/api/metro/bridge`,!0);throw F(r instanceof Error?r.message:String(r),!0)}let o=function(e,r,t){if(!e)return{};try{let r=JSON.parse(e);if(!r||"object"!=typeof r||Array.isArray(r))throw Error("Expected a JSON object");return r}catch(a){let n=e.slice(0,200),o=a instanceof Error?a.message:String(a);throw F(`/api/metro/bridge returned invalid JSON (${r}) from ${t}: ${o}. body=${JSON.stringify(n)}`,J(r,e))}}(await r.text(),r.status,e.baseUrl);if(!r.ok)throw F(`/api/metro/bridge failed (${r.status}): ${JSON.stringify(o)}`,J(r.status,o));var a=o;let i=a.data??a;if(!i||"object"!=typeof i||Array.isArray(i))throw F("/api/metro/bridge returned malformed descriptor: Expected a JSON object.",!1);try{return{enabled:i.enabled,baseUrl:i.base_url,statusUrl:i.status_url??"",bundleUrl:i.bundle_url??"",iosRuntime:L(i.ios_runtime,"ios"),androidRuntime:L(i.android_runtime,"android"),upstream:{bundleUrl:i.upstream.bundle_url??"",host:i.upstream.host??"",port:i.upstream.port??0,statusUrl:i.upstream.status_url??""},probe:{reachable:i.probe.reachable,statusCode:i.probe.status_code,latencyMs:i.probe.latency_ms,detail:i.probe.detail}}}catch(e){throw F(`/api/metro/bridge returned malformed descriptor: ${e instanceof Error?e.message:String(e)}`,!1)}}function W(e,r,t,n,o){let a=[`Metro bridge is required for this run but could not be configured via ${e}/api/metro/bridge.`];return r&&a.push(`bridgeError=${r}`),t?.probe.reachable===!1&&a.push(`bridgeProbe=${t.probe.detail||`unreachable (status ${t.probe.statusCode||0})`}`),n&&n!==r&&a.push(`initialBridgeError=${n}`),o&&a.push(`metroCompanionLog=${o}`),a.join(" ")}async function X(e,r,t){let n=Date.now()+r;for(;Date.now()<n;){let r=Math.min(t,Math.max(n-Date.now(),1));if(await H(e,r))return!0;let o=Math.min(500,Math.max(n-Date.now(),0));o>0&&await G(o)}return!1}async function Y(e){let r=Date.now()+e.startupTimeoutMs,t=null,n=null;for(;Date.now()<r;){try{let r=await z({baseUrl:e.baseUrl,bearerToken:e.bearerToken,scope:e.scope,runtime:e.runtime,timeoutMs:e.probeTimeoutMs});if(!1!==r.probe.reachable)return r;t=r,n=null}catch(e){if(n=e instanceof Error?e.message:String(e),!q(e))break}let o=Math.min(1e3,Math.max(r-Date.now(),0));o>0&&await G(o)}throw Error(W(e.baseUrl,n,t,e.initialBridgeError,e.companionLogPath))}async function Q(t={}){let n=t.env??process.env,s=process.cwd(),l=x(t.projectRoot??s,n,s),u=function(t,n){if("auto"!==n)return n;let o=function(t){let n=r.join(t,"package.json");if(!D(n))throw new i("INVALID_ARGS",`package.json not found at ${n}`);return JSON.parse(e.readFileSync(n,"utf8"))}(t);return"string"==typeof({...o.dependencies??{},...o.devDependencies??{}}).expo?"expo":"react-native"}(l,t.kind??"auto"),c=function(e){if(null==e||""===e)return 8081;let r=Number.parseInt(String(e),10);if(!Number.isInteger(r)||r<1||r>65535)throw new i("INVALID_ARGS",`Invalid Metro port: ${String(e)}. Use 1-65535.`);return r}(t.metroPort??8081),d=$(t.listenHost)??"0.0.0.0",m=$(t.statusHost)??"127.0.0.1",p=O(t.publicBaseUrl),f=j(t.startupTimeoutMs,18e4,3e4),h=j(t.probeTimeoutMs,1e4,1e3),g=t.reuseExisting??!0,y=t.installDependenciesIfNeeded??!0,b=t.runtimeFilePath?x(t.runtimeFilePath,n,s):null,E=x(t.logPath??r.join(l,".agent-device","metro.log"),n,s);if(!p)throw new i("INVALID_ARGS","metro prepare requires --public-base-url <url>.");let{proxyEnabled:S,proxyBaseUrl:_,proxyBearerToken:w}=function(e,r){if(e&&!r)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&&r)throw new i("INVALID_ARGS","metro prepare requires --proxy-base-url when proxy auth is provided.");return{proxyEnabled:!!(e&&r),proxyBaseUrl:e,proxyBearerToken:r}}(O(t.proxyBaseUrl),$(t.proxyBearerToken)??""),I=S?function(e){if(!e?.tenantId||!e.runId||!e.leaseId)throw new i("INVALID_ARGS","metro prepare with proxy requires tenantId, runId, and leaseId bridge scope.");return e}(t.bridgeScope):null,P=y?function(t,n){if(function(r){try{return e.statSync(r).isDirectory()}catch{return!1}}(r.join(t,"node_modules")))return{installed:!1};let a=D(r.join(t,"pnpm-lock.yaml"))?{command:"pnpm",installArgs:["install"]}:D(r.join(t,"yarn.lock"))?{command:"yarn",installArgs:["install"]}:{command:"npm",installArgs:["install"]};return o(a.command,a.installArgs,{cwd:t,env:n}),{installed:!0,packageManager:a.command}}(l,n):{installed:!1},N=`http://${m}:${c}/status`,M=!1,A=!1,U=0;if(g&&await H(N,h))A=!0;else if(M=!0,U=function(t,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(r.dirname(s),{recursive:!0});let c=e.openSync(s,"a"),d=0;try{d=a(u.command,u.installArgs,{cwd:t,env:l,stdio:["ignore",c,c]})}finally{e.closeSync(c)}if(!Number.isInteger(d)||d<=0)throw Error("Failed to start Metro. Expected a detached child PID.");return{pid:d}}(l,u,c,d,E,n).pid,!await X(N,f,h))throw await V(U).catch(()=>{}),Error(`Metro did not become ready at ${N} within ${f}ms. Check ${E}.`);let T=B(p,"ios"),R=B(p,"android"),k=null,C=null;if(I)try{k=await z({baseUrl:_,bearerToken:w,scope:I,runtime:{metro_bundle_url:T.bundleUrl},timeoutMs:h})}catch(e){if(!q(e))throw e;C=e instanceof Error?e.message:String(e)}if(I&&(!k||!1===k.probe.reachable)){let e;try{e=(await v({projectRoot:l,serverBaseUrl:_,bearerToken:w,bridgeScope:I,localBaseUrl:`http://${m}:${c}`,launchUrl:$(t.launchUrl),profileKey:$(t.companionProfileKey),consumerKey:$(t.companionConsumerKey),env:n})).logPath}catch(e){throw Error(W(_,e instanceof Error?e.message:String(e),k,C))}try{k=await Y({baseUrl:_,bearerToken:w,scope:I,runtime:{metro_bundle_url:T.bundleUrl},probeTimeoutMs:h,startupTimeoutMs:f,initialBridgeError:C,companionLogPath:e})}catch(e){throw e instanceof Error?e:Error(String(e))}}let L=k?.iosRuntime??T,G=k?.androidRuntime??R,K={projectRoot:l,kind:u,dependenciesInstalled:P.installed,packageManager:P.packageManager??null,started:M,reused:A,pid:U,logPath:E,statusUrl:N,runtimeFilePath:b,iosRuntime:L,androidRuntime:G,bridge:k};return b&&(e.mkdirSync(r.dirname(b),{recursive:!0}),e.writeFileSync(b,JSON.stringify(K,null,2))),K}export{E as buildBundleUrl,B as buildMetroRuntimeHints,v as ensureMetroCompanion,m as isAgentDeviceDaemonProcess,b as normalizeBaseUrl,Q as prepareMetroRuntime,C as stopMetroCompanion,h as stopProcessForTakeover};
|
|
File without changes
|
|
File without changes
|
|
File without changes
|