agent-device 0.13.0 → 0.13.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -0
- package/dist/src/1974.js +2 -2
- package/dist/src/2301.js +1 -0
- package/dist/src/3918.js +29 -28
- package/dist/src/4993.js +1 -0
- package/dist/src/5721.js +1 -0
- package/dist/src/7166.js +1 -0
- package/dist/src/7651.js +1 -1
- package/dist/src/8564.js +1 -1
- package/dist/src/8656.js +1 -0
- package/dist/src/9076.js +1 -1
- package/dist/src/9152.js +1 -1
- package/dist/src/9542.js +2 -2
- package/dist/src/backend.js +1 -1
- package/dist/src/bin.js +49 -41
- package/dist/src/contracts.d.ts +12 -1
- package/dist/src/contracts.js +1 -1
- package/dist/src/daemon.js +18 -15
- package/dist/src/index.d.ts +36 -8
- package/dist/src/metro-companion.js +1 -1
- package/dist/src/metro.d.ts +29 -8
- package/dist/src/metro.js +1 -1
- package/dist/src/observability.d.ts +91 -0
- package/dist/src/observability.js +1 -0
- package/package.json +5 -1
- package/skills/agent-device/SKILL.md +2 -0
- package/skills/agent-device/references/bootstrap-install.md +26 -6
- package/skills/agent-device/references/exploration.md +11 -0
- package/skills/agent-device/references/remote-tenancy.md +45 -26
- package/skills/react-devtools/SKILL.md +2 -0
- package/dist/src/320.js +0 -1
- package/dist/src/3883.js +0 -1
- package/dist/src/8164.js +0 -1
- package/dist/src/9323.js +0 -5
package/README.md
CHANGED
|
@@ -49,6 +49,10 @@ agent-device react-devtools profile slow --limit 5
|
|
|
49
49
|
|
|
50
50
|
`react-devtools` dynamically runs pinned `agent-react-devtools@0.4.0` commands 1:1, so `agent-device` covers both the device/app runtime layer and React component internals without making React DevTools part of the daemon.
|
|
51
51
|
|
|
52
|
+
When an Android session is connected through a remote bridge profile, `react-devtools` automatically opens a lease-scoped companion tunnel for the local DevTools daemon on port 8097 and cleans it up when the command exits.
|
|
53
|
+
|
|
54
|
+
Remote Android React DevTools assumes the React Native-bundled DevTools behavior in React Native 0.83+. Older browser/Chromium DevTools workflows are not assumed to exist inside remote sandboxes. Expo projects should be verified against the SDK's bundled React Native version before relying on this path; this release does not claim a separately verified Expo SDK version.
|
|
55
|
+
|
|
52
56
|
## Command Flow
|
|
53
57
|
|
|
54
58
|
The canonical loop is:
|
package/dist/src/1974.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
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{runCmdDetached as o,runCmdSync as
|
|
2
|
-
`,"utf8")}function N(r){try{let t=e.readdirSync(r);0===t.length&&e.rmdirSync(r)}catch{}}function R(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{}N(n),o!==n&&N(o),r.basename(n)===E&&N(r.dirname(n))}function $(e){return e.includes(u)}function x(e){return k(e.consumerKey)??k(e.profileKey)??null}function j(e,r){return!r||e.consumers.includes(r)?e:{...e,consumers:[...e.consumers,r]}}async function T(e){if(!l(e.pid))return;let r=i(e.pid);if(r&&$(r)){try{process.kill(e.pid,"SIGTERM")}catch(r){let e=r.code;if("ESRCH"===e||"EPERM"===e)return;throw r}if(!await s(e.pid,1e3)){try{process.kill(e.pid,"SIGKILL")}catch(r){let e=r.code;if("ESRCH"===e||"EPERM"===e)return;throw r}await s(e.pid,1e3)}}}async function B(t){let a=x(t),s=v(t.projectRoot,t.profileKey),p=M(s.statePath);if(p&&function(e,r){var t,n;if(!l(e.pid))return!1;if(e.startTime){let r=c(e.pid);if(!r||r!==e.startTime)return!1}let o=i(e.pid);return!!o&&!!$(o)&&!!e.bridgeScope&&e.serverBaseUrl===d(r.serverBaseUrl)&&e.localBaseUrl===d(r.localBaseUrl)&&e.launchUrl===k(r.launchUrl)&&(t=e.bridgeScope,n=r.bridgeScope,t.tenantId===n.tenantId&&t.runId===n.runId&&t.leaseId===n.leaseId)&&e.tokenHash===P(r.bearerToken)}(p,t)){let e=j(p,a);return e!==p&&A(s.statePath,e),{pid:p.pid,spawned:!1,statePath:s.statePath,logPath:s.logPath}}p&&(await T(p),R(s));let _=function(t,a){let s=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}(),l=s.endsWith(".ts")?["--experimental-strip-types"]:[];e.mkdirSync(r.dirname(a),{recursive:!0});let p=e.openSync(a,"a"),_=0;try{let e;_=o(process.execPath,[...l,s,u],{env:((e={...t.env??process.env,[m]:d(t.serverBaseUrl),[S]:t.bearerToken,[f]:d(t.localBaseUrl),[h]:v(t.projectRoot,t.profileKey).statePath})[y]=t.bridgeScope.tenantId,e[b]=t.bridgeScope.runId,e[w]=t.bridgeScope.leaseId,t.launchUrl?.trim()?e[g]=t.launchUrl.trim():delete e[g],e),stdio:["ignore",p,p]})}finally{e.closeSync(p)}if(!Number.isInteger(_)||_<=0)throw Error("Failed to start Metro companion process.");return{pid:_,startTime:c(_)??void 0,command:i(_)??void 0,serverBaseUrl:d(t.serverBaseUrl),localBaseUrl:d(t.localBaseUrl),launchUrl:k(t.launchUrl),bridgeScope:t.bridgeScope,tokenHash:P(t.bearerToken),consumers:[]}}(t,s.logPath);return A(s.statePath,j(_,a)),{pid:_.pid,spawned:!0,statePath:s.statePath,logPath:s.logPath}}async function C(e){let r=x(e),t=v(e.projectRoot,e.profileKey),n=M(t.statePath);if(!n)return R(t),{stopped:!1,statePath:t.statePath};let o=r?{...n,consumers:n.consumers.filter(e=>e!==r)}:{...n,consumers:[]};return o.consumers.length>0?(A(t.statePath,o),{stopped:!1,statePath:t.statePath}):(await T(n),R(t),{stopped:!0,statePath:t.statePath})}function K(e){return"string"==typeof e&&e.trim()?d(e.trim()):""}function H(e){return"string"==typeof e&&e.trim()?e.trim():void 0}function D(e,r,t){return U(e,{env:r,cwd:t})}function O(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 L(e,r){return{platform:r,bundleUrl:p(e,r)}}function G(e,r){return{platform:r,metroHost:H(e?.metro_host),metroPort:e?.metro_port,bundleUrl:H(e?.metro_bundle_url),launchUrl:H(e?.launch_url)}}async function F(e){await I(e)}async function V(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 q(e,r){try{let t=await V(e,r);return t.ok&&t.body.includes("packager-status:running")}catch{return!1}}async function z(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 s(e,1e3)){try{process.kill(e,"SIGKILL")}catch(r){let e=r.code;if("ESRCH"===e||"EPERM"===e)return;throw r}await s(e,1e3)}}}function W(e,r){let t=Error(e);return t.retryable=r,t}function X(e,r){return!!(e>=500||408===e||425===e||429===e||JSON.stringify(r).includes("Metro companion is not connected"))}function Y(e){return!!(e&&"object"==typeof e&&"retryable"in e&&!0===e.retryable)}async function Q(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,...e.runtime?{ios_runtime:e.runtime}:{},timeout_ms:e.timeoutMs}),signal:AbortSignal.timeout(e.timeoutMs)})}catch(r){if(r instanceof Error&&"TimeoutError"===r.name)throw W(`/api/metro/bridge timed out after ${e.timeoutMs}ms calling ${e.baseUrl}/api/metro/bridge`,!0);throw W(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 W(`/api/metro/bridge returned invalid JSON (${r}) from ${t}: ${o}. body=${JSON.stringify(n)}`,X(r,e))}}(await r.text(),r.status,e.baseUrl);if(!r.ok)throw W(`/api/metro/bridge failed (${r.status}): ${JSON.stringify(o)}`,X(r.status,o));var a=o;let i=a.data??a;if(!i||"object"!=typeof i||Array.isArray(i))throw W("/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:G(i.ios_runtime,"ios"),androidRuntime:G(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 W(`/api/metro/bridge returned malformed descriptor: ${e instanceof Error?e.message:String(e)}`,!1)}}function Z(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 ee(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 q(e,r))return!0;let o=Math.min(500,Math.max(n-Date.now(),0));o>0&&await F(o)}return!1}async function er(e){let r=Date.now()+e.startupTimeoutMs,t=null,n=null;for(;Date.now()<r;){try{let r=await Q({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),!Y(e))break}let o=Math.min(1e3,Math.max(r-Date.now(),0));o>0&&await F(o)}throw Error(Z(e.baseUrl,n,t,e.initialBridgeError,e.companionLogPath))}async function et(t={}){let n=t.env??process.env,i=process.cwd(),s=D(t.projectRoot??i,n,i),l=function(t,n){if("auto"!==n)return n;let o=function(t){let n=r.join(t,"package.json");if(!O(n))throw new _("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"}(s,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 _("INVALID_ARGS",`Invalid Metro port: ${String(e)}. Use 1-65535.`);return r}(t.metroPort??8081),u=H(t.listenHost)??"0.0.0.0",d=H(t.statusHost)??"127.0.0.1",p=K(t.publicBaseUrl),m=J(t.startupTimeoutMs,18e4,3e4),f=J(t.probeTimeoutMs,1e4,1e3),h=t.reuseExisting??!0,g=t.installDependenciesIfNeeded??!0,y=t.runtimeFilePath?D(t.runtimeFilePath,n,i):null,b=D(t.logPath??r.join(s,".agent-device","metro.log"),n,i);if(!p&&!K(t.proxyBaseUrl))throw new _("INVALID_ARGS","metro prepare requires --public-base-url <url>.");let{proxyEnabled:S,proxyBaseUrl:w,proxyBearerToken:U}=function(e,r){if(e&&!r)throw new _("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 _("INVALID_ARGS","metro prepare requires --proxy-base-url when proxy auth is provided.");return{proxyEnabled:!!(e&&r),proxyBaseUrl:e,proxyBearerToken:r}}(K(t.proxyBaseUrl),H(t.proxyBearerToken)??""),I=S?function(e){if(!e?.tenantId||!e.runId||!e.leaseId)throw new _("INVALID_ARGS","metro prepare with proxy requires tenantId, runId, and leaseId bridge scope.");return e}(t.bridgeScope):null,E=g?function(t,n){if(function(r){try{return e.statSync(r).isDirectory()}catch{return!1}}(r.join(t,"node_modules")))return{installed:!1};let o=O(r.join(t,"pnpm-lock.yaml"))?{command:"pnpm",installArgs:["install"]}:O(r.join(t,"yarn.lock"))?{command:"yarn",installArgs:["install"]}:{command:"npm",installArgs:["install"]};return a(o.command,o.installArgs,{cwd:t,env:n}),{installed:!0,packageManager:o.command}}(s,n):{installed:!1},P=`http://${d}:${c}/status`,k=!1,v=!1,M=0;if(h&&await q(P,f))v=!0;else if(k=!0,M=function(t,n,a,i,s,l){let c="expo"===n?{command:"npx",installArgs:["expo","start","--host","lan","--port",String(a)]}:{command:"npx",installArgs:["react-native","start","--host",i,"--port",String(a)]};e.mkdirSync(r.dirname(s),{recursive:!0});let u=e.openSync(s,"a"),d=0;try{d=o(c.command,c.installArgs,{cwd:t,env:l,stdio:["ignore",u,u]})}finally{e.closeSync(u)}if(!Number.isInteger(d)||d<=0)throw Error("Failed to start Metro. Expected a detached child PID.");return{pid:d}}(s,l,c,u,b,n).pid,!await ee(P,m,f))throw await z(M).catch(()=>{}),Error(`Metro did not become ready at ${P} within ${m}ms. Check ${b}.`);let A=p?L(p,"ios"):{platform:"ios"},N=p?L(p,"android"):{platform:"android"},R=null,$=null;if(I)try{R=await Q({baseUrl:w,bearerToken:U,scope:I,timeoutMs:f})}catch(e){if(!Y(e))throw e;$=e instanceof Error?e.message:String(e)}if(I&&(!R||!1===R.probe.reachable)){let e;try{e=(await B({projectRoot:s,serverBaseUrl:w,bearerToken:U,bridgeScope:I,localBaseUrl:`http://${d}:${c}`,launchUrl:H(t.launchUrl),profileKey:H(t.companionProfileKey),consumerKey:H(t.companionConsumerKey),env:n})).logPath}catch(e){throw Error(Z(w,e instanceof Error?e.message:String(e),R,$))}try{R=await er({baseUrl:w,bearerToken:U,scope:I,probeTimeoutMs:f,startupTimeoutMs:m,initialBridgeError:$,companionLogPath:e})}catch(e){throw e instanceof Error?e:Error(String(e))}}I&&function(e,r){if(!r?.iosRuntime.bundleUrl)throw Error(Z(e,"bridge descriptor is missing ios_runtime.metro_bundle_url",r))}(w,R);let x=R?.iosRuntime??A,j=R?.androidRuntime??N,T={projectRoot:s,kind:l,dependenciesInstalled:E.installed,packageManager:E.packageManager??null,started:k,reused:v,pid:M,logPath:b,statusUrl:P,runtimeFilePath:y,iosRuntime:x,androidRuntime:j,bridge:R};return y&&(e.mkdirSync(r.dirname(y),{recursive:!0}),e.writeFileSync(y,JSON.stringify(T,null,2))),T}export{L as buildMetroRuntimeHints,B as ensureMetroCompanion,et as prepareMetroRuntime,C as stopMetroCompanion};
|
|
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{runCmdDetached as o,runCmdSync as i}from"./9818.js";import{readProcessCommand as a,waitForProcessExit as s,resolveRuntimeTransportHints as l,isProcessAlive as u,readProcessStartTime as c}from"./8656.js";import{normalizeBaseUrl as d,ENV_COMPANION_TUNNEL_BEARER_TOKEN as m,ENV_COMPANION_TUNNEL_SERVER_BASE_URL as p,ENV_COMPANION_TUNNEL_STATE_PATH as f,ENV_COMPANION_TUNNEL_LAUNCH_URL as h,ENV_COMPANION_TUNNEL_SCOPE_LEASE_ID as g,ENV_COMPANION_TUNNEL_SCOPE_TENANT_ID as y,ENV_COMPANION_TUNNEL_DEVICE_PORT as b,buildBundleUrl as S,METRO_COMPANION_RUN_ARG as w,ENV_COMPANION_TUNNEL_SESSION as P,ENV_COMPANION_TUNNEL_SCOPE_RUN_ID as v,ENV_COMPANION_TUNNEL_REGISTER_PATH as U,ENV_COMPANION_TUNNEL_LOCAL_BASE_URL as _,ENV_COMPANION_TUNNEL_UNREGISTER_PATH as I}from"./2301.js";import{AppError as E}from"./9152.js";import{resolveUserPath as M}from"./3267.js";import{sleep as k}from"./4829.js";function N(e){return t("sha256").update(e).digest("hex")}function A(e){return e?.trim()?e.trim():void 0}function $(e,t,n,o){let i=o??r.join(e,".agent-device");if(!n)return{statePath:r.join(i,`${t.slug}.json`),logPath:r.join(i,`${t.slug}.log`)};let a=N(n).slice(0,12),s=r.join(i,t.slug);return{statePath:r.join(s,`${t.slug}-${a}.json`),logPath:r.join(s,`${t.slug}-${a}.log`)}}function R(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:A("string"==typeof t.launchUrl?t.launchUrl:void 0),registerPath:A("string"==typeof t.registerPath?t.registerPath:void 0),unregisterPath:A("string"==typeof t.unregisterPath?t.unregisterPath:void 0),devicePort:Number.isInteger(t.devicePort)?Number(t.devicePort):void 0,session:A("string"==typeof t.session?t.session: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 x(t,n){e.mkdirSync(r.dirname(t),{recursive:!0}),e.writeFileSync(t,`${JSON.stringify(n,null,2)}
|
|
2
|
+
`,"utf8")}function T(r){try{let t=e.readdirSync(r);0===t.length&&e.rmdirSync(r)}catch{}}function j(t,n){let o=r.dirname(t.statePath),i=r.dirname(t.logPath);var a=t.statePath;try{e.unlinkSync(a)}catch{}var s=t.logPath;try{e.unlinkSync(s)}catch{}T(o),i!==o&&T(i),r.basename(o)===n.slug&&T(r.dirname(o))}function C(e,r){return e.includes(r.runArg)}function B(e){return A(e.consumerKey)??A(e.profileKey)??null}function K(e,r){return!r||e.consumers.includes(r)?e:{...e,consumers:[...e.consumers,r]}}async function D(e,r){if(!u(e.pid))return;let t=a(e.pid);if(t&&C(t,r)){try{process.kill(e.pid,"SIGTERM")}catch(r){let e=r.code;if("ESRCH"===e||"EPERM"===e)return;throw r}if(!await s(e.pid,1e3)){try{process.kill(e.pid,"SIGKILL")}catch(r){let e=r.code;if("ESRCH"===e||"EPERM"===e)return;throw r}await s(e.pid,1e3)}}}async function H(t){let i=B(t),s=$(t.projectRoot,t.definition,t.profileKey,t.stateDir),l=R(s.statePath);if(l&&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=a(e.pid);return!!o&&!!C(o,r.definition)&&!!e.bridgeScope&&e.serverBaseUrl===d(r.serverBaseUrl)&&e.localBaseUrl===d(r.localBaseUrl)&&e.launchUrl===A(r.launchUrl)&&e.registerPath===A(r.registerPath)&&e.unregisterPath===A(r.unregisterPath)&&e.devicePort===r.devicePort&&e.session===A(r.session)&&(t=e.bridgeScope,n=r.bridgeScope,t.tenantId===n.tenantId&&t.runId===n.runId&&t.leaseId===n.leaseId)&&e.tokenHash===N(r.bearerToken)}(l,t)){let e=K(l,i);return e!==l&&x(s.statePath,e),{pid:l.pid,spawned:!1,statePath:s.statePath,logPath:s.logPath}}l&&(await D(l,t.definition),j(s,t.definition));let S=function(t,i){let s=function(t){let o=n(import.meta.url),i=r.extname(o)||".js",a=r.join(r.dirname(o),`metro-companion${i}`);if(!e.existsSync(a))throw Error(`${t.displayName} entrypoint not found at ${a}. Rebuild the package to include the companion worker entry.`);return a}(t.definition),l=s.endsWith(".ts")?["--experimental-strip-types"]:[];e.mkdirSync(r.dirname(i),{recursive:!0});let u=e.openSync(i,"a"),S=0;try{let e;S=o(process.execPath,[...l,s,t.definition.runArg],{env:((e={...t.env??process.env,[p]:d(t.serverBaseUrl),[m]:t.bearerToken,[_]:d(t.localBaseUrl),[f]:$(t.projectRoot,t.definition,t.profileKey,t.stateDir).statePath})[y]=t.bridgeScope.tenantId,e[v]=t.bridgeScope.runId,e[g]=t.bridgeScope.leaseId,t.launchUrl?.trim()?e[h]=t.launchUrl.trim():delete e[h],t.registerPath?.trim()?e[U]=t.registerPath.trim():delete e[U],t.unregisterPath?.trim()?e[I]=t.unregisterPath.trim():delete e[I],void 0!==t.devicePort?e[b]=String(t.devicePort):delete e[b],t.session?.trim()?e[P]=t.session.trim():delete e[P],e),stdio:["ignore",u,u]})}finally{e.closeSync(u)}if(!Number.isInteger(S)||S<=0)throw Error(`Failed to start ${t.definition.displayName} process.`);return{pid:S,startTime:c(S)??void 0,command:a(S)??void 0,serverBaseUrl:d(t.serverBaseUrl),localBaseUrl:d(t.localBaseUrl),launchUrl:A(t.launchUrl),registerPath:A(t.registerPath),unregisterPath:A(t.unregisterPath),devicePort:t.devicePort,session:A(t.session),bridgeScope:t.bridgeScope,tokenHash:N(t.bearerToken),consumers:[]}}(t,s.logPath);return x(s.statePath,K(S,i)),{pid:S.pid,spawned:!0,statePath:s.statePath,logPath:s.logPath}}async function O(e){let r=B(e),t=$(e.projectRoot,e.definition,e.profileKey,e.stateDir),n=R(t.statePath);if(!n)return j(t,e.definition),{stopped:!1,statePath:t.statePath};let o=r?{...n,consumers:n.consumers.filter(e=>e!==r)}:{...n,consumers:[]};return o.consumers.length>0?(x(t.statePath,o),{stopped:!1,statePath:t.statePath}):(await D(n,e.definition),j(t,e.definition),{stopped:!0,statePath:t.statePath})}let L={slug:"metro-companion",runArg:w,displayName:"Metro companion"};async function G(e){return await H({...e,definition:L,registerPath:e.registerPath??"/api/metro/companion/register"})}async function J(e){return await O({...e,definition:L})}function F(e){return"string"==typeof e&&e.trim()?d(e.trim()):""}function V(e){return"string"==typeof e&&e.trim()?e.trim():void 0}function q(e,r,t){return M(e,{env:r,cwd:t})}function W(r){try{return e.accessSync(r,e.constants.F_OK),!0}catch{return!1}}function z(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 X(e,r){if(null==e||""===e)return r;let t=Number.parseInt(String(e),10);if(!Number.isInteger(t)||t<1||t>65535)throw new E("INVALID_ARGS",`Invalid Metro port: ${String(e)}. Use 1-65535.`);return t}function Y(e,r){return{platform:r,bundleUrl:S(e,r)}}function Q(e,r){return{platform:r,metroHost:V(e?.metro_host),metroPort:e?.metro_port,bundleUrl:V(e?.metro_bundle_url),launchUrl:V(e?.launch_url)}}async function Z(e){await k(e)}async function ee(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 er(e,r){try{let t=await ee(e,r);return t.ok&&t.body.includes("packager-status:running")}catch{return!1}}async function et(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 s(e,1e3)){try{process.kill(e,"SIGKILL")}catch(r){let e=r.code;if("ESRCH"===e||"EPERM"===e)return;throw r}await s(e,1e3)}}}function en(e,r){let t=Error(e);return t.retryable=r,t}function eo(e,r){return!!(e>=500||408===e||425===e||429===e||JSON.stringify(r).includes("Metro companion is not connected"))}function ei(e){return!!(e&&"object"==typeof e&&"retryable"in e&&!0===e.retryable)}async function ea(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,...e.runtime?{ios_runtime:e.runtime}:{},timeout_ms:e.timeoutMs}),signal:AbortSignal.timeout(e.timeoutMs)})}catch(r){if(r instanceof Error&&"TimeoutError"===r.name)throw en(`/api/metro/bridge timed out after ${e.timeoutMs}ms calling ${e.baseUrl}/api/metro/bridge`,!0);throw en(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(i){let n=e.slice(0,200),o=i instanceof Error?i.message:String(i);throw en(`/api/metro/bridge returned invalid JSON (${r}) from ${t}: ${o}. body=${JSON.stringify(n)}`,eo(r,e))}}(await r.text(),r.status,e.baseUrl);if(!r.ok)throw en(`/api/metro/bridge failed (${r.status}): ${JSON.stringify(o)}`,eo(r.status,o));var i=o;let a=i.data??i;if(!a||"object"!=typeof a||Array.isArray(a))throw en("/api/metro/bridge returned malformed descriptor: Expected a JSON object.",!1);try{return{enabled:a.enabled,baseUrl:a.base_url,statusUrl:a.status_url??"",bundleUrl:a.bundle_url??"",iosRuntime:Q(a.ios_runtime,"ios"),androidRuntime:Q(a.android_runtime,"android"),upstream:{bundleUrl:a.upstream.bundle_url??"",host:a.upstream.host??"",port:a.upstream.port??0,statusUrl:a.upstream.status_url??""},probe:{reachable:a.probe.reachable,statusCode:a.probe.status_code,latencyMs:a.probe.latency_ms,detail:a.probe.detail}}}catch(e){throw en(`/api/metro/bridge returned malformed descriptor: ${e instanceof Error?e.message:String(e)}`,!1)}}function es(e,r,t,n,o){let i=[`Metro bridge is required for this run but could not be configured via ${e}/api/metro/bridge.`];return r&&i.push(`bridgeError=${r}`),t?.probe.reachable===!1&&i.push(`bridgeProbe=${t.probe.detail||`unreachable (status ${t.probe.statusCode||0})`}`),n&&n!==r&&i.push(`initialBridgeError=${n}`),o&&i.push(`metroCompanionLog=${o}`),i.join(" ")}async function el(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 er(e,r))return!0;let o=Math.min(500,Math.max(n-Date.now(),0));o>0&&await Z(o)}return!1}async function eu(e){let r=Date.now()+e.startupTimeoutMs,t=null,n=null;for(;Date.now()<r;){try{let r=await ea({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),!ei(e))break}let o=Math.min(1e3,Math.max(r-Date.now(),0));o>0&&await Z(o)}throw Error(es(e.baseUrl,n,t,e.initialBridgeError,e.companionLogPath))}async function ec(t={}){let n=t.env??process.env,a=process.cwd(),s=q(t.projectRoot??a,n,a),l=function(t,n){if("auto"!==n)return n;let o=function(t){let n=r.join(t,"package.json");if(!W(n))throw new E("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"}(s,t.kind??"auto"),u=X(t.metroPort??8081,8081),c=V(t.listenHost)??"0.0.0.0",d=V(t.statusHost)??"127.0.0.1",m=F(t.publicBaseUrl),p=z(t.startupTimeoutMs,18e4,3e4),f=z(t.probeTimeoutMs,1e4,1e3),h=t.reuseExisting??!0,g=t.installDependenciesIfNeeded??!0,y=t.runtimeFilePath?q(t.runtimeFilePath,n,a):null,b=q(t.logPath??r.join(s,".agent-device","metro.log"),n,a);if(!m&&!F(t.proxyBaseUrl))throw new E("INVALID_ARGS","metro prepare requires --public-base-url <url>.");let{proxyEnabled:S,proxyBaseUrl:w,proxyBearerToken:P}=function(e,r){if(e&&!r)throw new E("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 E("INVALID_ARGS","metro prepare requires --proxy-base-url when proxy auth is provided.");return{proxyEnabled:!!(e&&r),proxyBaseUrl:e,proxyBearerToken:r}}(F(t.proxyBaseUrl),V(t.proxyBearerToken)??""),v=S?function(e){if(!e?.tenantId||!e.runId||!e.leaseId)throw new E("INVALID_ARGS","metro prepare with proxy requires tenantId, runId, and leaseId bridge scope.");return e}(t.bridgeScope):null,U=g?function(t,n){if(function(r){try{return e.statSync(r).isDirectory()}catch{return!1}}(r.join(t,"node_modules")))return{installed:!1};let o=W(r.join(t,"pnpm-lock.yaml"))?{command:"pnpm",installArgs:["install"]}:W(r.join(t,"yarn.lock"))?{command:"yarn",installArgs:["install"]}:{command:"npm",installArgs:["install"]};return i(o.command,o.installArgs,{cwd:t,env:n}),{installed:!0,packageManager:o.command}}(s,n):{installed:!1},_=`http://${d}:${u}/status`,I=!1,M=!1,k=0;if(h&&await er(_,f))M=!0;else if(I=!0,k=function(t,n,i,a,s,l){let u="expo"===n?{command:"npx",installArgs:["expo","start","--host","lan","--port",String(i)]}:{command:"npx",installArgs:["react-native","start","--host",a,"--port",String(i)]};e.mkdirSync(r.dirname(s),{recursive:!0});let c=e.openSync(s,"a"),d=0;try{d=o(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}}(s,l,u,c,b,n).pid,!await el(_,p,f))throw await et(k).catch(()=>{}),Error(`Metro did not become ready at ${_} within ${p}ms. Check ${b}.`);let N=m?Y(m,"ios"):{platform:"ios"},A=m?Y(m,"android"):{platform:"android"},$=null,R=null;if(v)try{$=await ea({baseUrl:w,bearerToken:P,scope:v,timeoutMs:f})}catch(e){if(!ei(e))throw e;R=e instanceof Error?e.message:String(e)}if(v&&(!$||!1===$.probe.reachable)){let e;try{e=(await G({projectRoot:s,serverBaseUrl:w,bearerToken:P,bridgeScope:v,localBaseUrl:`http://${d}:${u}`,launchUrl:V(t.launchUrl),profileKey:V(t.companionProfileKey),consumerKey:V(t.companionConsumerKey),env:n})).logPath}catch(e){throw Error(es(w,e instanceof Error?e.message:String(e),$,R))}try{$=await eu({baseUrl:w,bearerToken:P,scope:v,probeTimeoutMs:f,startupTimeoutMs:p,initialBridgeError:R,companionLogPath:e})}catch(e){throw e instanceof Error?e:Error(String(e))}}v&&function(e,r){if(!r?.iosRuntime.bundleUrl)throw Error(es(e,"bridge descriptor is missing ios_runtime.metro_bundle_url",r))}(w,$);let x=$?.iosRuntime??N,T=$?.androidRuntime??A,j={projectRoot:s,kind:l,dependenciesInstalled:U.installed,packageManager:U.packageManager??null,started:I,reused:M,pid:k,logPath:b,statusUrl:_,runtimeFilePath:y,iosRuntime:x,androidRuntime:T,bridge:$};return y&&(e.mkdirSync(r.dirname(y),{recursive:!0}),e.writeFileSync(y,JSON.stringify(j,null,2))),j}async function ed(e={}){let r=z(e.timeoutMs,1e4,1e3),t=function(e){var r;let t,n=V(e.bundleUrl)??e.runtime?.bundleUrl,o=!!V(e.bundleUrl),i=!!V(n),a=l({metroHost:V(e.metroHost)??(o?void 0:V(e.runtime?.metroHost))??(i?void 0:"localhost"),metroPort:void 0!==e.metroPort?X(e.metroPort,8081):o?void 0:e.runtime?.metroPort??(i?void 0:8081),bundleUrl:n});if(!a)throw new E("INVALID_ARGS","Unable to resolve Metro host and port for reload.");return r=function(e){let r=V(e);if(!r)return"/reload";let t=new URL(r).pathname.replace(/\/+$/,"");return t.endsWith("/index.bundle")?`${t.slice(0,-13)}/reload`:"/reload"}(n),(t=new URL(`${a.scheme}://localhost`)).hostname=a.host,t.port=String(a.port),t.pathname=r,t.toString()}(e),n=await ee(t,r);if(!n.ok)throw new E("COMMAND_FAILED",`Metro reload failed (${n.status}).`,{reloadUrl:t,status:n.status,body:n.body,hint:"Verify Metro is running and the target React Native app is connected to this Metro instance."});return{reloaded:!0,reloadUrl:t,status:n.status,body:n.body}}export{Y as buildMetroRuntimeHints,H as ensureCompanionTunnel,G as ensureMetroCompanion,ec as prepareMetroRuntime,ed as reloadMetro,O as stopCompanionTunnel,J as stopMetroCompanion};
|
package/dist/src/2301.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
let _="--agent-device-run-metro-companion",E="--agent-device-run-react-devtools-companion",N="AGENT_DEVICE_METRO_COMPANION_SERVER_BASE_URL",O="AGENT_DEVICE_METRO_COMPANION_BEARER_TOKEN",A="AGENT_DEVICE_METRO_COMPANION_LOCAL_BASE_URL",T="AGENT_DEVICE_METRO_COMPANION_LAUNCH_URL",C="AGENT_DEVICE_METRO_COMPANION_STATE_PATH",I="AGENT_DEVICE_METRO_COMPANION_SCOPE_TENANT_ID",R="AGENT_DEVICE_METRO_COMPANION_SCOPE_RUN_ID",P="AGENT_DEVICE_METRO_COMPANION_SCOPE_LEASE_ID",M="AGENT_DEVICE_METRO_COMPANION_REGISTER_PATH",e="AGENT_DEVICE_METRO_COMPANION_UNREGISTER_PATH",U="AGENT_DEVICE_METRO_COMPANION_DEVICE_PORT",V="AGENT_DEVICE_METRO_COMPANION_SESSION";function L(_){let E=_.length;for(;E>0&&47===_.charCodeAt(E-1);)E-=1;return E===_.length?_:_.slice(0,E)}function S(_,E){let N=new URL(`${L(_)}/index.bundle`);return N.searchParams.set("platform",E),N.searchParams.set("dev","true"),N.searchParams.set("minify","false"),N.toString()}export{O as ENV_COMPANION_TUNNEL_BEARER_TOKEN,U as ENV_COMPANION_TUNNEL_DEVICE_PORT,T as ENV_COMPANION_TUNNEL_LAUNCH_URL,A as ENV_COMPANION_TUNNEL_LOCAL_BASE_URL,M as ENV_COMPANION_TUNNEL_REGISTER_PATH,P as ENV_COMPANION_TUNNEL_SCOPE_LEASE_ID,R as ENV_COMPANION_TUNNEL_SCOPE_RUN_ID,I as ENV_COMPANION_TUNNEL_SCOPE_TENANT_ID,N as ENV_COMPANION_TUNNEL_SERVER_BASE_URL,V as ENV_COMPANION_TUNNEL_SESSION,C as ENV_COMPANION_TUNNEL_STATE_PATH,e as ENV_COMPANION_TUNNEL_UNREGISTER_PATH,_ as METRO_COMPANION_RUN_ARG,E as REACT_DEVTOOLS_COMPANION_RUN_ARG,S as buildBundleUrl,L as normalizeBaseUrl};
|