agent-device 0.12.7 → 0.12.9
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/4829.js +1 -0
- package/dist/src/4993.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/9152.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/backend.js +1 -1
- package/dist/src/bin.d.ts +1 -0
- package/dist/src/bin.js +68 -70
- package/dist/src/commands/index.d.ts +4 -1
- package/dist/src/commands/index.js +1 -1
- package/dist/src/contracts.d.ts +3 -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.d.ts +17 -11
- 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.d.ts +9 -11
- 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 +9 -1
- package/skills/agent-device/references/exploration.md +1 -0
- package/skills/agent-device/references/remote-tenancy.md +9 -6
- package/skills/agent-device/references/verification.md +3 -0
- package/dist/src/152.js +0 -1
- 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/{1~rslib-runtime.js → rslib-runtime.js} +0 -0
package/dist/src/818.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{constants as t}from"node:fs";import{access as e,stat as r}from"node:fs/promises";import o from"node:path";import{spawn as n,spawnSync as i}from"node:child_process";import{AppError as u}from"./152.js";let s=/^[A-Za-z0-9][A-Za-z0-9._+-]*$/,d=[".com",".exe",".bat",".cmd"];async function f(t,e,r={}){let o=m(t);return new Promise((i,s)=>{let d=n(o,e,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],detached:r.detached,shell:!1}),f="",l=r.binaryStdout?Buffer.alloc(0):void 0,a="",c=!1,m=A(r.timeoutMs),p=m?setTimeout(()=>{c=!0,d.kill("SIGKILL")},m):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",t=>{r.binaryStdout?l=Buffer.concat([l??Buffer.alloc(0),Buffer.isBuffer(t)?t:Buffer.from(t)]):f+=t}),d.stderr.on("data",t=>{a+=t}),d.on("error",r=>{(p&&clearTimeout(p),"ENOENT"===r.code)?s(new u("TOOL_MISSING",`${o} not found in PATH`,{cmd:t},r)):s(new u("COMMAND_FAILED",`Failed to run ${o}`,{cmd:t,args:e},r))}),d.on("close",n=>{p&&clearTimeout(p);let d=n??1;c&&m?s(new u("COMMAND_FAILED",`${o} timed out after ${m}ms`,{cmd:t,args:e,stdout:f,stderr:a,exitCode:d,timeoutMs:m})):0===d||r.allowFailure?i({stdout:f,stderr:a,exitCode:d,stdoutBuffer:l}):s(new u("COMMAND_FAILED",`${o} exited with code ${d}`,{cmd:t,args:e,stdout:f,stderr:a,exitCode:d,processExitError:!0}))})})}async function l(t){let e=p(t);if(!e)return!1;if(o.isAbsolute(e))return w(e);let r=process.env.PATH;if(!r)return!1;let n=function(){if("win32"!==process.platform)return[""];let t=process.env.PATHEXT;if(!t)return d;let e=t.split(";").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0);return e.length>0?e:d}();for(let t of r.split(o.delimiter)){let r=t.trim();if(r){for(let t of function(t,e){if("win32"!==process.platform)return[t];let r=t.toLowerCase();return e.some(t=>r.endsWith(t))?[t]:e.map(e=>`${t}${e}`)}(e,n))if(await w(o.join(r,t)))return!0}}return!1}function a(t,e,r={}){let o=m(t),n=i(o,e,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],encoding:r.binaryStdout?void 0:"utf8",input:r.stdin,timeout:A(r.timeoutMs),shell:!1});if(n.error){let i=n.error.code;if("ETIMEDOUT"===i)throw new u("COMMAND_FAILED",`${o} timed out after ${A(r.timeoutMs)}ms`,{cmd:t,args:e,timeoutMs:A(r.timeoutMs)},n.error);if("ENOENT"===i)throw new u("TOOL_MISSING",`${o} not found in PATH`,{cmd:t},n.error);throw new u("COMMAND_FAILED",`Failed to run ${o}`,{cmd:t,args:e},n.error)}let s=r.binaryStdout?Buffer.isBuffer(n.stdout)?n.stdout:Buffer.from(n.stdout??""):void 0,d=r.binaryStdout?"":"string"==typeof n.stdout?n.stdout:(n.stdout??"").toString(),f="string"==typeof n.stderr?n.stderr:(n.stderr??"").toString(),l=n.status??1;if(0!==l&&!r.allowFailure)throw new u("COMMAND_FAILED",`${o} exited with code ${l}`,{cmd:t,args:e,stdout:d,stderr:f,exitCode:l,processExitError:!0});return{stdout:d,stderr:f,exitCode:l,stdoutBuffer:s}}function c(t,e,r={}){let o=n(m(t),e,{cwd:r.cwd,env:r.env,stdio:r.stdio??"ignore",detached:!0,shell:!1});return o.unref(),o.pid??0}function m(t){let e=p(t);if(!e)throw new u("INVALID_ARGS",`Invalid executable command: ${JSON.stringify(t)}`,{cmd:t,hint:"Use a bare command name from PATH or an absolute executable path."});return e}function p(t){let e=t.trim();return!e||e.includes("\0")?null:o.isAbsolute(e)?e:e.includes("/")||e.includes("\\")?null:s.test(e)?e:null}async function w(r){try{if(!await h(r))return!1;return await e(r,"win32"===process.platform?t.F_OK:t.X_OK),!0}catch{return!1}}async function h(t){try{return(await r(t)).isFile()}catch{return!1}}function A(t){if(!Number.isFinite(t))return;let e=Math.floor(t);if(!(e<=0))return e}export{w as isExecutablePath,f as runCmd,c as runCmdDetached,a as runCmdSync,l as whichCmd};(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
|