@radhya/mach 1.4.22 → 1.4.23

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.
Files changed (2) hide show
  1. package/dist/index.js +76 -75
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import{a as ci,c as Je}from"./chunk-YXFDQM4S.js";import{a as f,b as ri,c as ue,d as si,e as gt,f as ai,g as _}from"./chunk-YZYFEHP5.js";import{Command as qr,Option as Cn}from"commander";import{configDotenv as Jr}from"dotenv";import{intro as de,outro as Tn}from"@clack/prompts";import re from"chalk";import{text as li,confirm as Nn,spinner as kn,isCancel as Ut,cancel as Xe,note as xn,outro as Ln}from"@clack/prompts";import Ze from"chalk";async function di(){try{let e=await li({message:"Enter Bucket Name:",placeholder:"e.g. my-app-dev",validate(o){if(o.length===0)return"Bucket name is required"}});Ut(e)&&(Xe("Operation cancelled."),process.exit(0));let n=await li({message:"Enter Region:",initialValue:"ap-south-1"});Ut(n)&&(Xe("Operation cancelled."),process.exit(0));let t=await Nn({message:"Do you want to create a CloudFront Distribution for this bucket?",initialValue:!0});Ut(t)&&(Xe("Operation cancelled."),process.exit(0));let i=kn();i.start("Setting up hosting infrastructure...");try{let o=await _.post("/hosting/setup",{bucketName:e,region:n,createCloudFront:t});if(o.data.status!=="success")throw new Error(o.data.message||"Hosting setup failed");i.stop("Hosting setup complete!");let r=o.data,a=`Bucket Name: ${Ze.cyan(r.bucketName)}
2
+ import{a as li,c as qe}from"./chunk-YXFDQM4S.js";import{a as f,b as si,c as fe,d as ai,e as yt,f as ci,g as D}from"./chunk-YZYFEHP5.js";import{Command as qr,Option as Tn}from"commander";import{configDotenv as Xr}from"dotenv";import{intro as ue,outro as Nn}from"@clack/prompts";import se from"chalk";import{text as di,confirm as kn,spinner as xn,isCancel as Mt,cancel as Xe,note as Ln,outro as Un}from"@clack/prompts";import Ze from"chalk";async function ui(){try{let e=await di({message:"Enter Bucket Name:",placeholder:"e.g. my-app-dev",validate(o){if(o.length===0)return"Bucket name is required"}});Mt(e)&&(Xe("Operation cancelled."),process.exit(0));let n=await di({message:"Enter Region:",initialValue:"ap-south-1"});Mt(n)&&(Xe("Operation cancelled."),process.exit(0));let t=await kn({message:"Do you want to create a CloudFront Distribution for this bucket?",initialValue:!0});Mt(t)&&(Xe("Operation cancelled."),process.exit(0));let i=xn();i.start("Setting up hosting infrastructure...");try{let o=await D.post("/hosting/setup",{bucketName:e,region:n,createCloudFront:t});if(o.data.status!=="success")throw new Error(o.data.message||"Hosting setup failed");i.stop("Hosting setup complete!");let r=o.data,a=`Bucket Name: ${Ze.cyan(r.bucketName)}
3
3
  `;a+=`Region: ${Ze.cyan(r.region)}
4
4
  `,a+=`S3 Website URL: ${Ze.blue(r.s3WebsiteUrl)}`,r.cloudFrontId&&(a+=`
5
5
 
6
6
  CloudFront ID: ${Ze.cyan(r.cloudFrontId)}`,a+=`
7
- CloudFront URL: ${Ze.blue(r.cloudFrontUrl)}`),xn(a,"Setup Complete!"),Ln("You are all set!")}catch(o){i.stop("Setup failed"),Xe(`Error: ${o.response?.data?.message||o.message}`)}}catch(e){Xe(`An unexpected error occurred: ${e.message}`)}}import{readdir as Un,writeFile as Mn,access as Fn,mkdir as Hn}from"fs/promises";import{join as ui}from"path";import{spinner as Gn,text as pi,isCancel as fi,cancel as Mt,note as jn,outro as Bn}from"@clack/prompts";import Kn from"chalk";async function Vn(){let e=["./app","./src/app"];for(let n of e)try{return await Fn(n),n}catch{}return null}async function mi(e){try{let t=await Vn()||"./app",i=await pi({message:"Enter path to your app directory:",placeholder:t,initialValue:t,validate(d){if(d.length===0)return"Path is required"}});fi(i)&&(Mt("Operation cancelled."),process.exit(0));let o=await pi({message:"Enter your website base URL:",placeholder:"https://example.com",validate(d){if(d.length===0)return"Base URL is required";if(!d.startsWith("http"))return"URL must start with http:// or https://"}});fi(o)&&(Mt("Operation cancelled."),process.exit(0));let r=Gn();r.start("Scanning app directory for routes...");let a=await gi(i);r.stop(`Found ${a.length} routes`);let c=zn(a,o),s=e.output||"./public/sitemap.xml";r.start(`Writing sitemap to ${s}...`);let l=s.substring(0,s.lastIndexOf("/"));if(l)try{await Hn(l,{recursive:!0})}catch{}await Mn(s,c,"utf-8"),r.stop("Sitemap generated successfully!"),jn(`Routes included:
7
+ CloudFront URL: ${Ze.blue(r.cloudFrontUrl)}`),Ln(a,"Setup Complete!"),Un("You are all set!")}catch(o){i.stop("Setup failed"),Xe(`Error: ${o.response?.data?.message||o.message}`)}}catch(e){Xe(`An unexpected error occurred: ${e.message}`)}}import{readdir as Mn,writeFile as Fn,access as Hn,mkdir as Gn}from"fs/promises";import{join as pi}from"path";import{spinner as jn,text as fi,isCancel as mi,cancel as Ft,note as Bn,outro as Kn}from"@clack/prompts";import Vn from"chalk";async function zn(){let e=["./app","./src/app"];for(let n of e)try{return await Hn(n),n}catch{}return null}async function gi(e){try{let t=await zn()||"./app",i=await fi({message:"Enter path to your app directory:",placeholder:t,initialValue:t,validate(d){if(d.length===0)return"Path is required"}});mi(i)&&(Ft("Operation cancelled."),process.exit(0));let o=await fi({message:"Enter your website base URL:",placeholder:"https://example.com",validate(d){if(d.length===0)return"Base URL is required";if(!d.startsWith("http"))return"URL must start with http:// or https://"}});mi(o)&&(Ft("Operation cancelled."),process.exit(0));let r=jn();r.start("Scanning app directory for routes...");let a=await hi(i);r.stop(`Found ${a.length} routes`);let c=Wn(a,o),s=e.output||"./public/sitemap.xml";r.start(`Writing sitemap to ${s}...`);let l=s.substring(0,s.lastIndexOf("/"));if(l)try{await Gn(l,{recursive:!0})}catch{}await Fn(s,c,"utf-8"),r.stop("Sitemap generated successfully!"),Bn(`Routes included:
8
8
  ${a.map(d=>` \u2022 ${d.path}`).join(`
9
- `)}`,"Sitemap Summary"),Bn(`Sitemap saved to ${Kn.cyan(s)}`)}catch(n){Mt(`An error occurred: ${n.message}`)}}async function gi(e,n=""){let t=[];try{let i=await Un(e,{withFileTypes:!0});for(let o of i){let r=ui(e,o.name);if(!(o.name.startsWith("_")||o.name.startsWith("."))){if(o.isDirectory()){let a=await gi(r,ui(n,o.name));t.push(...a)}else if(o.isFile()){if(o.name==="index.tsx"||o.name==="index.ts"||o.name==="index.jsx"||o.name==="index.js"){let a=n===""?"/":`/${n}`;t.push({path:a,file:r})}else if(o.name.match(/\.(tsx|ts|jsx|js)$/)&&!o.name.includes("_layout")&&!o.name.includes("+")){let a=o.name.replace(/\.(tsx|ts|jsx|js)$/,""),c=`/${n}/${a}`.replace(/\/+/g,"/");t.push({path:c,file:r})}}}}}catch(i){throw new Error(`Failed to scan directory ${e}: ${i.message}`)}return t}function zn(e,n){let t=new Date().toISOString().split("T")[0];return`<?xml version="1.0" encoding="UTF-8"?>
9
+ `)}`,"Sitemap Summary"),Kn(`Sitemap saved to ${Vn.cyan(s)}`)}catch(n){Ft(`An error occurred: ${n.message}`)}}async function hi(e,n=""){let t=[];try{let i=await Mn(e,{withFileTypes:!0});for(let o of i){let r=pi(e,o.name);if(!(o.name.startsWith("_")||o.name.startsWith("."))){if(o.isDirectory()){let a=await hi(r,pi(n,o.name));t.push(...a)}else if(o.isFile()){if(o.name==="index.tsx"||o.name==="index.ts"||o.name==="index.jsx"||o.name==="index.js"){let a=n===""?"/":`/${n}`;t.push({path:a,file:r})}else if(o.name.match(/\.(tsx|ts|jsx|js)$/)&&!o.name.includes("_layout")&&!o.name.includes("+")){let a=o.name.replace(/\.(tsx|ts|jsx|js)$/,""),c=`/${n}/${a}`.replace(/\/+/g,"/");t.push({path:c,file:r})}}}}}catch(i){throw new Error(`Failed to scan directory ${e}: ${i.message}`)}return t}function Wn(e,n){let t=new Date().toISOString().split("T")[0];return`<?xml version="1.0" encoding="UTF-8"?>
10
10
  <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
11
11
  ${e.map(o=>{let r=o.path;return r=r.replace(/\/\([^)]+\)/g,""),r=r.replace(/\/\[.*?\]/g,"/:id"),r=r.replace(/\/+/g,"/"),r===""&&(r="/"),` <url>
12
12
  <loc>${n}${r}</loc>
@@ -15,7 +15,7 @@ ${e.map(o=>{let r=o.path;return r=r.replace(/\/\([^)]+\)/g,""),r=r.replace(/\/\[
15
15
  <priority>0.8</priority>
16
16
  </url>`}).join(`
17
17
  `)}
18
- </urlset>`}import{randomUUID as go}from"crypto";import we from"path";import tt from"axios";import ho from"os";import{spinner as Gt,confirm as _i,isCancel as Di,log as D}from"@clack/prompts";import v from"chalk";import ce from"fs";import{execSync as wi}from"child_process";import vi from"adm-zip";import{spinner as Wn,log as yi}from"@clack/prompts";import Yn from"chalk";var hi=`#!/bin/bash
18
+ </urlset>`}import{randomUUID as ho}from"crypto";import we from"path";import tt from"axios";import yo from"os";import{spinner as jt,confirm as Di,isCancel as wi,log as w}from"@clack/prompts";import R from"chalk";import ce from"fs";import{execSync as vi}from"child_process";import Ri from"adm-zip";import{spinner as Yn,log as Si}from"@clack/prompts";import Jn from"chalk";var yi=`#!/bin/bash
19
19
  # --- Mach Cloud Build Script (Android) ---
20
20
  # All S3 operations use presigned URLs via curl \u2014 zero AWS credentials on instance.
21
21
  BUILD_ID="{{BUILD_ID}}"
@@ -269,12 +269,12 @@ touch /opt/mach-prewarmed
269
269
  echo "Build orchestrator finished. Auto-terminating instance in 5 seconds..."
270
270
  sleep 5
271
271
  sudo shutdown -h now
272
- `;var Si=async(e,n,t={},i)=>{let o=Wn(),r=e.buildProfile||"production",a=r==="production",c=e.apk===!0,s=a?"bundleRelease":"assembleRelease",l=e.buildCommand||(c?"assembleRelease":s),d=e.nodeVersion?['export NVM_DIR="$HOME/.nvm"','[ -s "$NVM_DIR/nvm.sh" ] && source "$NVM_DIR/nvm.sh"',`nvm install ${e.nodeVersion} 2>/dev/null || true`,`nvm use ${e.nodeVersion}`,'export PATH="$NVM_BIN:$PATH"','echo "[NODE] Using Node $(node -v) at $(which node)"'].join(`
273
- `):"",u=hi.replace(/\{\{BUILD_ID\}\}/g,n).replace(/\{\{BUILD_COMMAND\}\}/g,l).replace("{{NODE_VERSION_SETUP}}",d).replace("{{ENV_VARS}}",`
272
+ `;var Ai=async(e,n,t={},i)=>{let o=Yn(),r=e.buildProfile||"production",a=r==="production",c=e.apk===!0,s=a?"bundleRelease":"assembleRelease",l=e.buildCommand||(c?"assembleRelease":s),d=e.nodeVersion?['export NVM_DIR="$HOME/.nvm"','[ -s "$NVM_DIR/nvm.sh" ] && source "$NVM_DIR/nvm.sh"',`nvm install ${e.nodeVersion} 2>/dev/null || true`,`nvm use ${e.nodeVersion}`,'export PATH="$NVM_BIN:$PATH"','echo "[NODE] Using Node $(node -v) at $(which node)"'].join(`
273
+ `):"",u=yi.replace(/\{\{BUILD_ID\}\}/g,n).replace(/\{\{BUILD_COMMAND\}\}/g,l).replace("{{NODE_VERSION_SETUP}}",d).replace("{{ENV_VARS}}",`
274
274
  export MACH_APP_NAME="${e.appName||"App"}"
275
275
  export MACH_BUILD_PROFILE="${r}"
276
276
  {{ENV_VARS}}
277
- `);if(e.dryRun){yi.info("User Data Script (dry run):"),console.log(u);return}o.start("Requesting cloud build instance...");try{let p=await _.post("/builds/launch-android",{projectId:i,buildId:n,platform:e.platform,buildProfile:e.buildProfile,buildCommand:l,instanceType:e.instanceType,ami:e.ami,keepInstance:e.keepInstance,region:e.region,subnet:e.subnet,securityGroup:e.securityGroup,projectSecrets:t,dryRun:e.dryRun,userDataScript:u});if(p.data.status!=="success")throw new Error(p.data.message||"Failed to launch build instance");let g=p.data.instanceId;return o.stop("Build Started"),yi.success(Yn.green(`Build initiated on cloud instance (${g}).`)),{instanceId:g}}catch(p){o.stop("Android Build Failed");let g=p.response?.data?.message||p.message;throw new Error(`Failed to launch Android build: ${g}`)}};import{spinner as qn,log as He}from"@clack/prompts";import Te from"chalk";import Jn from"fs";import{execSync as Qe}from"child_process";var Ai=`#!/bin/bash
277
+ `);if(e.dryRun){Si.info("User Data Script (dry run):"),console.log(u);return}o.start("Requesting cloud build instance...");try{let p=await D.post("/builds/launch-android",{projectId:i,buildId:n,platform:e.platform,buildProfile:e.buildProfile,buildCommand:l,instanceType:e.instanceType,ami:e.ami,keepInstance:e.keepInstance,region:e.region,subnet:e.subnet,securityGroup:e.securityGroup,projectSecrets:t,dryRun:e.dryRun,userDataScript:u});if(p.data.status!=="success")throw new Error(p.data.message||"Failed to launch build instance");let g=p.data.instanceId;return o.stop("Build Started"),Si.success(Jn.green(`Build initiated on cloud instance (${g}).`)),{instanceId:g}}catch(p){o.stop("Android Build Failed");let g=p.response?.data?.message||p.message;throw new Error(`Failed to launch Android build: ${g}`)}};import{spinner as qn,log as Ge}from"@clack/prompts";import Ne from"chalk";import Xn from"fs";import{execSync as Qe}from"child_process";var Ei=`#!/bin/bash
278
278
  # --- Mach Cloud Build Script (iOS) ---
279
279
  # All S3 operations use presigned URLs via curl \u2014 zero AWS credentials on Mac.
280
280
 
@@ -712,52 +712,53 @@ touch done
712
712
  if [ ! -z "$PRESIGNED_DONE_MARKER" ]; then
713
713
  curl -X PUT -T done "$PRESIGNED_DONE_MARKER" --silent
714
714
  fi
715
- `;var Ei=async(e,n,t={},i)=>{let o=qn();e.sshHost||(e.sshHost="localhost",He.message(Te.yellow("No SSH host provided, defaulting to localhost."))),o.start(`Connecting to remote Mac at ${Te.cyan(e.sshHost)}...`);let r=e.sshUser||process.env.USER||"ubuntu",a=e.sshKey,c=`${r}@${e.sshHost}`,s=`ssh ${a?`-i ${a}`:""} -o StrictHostKeyChecking=no ${c}`,l=`scp ${a?`-i ${a}`:""} -o StrictHostKeyChecking=no`;try{let d=r==="ubuntu"?"/home/ubuntu":`/Users/${r}`,u=(t.PROJECT_ID||"default_project").replace(/[^a-zA-Z0-9-_]/g,"_"),p=`${d}/${f.remoteWorkspacesDir}/${u}`;o.message(`Preparing stable workspace: ${p}...`),Qe(`${s} "mkdir -p ${p}"`,{stdio:"inherit"}),o.message("Transferring source code...");let g=`/tmp/${f.nameLower}-source-${n}.zip`;Qe(`${l} ${g} ${c}:${p}/source.zip`,{stdio:"inherit"});let m=e.iosApiKeyPath?`${p}/api_key.p8`:"",h="";e.iosApiKeyPath&&(o.message("Uploading App Store Connect API key..."),Qe(`${l} ${e.iosApiKeyPath} ${c}:${m}`),e.iosApiKeyId&&e.iosApiKeyIssuer&&(h=`-authenticationKeyID ${e.iosApiKeyId} -authenticationKeyIssuerID ${e.iosApiKeyIssuer} -authenticationKeyPath ${m}`));let $={};if(i)try{let I=await _.post(`/builds/${i}/${n}/build-urls`,{platform:"ios"});I.data.status==="success"&&($=I.data.urls)}catch(I){He.warn(Te.yellow(`Could not fetch build URLs: ${I.message}`))}let N="";if($.credentials&&$.credentials.length>0)for(let I of $.credentials)I.type==="p12"?N+=`curl -sf -o "$CERT_DIR/${I.name}" "${I.downloadUrl}" || true
716
- `:I.type==="mobileprovision"&&(N+=`curl -sf -o "$PROV_TEMP/${I.name}" "${I.downloadUrl}" || true
715
+ `;var Ii=async(e,n,t={},i)=>{let o=qn();e.sshHost||(e.sshHost="localhost",Ge.message(Ne.yellow("No SSH host provided, defaulting to localhost."))),o.start(`Connecting to remote Mac at ${Ne.cyan(e.sshHost)}...`);let r=e.sshUser||process.env.USER||"ubuntu",a=e.sshKey,c=`${r}@${e.sshHost}`,s=`ssh ${a?`-i ${a}`:""} -o StrictHostKeyChecking=no ${c}`,l=`scp ${a?`-i ${a}`:""} -o StrictHostKeyChecking=no`;try{let d=r==="ubuntu"?"/home/ubuntu":`/Users/${r}`,u=(t.PROJECT_ID||"default_project").replace(/[^a-zA-Z0-9-_]/g,"_"),p=`${d}/${f.remoteWorkspacesDir}/${u}`;o.message(`Preparing stable workspace: ${p}...`),Qe(`${s} "mkdir -p ${p}"`,{stdio:"inherit"}),o.message("Transferring source code...");let g=`/tmp/${f.nameLower}-source-${n}.zip`;Qe(`${l} ${g} ${c}:${p}/source.zip`,{stdio:"inherit"});let m=e.iosApiKeyPath?`${p}/api_key.p8`:"",h="";e.iosApiKeyPath&&(o.message("Uploading App Store Connect API key..."),Qe(`${l} ${e.iosApiKeyPath} ${c}:${m}`),e.iosApiKeyId&&e.iosApiKeyIssuer&&(h=`-authenticationKeyID ${e.iosApiKeyId} -authenticationKeyIssuerID ${e.iosApiKeyIssuer} -authenticationKeyPath ${m}`));let P={};if(i)try{let I=await D.post(`/builds/${i}/${n}/build-urls`,{platform:"ios"});I.data.status==="success"&&(P=I.data.urls)}catch(I){Ge.warn(Ne.yellow(`Could not fetch build URLs: ${I.message}`))}let k="";if(P.credentials&&P.credentials.length>0)for(let I of P.credentials)I.type==="p12"?k+=`curl -sf -o "$CERT_DIR/${I.name}" "${I.downloadUrl}" || true
716
+ `:I.type==="mobileprovision"&&(k+=`curl -sf -o "$PROV_TEMP/${I.name}" "${I.downloadUrl}" || true
717
717
  `);o.message("Generating macOS build script...");let C=process.env.CODEARTIFACT_AUTH_TOKEN?`export CODEARTIFACT_AUTH_TOKEN="${process.env.CODEARTIFACT_AUTH_TOKEN}"
718
718
  `:"";if(t)for(let[I,b]of Object.entries(t)){let O=b.replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");C+=`export ${I}="${O}"
719
- `}let x=[C,$.logUpload?`export PRESIGNED_LOG_UPLOAD="${$.logUpload}"`:"",$.doneMarker?`export PRESIGNED_DONE_MARKER="${$.doneMarker}"`:"",$.cacheDerivedDataDownload?`export PRESIGNED_CACHE_DD_DOWNLOAD="${$.cacheDerivedDataDownload}"`:"",$.cacheDerivedDataUpload?`export PRESIGNED_CACHE_DD_UPLOAD="${$.cacheDerivedDataUpload}"`:"",$.cacheNodeModulesDownload?`export PRESIGNED_CACHE_NODE_DOWNLOAD="${$.cacheNodeModulesDownload}"`:"",$.cacheNodeModulesUpload?`export PRESIGNED_CACHE_NODE_UPLOAD="${$.cacheNodeModulesUpload}"`:"",$.cachePodsDownload?`export PRESIGNED_CACHE_PODS_DOWNLOAD="${$.cachePodsDownload}"`:"",$.cachePodsUpload?`export PRESIGNED_CACHE_PODS_UPLOAD="${$.cachePodsUpload}"`:"",$.artifactIpaUpload?`export PRESIGNED_ARTIFACT_IPA_UPLOAD="${$.artifactIpaUpload}"`:"",$.artifactAppZipUpload?`export PRESIGNED_ARTIFACT_APP_ZIP_UPLOAD="${$.artifactAppZipUpload}"`:"",`export BUILD_ID="${n}"`,`export ${f.envPrefix}PROJECT_ID="${u}"`,t.MATCH_ENCRYPTION_PASSPHRASE?`export MATCH_PASSWORD="${t.MATCH_ENCRYPTION_PASSPHRASE}"`:"",t.APPLE_TEAM_ID?`export FASTLANE_TEAM_ID="${t.APPLE_TEAM_ID}"`:"",`export MATCH_KEYCHAIN_NAME="${f.credentialsKeychain}"`,`export MATCH_KEYCHAIN_PASSWORD="${f.keychainPassword}"`].filter(Boolean).join(`
719
+ `}let x=[C,P.logUpload?`export PRESIGNED_LOG_UPLOAD="${P.logUpload}"`:"",P.doneMarker?`export PRESIGNED_DONE_MARKER="${P.doneMarker}"`:"",P.cacheDerivedDataDownload?`export PRESIGNED_CACHE_DD_DOWNLOAD="${P.cacheDerivedDataDownload}"`:"",P.cacheDerivedDataUpload?`export PRESIGNED_CACHE_DD_UPLOAD="${P.cacheDerivedDataUpload}"`:"",P.cacheNodeModulesDownload?`export PRESIGNED_CACHE_NODE_DOWNLOAD="${P.cacheNodeModulesDownload}"`:"",P.cacheNodeModulesUpload?`export PRESIGNED_CACHE_NODE_UPLOAD="${P.cacheNodeModulesUpload}"`:"",P.cachePodsDownload?`export PRESIGNED_CACHE_PODS_DOWNLOAD="${P.cachePodsDownload}"`:"",P.cachePodsUpload?`export PRESIGNED_CACHE_PODS_UPLOAD="${P.cachePodsUpload}"`:"",P.artifactIpaUpload?`export PRESIGNED_ARTIFACT_IPA_UPLOAD="${P.artifactIpaUpload}"`:"",P.artifactAppZipUpload?`export PRESIGNED_ARTIFACT_APP_ZIP_UPLOAD="${P.artifactAppZipUpload}"`:"",`export BUILD_ID="${n}"`,`export ${f.envPrefix}PROJECT_ID="${u}"`,t.MATCH_ENCRYPTION_PASSPHRASE?`export MATCH_PASSWORD="${t.MATCH_ENCRYPTION_PASSPHRASE}"`:"",t.APPLE_TEAM_ID?`export FASTLANE_TEAM_ID="${t.APPLE_TEAM_ID}"`:"",`export MATCH_KEYCHAIN_NAME="${f.credentialsKeychain}"`,`export MATCH_KEYCHAIN_PASSWORD="${f.keychainPassword}"`].filter(Boolean).join(`
720
720
  `),H=e.nodeVersion?[`echo "[NODE] Switching to Node ${e.nodeVersion}..."`,'export NVM_DIR="$HOME/.nvm"','[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" --no-use',`nvm install ${e.nodeVersion} 2>/dev/null || true`,`nvm use ${e.nodeVersion} --silent`,`export PATH="$NVM_DIR/versions/node/$(nvm version ${e.nodeVersion})/bin:$PATH"`,'echo "[NODE] Now using: $(node -v) at $(which node)"'].join(`
721
- `):"",X=Ai,y={"{{REMOTE_DIR}}":p,"{{ENV_VARS}}":x,"{{CREDENTIAL_DOWNLOADS}}":N,"{{IOS_SCHEME}}":e.iosScheme||"","{{IOS_CONFIG}}":e.iosConfiguration||"Release","{{TEAM_ID}}":e.iosTeamId||"","{{AUTH_PARAMS}}":h,"{{IS_SIMULATOR}}":e.simulator?"true":"false","{{BUILD_ID}}":n,"{{EXPORT_METHOD}}":e.iosExportMethod||"ad-hoc","{{NODE_VERSION_SETUP}}":H};Object.entries(y).forEach(([I,b])=>{X=X.split(I).join(b)});let w=`/tmp/${f.nameLower}-mac-build-${n}.sh`;if(Jn.writeFileSync(w,X),Qe(`${l} ${w} ${c}:${p}/build.sh`),o.stop("Remote script uploaded."),He.info(Te.cyan("Executing remote build. This might take a while...")),Qe(`${s} "bash ${p}/build.sh"`,{stdio:"inherit"}),o.stop("Remote build finished!"),i){o.start("Fetching artifact links...");try{let b=(await _.get(`/builds/${i}/${n}/artifacts`)).data.artifacts||[],O=e.simulator===!0;if(b.length===0&&!O)throw o.stop("Build Failed!"),new Error("Build completed but no artifacts were generated. Check build logs for errors.");if(o.stop("Build Successful!"),b.length>0){He.success("Build Artifacts Ready:");for(let G of b)console.log(`
722
- ${Te.yellow(G.name)}:
723
- ${Te.cyan(G.downloadUrl)}`);console.log(`
724
- ${Te.dim("Note: Links are valid for 7 days.")}`)}else O&&He.warn("Simulator build completed. No artifacts uploaded.")}catch(I){o.stop("Could not fetch artifacts"),He.warn(Te.yellow(`Artifact listing failed: ${I.message}`))}}}catch(d){throw o.stop("iOS Build Failed"),d}};import Xn from"crypto";import et from"axios";async function Ii(e,n){try{let t=await Zn(n),o=(await et.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${e}/edits`,{},{headers:{Authorization:`Bearer ${t}`,Connection:"close"}})).data.id,r=0,c=(await et.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${e}/edits/${o}/tracks`,{headers:{Authorization:`Bearer ${t}`,Connection:"close"}})).data.tracks||[];for(let s of c)if(s.releases){for(let l of s.releases)if(l.versionCodes)for(let d of l.versionCodes){let u=parseInt(d,10);u>r&&(r=u)}}try{let l=(await et.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${e}/edits/${o}/bundles`,{headers:{Authorization:`Bearer ${t}`,Connection:"close"}})).data.bundles||[];for(let d of l)d.versionCode&&d.versionCode>r&&(r=d.versionCode)}catch{}try{let l=(await et.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${e}/edits/${o}/apks`,{headers:{Authorization:`Bearer ${t}`,Connection:"close"}})).data.apks||[];for(let d of l)d.versionCode&&d.versionCode>r&&(r=d.versionCode)}catch{}return r}catch(t){let i=t.response?.data?.error?.message||t.message;throw new Error(`Google Play API Error: ${i}`)}}async function Zn(e){let n=Math.floor(Date.now()/1e3),t=n+3600,i={alg:"RS256",typ:"JWT"},o={iss:e.client_email,sub:e.client_email,aud:"https://oauth2.googleapis.com/token",iat:n,exp:t,scope:"https://www.googleapis.com/auth/androidpublisher"},r=Buffer.from(JSON.stringify(i)).toString("base64url"),a=Buffer.from(JSON.stringify(o)).toString("base64url"),c=`${r}.${a}`,s=Xn.createSign("RSA-SHA256");s.update(c);let l=s.sign(e.private_key,"base64url"),d=`${c}.${l}`;return(await et.post("https://oauth2.googleapis.com/token",{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:d},{headers:{Connection:"close"}})).data.access_token}import{spinner as ht,log as A,isCancel as yt,confirm as Qn,select as Ft}from"@clack/prompts";import S from"chalk";import E from"fs";import P from"path";import{execSync as F,spawn as $i}from"child_process";import _e from"os";import eo from"crypto";var Pi=(e,n)=>n.filter(t=>E.existsSync(P.join(e,t))).reduce((t,i)=>t.update(E.readFileSync(P.join(e,i))),eo.createHash("sha256")).digest("hex").slice(0,16),to=e=>Pi(e,["package.json","yarn.lock","package-lock.json","bun.lockb"]),io=e=>Pi(e,["Podfile","Podfile.lock"]),no=e=>{let n=P.join(e,"fingerprint.json");try{return JSON.parse(E.readFileSync(n,"utf-8"))}catch{return{}}},bi=(e,n)=>{E.mkdirSync(e,{recursive:!0}),E.writeFileSync(P.join(e,"fingerprint.json"),JSON.stringify(n,null,2))},oo=7200*1e3,ro=(e,n)=>{E.mkdirSync(e,{recursive:!0});let t=P.join(e,"build.lock");if(E.existsSync(t))try{let i=JSON.parse(E.readFileSync(t,"utf-8")),o=Date.now()-(i.timestamp||0);if(o<oo)throw new Error(`Another build is already running for this project (build ${i.buildId}, started ${Math.round(o/6e4)}m ago). Cancel it from the dashboard first, or wait for it to complete.`)}catch(i){if(i.message.includes("Another build"))throw i}E.writeFileSync(t,JSON.stringify({buildId:n,pid:process.pid,timestamp:Date.now()}))},so=(e,n)=>{let t=P.join(e,"build.lock");try{E.existsSync(t)&&JSON.parse(E.readFileSync(t,"utf-8")).buildId===n&&E.unlinkSync(t)}catch{}},De=(e,n,t=process.cwd(),i={},o,r)=>new Promise((a,c)=>{let s=["/opt/homebrew/bin","/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin",P.join(_e.homedir(),".npm-global/bin")],d=[...(process.env.PATH||"").split(":"),...s].filter((m,h,$)=>m&&$.indexOf(m)===h).join(":");process.env[`${f.envPrefix}DEBUG`]&&console.log(S.magenta(`[${f.nameUpper}_DEBUG] Execution PATH: ${d}`));let u={...process.env,...i,PATH:d,LANG:"en_US.UTF-8",LC_ALL:"en_US.UTF-8"};o&&process.env[`${f.envPrefix}DEBUG`]&&(o(S.magenta(`[ENVIRONMENT] node: ${process.execPath}
721
+ `):"",Z=Ei,y={"{{REMOTE_DIR}}":p,"{{ENV_VARS}}":x,"{{CREDENTIAL_DOWNLOADS}}":k,"{{IOS_SCHEME}}":e.iosScheme||"","{{IOS_CONFIG}}":e.iosConfiguration||"Release","{{TEAM_ID}}":e.iosTeamId||"","{{AUTH_PARAMS}}":h,"{{IS_SIMULATOR}}":e.simulator?"true":"false","{{BUILD_ID}}":n,"{{EXPORT_METHOD}}":e.iosExportMethod||"ad-hoc","{{NODE_VERSION_SETUP}}":H};Object.entries(y).forEach(([I,b])=>{Z=Z.split(I).join(b)});let v=`/tmp/${f.nameLower}-mac-build-${n}.sh`;if(Xn.writeFileSync(v,Z),Qe(`${l} ${v} ${c}:${p}/build.sh`),o.stop("Remote script uploaded."),Ge.info(Ne.cyan("Executing remote build. This might take a while...")),Qe(`${s} "bash ${p}/build.sh"`,{stdio:"inherit"}),o.stop("Remote build finished!"),i){o.start("Fetching artifact links...");try{let b=(await D.get(`/builds/${i}/${n}/artifacts`)).data.artifacts||[],O=e.simulator===!0;if(b.length===0&&!O)throw o.stop("Build Failed!"),new Error("Build completed but no artifacts were generated. Check build logs for errors.");if(o.stop("Build Successful!"),b.length>0){Ge.success("Build Artifacts Ready:");for(let G of b)console.log(`
722
+ ${Ne.yellow(G.name)}:
723
+ ${Ne.cyan(G.downloadUrl)}`);console.log(`
724
+ ${Ne.dim("Note: Links are valid for 7 days.")}`)}else O&&Ge.warn("Simulator build completed. No artifacts uploaded.")}catch(I){o.stop("Could not fetch artifacts"),Ge.warn(Ne.yellow(`Artifact listing failed: ${I.message}`))}}}catch(d){throw o.stop("iOS Build Failed"),d}};import Zn from"crypto";import et from"axios";async function bi(e,n){try{let t=await Qn(n),o=(await et.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${e}/edits`,{},{headers:{Authorization:`Bearer ${t}`,Connection:"close"}})).data.id,r=0,c=(await et.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${e}/edits/${o}/tracks`,{headers:{Authorization:`Bearer ${t}`,Connection:"close"}})).data.tracks||[];for(let s of c)if(s.releases){for(let l of s.releases)if(l.versionCodes)for(let d of l.versionCodes){let u=parseInt(d,10);u>r&&(r=u)}}try{let l=(await et.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${e}/edits/${o}/bundles`,{headers:{Authorization:`Bearer ${t}`,Connection:"close"}})).data.bundles||[];for(let d of l)d.versionCode&&d.versionCode>r&&(r=d.versionCode)}catch{}try{let l=(await et.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${e}/edits/${o}/apks`,{headers:{Authorization:`Bearer ${t}`,Connection:"close"}})).data.apks||[];for(let d of l)d.versionCode&&d.versionCode>r&&(r=d.versionCode)}catch{}return r}catch(t){let i=t.response?.data?.error?.message||t.message;throw new Error(`Google Play API Error: ${i}`)}}async function Qn(e){let n=Math.floor(Date.now()/1e3),t=n+3600,i={alg:"RS256",typ:"JWT"},o={iss:e.client_email,sub:e.client_email,aud:"https://oauth2.googleapis.com/token",iat:n,exp:t,scope:"https://www.googleapis.com/auth/androidpublisher"},r=Buffer.from(JSON.stringify(i)).toString("base64url"),a=Buffer.from(JSON.stringify(o)).toString("base64url"),c=`${r}.${a}`,s=Zn.createSign("RSA-SHA256");s.update(c);let l=s.sign(e.private_key,"base64url"),d=`${c}.${l}`;return(await et.post("https://oauth2.googleapis.com/token",{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:d},{headers:{Connection:"close"}})).data.access_token}import{spinner as St,log as E,isCancel as At,confirm as eo,select as Ht}from"@clack/prompts";import S from"chalk";import A from"fs";import _ from"path";import{execSync as F,spawn as $i}from"child_process";import _e from"os";import to from"crypto";var _i=(e,n)=>n.filter(t=>A.existsSync(_.join(e,t))).reduce((t,i)=>t.update(A.readFileSync(_.join(e,i))),to.createHash("sha256")).digest("hex").slice(0,16),io=e=>_i(e,["package.json","yarn.lock","package-lock.json","bun.lockb"]),no=e=>_i(e,["Podfile","Podfile.lock"]),oo=e=>{let n=_.join(e,"fingerprint.json");try{return JSON.parse(A.readFileSync(n,"utf-8"))}catch{return{}}},Pi=(e,n)=>{A.mkdirSync(e,{recursive:!0}),A.writeFileSync(_.join(e,"fingerprint.json"),JSON.stringify(n,null,2))},ro=7200*1e3,so=(e,n)=>{A.mkdirSync(e,{recursive:!0});let t=_.join(e,"build.lock");if(A.existsSync(t))try{let i=JSON.parse(A.readFileSync(t,"utf-8")),o=Date.now()-(i.timestamp||0);if(o<ro)throw new Error(`Another build is already running for this project (build ${i.buildId}, started ${Math.round(o/6e4)}m ago). Cancel it from the dashboard first, or wait for it to complete.`)}catch(i){if(i.message.includes("Another build"))throw i}A.writeFileSync(t,JSON.stringify({buildId:n,pid:process.pid,timestamp:Date.now()}))},ao=(e,n)=>{let t=_.join(e,"build.lock");try{A.existsSync(t)&&JSON.parse(A.readFileSync(t,"utf-8")).buildId===n&&A.unlinkSync(t)}catch{}},De=(e,n,t=process.cwd(),i={},o,r)=>new Promise((a,c)=>{let s=["/opt/homebrew/bin","/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin",_.join(_e.homedir(),".npm-global/bin")],d=[...(process.env.PATH||"").split(":"),...s].filter((m,h,P)=>m&&P.indexOf(m)===h).join(":");process.env[`${f.envPrefix}DEBUG`]&&console.log(S.magenta(`[${f.nameUpper}_DEBUG] Execution PATH: ${d}`));let u={...process.env,...i,PATH:d,LANG:"en_US.UTF-8",LC_ALL:"en_US.UTF-8"};o&&process.env[`${f.envPrefix}DEBUG`]&&(o(S.magenta(`[ENVIRONMENT] node: ${process.execPath}
725
725
  `)),o(S.magenta(`[ENVIRONMENT] PATH: ${d}
726
726
  `)),o(S.magenta(`[ENVIRONMENT] command: ${e} ${n.join(" ")}
727
- `)));let p=e;if(["node","npm","npx","pod"].includes(e)){let m=P.dirname(process.execPath),h=P.join(m,e);E.existsSync(h)&&(p=h,o&&o(S.dim(`[EXEC] Using absolute path: ${p}
728
- `)))}let g=$i(p,n,{stdio:"pipe",cwd:t,shell:!0,env:u,detached:process.platform!=="win32"});if(r){if(r.aborted){if(g.pid)try{process.kill(-g.pid,"SIGTERM")}catch{g.kill()}return c(new Error("Command aborted"))}r.addEventListener("abort",()=>{if(g.pid)try{process.kill(-g.pid,"SIGTERM")}catch{g.kill()}c(new Error("Command aborted"))})}g.stdout.on("data",m=>{let h=m.toString();process.stdout.write(h),o&&o(h)}),g.stderr.on("data",m=>{let h=m.toString();process.stderr.write(h),o&&o(h)}),g.on("close",m=>{m===0?a(m):c(new Error(`Command failed with code ${m}: ${e} ${n.join(" ")}`))}),g.on("error",m=>c(m))}),ao=e=>{let n=Math.floor(e/1e3%60),t=Math.floor(e/(1e3*60)%60),i=Math.floor(e/(1e3*60*60)%24),o=[];return i>0&&o.push(`${i}h`),t>0&&o.push(`${t}m`),(n>0||o.length===0)&&o.push(`${n}s`),o.join(" ")},Ge=(e,n)=>{let t=[];try{if(!E.existsSync(e))return t;let i=E.readdirSync(e);for(let o of i){let r=P.join(e,o);try{let a=E.statSync(r);if(n.some(s=>o.endsWith(s))){t.push(P.resolve(r));continue}a.isDirectory()&&(t=t.concat(Ge(r,n)))}catch{}}}catch{}return t},Ht=async(e,n,t={},i,o={})=>{let r=ht(),a=Date.now(),c=e.platform,s=e.buildProfile||"production",l=async(y,w={})=>{if(i)for(let I=1;I<=3;I++)try{await _.patch(`/builds/${i}/${n}`,{status:y,...w});return}catch(b){let O=b?.response?.data?.message||b?.message||String(b);console.error(`[reportStatus] attempt ${I}/3 failed (status=${y}): ${O}`),I<3&&await new Promise(G=>setTimeout(G,2e3))}},d=new AbortController,{signal:u}=d,p=null;i&&(p=setInterval(async()=>{try{(await _.get(`/builds/${i}/${n}`)).data.status==="cancelled"&&(A.warn(S.yellow(`
729
- \u{1F6D1} Build cancelled from dashboard. Terminating...`)),d.abort(),p&&clearInterval(p))}catch{}},5e3));let g=P.join(process.cwd(),".mach-cache"),m="setup",h="",$=null,N=async()=>{if(!h||!i)return;let y=h;h="";try{let w=y;Object.values(t).forEach(I=>{if(I&&I.length>5){let b=I.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");w=w.replace(new RegExp(b,"g"),"[SECRET]")}}),await _.post(`/builds/${i}/${n}/logs`,{log:w,step:m})}catch{}},C=async()=>{$&&(clearTimeout($),$=null),await N(),so(g,n),p&&(clearInterval(p),p=null)},x=async y=>{i&&(h+=y,h.length>=8192?($&&(clearTimeout($),$=null),await N()):$||($=setTimeout(()=>{$=null,N()},2e3)))},H=async y=>{m=y,await x(`[STEP_START:${y}] ${Math.floor(Date.now()/1e3)}
730
- `)},X=async(y,w,I,b)=>await De(y,w,I,b,O=>{x(O)},u);A.info(S.blue(`\u{1F680} Starting local build for ${c} (${s})...`));try{ro(g,n)}catch(y){throw await l("failed",{error:y.message}),y}if(await l("building"),await H("setup"),i&&c==="ios"&&!e.simulator)try{let y=parseInt(t.BUILD_NUMBER||"0",10),w=await _.post(`/projects/${i}/next-build-number`,{platform:"ios",startFrom:y});w.data.status==="success"&&(t.BUILD_NUMBER=String(w.data.buildNumber),A.info(S.dim(`Auto build number: ${t.BUILD_NUMBER}`)),await x(`[BUILD_NUMBER] ${t.BUILD_NUMBER}
731
- `))}catch(y){A.warn(S.yellow(`Could not fetch auto build number: ${y.message}`))}await H("lock"),e.developmentClient?(A.info(S.blue("\u2139\uFE0F Configuring build to INCLUDE expo-dev-client (Development Client mode)...")),delete process.env.EXPO_NO_DEV_CLIENT,delete process.env.EXPO_AUTOLINKING_EXCLUDE):(A.info(S.blue("\u2139\uFE0F Configuring build to EXCLUDE expo-dev-client (Production/Staging mode)...")),process.env.EXPO_NO_DEV_CLIENT="1",process.env.EXPO_AUTOLINKING_EXCLUDE="expo-dev-client");try{await H("clone"),A.info(S.dim("Preparing source...")),await H("read_config");let y=P.join(process.cwd(),f.configFileName);if(E.existsSync(y)){let U=JSON.parse(E.readFileSync(y,"utf-8"))?.build?.[s]||{};await x(`[CONFIG] Profile: ${s}, distribution: ${U.distribution||"not set"}, simulator: ${U.simulator||!1}
732
- `)}if(await H("read_package"),e.nodeVersion){let k=process.env.NVM_DIR||P.join(_e.homedir(),".nvm"),U=P.join(k,"versions","node"),q;if(E.existsSync(U)){let R=E.readdirSync(U).sort().reverse(),Z=e.nodeVersion.startsWith("v")?e.nodeVersion:`v${e.nodeVersion}`,V=R.find(Y=>Y===Z||Y.startsWith(Z+".")||Y.startsWith(`v${e.nodeVersion}.`));V&&(q=P.join(U,V,"bin"))}if(q&&E.existsSync(q)){let R=process.env.PATH||"";process.env.PATH=`${q}:${R}`,await x(`[NODE] Switched to Node ${e.nodeVersion} \u2014 using ${q}
733
- `),A.info(S.green(`\u2713 Node switched to ${e.nodeVersion} (${q})`))}else await x(`[NODE] Warning: Node ${e.nodeVersion} not found in nvm. Run: nvm install ${e.nodeVersion} on the build machine.
734
- `),A.warn(S.yellow(`Node ${e.nodeVersion} not found in nvm \u2014 using system default`))}await H("deps"),r.start("Checking dependencies...");let w=no(g),I=to(process.cwd()),b=E.existsSync("node_modules"),O=E.existsSync("yarn.lock"),G=E.existsSync("bun.lockb");b&&w.node&&w.node!==I&&(r.stop("Dependency fingerprint changed \u2014 clearing node_modules for clean install..."),await x(`[CACHE] package.json/lockfile changed \u2014 wiping node_modules
735
- `),E.rmSync(P.join(process.cwd(),"node_modules"),{recursive:!0,force:!0}),b=!1);let M="npm",T=["install","--prefer-offline"];O?(M="yarn",T=["install","--prefer-offline"]):G&&(M="bun",T=["install"]),b?r.stop("Cached node_modules found. Syncing dependencies..."):r.stop("No cached dependencies. Running fresh install..."),A.info(S.dim(`Running ${M} ${T.join(" ")}...`)),await X(M,T,process.cwd(),t),w.node=I,bi(g,w),e.preBuild&&(A.info(S.blue("Running pre-install hook...")),A.info(S.dim(`> ${e.preBuild}`)),await H("prebuild"),await X("bash",[e.preBuild],process.cwd(),t));let L=JSON.parse(E.readFileSync("package.json","utf-8")),Q=L.dependencies?.expo||L.devDependencies?.expo,K=e.iosBundleIdentifier||"",j=e.name||"";if(Q){r.start(`Enforcing ${f.name} configuration...`);let k=P.join(process.cwd(),"app.json"),U=null;if(E.existsSync(k)){U=E.readFileSync(k,"utf-8");let R=JSON.parse(U);R.expo=R.expo||{},j||(j=R.expo.name||""),c==="ios"&&!K&&(K=R.expo?.ios?.bundleIdentifier||""),e.name&&(R.expo.name=e.name),e.scheme&&(R.expo.scheme=e.scheme),c==="ios"&&e.iosBundleIdentifier?(R.expo.ios=R.expo.ios||{},R.expo.ios.bundleIdentifier=e.iosBundleIdentifier):c==="android"&&e.androidPackage&&(R.expo.android=R.expo.android||{},R.expo.android.package=e.androidPackage),E.writeFileSync(k,JSON.stringify(R,null,2))}let q=["exec","--","expo","prebuild","--platform",c,"--no-install"];try{if(await H("prebuild"),await X("npm",q,process.cwd(),t),c==="ios"&&E.existsSync("ios")){await H("pods"),A.info(S.blue("Running pod install..."));try{let R=P.resolve("ios"),Z=P.join(R,"Podfile");if(!E.existsSync(Z))throw new Error("ios/Podfile not found. Skipping pod install.");let V=E.readFileSync(Z,"utf-8"),Y=e.iosDeploymentTarget||"13.4";if(!e.developmentClient&&(A.info(S.blue("\u2139\uFE0F Patching Podfile to EXCLUDE expo-dev-client...")),V.includes("use_expo_modules!")&&!V.includes("exclude:"))){let ae=/use_expo_modules!(\s*)$/m;ae.test(V)?V=V.replace(ae,'use_expo_modules!(exclude: ["expo-dev-client"])$1'):V=V.replace("use_expo_modules!",'use_expo_modules!(exclude: ["expo-dev-client"])')}let oe=`
727
+ `)));let p=e;if(["node","npm","npx","pod"].includes(e)){let m=_.dirname(process.execPath),h=_.join(m,e);A.existsSync(h)&&(p=h,o&&o(S.dim(`[EXEC] Using absolute path: ${p}
728
+ `)))}let g=$i(p,n,{stdio:"pipe",cwd:t,shell:!0,env:u,detached:process.platform!=="win32"});if(r){if(r.aborted){if(g.pid)try{process.kill(-g.pid,"SIGTERM")}catch{g.kill()}return c(new Error("Command aborted"))}r.addEventListener("abort",()=>{if(g.pid)try{process.kill(-g.pid,"SIGTERM")}catch{g.kill()}c(new Error("Command aborted"))})}g.stdout.on("data",m=>{let h=m.toString();process.stdout.write(h),o&&o(h)}),g.stderr.on("data",m=>{let h=m.toString();process.stderr.write(h),o&&o(h)}),g.on("close",m=>{m===0?a(m):c(new Error(`Command failed with code ${m}: ${e} ${n.join(" ")}`))}),g.on("error",m=>c(m))}),co=e=>{let n=Math.floor(e/1e3%60),t=Math.floor(e/(1e3*60)%60),i=Math.floor(e/(1e3*60*60)%24),o=[];return i>0&&o.push(`${i}h`),t>0&&o.push(`${t}m`),(n>0||o.length===0)&&o.push(`${n}s`),o.join(" ")},je=(e,n)=>{let t=[];try{if(!A.existsSync(e))return t;let i=A.readdirSync(e);for(let o of i){let r=_.join(e,o);try{let a=A.statSync(r);if(n.some(s=>o.endsWith(s))){t.push(_.resolve(r));continue}a.isDirectory()&&(t=t.concat(je(r,n)))}catch{}}}catch{}return t},Gt=async(e,n,t={},i,o={})=>{let r=St(),a=Date.now(),c=e.platform,s=e.buildProfile||"production",l=async(y,v={})=>{if(i)for(let I=1;I<=3;I++)try{await D.patch(`/builds/${i}/${n}`,{status:y,...v});return}catch(b){let O=b?.response?.data?.message||b?.message||String(b);console.error(`[reportStatus] attempt ${I}/3 failed (status=${y}): ${O}`),I<3&&await new Promise(G=>setTimeout(G,2e3))}},d=new AbortController,{signal:u}=d,p=null;i&&(p=setInterval(async()=>{try{(await D.get(`/builds/${i}/${n}`)).data.status==="cancelled"&&(E.warn(S.yellow(`
729
+ \u{1F6D1} Build cancelled from dashboard. Terminating...`)),d.abort(),p&&clearInterval(p))}catch{}},5e3));let g=_.join(process.cwd(),".mach-cache"),m="setup",h="",P=null,k=async()=>{if(!h||!i)return;let y=h;h="";try{let v=y;Object.values(t).forEach(I=>{if(I&&I.length>5){let b=I.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");v=v.replace(new RegExp(b,"g"),"[SECRET]")}}),await D.post(`/builds/${i}/${n}/logs`,{log:v,step:m})}catch{}},C=async()=>{P&&(clearTimeout(P),P=null),await k(),ao(g,n),p&&(clearInterval(p),p=null)},x=async y=>{i&&(h+=y,h.length>=8192?(P&&(clearTimeout(P),P=null),await k()):P||(P=setTimeout(()=>{P=null,k()},2e3)))},H=async y=>{m=y,await x(`[STEP_START:${y}] ${Math.floor(Date.now()/1e3)}
730
+ `)},Z=async(y,v,I,b)=>await De(y,v,I,b,O=>{x(O)},u);E.info(S.blue(`\u{1F680} Starting local build for ${c} (${s})...`));try{so(g,n)}catch(y){throw await l("failed",{error:y.message}),y}if(await l("building"),await H("setup"),i&&c==="ios"&&!e.simulator)try{let y=parseInt(t.BUILD_NUMBER||"0",10),v=await D.post(`/projects/${i}/next-build-number`,{platform:"ios",startFrom:y});v.data.status==="success"&&(t.BUILD_NUMBER=String(v.data.buildNumber),E.info(S.dim(`Auto build number: ${t.BUILD_NUMBER}`)),await x(`[BUILD_NUMBER] ${t.BUILD_NUMBER}
731
+ `))}catch(y){E.warn(S.yellow(`Could not fetch auto build number: ${y.message}`))}await H("lock"),e.developmentClient?(E.info(S.blue("\u2139\uFE0F Configuring build to INCLUDE expo-dev-client (Development Client mode)...")),delete process.env.EXPO_NO_DEV_CLIENT,delete process.env.EXPO_AUTOLINKING_EXCLUDE):(E.info(S.blue("\u2139\uFE0F Configuring build to EXCLUDE expo-dev-client (Production/Staging mode)...")),process.env.EXPO_NO_DEV_CLIENT="1",process.env.EXPO_AUTOLINKING_EXCLUDE="expo-dev-client");try{await H("clone"),E.info(S.dim("Preparing source...")),await H("read_config");let y=_.join(process.cwd(),f.configFileName);if(A.existsSync(y)){let L=JSON.parse(A.readFileSync(y,"utf-8"))?.build?.[s]||{};await x(`[CONFIG] Profile: ${s}, distribution: ${L.distribution||"not set"}, simulator: ${L.simulator||!1}
732
+ `)}if(await H("read_package"),e.nodeVersion){let U=process.env.NVM_DIR||_.join(_e.homedir(),".nvm"),L=_.join(U,"versions","node"),B;if(A.existsSync(L)){let $=A.readdirSync(L).sort().reverse(),K=e.nodeVersion.startsWith("v")?e.nodeVersion:`v${e.nodeVersion}`,j=$.find(V=>V===K||V.startsWith(K+".")||V.startsWith(`v${e.nodeVersion}.`));j&&(B=_.join(L,j,"bin"))}if(B&&A.existsSync(B)){let $=process.env.PATH||"";process.env.PATH=`${B}:${$}`,await x(`[NODE] Switched to Node ${e.nodeVersion} \u2014 using ${B}
733
+ `),E.info(S.green(`\u2713 Node switched to ${e.nodeVersion} (${B})`))}else await x(`[NODE] Warning: Node ${e.nodeVersion} not found in nvm. Run: nvm install ${e.nodeVersion} on the build machine.
734
+ `),E.warn(S.yellow(`Node ${e.nodeVersion} not found in nvm \u2014 using system default`))}await H("deps"),r.start("Checking dependencies...");let v=oo(g),I=io(process.cwd()),b=A.existsSync("node_modules"),O=A.existsSync("yarn.lock"),G=A.existsSync("bun.lockb");b&&v.node&&v.node!==I&&(r.stop("Dependency fingerprint changed \u2014 clearing node_modules for clean install..."),await x(`[CACHE] package.json/lockfile changed \u2014 wiping node_modules
735
+ `),A.rmSync(_.join(process.cwd(),"node_modules"),{recursive:!0,force:!0}),b=!1);let M="npm",T=["install","--prefer-offline"];O?(M="yarn",T=["install","--prefer-offline"]):G&&(M="bun",T=["install"]),b?r.stop("Cached node_modules found. Syncing dependencies..."):r.stop("No cached dependencies. Running fresh install...");let N=_.join(process.cwd(),"package.json"),q=null;if(e.preBuild&&A.existsSync(N)){let U=JSON.parse(A.readFileSync(N,"utf-8")),L=$=>typeof $=="string"&&($.includes("bitbucket.org")||$.includes("github.com")||$.startsWith("git+")||$.startsWith("git://")||$.includes(".git")),B={...U};for(let $ of["dependencies","devDependencies","optionalDependencies"])if(B[$]){let K={...B[$]};for(let[j,V]of Object.entries(K))L(V)&&(delete K[j],await x(`[DEPS] Skipping git dependency ${j} \u2014 will be installed by preBuild script
736
+ `));B[$]=K}q=A.readFileSync(N,"utf-8"),A.writeFileSync(N,JSON.stringify(B,null,2))}try{E.info(S.dim(`Running ${M} ${T.join(" ")}...`)),await Z(M,T,process.cwd(),t)}finally{q!==null&&A.writeFileSync(N,q)}v.node=I,Pi(g,v),e.preBuild&&(E.info(S.blue("Running pre-install hook...")),E.info(S.dim(`> ${e.preBuild}`)),await H("prebuild"),await Z("bash",[e.preBuild],process.cwd(),t));let z=JSON.parse(A.readFileSync("package.json","utf-8")),W=z.dependencies?.expo||z.devDependencies?.expo,ee=e.iosBundleIdentifier||"",le=e.name||"";if(W){r.start(`Enforcing ${f.name} configuration...`);let U=_.join(process.cwd(),"app.json"),L=null;if(A.existsSync(U)){L=A.readFileSync(U,"utf-8");let $=JSON.parse(L);$.expo=$.expo||{},le||(le=$.expo.name||""),c==="ios"&&!ee&&(ee=$.expo?.ios?.bundleIdentifier||""),e.name&&($.expo.name=e.name),e.scheme&&($.expo.scheme=e.scheme),c==="ios"&&e.iosBundleIdentifier?($.expo.ios=$.expo.ios||{},$.expo.ios.bundleIdentifier=e.iosBundleIdentifier):c==="android"&&e.androidPackage&&($.expo.android=$.expo.android||{},$.expo.android.package=e.androidPackage),A.writeFileSync(U,JSON.stringify($,null,2))}let B=["exec","--","expo","prebuild","--platform",c,"--no-install"];try{if(await H("prebuild"),await Z("npm",B,process.cwd(),t),c==="ios"&&A.existsSync("ios")){await H("pods"),E.info(S.blue("Running pod install..."));try{let $=_.resolve("ios"),K=_.join($,"Podfile");if(!A.existsSync(K))throw new Error("ios/Podfile not found. Skipping pod install.");let j=A.readFileSync(K,"utf-8"),V=e.iosDeploymentTarget||"13.4";if(!e.developmentClient&&(E.info(S.blue("\u2139\uFE0F Patching Podfile to EXCLUDE expo-dev-client...")),j.includes("use_expo_modules!")&&!j.includes("exclude:"))){let ht=/use_expo_modules!(\s*)$/m;ht.test(j)?j=j.replace(ht,'use_expo_modules!(exclude: ["expo-dev-client"])$1'):j=j.replace("use_expo_modules!",'use_expo_modules!(exclude: ["expo-dev-client"])')}let ae=`
736
737
  installer.generated_projects.each do |project|
737
738
  project.targets.each do |target|
738
739
  target.build_configurations.each do |config|
739
- config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '${Y}'
740
+ config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '${V}'
740
741
  end
741
742
  end
742
743
  end
743
744
  installer.pods_project.targets.each do |target|
744
745
  target.build_configurations.each do |config|
745
- config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '${Y}'
746
+ config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '${V}'
746
747
  end
747
748
  end
748
- `,Ee=/post_install\s+do\s+\|installer\|/;if(Ee.test(V))A.info(S.dim(`Injecting deployment target (${Y}) into existing post_install hook...`)),V=V.replace(Ee,`post_install do |installer|
749
- ${oe}`),E.writeFileSync(Z,V);else{A.info(S.dim(`Appending new post_install hook for deployment target (${Y})...`));let ae=`
749
+ `,Te=/post_install\s+do\s+\|installer\|/;if(Te.test(j))E.info(S.dim(`Injecting deployment target (${V}) into existing post_install hook...`)),j=j.replace(Te,`post_install do |installer|
750
+ ${ae}`),A.writeFileSync(K,j);else{E.info(S.dim(`Appending new post_install hook for deployment target (${V})...`));let ht=`
750
751
  post_install do |installer|
751
- ${oe}
752
+ ${ae}
752
753
  end
753
- `;E.appendFileSync(Z,ae)}let qe="/opt/homebrew/bin/pod",Lt=E.existsSync(qe)?qe:"pod",Fe=io(R);E.existsSync(P.join(R,"Pods"))&&w.pods&&w.pods!==Fe&&(await x(`[CACHE] Podfile/Podfile.lock changed \u2014 wiping ios/Pods
754
- `),A.info(S.dim("Podfile fingerprint changed \u2014 clearing Pods for clean install...")),E.rmSync(P.join(R,"Pods"),{recursive:!0,force:!0})),A.info(S.dim(`Using pod command: ${Lt} in ${R}`)),await X(Lt,["install"],R,t),w.pods=Fe,bi(g,w)}catch(R){let Z=R.message||"Unknown error";A.warn(S.yellow(`Native "pod" command failed: ${Z}`)),A.info(S.dim("Falling back to npm exec pod-install...")),A.info(S.magenta(`${f.nameUpper}_DEBUG: Executing pod-install override via npx --yes pod-install@latest`)),await X("npx",["--yes","pod-install@latest","ios"],process.cwd(),t)}if(E.existsSync("ios/Pods")){A.info(S.dim("Disabling signing for Pod targets to prevent conflicts..."));try{F(`find ios/Pods -name "project.pbxproj" -exec sed -i '' 's/buildSettings = {/buildSettings = { CODE_SIGNING_ALLOWED = NO; CODE_SIGNING_REQUIRED = NO; PROVISIONING_PROFILE_SPECIFIER = ""; EXPANDED_CODE_SIGN_IDENTITY = "";/g' {} +`,{stdio:"ignore"})}catch{}}}}finally{U&&E.writeFileSync(k,U)}r.stop(`Expo prebuild complete (${f.name} config enforced).`)}let B=[];if(c==="android")await H("build"),B=await co(e,s,t,k=>x(k),u);else if(c==="ios"){await H("signing"),A.info(S.dim("Preparing credentials..."));let k=o?.distributionType;B=await lo(e,n,s,t,i,U=>x(U),u,k,U=>H(U))}e.postBuild&&(A.info(S.blue("Running post-build hook...")),A.info(S.dim(`> ${e.postBuild}`)),await X(e.postBuild,[],process.cwd(),t));let Se=ao(Date.now()-a);if(A.success(S.green(`
755
- \u2713 Local build completed successfully in ${Se}`)),await l("building",{...K&&{bundleId:K},...j&&{appName:j}}),B.length>0&&(A.info(S.cyan(`
756
- \u{1F4E6} Generated Artifacts:`)),B.forEach(k=>{let U=P.resolve(k);A.info(S.dim(` - ${k}`)),A.info(S.gray(` Path: ${U}`))}),e.interactive)){let k=await Qn({message:"Install on connected device?"});if(!yt(k)&&k){if(c==="android"){let U=B.find(q=>q.endsWith(".apk"))||B[0];await po(U,q=>x(q))}else if(c==="ios"){let U=B.find(R=>R.endsWith(".ipa"))||B.find(R=>R.endsWith(".app"))||B[0],q=Oe("ios");e.simulator?await fo(U,q||"",R=>x(R)):await mo(U,q||"",R=>x(R))}}}await H("upload");let Ae=[];for(let k of B)try{let U=P.join(_e.tmpdir(),`${n}-${P.basename(k)}`);E.copyFileSync(k,U),Ae.push(U),A.info(S.dim(` \u{1F4CB} Preserved artifact: ${P.basename(k)}`))}catch{A.warn(S.yellow(` Failed to preserve artifact: ${P.basename(k)}`))}B=Ae,A.info(S.dim("\u{1F9F9} Cleaning workspace (preserving dependency cache)..."));try{let k=process.cwd(),U=new Set(["node_modules"]),q=E.readdirSync(k),R=0;for(let Z of q)if(!U.has(Z)){if(Z==="ios"){let V=P.join(k,"ios"),Y=E.readdirSync(V);for(let oe of Y)if(oe!=="Pods")try{E.rmSync(P.join(V,oe),{recursive:!0,force:!0}),R++}catch{}continue}try{E.rmSync(P.join(k,Z),{recursive:!0,force:!0}),R++}catch{}}try{let Z=P.join(_e.tmpdir(),`${f.buildPrefix}-${n}.keychain-db`);E.existsSync(Z)&&F(`security delete-keychain "${Z}"`,{stdio:"ignore"})}catch{}A.info(S.dim(` Cleaned ${R} items. Cached: node_modules${E.existsSync(P.join(k,"ios","Pods"))?", ios/Pods":""}`)),A.info(S.green("\u{1F512} Security: No source code retained on build server. Only public dependencies cached."))}catch{A.warn(S.yellow("Post-build cleanup encountered errors (non-fatal)."))}try{let U=P.join(_e.homedir(),f.workspacesDir),q=F(`df -k "${U}" | tail -1 | awk '{print $4}'`,{encoding:"utf8"}).trim(),R=parseInt(q,10)*1024;if(R<53687091200&&E.existsSync(U)){A.info(S.dim(` \u26A0\uFE0F Low disk space (${(R/1024/1024/1024).toFixed(0)} GB free). Running cache eviction...`));let Z=P.basename(process.cwd()),V=E.readdirSync(U).filter(Y=>Y!==Z).map(Y=>{let oe=P.join(U,Y);try{let Ee=E.statSync(oe);return Ee.isDirectory()?{name:Y,dir:oe,mtime:Ee.mtimeMs}:null}catch{return null}}).filter(Boolean);V.sort((Y,oe)=>Y.mtime-oe.mtime);for(let Y of V){if(R>=53687091200)break;try{E.rmSync(Y.dir,{recursive:!0,force:!0}),A.info(S.dim(` \u{1F5D1}\uFE0F Evicted stale workspace: ${Y.name}`));let oe=F(`df -k "${U}" | tail -1 | awk '{print $4}'`,{encoding:"utf8"}).trim();if(parseInt(oe,10)*1024>=53687091200)break}catch{}}}}catch{}return await C(),B}catch(y){throw await C(),y.message==="Command aborted"?(A.warn(S.yellow(`
757
- \u274C Build aborted.`)),await l("failed",{error:"Aborted by user"}),y):(A.error(S.red(`
758
- \u2717 Local build failed: ${y.message}`)),await l("failed",{error:y.message}),y)}},co=async(e,n,t={},i,o)=>{let r=E.existsSync("android/gradlew")?"android/gradlew":E.existsSync("gradlew")?"./gradlew":null;if(!r)throw new Error("Could not find gradlew. Is this an Android project?");let a="assembleRelease";e.distribution==="store"?a="bundleRelease":e.distribution==="internal"&&(a="assembleRelease");let c=e.buildCommand||a;A.info(S.blue(`Running Android build: ${c}...`));let s=r.includes("android/")?"android":".",l=(r.includes("android/"),"./gradlew");await De(l,[c],s,t,i,o);let d=P.join(s,"app/build/outputs");return Ge(d,[".apk",".aab"])},lo=async(e,n,t,i={},o,r,a,c,s)=>{if(process.platform!=="darwin")throw new Error("iOS builds can only be run on macOS.");let l=P.resolve(process.cwd(),E.existsSync("ios")?"ios":"."),d=E.readdirSync(l),u=d.find(C=>C.endsWith(".xcworkspace")),p=d.find(C=>C.endsWith(".xcodeproj"));if(!u&&!p)throw new Error("Could not find Xcode workspace or project in ios/ directory.");try{let C=F("xcode-select -p").toString().trim();A.info(S.dim(`Using Xcode at: ${C}`))}catch{A.warn(S.dim("Could not detect Xcode path."))}A.info(S.blue("Running iOS build via xcodebuild..."));let g=u?u.replace(".xcworkspace",""):p?.replace(".xcodeproj",""),m=e.iosScheme||g||e.scheme,h=e.developmentClient?"Debug":e.iosConfiguration||"Release",$=(o||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),N=P.join(_e.homedir(),`Library/Developer/Xcode/DerivedData/${f.nameLower}`,$);if(E.mkdirSync(N,{recursive:!0}),e.simulator){A.info(S.dim(`Building for simulator (Scheme: ${m}, Config: ${h})...`)),await De("xcodebuild",[u?"-workspace":"-project",u||p,"-scheme",m,"-configuration",h,"-sdk","iphonesimulator","-derivedDataPath",N,"CODE_SIGNING_ALLOWED=NO","CODE_SIGNING_REQUIRED=NO"],l,i,r,a);let C=P.join(N,"Build/Products",`${h}-iphonesimulator`),x=Ge(C,[".app"]);if(x.length>0){let H=x[0],X=P.basename(H,".app"),y=P.join(C,`${X}_simulator.zip`);return A.info(S.dim(`Creating simulator artifact: ${y}...`)),F(`cd "${C}" && zip -r "${y}" "${P.basename(H)}"`),[y]}return[]}else{A.info(S.dim(`Archiving (Scheme: ${m}, Config: ${h})...`));let C=P.join(l,"build.xcarchive"),x=P.join(l,"export"),H=i.IOS_DIST_P12,X=i.IOS_PROVISIONING_PROFILE,y=i.IOS_P12_PASSWORD||"",w=[],I,b,O={isAppStore:!1,isDevelopment:!1};if(H&&X){A.info(S.blue("\u{1F510} CI/CD Signing: Importing certificates..."));try{let j=`${f.buildPrefix}-${n}.keychain-db`,B=P.join(_e.tmpdir(),j),Se=f.keychainPassword;F(`security create-keychain -p "${Se}" "${B}" 2>/dev/null || true`),F(`security set-keychain-settings -t 3600 -l "${B}"`),F(`security unlock-keychain -p "${Se}" "${B}"`);let Ae=P.join(_e.tmpdir(),`cert-${n}.p12`),k=Buffer.from(H,"base64");E.writeFileSync(Ae,k),A.info(S.dim(`P12 data size: ${k.length} bytes, first bytes: ${k.slice(0,4).toString("hex")}`)),(k.length<100||k[0]!==48)&&(A.warn(S.yellow("\u26A0\uFE0F P12 data looks corrupted or was not decrypted correctly.")),A.warn(S.yellow(" This usually means MACH_ENCRYPTION_KEY on the Remote API differs from when credentials were uploaded.")));let U=[y,"",f.keychainPassword],q=!1;for(let se of U)try{F(`security import "${Ae}" -k "${B}" -P "${se}" -A -T /usr/bin/codesign -T /usr/bin/security`,{stdio:"pipe"}),q=!0,A.info(S.dim(`\u2713 P12 imported successfully with password: ${se?"[set]":"[empty]"}`));break}catch(ae){A.info(S.dim(` P12 import attempt with password ${se?`"${se.substring(0,3)}..."`:"[empty]"} failed: ${ae.message?.split(`
759
- `)[0]||"unknown"}`))}if(!q)throw new Error("Failed to import P12.");E.unlinkSync(Ae),F(`security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "${Se}" "${B}"`);let R=F("security list-keychains -d user",{encoding:"utf-8"}).split(`
760
- `).map(se=>se.trim().replace(/^"|"$/g,"")).filter(se=>se.length>0),Z=[B,...R].map(se=>`"${se}"`).join(" ");F(`security list-keychains -d user -s ${Z}`),F(`security default-keychain -s "${B}"`);let V=P.join(_e.homedir(),"Library/MobileDevice/Provisioning Profiles");E.mkdirSync(V,{recursive:!0});let Y=Buffer.from(X,"base64"),oe=P.join(V,`${f.nameLower}-temp-${n}.mobileprovision`);E.writeFileSync(oe,Y);let Ee=Y.toString("utf-8"),qe=/<key>get-task-allow<\/key>\s*<true\/>/.test(Ee);O={isAppStore:!Ee.includes("<key>ProvisionedDevices</key>")&&!qe,isDevelopment:qe};try{let ae=F(`security cms -D -i "${oe}"`,{encoding:"utf-8"}).match(/<key>UUID<\/key>\s*<string>([^<]+)<\/string>/);b=ae?ae[1]:void 0}catch{let ae=Ee.match(/<key>UUID<\/key>\s*<string>([^<]+)<\/string>/);b=ae?ae[1]:void 0}b||(A.warn("Could not extract UUID from provisioning profile. Using fallback."),b=`${f.nameLower}-${n}`);let Fe=P.join(V,`${b}.mobileprovision`);E.existsSync(Fe)&&E.unlinkSync(Fe),E.renameSync(oe,Fe);try{let ae=F(`security find-identity -v -p codesigning "${B}"`,{encoding:"utf-8"}).match(/"((?:Apple|iPhone) (?:Distribution|Developer|Development)[^"]*)"/);ae&&(I=ae[1],A.info(S.blue(`Identity auto-detected from keychain: "${I}"`)))}catch{}I||(I=O.isDevelopment?"Apple Development":"Apple Distribution",A.info(S.blue(`Identity fallback (profile heuristic): "${I}"`))),A.info(S.dim(`Profile type: ${O.isDevelopment?"Development":O.isAppStore?"App Store":"Ad-Hoc"}`)),A.info(S.dim(`Identity Detection: get-task-allow=${O.isDevelopment}, Selected Identity="${I}"`)),w.push("CODE_SIGN_STYLE=Manual"),w.push(`CODE_SIGN_IDENTITY="${I}"`),w.push(`PROVISIONING_PROFILE_SPECIFIER=${b}`),e.iosTeamId&&w.push(`DEVELOPMENT_TEAM=${e.iosTeamId}`)}catch(j){throw A.error(`Signing setup failed: ${j.message}`),j}}else w.push("-allowProvisioningUpdates"),e.iosTeamId&&w.push(`DEVELOPMENT_TEAM=${e.iosTeamId}`);s&&await s("archive"),A.info(S.blue(`Archive detected Identity: "${I}"`)),A.info(S.blue(`Archive detected UUID: "${b}"`)),await De("xcodebuild",["archive",u?"-workspace":"-project",u||p,"-scheme",m,"-configuration",h,"-archivePath",C,"-derivedDataPath",N,...w],l,i,r,a);let G;b?(O.isAppStore?G="app-store":O.isDevelopment?G="development":G="ad-hoc",A.info(S.blue(`Export method from profile: "${G}"`))):(G=e.distribution==="store"?"app-store":e.distribution==="internal"?"ad-hoc":"development",A.warn(S.yellow(`No profile UUID detected. Export method from distribution flag: "${G}"`)));let M=e.iosExportMethod||G,T=Oe("ios"),L=P.join(l,"ExportOptions.plist"),Q=`<?xml version="1.0" encoding="UTF-8"?>
754
+ `;A.appendFileSync(K,ht)}let He="/opt/homebrew/bin/pod",oe=A.existsSync(He)?He:"pod",pe=no($);A.existsSync(_.join($,"Pods"))&&v.pods&&v.pods!==pe&&(await x(`[CACHE] Podfile/Podfile.lock changed \u2014 wiping ios/Pods
755
+ `),E.info(S.dim("Podfile fingerprint changed \u2014 clearing Pods for clean install...")),A.rmSync(_.join($,"Pods"),{recursive:!0,force:!0})),E.info(S.dim(`Using pod command: ${oe} in ${$}`)),await Z(oe,["install"],$,t),v.pods=pe,Pi(g,v)}catch($){let K=$.message||"Unknown error";E.warn(S.yellow(`Native "pod" command failed: ${K}`)),E.info(S.dim("Falling back to npm exec pod-install...")),E.info(S.magenta(`${f.nameUpper}_DEBUG: Executing pod-install override via npx --yes pod-install@latest`)),await Z("npx",["--yes","pod-install@latest","ios"],process.cwd(),t)}if(A.existsSync("ios/Pods")){E.info(S.dim("Disabling signing for Pod targets to prevent conflicts..."));try{F(`find ios/Pods -name "project.pbxproj" -exec sed -i '' 's/buildSettings = {/buildSettings = { CODE_SIGNING_ALLOWED = NO; CODE_SIGNING_REQUIRED = NO; PROVISIONING_PROFILE_SPECIFIER = ""; EXPANDED_CODE_SIGN_IDENTITY = "";/g' {} +`,{stdio:"ignore"})}catch{}}}}finally{L&&A.writeFileSync(U,L)}r.stop(`Expo prebuild complete (${f.name} config enforced).`)}let Q=[];if(c==="android")await H("build"),Q=await lo(e,s,t,U=>x(U),u);else if(c==="ios"){await H("signing"),E.info(S.dim("Preparing credentials..."));let U=o?.distributionType;Q=await uo(e,n,s,t,i,L=>x(L),u,U,L=>H(L))}e.postBuild&&(E.info(S.blue("Running post-build hook...")),E.info(S.dim(`> ${e.postBuild}`)),await Z(e.postBuild,[],process.cwd(),t));let Ee=co(Date.now()-a);if(E.success(S.green(`
756
+ \u2713 Local build completed successfully in ${Ee}`)),await l("building",{...ee&&{bundleId:ee},...le&&{appName:le}}),Q.length>0&&(E.info(S.cyan(`
757
+ \u{1F4E6} Generated Artifacts:`)),Q.forEach(U=>{let L=_.resolve(U);E.info(S.dim(` - ${U}`)),E.info(S.gray(` Path: ${L}`))}),e.interactive)){let U=await eo({message:"Install on connected device?"});if(!At(U)&&U){if(c==="android"){let L=Q.find(B=>B.endsWith(".apk"))||Q[0];await fo(L,B=>x(B))}else if(c==="ios"){let L=Q.find($=>$.endsWith(".ipa"))||Q.find($=>$.endsWith(".app"))||Q[0],B=Oe("ios");e.simulator?await mo(L,B||"",$=>x($)):await go(L,B||"",$=>x($))}}}await H("upload");let gt=[];for(let U of Q)try{let L=_.join(_e.tmpdir(),`${n}-${_.basename(U)}`);A.copyFileSync(U,L),gt.push(L),E.info(S.dim(` \u{1F4CB} Preserved artifact: ${_.basename(U)}`))}catch{E.warn(S.yellow(` Failed to preserve artifact: ${_.basename(U)}`))}Q=gt,E.info(S.dim("\u{1F9F9} Cleaning workspace (preserving dependency cache)..."));try{let U=process.cwd(),L=new Set(["node_modules"]),B=A.readdirSync(U),$=0;for(let K of B)if(!L.has(K)){if(K==="ios"){let j=_.join(U,"ios"),V=A.readdirSync(j);for(let ae of V)if(ae!=="Pods")try{A.rmSync(_.join(j,ae),{recursive:!0,force:!0}),$++}catch{}continue}try{A.rmSync(_.join(U,K),{recursive:!0,force:!0}),$++}catch{}}try{let K=_.join(_e.tmpdir(),`${f.buildPrefix}-${n}.keychain-db`);A.existsSync(K)&&F(`security delete-keychain "${K}"`,{stdio:"ignore"})}catch{}E.info(S.dim(` Cleaned ${$} items. Cached: node_modules${A.existsSync(_.join(U,"ios","Pods"))?", ios/Pods":""}`)),E.info(S.green("\u{1F512} Security: No source code retained on build server. Only public dependencies cached."))}catch{E.warn(S.yellow("Post-build cleanup encountered errors (non-fatal)."))}try{let L=_.join(_e.homedir(),f.workspacesDir),B=F(`df -k "${L}" | tail -1 | awk '{print $4}'`,{encoding:"utf8"}).trim(),$=parseInt(B,10)*1024;if($<53687091200&&A.existsSync(L)){E.info(S.dim(` \u26A0\uFE0F Low disk space (${($/1024/1024/1024).toFixed(0)} GB free). Running cache eviction...`));let K=_.basename(process.cwd()),j=A.readdirSync(L).filter(V=>V!==K).map(V=>{let ae=_.join(L,V);try{let Te=A.statSync(ae);return Te.isDirectory()?{name:V,dir:ae,mtime:Te.mtimeMs}:null}catch{return null}}).filter(Boolean);j.sort((V,ae)=>V.mtime-ae.mtime);for(let V of j){if($>=53687091200)break;try{A.rmSync(V.dir,{recursive:!0,force:!0}),E.info(S.dim(` \u{1F5D1}\uFE0F Evicted stale workspace: ${V.name}`));let ae=F(`df -k "${L}" | tail -1 | awk '{print $4}'`,{encoding:"utf8"}).trim();if(parseInt(ae,10)*1024>=53687091200)break}catch{}}}}catch{}return await C(),Q}catch(y){throw await C(),y.message==="Command aborted"?(E.warn(S.yellow(`
758
+ \u274C Build aborted.`)),await l("failed",{error:"Aborted by user"}),y):(E.error(S.red(`
759
+ \u2717 Local build failed: ${y.message}`)),await l("failed",{error:y.message}),y)}},lo=async(e,n,t={},i,o)=>{let r=A.existsSync("android/gradlew")?"android/gradlew":A.existsSync("gradlew")?"./gradlew":null;if(!r)throw new Error("Could not find gradlew. Is this an Android project?");let a="assembleRelease";e.distribution==="store"?a="bundleRelease":e.distribution==="internal"&&(a="assembleRelease");let c=e.buildCommand||a;E.info(S.blue(`Running Android build: ${c}...`));let s=r.includes("android/")?"android":".",l=(r.includes("android/"),"./gradlew");await De(l,[c],s,t,i,o);let d=_.join(s,"app/build/outputs");return je(d,[".apk",".aab"])},uo=async(e,n,t,i={},o,r,a,c,s)=>{if(process.platform!=="darwin")throw new Error("iOS builds can only be run on macOS.");let l=_.resolve(process.cwd(),A.existsSync("ios")?"ios":"."),d=A.readdirSync(l),u=d.find(C=>C.endsWith(".xcworkspace")),p=d.find(C=>C.endsWith(".xcodeproj"));if(!u&&!p)throw new Error("Could not find Xcode workspace or project in ios/ directory.");try{let C=F("xcode-select -p").toString().trim();E.info(S.dim(`Using Xcode at: ${C}`))}catch{E.warn(S.dim("Could not detect Xcode path."))}E.info(S.blue("Running iOS build via xcodebuild..."));let g=u?u.replace(".xcworkspace",""):p?.replace(".xcodeproj",""),m=e.iosScheme||g||e.scheme,h=e.developmentClient?"Debug":e.iosConfiguration||"Release",P=(o||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),k=_.join(_e.homedir(),`Library/Developer/Xcode/DerivedData/${f.nameLower}`,P);if(A.mkdirSync(k,{recursive:!0}),e.simulator){E.info(S.dim(`Building for simulator (Scheme: ${m}, Config: ${h})...`)),await De("xcodebuild",[u?"-workspace":"-project",u||p,"-scheme",m,"-configuration",h,"-sdk","iphonesimulator","-derivedDataPath",k,"CODE_SIGNING_ALLOWED=NO","CODE_SIGNING_REQUIRED=NO"],l,i,r,a);let C=_.join(k,"Build/Products",`${h}-iphonesimulator`),x=je(C,[".app"]);if(x.length>0){let H=x[0],Z=_.basename(H,".app"),y=_.join(C,`${Z}_simulator.zip`);return E.info(S.dim(`Creating simulator artifact: ${y}...`)),F(`cd "${C}" && zip -r "${y}" "${_.basename(H)}"`),[y]}return[]}else{E.info(S.dim(`Archiving (Scheme: ${m}, Config: ${h})...`));let C=_.join(l,"build.xcarchive"),x=_.join(l,"export"),H=i.IOS_DIST_P12,Z=i.IOS_PROVISIONING_PROFILE,y=i.IOS_P12_PASSWORD||"",v=[],I,b,O={isAppStore:!1,isDevelopment:!1};if(H&&Z){E.info(S.blue("\u{1F510} CI/CD Signing: Importing certificates..."));try{let W=`${f.buildPrefix}-${n}.keychain-db`,ee=_.join(_e.tmpdir(),W),le=f.keychainPassword;F(`security create-keychain -p "${le}" "${ee}" 2>/dev/null || true`),F(`security set-keychain-settings -t 3600 -l "${ee}"`),F(`security unlock-keychain -p "${le}" "${ee}"`);let Q=_.join(_e.tmpdir(),`cert-${n}.p12`),Ee=Buffer.from(H,"base64");A.writeFileSync(Q,Ee),E.info(S.dim(`P12 data size: ${Ee.length} bytes, first bytes: ${Ee.slice(0,4).toString("hex")}`)),(Ee.length<100||Ee[0]!==48)&&(E.warn(S.yellow("\u26A0\uFE0F P12 data looks corrupted or was not decrypted correctly.")),E.warn(S.yellow(" This usually means MACH_ENCRYPTION_KEY on the Remote API differs from when credentials were uploaded.")));let gt=[y,"",f.keychainPassword],U=!1;for(let oe of gt)try{F(`security import "${Q}" -k "${ee}" -P "${oe}" -A -T /usr/bin/codesign -T /usr/bin/security`,{stdio:"pipe"}),U=!0,E.info(S.dim(`\u2713 P12 imported successfully with password: ${oe?"[set]":"[empty]"}`));break}catch(pe){E.info(S.dim(` P12 import attempt with password ${oe?`"${oe.substring(0,3)}..."`:"[empty]"} failed: ${pe.message?.split(`
760
+ `)[0]||"unknown"}`))}if(!U)throw new Error("Failed to import P12.");A.unlinkSync(Q),F(`security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "${le}" "${ee}"`);let L=F("security list-keychains -d user",{encoding:"utf-8"}).split(`
761
+ `).map(oe=>oe.trim().replace(/^"|"$/g,"")).filter(oe=>oe.length>0),B=[ee,...L].map(oe=>`"${oe}"`).join(" ");F(`security list-keychains -d user -s ${B}`),F(`security default-keychain -s "${ee}"`);let $=_.join(_e.homedir(),"Library/MobileDevice/Provisioning Profiles");A.mkdirSync($,{recursive:!0});let K=Buffer.from(Z,"base64"),j=_.join($,`${f.nameLower}-temp-${n}.mobileprovision`);A.writeFileSync(j,K);let V=K.toString("utf-8"),ae=/<key>get-task-allow<\/key>\s*<true\/>/.test(V);O={isAppStore:!V.includes("<key>ProvisionedDevices</key>")&&!ae,isDevelopment:ae};try{let pe=F(`security cms -D -i "${j}"`,{encoding:"utf-8"}).match(/<key>UUID<\/key>\s*<string>([^<]+)<\/string>/);b=pe?pe[1]:void 0}catch{let pe=V.match(/<key>UUID<\/key>\s*<string>([^<]+)<\/string>/);b=pe?pe[1]:void 0}b||(E.warn("Could not extract UUID from provisioning profile. Using fallback."),b=`${f.nameLower}-${n}`);let He=_.join($,`${b}.mobileprovision`);A.existsSync(He)&&A.unlinkSync(He),A.renameSync(j,He);try{let pe=F(`security find-identity -v -p codesigning "${ee}"`,{encoding:"utf-8"}).match(/"((?:Apple|iPhone) (?:Distribution|Developer|Development)[^"]*)"/);pe&&(I=pe[1],E.info(S.blue(`Identity auto-detected from keychain: "${I}"`)))}catch{}I||(I=O.isDevelopment?"Apple Development":"Apple Distribution",E.info(S.blue(`Identity fallback (profile heuristic): "${I}"`))),E.info(S.dim(`Profile type: ${O.isDevelopment?"Development":O.isAppStore?"App Store":"Ad-Hoc"}`)),E.info(S.dim(`Identity Detection: get-task-allow=${O.isDevelopment}, Selected Identity="${I}"`)),v.push("CODE_SIGN_STYLE=Manual"),v.push(`CODE_SIGN_IDENTITY="${I}"`),v.push(`PROVISIONING_PROFILE_SPECIFIER=${b}`),e.iosTeamId&&v.push(`DEVELOPMENT_TEAM=${e.iosTeamId}`)}catch(W){throw E.error(`Signing setup failed: ${W.message}`),W}}else v.push("-allowProvisioningUpdates"),e.iosTeamId&&v.push(`DEVELOPMENT_TEAM=${e.iosTeamId}`);s&&await s("archive"),E.info(S.blue(`Archive detected Identity: "${I}"`)),E.info(S.blue(`Archive detected UUID: "${b}"`)),await De("xcodebuild",["archive",u?"-workspace":"-project",u||p,"-scheme",m,"-configuration",h,"-archivePath",C,"-derivedDataPath",k,...v],l,i,r,a);let G;b?(O.isAppStore?G="app-store":O.isDevelopment?G="development":G="ad-hoc",E.info(S.blue(`Export method from profile: "${G}"`))):(G=e.distribution==="store"?"app-store":e.distribution==="internal"?"ad-hoc":"development",E.warn(S.yellow(`No profile UUID detected. Export method from distribution flag: "${G}"`)));let M=e.iosExportMethod||G,T=Oe("ios"),N=_.join(l,"ExportOptions.plist"),q=`<?xml version="1.0" encoding="UTF-8"?>
761
762
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
762
763
  <plist version="1.0">
763
764
  <dict>
@@ -777,46 +778,46 @@ end
777
778
  <string>${b}</string>
778
779
  </dict>`:""}
779
780
  </dict>
780
- </plist>`;if(E.writeFileSync(L,Q),process.env[`${f.envPrefix}DEBUG`]&&A.info(S.magenta(`[${f.nameUpper}_DEBUG] ExportOptions.plist:
781
- ${Q}`)),s&&await s("export"),A.info(S.blue(`Exporting with Bundle ID: "${T}"`)),A.info(S.blue(`Exporting with Method: "${M}"`)),r){r(S.magenta(`
781
+ </plist>`;if(A.writeFileSync(N,q),process.env[`${f.envPrefix}DEBUG`]&&E.info(S.magenta(`[${f.nameUpper}_DEBUG] ExportOptions.plist:
782
+ ${q}`)),s&&await s("export"),E.info(S.blue(`Exporting with Bundle ID: "${T}"`)),E.info(S.blue(`Exporting with Method: "${M}"`)),r){r(S.magenta(`
782
783
  [DIAGNOSTIC] Checking available signing identities...
783
- `));try{let j=F("security find-identity -v -p codesigning",{encoding:"utf-8"});r(S.magenta(`${j}
784
- `))}catch(j){r(S.red(`[DIAGNOSTIC] Failed to list identities: ${j.message}
785
- `))}}await De("xcodebuild",["-exportArchive","-archivePath",C,"-exportPath",x,"-exportOptionsPlist",L],l,i,r,a),s&&await s("validate");let K=Ge(x,[".ipa"]);for(let j of K)try{F(`unzip -t "${j}"`,{stdio:"pipe"}),r&&r(`[IPA VALID] ${P.basename(j)} \u2014 archive integrity OK
786
- `)}catch{let Se=`IPA validation failed for ${P.basename(j)}: archive may be corrupt`;throw r&&r(`[IPA CORRUPT] ${Se}
787
- `),new Error(Se)}return K}},Oe=e=>{try{let n=P.join(process.cwd(),f.configFileName);if(E.existsSync(n)){let t=JSON.parse(E.readFileSync(n,"utf-8"));if(e==="android"&&t.android?.package)return t.android.package;if(e==="ios"&&t.ios?.bundleIdentifier)return t.ios.bundleIdentifier}if(e==="android"){let t=["android/app/build.gradle","app/build.gradle","build.gradle"];for(let i of t)if(E.existsSync(i)){let r=E.readFileSync(i,"utf-8").match(/applicationId\s+['"]([^'"]+)['"]/);if(r)return r[1]}}else{let t=P.resolve(process.cwd(),E.existsSync("ios")?"ios":"."),i=Ge(t,["Info.plist"]).filter(a=>!a.includes("/Pods/")&&!a.includes("/build/")&&!a.includes("/DerivedData/"));i.sort((a,c)=>c.split("/").length-a.split("/").length);for(let a of i){let s=E.readFileSync(a,"utf-8").match(/<key>CFBundleIdentifier<\/key>\s*<string>([^<]+)<\/string>/);if(s&&!s[1].includes("$"))return s[1]}let o=Ge(t,[".xcodeproj"]);if(o.length>0){let a=P.join(o[0],"project.pbxproj");if(E.existsSync(a)){let s=E.readFileSync(a,"utf-8").match(/PRODUCT_BUNDLE_IDENTIFIER\s*=\s*"?([^";\s]+)"?;/);if(s)return s[1]}}let r=["app.json","app.config.json","app.config.js","app.config.ts"];for(let a of r)if(E.existsSync(a)){let s=E.readFileSync(a,"utf-8").match(/"bundleIdentifier":\s*"([^"]+)"/);if(s)return s[1]}}}catch{return null}return null},uo=()=>{try{return F("emulator -version",{stdio:"ignore"}),"emulator"}catch{let n=_e.homedir(),t=[P.join(n,"Library/Android/sdk/emulator/emulator"),P.join(n,"Android/Sdk/emulator/emulator"),"/usr/local/lib/android/sdk/emulator/emulator"];for(let i of t)if(E.existsSync(i))return i}return"emulator"},po=async(e,n)=>{let t=ht();try{if(F("adb devices").toString().split(`
788
- `).slice(1).map(a=>a.trim()).filter(a=>a.length>0&&!a.startsWith("*")).map(a=>a.split(" ")[0]).length===0){A.warn(S.yellow("No Android devices or emulators found."));let a=uo(),c=[];try{c=F(`${a} -list-avds`).toString().split(`
789
- `).filter(s=>s.trim().length>0)}catch{}if(c.length>0){let s=await Ft({message:"Select an emulator to launch:",options:c.map(u=>({value:u,label:u}))});if(yt(s))return;t.start(`Launching emulator ${s}...`),$i(a,["-avd",s],{detached:!0,stdio:"ignore"}).unref();let l=0,d=!1;for(;l<60;){try{if(F("adb shell getprop sys.boot_completed",{stdio:"pipe"}).toString().trim()==="1"){d=!0;break}}catch{}await new Promise(u=>setTimeout(u,2e3)),l++}if(!d)throw t.stop("Emulator launch timed out."),new Error("Emulator launch timed out. Please try launching it manually.");t.stop("Emulator launched.")}else throw new Error("No devices found and no emulators available to launch. (Make sure Android SDK is installed)")}t.start("Installing APK on device..."),await De("adb",["install","-r",e],process.cwd(),{},n),t.stop("Installation complete.");let r=Oe("android");if(r){A.info(S.blue(`\u{1F680} Launching ${r}...`));try{F(`adb shell dumpsys package ${r}`).toString().split(`
790
- `).find(s=>s.includes("android.intent.action.MAIN")&&s.includes("android.intent.category.LAUNCHER"))?F(`adb shell monkey -p ${r} -c android.intent.category.LAUNCHER 1`,{stdio:"ignore"}):F(`adb shell monkey -p ${r} -c android.intent.category.LAUNCHER 1`,{stdio:"ignore"})}catch{A.warn("Could not auto-launch app. You may need to open it manually.")}}}catch(i){t.stop("Installation failed."),A.error(S.red(`Failed to install APK: ${i.message}`))}},fo=async(e,n,t)=>{let i=ht();try{if(!F("xcrun simctl list devices booted").toString().includes("(Booted)")){A.warn(S.yellow("No iOS Simulator is currently booted."));let r=F("xcrun simctl list devices --json").toString(),a=JSON.parse(r).devices,c=[];Object.keys(a).forEach(u=>{a[u].forEach(p=>{p.isAvailable&&c.push({...p,runtime:u})})});let s=await Ft({message:"Select a simulator to launch:",options:c.map(u=>({value:u.udid,label:`${u.name} (${u.runtime.split(".").pop()})`}))});if(yt(s))return;i.start(`Booting ${s}...`),F(`xcrun simctl boot ${s}`),F(`open -a Simulator --args -CurrentDeviceUDID ${s}`);let l=0,d=!1;for(;l<30;){try{if(F("xcrun simctl list devices booted").toString().includes(s)){d=!0;break}}catch{}await new Promise(u=>setTimeout(u,2e3)),l++}if(!d)throw i.stop("Simulator boot timed out."),new Error("Simulator boot timed out.");i.stop("Simulator booted.")}i.start("Installing on iOS Simulator..."),await De("xcrun",["simctl","install","booted",e],process.cwd(),{},t),i.stop("Installation complete."),A.info(S.blue(`\u{1F680} Launching ${n}...`)),await De("xcrun",["simctl","launch","booted",n],process.cwd(),{},t)}catch(o){i.stop("Installation failed."),A.error(S.red(`Failed to install on Simulator: ${o.message}`))}},mo=async(e,n,t)=>{let i=ht();i.start("Scanning for connected iOS devices...");try{let o=F("xcrun devicectl list devices --json-output -").toString(),a=(JSON.parse(o).result?.devices||[]).filter(s=>s.connectionProperties?.transportType==="wired"||s.connectionProperties?.transportType==="localNetwork");if(a.length===0)throw i.stop("No connected iOS devices found."),new Error("Please connect your iPhone via USB or ensure it is on the same Wi-Fi for wireless debugging.");let c=a[0].identifier;if(a.length>1){i.stop();let s=await Ft({message:"Select a device to install on:",options:a.map(l=>({value:l.identifier,label:`${l.deviceProperties?.name||l.name||l.model?.name} (${l.model?.name||"iPhone"}) - ${l.identifier}`}))});if(yt(s))return;c=s,i.start(`Installing on ${c}...`)}else i.message(`Installing on ${a[0].model.name}...`);await De("xcrun",["devicectl","device","install","app","--device",c,e],process.cwd(),{},t),i.stop("Installation complete."),A.info(S.blue(`\u{1F680} Launching ${n}...`)),await De("xcrun",["devicectl","device","launch","app","--device",c,n],process.cwd(),{},t)}catch(o){i.stop("Installation failed."),A.error(S.red(`Failed to install on device: ${o.message}`)),A.info(S.dim('Make sure your device is unlocked and "Developer Mode" is enabled in Settings -> Privacy & Security.'))}};import St from"fs";function Ne(e){if(e){if(!St.existsSync(e))return null;try{return JSON.parse(St.readFileSync(e,"utf-8"))}catch{return null}}if(!St.existsSync(`./${f.configFileName}`))return null;try{return JSON.parse(St.readFileSync(`./${f.configFileName}`,"utf-8"))}catch{return null}}function Ue(e,n,t=new Set){if(t.has(n))throw new Error(`Circular inheritance detected in profile: ${n}`);t.add(n);let i=e.build?.[n];if(!i)return null;let o={...i};if(i.extends){let r=Ue(e,i.extends,t);r&&(o={...r,...i,env:{...r.env,...i.env},ios:{...r.ios,...i.ios},android:{...r.android,...i.android}})}if(o.envGroups&&Array.isArray(o.envGroups)){let r={};for(let a of o.envGroups){let c=e.envGroups?.[a];c?Object.assign(r,c):log.warn(`Environment group not found: ${a}`)}o.env={...r,...o.env}}return o}var je=(e,n=`${f.envPrefix}`)=>{let t={},i=(o,r)=>{if(o)for(let a in o){let c=o[a],s=`${r}${a.toUpperCase().replace(/[^A-Z0-9]/g,"_")}`;c!==null&&typeof c=="object"&&!Array.isArray(c)?i(c,`${s}_`):t[s]=String(c)}};return i(e,n),t};var At=async e=>{e.platform!=="android"&&e.platform!=="ios"&&(D.error(`Platform ${e.platform} is not supported. Use 'android' or 'ios'.`),process.exit(1));let n=Gt(),t=e.buildId||go(),i=e.projectId,o=Date.now(),r=!!i,a=async c=>{if(i)try{await _.patch(`/builds/${i}/${t}`,{status:"failed",error:c})}catch{}};if(e.local&&e.buildId){e.quiet||n.start(`Preparing isolated workspace for build: ${e.buildId}`);try{let c=await _.get(`/builds/${i}/${e.buildId}/source-url`);if(c.data.status!=="success")throw new Error("Failed to get source download URL from API");let s=await tt.get(c.data.downloadUrl,{responseType:"stream"}),l=(i||e.projectId||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),d=we.join(ho.homedir(),f.workspacesDir,l);ce.mkdirSync(d,{recursive:!0});let u=new Set(["node_modules",`.${f.nameLower}-cache-meta`]),p=new Set(["Pods"]);if(ce.existsSync(d)){let N=ce.readdirSync(d);for(let C of N){if(u.has(C))continue;if(C==="ios"){let H=we.join(d,"ios");try{let X=ce.readdirSync(H);for(let y of X)if(!p.has(y))try{ce.rmSync(we.join(H,y),{recursive:!0,force:!0})}catch{}}catch{}continue}let x=we.join(d,C);try{ce.rmSync(x,{recursive:!0,force:!0})}catch{}}}let g=we.join(d,"source.zip"),m=s.data,h=ce.createWriteStream(g);await new Promise((N,C)=>{m.pipe(h),m.on("error",x=>C(x)),h.on("finish",()=>N())}),new vi(g).extractAllTo(d,!0);try{ce.unlinkSync(g)}catch{}process.chdir(d),D.info(v.green(`\u2713 Persistent workspace ready: ${d}`)),D.info(v.dim(` \u{1F4E6} Cached dirs preserved: node_modules=${ce.existsSync(we.join(d,"node_modules"))?"\u2705":"\u274C"}, Pods=${ce.existsSync(we.join(d,"ios","Pods"))?"\u2705":"\u274C"}`)),n.stop()}catch(c){n.stop(`Failed to prepare isolated workspace: ${c.message}`),i&&await a(`Setup Error: ${c.message}`),process.exit(1)}}try{let c=e.repo;if(!c)try{c=wi("git config --get remote.origin.url").toString().trim()}catch{D.warn("Could not detect git repository URL.")}!c&&e.dryRun,c||(c="https://github.com/placeholder/repo.git"),D.info(`Build ID: ${v.cyan(t)}`);let s={},l={},d=Ne(`./${f.configFileName}`);if(d){i=d.projectId;let y=e.buildProfile||"production",w=Ue(d,y);!w&&e.buildProfile&&(D.error(`Build profile '${y}' not found in ${f.configFileName}`),process.exit(1));let I=w||{};process.env.MACH_DEBUG&&D.info(v.dim(`Build profile: ${y} | Platform: ${e.platform} | Distribution: ${I.distribution||"store"} | Environment: ${I.environment||y}`)),I.env&&(l=I.env,D.info(v.blue(`Use Build Profile: ${y}`)));let b=e.platform,O=I[b]||{},G=["developmentClient","simulator","distribution","buildCommand","apk","iosScheme","preBuild","postBuild","scheme","environment","androidPackage","iosBundleIdentifier","name","iosDeploymentTarget","iosApiKeyId","iosApiKeyIssuer","iosApiKeyPath","iosTeamId","iosConfiguration","iosExportMethod","branch","repo","instanceType","ami","bucket","region","nodeVersion"];e.name=d.name,e.appName=d.name,e.androidPackage=d.android?.package,e.iosBundleIdentifier=d.ios?.bundleIdentifier,e.iosScheme=d.ios?.iosScheme,!e.nodeVersion&&d.nodeVersion&&(e.nodeVersion=d.nodeVersion);for(let L of G){let Q=O[L]!==void 0?O[L]:I[L];Q!==void 0&&e[L]===void 0&&(e[L]=Q)}e.branch=e.branch||"main",e.iosConfiguration=e.iosConfiguration||(e.developmentClient||e.simulator?"Debug":"Release"),e.sshUser=e.sshUser||process.env.USER||"ubuntu",e.simulator===void 0&&(e.simulator=!1),e.local===void 0&&(e.local=!1),e.verbose===void 0&&(e.verbose=!1);let M=L=>{if(!L)return L;if(L.startsWith("scripts.")){let Q=L.split(".")[1],K=d.scripts?.[Q];if(K)return K;D.warn(`Script reference not found: ${L}`)}return L};e.buildCommand=M(e.buildCommand),e.preBuild=M(e.preBuild),e.postBuild=M(e.postBuild),!e.scheme&&d.scheme&&(e.scheme=d.scheme);let T={...je(d,f.envPrefix),...je(I,`${f.envPrefix}PROFILE_`)};s={...s,...l,...T},process.env.IOS_P12_PASSWORD&&!s.IOS_P12_PASSWORD&&(s.IOS_P12_PASSWORD=process.env.IOS_P12_PASSWORD),process.env.MATCH_PASSWORD&&!s.MATCH_PASSWORD&&(s.MATCH_PASSWORD=process.env.MATCH_PASSWORD),e.platform==="ios"&&(!e.iosTeamId&&I.ios?.appleTeamId&&(e.iosTeamId=I.ios.appleTeamId),!e.iosTeamId&&d.submit?.[y]?.ios?.appleTeamId&&(e.iosTeamId=d.submit[y].ios.appleTeamId),!e.iosTeamId&&d.submit?.production?.ios?.appleTeamId&&(D.warn(v.yellow(`Check: Using 'production' Team ID for '${y}' build.`)),e.iosTeamId=d.submit.production.ios.appleTeamId),e.iosTeamId?D.info(v.magenta(`\u2713 Injected iOS Team ID from config: ${e.iosTeamId}`)):D.warn(v.yellow("\u26A0\uFE0F No iOS Team ID found. Signing might fail if not managed automatically via Expo.")))}let u="unknown";try{u=wi("git rev-parse --abbrev-ref HEAD").toString().trim()}catch{D.warn("Failed to detect git branch.")}let p="1.0.0";try{ce.existsSync("./package.json")&&(p=JSON.parse(ce.readFileSync("./package.json","utf-8")).version||"1.0.0")}catch{}let g=e.buildProfile||"production",m="Internal";e.developmentClient?m="DevelopmentClient":g.toLowerCase().includes("store")||g.toLowerCase()==="production"?m="Store":g.toLowerCase().includes("preview")||g.toLowerCase().includes("staging")?m="Staging":(g.toLowerCase().includes("development")||g.toLowerCase().includes("dev"))&&(m="Development");let h=e.platform==="ios"?"iOS":"Android",$=e.platform==="ios"&&e.simulator?" (Simulator)":"",N=`${h}${$} v${p} (${m})`;if(i){try{let y=e.buildProfile||"production";D.info(v.blue(`Fetching managed secrets for profile: ${y}...`));let w=e.environment||y,b=(await _.get(`/projects/${i}/secrets/export?env=${w}`)).data;b.status==="success"&&b.secrets&&(s={...s,...b.secrets},Object.keys(b.secrets).length>0&&D.info(v.magenta(`\u2713 Injected ${Object.keys(b.secrets).length} secrets from Dashboard.`)))}catch(y){D.warn(`Failed to load managed secrets from Dashboard: ${y.message}`)}try{D.info(v.blue("Fetching managed credentials..."));let y="development";e.distribution==="store"?y="store":e.distribution==="internal"&&(y=e.platform==="ios"?"adhoc":"internal"),m==="Staging"&&e.developmentClient&&(y="development");let w=await _.get("/credentials/resolve",{params:{projectId:i,platform:e.platform,bundleId:e.iosBundleIdentifier||e.androidPackage,distributionType:y}});if(w.data.status==="success"&&w.data.credentials){let I=w.data.credentials;D.info(v.magenta(`\u2713 Found ${I.length} relevant credentials.`));let b=I.filter(T=>{if(T.distributionType){let L=y==="internal"?"adhoc":y;return T.distributionType===L||T.distributionType===y}return!0});D.info(v.dim(` Filtered to ${b.length} credentials for distributionType: ${y}`));let O=!1,G=!1,M=!1;for(let T of b)if(T.downloadUrl)try{let L="",Q=5;for(;Q>0;)try{let K=await tt.get(T.downloadUrl,{responseType:"arraybuffer",timeout:3e4,headers:{Connection:"close"}});L=Buffer.from(K.data).toString("base64");break}catch(K){if(Q--,Q===0)throw K;D.warn(v.dim(` - Temporary network error downloading ${T.name}. Retrying... (${5-Q}/5)`)),await new Promise(j=>setTimeout(j,2e3))}if(T.type==="ios_cert"&&!O)s.IOS_DIST_P12=L,T.password?(s.IOS_P12_PASSWORD=T.password,D.info(v.dim(` - Injected ${T.name} as IOS_DIST_P12 with password from credential record`))):D.info(v.dim(` - Injected ${T.name} as IOS_DIST_P12`)),O=!0;else if(T.type==="ios_profile"&&!G)s.IOS_PROVISIONING_PROFILE=L,D.info(v.dim(` - Injected ${T.name} as IOS_PROVISIONING_PROFILE`)),G=!0;else if(T.type==="android_keystore"&&!M){s.ANDROID_KEYSTORE_BASE64=L;let K=T.password,j=T.alias||T.meta?.alias;if(K)s.ANDROID_KEY_PASSWORD=K,s.ANDROID_STORE_PASSWORD=K,D.info(v.dim(" - Injected keystore password from credential record"));else{let Ae=["ANDROID_KEY_PASSWORD",...[y==="store"?"PRODUCTION":y==="internal"?"STAGING":"DEVELOPMENT",y.toUpperCase(),"PRODUCTION","STORE","INTERNAL","STAGING","RELEASE","DEBUG"].map(k=>`KEYSTORE_PASSWORD_${k}`),"KEYSTORE_PASSWORD"].find(k=>!!s[k]);Ae&&s[Ae]&&(s.ANDROID_KEY_PASSWORD=s[Ae],s.ANDROID_STORE_PASSWORD=s[Ae])}if(j)s.ANDROID_KEY_ALIAS=j;else{let B=["ANDROID_KEY_ALIAS","KEYSTORE_ALIAS"].find(Se=>!!s[Se]);B&&(s.ANDROID_KEY_ALIAS=s[B])}D.info(v.dim(` - Injected ${T.name} as ANDROID_KEYSTORE_BASE64`)),M=!0}}catch(L){D.warn(`Failed to download credential ${T.name}: ${L.message}`)}}if(e.platform==="android"){let I=d.android?.versionCode==="auto"||d.expo?.android?.versionCode==="auto";if(e.autoVersion||I){n.start("Resolving latest versionCode from Google Play...");try{let b=(w.data.credentials||[]).find(K=>K.type==="google_service_account");if(b||(b=((await _.get(`/credentials/${i}`)).data.credentials||[]).find(j=>j.type==="google_service_account")),!b)throw new Error("Google Service Account not found. Upload it via Dashboard to use auto-versioning.");let O=await _.get(`/credentials/${b.credentialId}/download`,{params:{projectId:i}});if(O.data.status!=="success"||!O.data.downloadUrl)throw new Error("Failed to get secure download URL for service account");let M=(await tt.get(O.data.downloadUrl,{headers:{Connection:"close"}})).data,T=e.androidPackage||d.android?.package||d.expo?.android?.package||d.name,L=await Ii(T,M);if(L==null)throw new Error("Could not retrieve any version information from Google Play.");let Q=L+1;s.ANDROID_VERSION_CODE=Q.toString(),n.stop(`\u2713 Resolved versionCode: ${v.green(Q)} (Latest on Play Store: ${L})`)}catch(b){n.stop("Version resolution failed");let O=b.response?.data?.error?.message||b.message;D.warn(v.yellow(` \u26A0\uFE0F Auto-versioning failed: ${O}`)),D.warn(v.dim(' Falling back to version code from config. To fix: ensure Service Account has "View App Metadata" and "View App Information" permissions in Google Play Console.'))}}}if(e.platform==="ios"&&!e.simulator){let I=!!s.IOS_DIST_P12,b=!!s.IOS_PROVISIONING_PROFILE;if(!I||!b){let O=[...I?[]:["Distribution Certificate"],...b?[]:["Provisioning Profile"]].join(" and ");D.error(v.red(`Missing iOS credentials: ${O}`)),e.quiet&&process.exit(1);let G=e.yes||await _i({message:"Would you like to generate these credentials now?",initialValue:!0});if(G&&!Di(G))return await Je({platform:"ios",profile:g}),e.quiet||D.info(v.green("\u2713 Credentials setup complete! Restarting build phase...")),At(e);e.quiet||D.info(v.yellow(`Run \`${f.nameLower} credentials\` to set up signing credentials manually.`)),process.exit(1)}}if(e.platform==="android"&&(e.distribution==="internal"||e.distribution==="store")&&!(!!s.ANDROID_KEYSTORE_BASE64||!!s.ANDROID_KEYSTORE)){D.error(v.red("Missing Android credentials: Signing Keystore")),e.quiet&&process.exit(1);let b=e.yes||await _i({message:"Would you like to automatically create and upload an Android Keystore for this profile now?",initialValue:!0});if(b&&!Di(b))return await Je({platform:"android",profile:g}),e.quiet||D.info(v.green("\u2713 Android Keystore setup complete! Restarting build phase...")),At(e);e.quiet||D.info(v.yellow(`Run \`${f.nameLower} credentials --platform android\` to set up a signing keystore manually.`)),process.exit(1)}}catch(y){D.warn(`Failed to resolve credentials: ${y.message}`)}}let C=!!(e.local&&e.buildId),x=!!(e.local||e.sshHost),H=!x&&!C;if(C){D.info(v.magenta("\u{1F3D7}\uFE0F Runner Mode: Executing isolated build task..."));let y=await Ht({...e,interactive:!1},t,s,i,{branch:u,version:p,summary:N,buildType:m});await X(y),process.exit(0)}async function X(y){if(i&&y.length>0){let w=Gt(),I=[];e.quiet||w.start("Uploading artifacts to Dashboard...");try{for(let b of y){let O=we.basename(b),G=ce.readFileSync(b),M=we.extname(O).toLowerCase(),T="application/octet-stream",L=await _.post(`/builds/${i}/${t}/artifact-upload-url`,{fileName:O,fileType:T});if(L.data.status!=="success")throw new Error(`Failed to get upload URL for ${O}`);let Q=!1;for(let K=1;K<=3;K++)try{await tt.put(L.data.uploadUrl,G,{headers:{"Content-Type":T},maxBodyLength:1/0,maxContentLength:1/0,timeout:12e4}),Q=!0;break}catch(j){if(D.warn(v.yellow(`Artifact upload attempt ${K}/3 failed (${j.code||j.message})`)),K<3)await new Promise(B=>setTimeout(B,3e3*K));else throw j}Q&&I.push({name:O,url:L.data.downloadUrl,size:G.length,type:M.substring(1)})}e.quiet||w.stop("Artifacts uploaded.")}catch(b){e.quiet||w.stop("Failed to upload artifacts."),D.error(v.red(`Upload error: ${b.message}`));try{await _.patch(`/builds/${i}/${t}`,{status:"completed",artifacts:y.map(O=>we.basename(O)),endTime:Date.now()})}catch(O){D.warn(v.yellow(`Could not set fallback build status: ${O.message}`))}return}if(i&&I.length>0)try{D.info(v.cyan(`
791
- \u{1F517} Download Links:`));for(let b of I)D.info(v.dim(` - ${b.name}: `)+v.blue.underline(b.url));await _.patch(`/builds/${i}/${t}`,{status:"success",artifacts:I,endTime:Date.now()}),D.success(v.green(`
792
- \u2713 Build completed and reported to dashboard.`))}catch(b){D.warn(v.yellow(`
793
- \u26A0\uFE0F Could not report to dashboard: ${b.message}`))}}else if(i)try{await _.patch(`/builds/${i}/${t}`,{status:"completed",endTime:Date.now()})}catch{}}if(x){if(D.info(v.cyan(`\u{1F680} Direct Build Mode: Executing on ${e.sshHost||"local"}...`)),i&&!r){let y=process.argv.slice(3).join(" ");await _.post("/builds",{projectId:i,buildId:t,platform:e.platform,status:"building",branch:u,version:p,summary:N,startTime:o,buildType:m,buildProfile:g,buildArgs:y,simulator:!!e.simulator})}if(e.sshHost&&e.platform==="ios"){let y=await Ei(e,t,s,i)}else{let y=await Ht({...e,interactive:!!e.local},t,s,i,{branch:u,version:p,summary:N,buildType:m});await X(y)}return}if(H&&(D.info(v.blue("\u{1F6F0}\uFE0F Cloud Initiator Mode: Preparing orchestration...")),!e.dryRun)){e.quiet||n.start("Zipping and uploading local source...");let y=await _.post("/builds/source-upload-url",{projectId:i,buildId:t});if(y.data.status!=="success")throw n.stop("Failed to get upload URL."),new Error("Failed to get source upload URL from API");let w=new vi,I=ce.readdirSync("."),b=["node_modules",".git","dist","build","builds",".gradle",".idea","android/build","ios/build","ios/Pods",`.${f.nameLower}_cli`];for(let M of I){if(b.includes(M))continue;ce.statSync(M).isDirectory()?w.addLocalFolder(M,M):w.addLocalFile(M)}let O=w.toBuffer();e.quiet||n.message(`Uploading source (${(O.length/1024/1024).toFixed(1)} MB)...`);let G=!1;for(let M=1;M<=3;M++)try{await tt.put(y.data.uploadUrl,O,{headers:{"Content-Type":"application/zip"},maxBodyLength:1/0,maxContentLength:1/0,timeout:12e4}),G=!0;break}catch(T){if(M<3)n.message(`Upload attempt ${M} failed (${T.code||T.message}), retrying...`),await new Promise(L=>setTimeout(L,2e3*M));else throw T}if(e.quiet||n.stop("Source uploaded"),i){let M=process.argv.slice(3).join(" ");await _.post("/builds",{projectId:i,buildId:t,platform:e.platform,status:"pending",branch:u,version:p,summary:N,startTime:o,buildType:m,buildProfile:g,buildArgs:M,simulator:!!e.simulator}),D.info(v.green("\u2713 Cloud build registered."))}e.platform==="android"&&await Si(e,t,s,i),e.quiet||D.info(v.cyan("\u{1F4E1} Connecting to build stream...")),await yo(i,t,e);return}}catch(c){let s=c.message||"Build failed";c.response?.data?.message?s=c.response.data.message:c.message.includes("status code 402")?s="Insufficient wallet balance. Please add credits in the Dashboard.":c.message.includes("status code 403")&&(s="Monthly build quota exceeded. Upgrade your plan in the Dashboard."),i&&!e.local&&await a(s),D.error(v.red(`\u2717 Build failed: ${s}`)),process.exit(1)}};async function yo(e,n,t){let i=Gt(),o="pending",r=0,a=0;for(t.quiet||i.start("Connecting to build stream...");;){try{let s=(await _.get(`/builds/${e}/${n}`)).data.build;if(s){if(o=s.status,o==="building")t.quiet||i.message("Building on M4 Mac Mini...");else if(o==="failed")t.quiet||i.stop("Build failed."),D.error(v.red(`
794
- \u2717 Build failed: ${s.error||"Unknown error"}`)),process.exit(1);else if(o==="completed"||o==="success"){t.quiet||i.stop("Build successful!"),D.success(v.green(`
795
- \u2713 Build completed successfully!`));try{t.quiet||(D.info(v.magenta(`
796
- \u{1F4F1} Installation Hub:`)),D.info(v.dim(" - View & Install Build: ")+v.white.underline(`${ai}/build/${n}`)))}catch{}return}else if(o!=="pending"){t.quiet||i.stop(`Build status: ${o}`);return}}try{let d=(await _.get(`/builds/${e}/${n}/logs`)).data;if(d&&typeof d=="string"&&!t.quiet){let u=d.split(`
797
- `);if(u.length>r){for(let p=r;p<u.length;p++)u[p].trim()&&console.log(v.dim(` ${u[p]}`));r=u.length}}}catch{}a=0}catch{a++,a>10&&(i.stop("Connection lost."),D.error(v.red(`
798
- \u2717 Lost connection to Dashboard API.`)),process.exit(1))}await new Promise(c=>setTimeout(c,3e3))}}import So from"http";import{execSync as Et}from"child_process";import jt from"chalk";import{log as Be}from"@clack/prompts";var It=7070;function Ao(){let e=[];try{let n=Et("adb devices -l",{stdio:"pipe"}).toString(),t=new Set;n.split(`
799
- `).forEach(i=>{if(i.includes("List of devices")||!i.trim())return;let o=i.split(/\s+/);if(o.length<2||o[1]!=="device")return;let r=o[0];t.add(r);let a=i.match(/model:([^\s]+)/);e.push({id:r,platform:"android",type:r.startsWith("emulator-")?"emulator":"physical",name:a?a[1].replace(/_/g," "):r,status:"online",details:i.trim()})})}catch{}try{let n=`${process.env.ANDROID_HOME||`${process.env.HOME}/Library/Android/sdk`}/emulator/emulator`,i=Et(`${n} -list-avds`,{stdio:"pipe"}).toString().split(`
800
- `).filter(r=>!!r.trim()),o=e.some(r=>r.platform==="android"&&r.id.startsWith("emulator-"));i.forEach(r=>{o||e.push({id:r,platform:"android",type:"emulator",name:r.replace(/_/g," "),status:"offline",details:`Android Virtual Device: ${r}`})})}catch{}if(process.platform!=="darwin")return e;try{let n=Et("/usr/bin/xcrun simctl list devices --json",{stdio:"pipe"}).toString(),t=JSON.parse(n);Object.entries(t.devices).forEach(([i,o])=>{o.forEach(r=>{r.isAvailable&&e.push({id:r.udid,platform:"ios",type:"simulator",name:r.name,status:r.state?.toLowerCase()==="booted"?"online":"offline",runtime:i,details:`${r.name} (${i})`})})})}catch{}try{let n=Et("/usr/bin/xcrun devicectl list devices --json-output -",{stdio:"pipe"}).toString();(JSON.parse(n).result?.devices||[]).forEach(i=>{let o=i.connectionProperties?.transportType;(o==="wired"||o==="localNetwork")&&e.push({id:i.identifier,platform:"ios",type:"physical",name:i.deviceProperties?.name||"iPhone",status:"online",details:`${i.deviceProperties?.name||"iPhone"} (${i.model?.name||i.hardwareModel||""}) - ${o}`})})}catch{}return e}async function Ri(){process.platform!=="darwin"&&Be.warn("Running on non-macOS \u2014 iOS discovery unavailable, Android only.");let e=So.createServer((n,t)=>{if(t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Access-Control-Allow-Methods","GET, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),n.method==="OPTIONS"){t.writeHead(204),t.end();return}let i=new URL(n.url||"/",`http://localhost:${It}`);if(n.method==="GET"&&i.pathname==="/local/devices"){try{let o=Ao();t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({status:"success",targets:o}))}catch(o){t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({status:"error",message:o.message}))}return}t.writeHead(404),t.end()});e.listen(It,"127.0.0.1",()=>{Be.success(jt.green(`Local device agent running on http://localhost:${It}`)),Be.info(jt.dim("Keep this running while using the Install Hub on the dashboard.")),Be.info(jt.dim("Press Ctrl+C to stop."))}),e.on("error",n=>{n.code==="EADDRINUSE"?Be.error(`Port ${It} is already in use \u2014 agent may already be running.`):Be.error(`Agent error: ${n.message}`),process.exit(1)}),await new Promise(()=>{})}import{createRequire as Zr}from"module";import{text as Io,password as bo,spinner as $o,isCancel as Ti}from"@clack/prompts";import zt from"chalk";import it from"fs";import Oi from"path";import Eo from"os";var Bt=Oi.join(Eo.homedir(),f.configDir),Kt=Oi.join(Bt,"config.json");function Vt(){if(!it.existsSync(Kt))return{};try{return JSON.parse(it.readFileSync(Kt,"utf-8"))}catch{return{}}}function Ci(e){it.existsSync(Bt)||it.mkdirSync(Bt,{recursive:!0});let t={...Vt(),...e};it.writeFileSync(Kt,JSON.stringify(t,null,2))}async function Ni(){let e=Vt(),n=await Io({message:"Enter your email:",placeholder:"user@example.com",initialValue:e.lastLoginEmail,validate(o){if(o.length===0)return"Email is required!"}});if(Ti(n))return;let t=await bo({message:"Enter your password:",validate(o){if(o.length===0)return"Password is required!"}});if(Ti(t))return;let i=$o();i.start("Authenticating...");try{let r=await(await fetch(`${gt}/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:n,password:t})})).json();r.status==="success"&&r.user.token?(ri({id:r.user.id,email:n,token:r.user.token,refreshToken:r.user.refreshToken}),Ci({lastLoginEmail:n}),i.stop(zt.green("Login successful!"))):i.stop(zt.red("Login failed: "+(r.message||"Unknown error")))}catch(o){i.stop(zt.red("Network error: "+o.message))}}import{outro as Po,select as _o,spinner as Do,isCancel as wo}from"@clack/prompts";import bt from"chalk";import Wt from"fs";import vo from"path";async function ki(){if(!ue()){console.log(bt.red(`You are not logged in. Run \`${f.nameLower} login\` first.`));return}let n=Do();n.start("Fetching projects...");try{let{data:t}=await _.get("/projects");if(n.stop("Projects loaded."),t.status!=="success"||!t.projects||t.projects.length===0){console.log(bt.yellow(`No projects found. Run \`${f.nameLower} init\` to create one.`));return}let i=t.projects.map(u=>({value:u.projectId,label:`${u.name} (${u.slug})`})),o=await _o({message:"Select a project to link:",options:i});if(wo(o))return;let r=vo.join(process.cwd(),f.configFileName),a={};if(Wt.existsSync(r))try{a=JSON.parse(Wt.readFileSync(r,"utf-8"))}catch{}let c=t.projects.find(u=>u.projectId===o),s=a.android?.package||Oe("android"),l=a.ios?.bundleIdentifier||Oe("ios"),d={projectId:o,name:c?.name,slug:c?.slug,scheme:c?.slug?.toLowerCase()||"app",android:{package:s||""},ios:{bundleIdentifier:l||""},build:{development:{environment:"development",distribution:"internal"},staging:{environment:"staging",distribution:"internal"},production:{environment:"production",distribution:"store"}},submit:{production:{android:a.submit?.production?.android||{track:"internal"},ios:{ascAppId:a.submit?.production?.ios?.ascAppId||"1234567890",appleTeamId:a.submit?.production?.ios?.appleTeamId||"ABC123DEFG"}}}};Wt.writeFileSync(r,JSON.stringify(d,null,2)),Po(bt.green(`Linked to project ${d.name} (${d.slug})`))}catch(t){n.stop(bt.red("Error fetching projects: "+t.message))}}import{outro as Ro,text as $t,select as Oo,spinner as Co,isCancel as nt}from"@clack/prompts";import ot from"chalk";import To from"fs";import No from"path";import{randomUUID as ko}from"crypto";async function xi(){if(!ue()){console.log(ot.red(`You are not logged in. Run \`${f.nameLower} login\` first.`));return}let n=await $t({message:"Project Name:",placeholder:"My Awesome App",validate(c){if(c.length===0)return"Name is required!"}});if(nt(n))return;let t=await $t({message:"Project Slug (URL friendly):",placeholder:"my-awesome-app",validate(c){if(c.length===0)return"Slug is required!";if(!/^[a-z0-9-]+$/.test(c))return"Slug must be lowercase alphanumeric with dashes."}});if(nt(t))return;let i=await Oo({message:"Platform:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"},{value:"web",label:"Web"},{value:"all",label:"All Platforms"}]});if(nt(i))return;let o="";if(i==="android"||i==="all"){let c=Oe("android");if(o=await $t({message:"Android Package Name:",initialValue:c||"",placeholder:"com.example.app",validate(s){if(s.length===0)return"Package name is required for Android!"}}),nt(o))return}let r="";if(i==="ios"||i==="all"){let c=Oe("ios");if(r=await $t({message:"iOS Bundle Identifier:",initialValue:c||"",placeholder:"com.example.app",validate(s){if(s.length===0)return"Bundle ID is required for iOS!"}}),nt(r))return}let a=Co();a.start("Creating project...");try{let c=ko(),l={projectId:c,name:n,slug:t,storageType:"managed",platforms:i==="all"?["android","ios","web"]:[i]},{data:d}=await _.post("/projects",l);if(d.status==="success"){a.stop(ot.green("Project created successfully!"));let u=No.join(process.cwd(),f.configFileName);To.writeFileSync(u,JSON.stringify({projectId:c,name:n,slug:t,...o?{android:{package:o}}:{},...r?{ios:{bundleIdentifier:r}}:{},build:{development:{environment:"development",distribution:"internal"},staging:{environment:"staging",distribution:"internal"},production:{environment:"production",distribution:"store"}},submit:{production:{android:{track:"internal"},ios:{ascAppId:"1234567890",appleTeamId:"ABC123DEFG",...r?{bundleId:r}:{}}}}},null,2)),Ro(ot.green(`Initialized project ${n} and linked locally!`))}else a.stop(ot.red("creation failed: "+d.message))}catch(c){a.stop(ot.red("Network error: "+c.message))}}import{spinner as Ui,log as me}from"@clack/prompts";import Pt from"chalk";import Li from"fs";import xo from"path";async function Mi(e,n){let t=ue();if(!t){me.error(`You are not logged in. Run \`${f.nameLower} login\` first.`);return}let i=xo.join(process.cwd(),f.configFileName);if(!Li.existsSync(i)){me.error(`No ${f.configFileName} found. Run \`${f.nameLower} init\` or \`${f.nameLower} link\` first.`);return}let o;try{o=JSON.parse(Li.readFileSync(i,"utf-8"))}catch{me.error(`Failed to parse ${f.configFileName}`);return}let{projectId:r}=o;if(!r){me.error(`${f.configFileName} is missing projectId.`);return}e==="set"?await Lo(r,n,t):e==="list"?await Uo(r,t):me.error(`Unknown env action: ${e}. Use 'set' or 'list'.`)}async function Lo(e,n,t){if(n.length===0){me.error(`Usage: ${f.nameLower} env set KEY=VALUE [KEY2=VALUE2 ...]`);return}let i=Ui();i.start("Setting environment variables...");let o=0,r=0;for(let a of n){let[c,...s]=a.split("="),l=s.join("=");if(!c||l===void 0){me.warn(`Invalid format for argument: ${a}. Expected KEY=VALUE.`),r++;continue}try{let d={key:c.trim(),value:l,type:"env",environment:"global",visibility:"secret"},{data:u}=await _.post(`/projects/${e}/secrets`,d);u.status==="success"?o++:(me.error(`Failed to set ${c}: ${u.message}`),r++)}catch(d){me.error(`Network error setting ${c}: ${d.message}`),r++}}i.stop(`Set ${o} variable(s). ${r>0?`${r} failed.`:""}`)}async function Uo(e,n){let t=Ui();t.start("Fetching environment variables...");try{let{data:i}=await _.get(`/projects/${e}/secrets`);if(i.status==="success"){t.stop("Fetched variables.");let o=i.secrets||[];o.length===0?me.info("No environment variables found for this project."):(me.info(Pt.bold("Environment Variables (Global & Scoped):")),o.forEach(r=>{let a=r.visibility==="plain"?r.value:"********";console.log(` ${Pt.cyan(r.key)} = ${a} ${Pt.gray(`[${r.environment}]`)}`)}))}else t.stop(Pt.red(`Failed to fetch variables: ${i.message}`))}catch(i){t.stop("Failed to fetch variables."),me.error(`Network error: ${i.message}`)}}import{spinner as st,text as rt,select as qt,isCancel as ke,cancel as Jt}from"@clack/prompts";import ne from"chalk";import le from"fs";import Ke from"path";import{spawn as Mo,spawnSync as Fo}from"child_process";import Hi from"axios";import Xt from"os";import Ho from"crypto";async function Gi(e){let n=st(),t=ue(),i=`./${f.configFileName}`;if(!le.existsSync(i)){ge(`No ${f.configFileName} found. Run \`${f.nameLower} init\` or \`${f.nameLower} link\` first.`);return}let o=JSON.parse(le.readFileSync(i,"utf-8")),{projectId:r}=o;if(!r){ge(`${f.configFileName} is missing projectId.`);return}ve(ne.dim(`Submit for project: ${o.name||r} `));let a=e.platform;if(!a){let h=await qt({message:"Select platform to submit:",options:[{value:"ios",label:"iOS (App Store Connect / TestFlight)"},{value:"android",label:"Android (Google Play Console)"}]});if(ke(h)){Jt("Operation cancelled");return}a=h}let c=await Go(r,a,e,t?.token);if(!c)return;ve(`Using artifact: ${ne.green(Ke.basename(c))} `),n.start("Fetching submission credentials from Dashboard...");let s;try{let N=((await _.get(`/credentials/${r}`)).data.credentials||[]).filter(C=>a==="ios"?C.type==="asc_api_key":C.type==="google_service_account");if(N.length===0){n.stop("Credentials missing"),ge(`No Service Credentials found for ${a}.`),ve(`Use '${f.nameLower} credentials:service --platform ${a}' or use the Dashboard to upload them.`);return}if(N.length===1)s=N[0],n.stop(`Using: ${s.name}`);else{n.stop("Multiple credentials found");let C=await qt({message:`Choose a ${a==="ios"?"App Store Connect":"Google Play"} credential:`,options:N.map(x=>({value:x.credentialId,label:x.name,hint:`${x.keyId?`ID: ${x.keyId}`:""} ${x.issuerId?`(Issuer: ${x.issuerId.substring(0,8)}...)`:""}`}))});if(ke(C)){Jt("Submission cancelled");return}s=N.find(x=>x.credentialId===C),ve(`Using selected: ${ne.green(s.name)}`)}}catch(h){n.stop("Failed to fetch credentials"),ge(`API Error: ${h.message} `);return}let l=le.mkdtempSync(Ke.join(Xt.tmpdir(),`${f.nameLower}-submit-`)),d=s.keyId||s.meta?.keyId,u=s.issuerId||s.meta?.issuerId,p=s.type==="asc_api_key"?`AuthKey_${d}.p8`:"service-account.json",g=Ke.join(l,p);n.start("Downloading secure key...");try{let h=await _.get(`/credentials/${s.credentialId}/download`,{params:{projectId:r}});if(h.data.status!=="success"||!h.data.downloadUrl)throw new Error("Failed to get secure download URL");let $=await Hi.get(h.data.downloadUrl,{responseType:"arraybuffer"});le.writeFileSync(g,Buffer.from($.data)),n.stop("Key downloaded to secure temp storage")}catch(h){n.stop("Download failed"),ge(`Failed to download key: ${h.message}`);try{le.rmSync(l,{recursive:!0,force:!0})}catch{}return}ve(ne.blue(`Initiating ${a==="ios"?"TestFlight":"Google Play"} submission...`));let m=a==="android"?e.track||o.submit?.production?.android?.track||"internal":void 0;try{if(a==="ios"){if(!d){let N=await rt({message:"Enter App Store Connect Key ID (e.g. 2X948D...):",validate:C=>C.length>0?void 0:"Key ID is required"});if(ke(N))return;d=N}if(!u||u==="undefined"){let N=await rt({message:"Enter App Store Connect Issuer ID (Found on ASC Keys page):",validate:C=>C.length>0?void 0:"Issuer ID is required"});if(ke(N))return;u=N}ve(`Using ASC Key ID: ${d}`),ve(`Using ASC Issuer ID: ${u}`);let h=o.ios?.bundleIdentifier,$=await jo(c,g,u,d,h);if($&&$.apiKeyJsonPath)throw ve(ne.cyan(`
801
- [DIAGNOSTIC] API key written to: ${$.apiKeyJsonPath}
802
- `)),new Error("fastlane pilot execution failed");Fi(`${a==="ios"?"App Store":"Google Play"} submission successful!`)}else{let h=o.android?.package||s.bundleId;await Bo(c,g,m,h),Fi("Google Play submission successful!")}}catch(h){ge(`Submission failed: ${h.message}`)}finally{Ko(l),c.includes(`${f.nameLower}-artifact-`)}}async function Go(e,n,t,i){let o=t.buildId?"id":t.latest?"latest":null;if(!o&&(o=await qt({message:"Select artifact source:",options:[{value:"latest",label:`Latest Production Build (${f.name})`},{value:"id",label:`Input Build ID (${f.name})`},{value:"url",label:"Remote URL"},{value:"local",label:"Local File Path"}]}),ke(o)))return Jt("Operation cancelled"),null;if(o==="local"){let a=await rt({message:"Enter path to artifact (.ipa/.aab):",validate:c=>{if(!le.existsSync(c))return"File not found";if(n==="ios"&&!c.endsWith(".ipa"))return"Must be an .ipa file";if(n==="android"&&!c.endsWith(".aab"))return"Must be an .aab file"}});return ke(a)?null:a}let r=st();if(o==="latest"){r.start("Fetching latest build...");try{let a=await _.get(`/builds/${e}`,{params:{limit:50}});if(a.data.status!=="success")throw new Error(a.data.message);let c=a.data.builds||[],s=c.find(m=>m.platform?.toLowerCase()===n.toLowerCase()&&m.status?.toLowerCase()==="success"&&m.buildType?.toLowerCase()==="store")||c.find(m=>m.platform?.toLowerCase()===n.toLowerCase()&&m.status?.toLowerCase()==="success");if(!s)return r.stop("No suitable build found"),ge("No successful builds found for this platform."),null;r.stop(`Found build: ${s.buildId}`);let l=s.artifacts||[];if(l.length===0||l.every(m=>!(m.url||m.downloadUrl)))try{let m=await _.get(`/builds/${e}/${s.buildId}/artifacts`);m.data.status==="success"&&m.data.artifacts?.length>0?(l=m.data.artifacts.map(h=>({...h,url:h.url||h.downloadUrl})),console.log(ne.cyan(` [RECOVERY] Fetched ${l.length} artifact(s) with download URLs.`))):console.log(ne.yellow(" [RECOVERY] /artifacts endpoint returned 0 artifacts."))}catch(m){console.log(ne.red(` [RECOVERY] /artifacts fetch failed: ${m.message}`))}let u=n==="ios",p=l.find(m=>{let h=(m.type||"").toLowerCase(),$=(m.name||"").toLowerCase();if(console.log(ne.dim(` - Checking: ${m.name} (Type: ${m.type}, HasLink: ${!!(m.url||m.downloadUrl)})`)),h)return h===(u?"ipa":"aab");let N=u?".ipa":".aab",C=(m.url||m.downloadUrl||"").toLowerCase();return $.endsWith(N)||C.includes(N)});if(!p||!(p.url||p.downloadUrl))return ge("Build found but artifact URL is missing."),null;let g=p.url||p.downloadUrl;return await Yt(g,u?"ios":"android")}catch(a){return r.stop("Fetch failed"),ge(`API Error: ${a.message}`),null}}if(o==="id"){let a=t.buildId||await rt({message:"Enter Build ID:",validate:c=>c.length<5?"Invalid ID":void 0});if(ke(a))return null;r.start("Fetching build...");try{let c=await _.get(`/build/${a}`);if(c.data.status!=="success")throw new Error(c.data.message);let s=c.data.build;if(!s)throw new Error("Build not found");let l=n==="ios",d=s.artifacts?.find(u=>{if(u.type)return u.type===(l?"ipa":"aab");let p=l?".ipa":".aab";return u.name&&u.name.endsWith(p)||u.url&&u.url.includes(p)});return!d||!d.url?(r.stop("Missing artifact"),ge("Artifact URL not found on build record."),null):(r.stop(`Found build: ${s.buildId}`),await Yt(d.url,l?"ios":"android"))}catch(c){return r.stop("Fetch failed"),ge(c.message),null}}if(o==="url"){let a=await rt({message:"Enter Artifact URL:",validate:c=>c.startsWith("http")?void 0:"Must be a valid URL"});return ke(a)?null:await Yt(a,n)}return null}async function Yt(e,n,t=3){let i=st();i.start("Downloading artifact...");let o=le.mkdtempSync(Ke.join(Xt.tmpdir(),`${f.nameLower}-artifact-`)),r=`app.${n==="ios"?"ipa":"aab"}`,a=Ke.join(o,r);for(let c=1;c<=t;c++)try{c>1&&(i.message(`Downloading artifact (Retry ${c}/${t})...`),await new Promise(d=>setTimeout(d,2e3*c)));let s=le.createWriteStream(a),l=await Hi({url:e,method:"GET",responseType:"stream",timeout:6e4});return await new Promise((d,u)=>{l.data.pipe(s);let p=!1;l.data.on("error",g=>{p||(p=!0,s.close(),u(g))}),s.on("finish",()=>{p||d()}),s.on("error",g=>{p||(p=!0,u(g))})}),i.stop("Download complete"),a}catch(s){if(c===t)throw i.stop("Download failed"),s}throw new Error("Download failed after retries")}async function jo(e,n,t,i,o){let r=st();if(o&&ve(`Bundled ID: ${ne.green(o)}`),!t||!i)throw ge(`Missing credentials: issuerId=${t}, keyId=${i}. Check your Dashboard.`),new Error("Missing ASC API Key Metadata (IssuerID or KeyID)");let a=le.readFileSync(n,"utf8"),c;try{c=Ho.createPrivateKey(a).export({type:"pkcs8",format:"pem"})}catch{ve("Key normalization failed, falling back to manual re-wrapping..."),c=`-----BEGIN PRIVATE KEY-----
784
+ `));try{let W=F("security find-identity -v -p codesigning",{encoding:"utf-8"});r(S.magenta(`${W}
785
+ `))}catch(W){r(S.red(`[DIAGNOSTIC] Failed to list identities: ${W.message}
786
+ `))}}await De("xcodebuild",["-exportArchive","-archivePath",C,"-exportPath",x,"-exportOptionsPlist",N],l,i,r,a),s&&await s("validate");let z=je(x,[".ipa"]);for(let W of z)try{F(`unzip -t "${W}"`,{stdio:"pipe"}),r&&r(`[IPA VALID] ${_.basename(W)} \u2014 archive integrity OK
787
+ `)}catch{let le=`IPA validation failed for ${_.basename(W)}: archive may be corrupt`;throw r&&r(`[IPA CORRUPT] ${le}
788
+ `),new Error(le)}return z}},Oe=e=>{try{let n=_.join(process.cwd(),f.configFileName);if(A.existsSync(n)){let t=JSON.parse(A.readFileSync(n,"utf-8"));if(e==="android"&&t.android?.package)return t.android.package;if(e==="ios"&&t.ios?.bundleIdentifier)return t.ios.bundleIdentifier}if(e==="android"){let t=["android/app/build.gradle","app/build.gradle","build.gradle"];for(let i of t)if(A.existsSync(i)){let r=A.readFileSync(i,"utf-8").match(/applicationId\s+['"]([^'"]+)['"]/);if(r)return r[1]}}else{let t=_.resolve(process.cwd(),A.existsSync("ios")?"ios":"."),i=je(t,["Info.plist"]).filter(a=>!a.includes("/Pods/")&&!a.includes("/build/")&&!a.includes("/DerivedData/"));i.sort((a,c)=>c.split("/").length-a.split("/").length);for(let a of i){let s=A.readFileSync(a,"utf-8").match(/<key>CFBundleIdentifier<\/key>\s*<string>([^<]+)<\/string>/);if(s&&!s[1].includes("$"))return s[1]}let o=je(t,[".xcodeproj"]);if(o.length>0){let a=_.join(o[0],"project.pbxproj");if(A.existsSync(a)){let s=A.readFileSync(a,"utf-8").match(/PRODUCT_BUNDLE_IDENTIFIER\s*=\s*"?([^";\s]+)"?;/);if(s)return s[1]}}let r=["app.json","app.config.json","app.config.js","app.config.ts"];for(let a of r)if(A.existsSync(a)){let s=A.readFileSync(a,"utf-8").match(/"bundleIdentifier":\s*"([^"]+)"/);if(s)return s[1]}}}catch{return null}return null},po=()=>{try{return F("emulator -version",{stdio:"ignore"}),"emulator"}catch{let n=_e.homedir(),t=[_.join(n,"Library/Android/sdk/emulator/emulator"),_.join(n,"Android/Sdk/emulator/emulator"),"/usr/local/lib/android/sdk/emulator/emulator"];for(let i of t)if(A.existsSync(i))return i}return"emulator"},fo=async(e,n)=>{let t=St();try{if(F("adb devices").toString().split(`
789
+ `).slice(1).map(a=>a.trim()).filter(a=>a.length>0&&!a.startsWith("*")).map(a=>a.split(" ")[0]).length===0){E.warn(S.yellow("No Android devices or emulators found."));let a=po(),c=[];try{c=F(`${a} -list-avds`).toString().split(`
790
+ `).filter(s=>s.trim().length>0)}catch{}if(c.length>0){let s=await Ht({message:"Select an emulator to launch:",options:c.map(u=>({value:u,label:u}))});if(At(s))return;t.start(`Launching emulator ${s}...`),$i(a,["-avd",s],{detached:!0,stdio:"ignore"}).unref();let l=0,d=!1;for(;l<60;){try{if(F("adb shell getprop sys.boot_completed",{stdio:"pipe"}).toString().trim()==="1"){d=!0;break}}catch{}await new Promise(u=>setTimeout(u,2e3)),l++}if(!d)throw t.stop("Emulator launch timed out."),new Error("Emulator launch timed out. Please try launching it manually.");t.stop("Emulator launched.")}else throw new Error("No devices found and no emulators available to launch. (Make sure Android SDK is installed)")}t.start("Installing APK on device..."),await De("adb",["install","-r",e],process.cwd(),{},n),t.stop("Installation complete.");let r=Oe("android");if(r){E.info(S.blue(`\u{1F680} Launching ${r}...`));try{F(`adb shell dumpsys package ${r}`).toString().split(`
791
+ `).find(s=>s.includes("android.intent.action.MAIN")&&s.includes("android.intent.category.LAUNCHER"))?F(`adb shell monkey -p ${r} -c android.intent.category.LAUNCHER 1`,{stdio:"ignore"}):F(`adb shell monkey -p ${r} -c android.intent.category.LAUNCHER 1`,{stdio:"ignore"})}catch{E.warn("Could not auto-launch app. You may need to open it manually.")}}}catch(i){t.stop("Installation failed."),E.error(S.red(`Failed to install APK: ${i.message}`))}},mo=async(e,n,t)=>{let i=St();try{if(!F("xcrun simctl list devices booted").toString().includes("(Booted)")){E.warn(S.yellow("No iOS Simulator is currently booted."));let r=F("xcrun simctl list devices --json").toString(),a=JSON.parse(r).devices,c=[];Object.keys(a).forEach(u=>{a[u].forEach(p=>{p.isAvailable&&c.push({...p,runtime:u})})});let s=await Ht({message:"Select a simulator to launch:",options:c.map(u=>({value:u.udid,label:`${u.name} (${u.runtime.split(".").pop()})`}))});if(At(s))return;i.start(`Booting ${s}...`),F(`xcrun simctl boot ${s}`),F(`open -a Simulator --args -CurrentDeviceUDID ${s}`);let l=0,d=!1;for(;l<30;){try{if(F("xcrun simctl list devices booted").toString().includes(s)){d=!0;break}}catch{}await new Promise(u=>setTimeout(u,2e3)),l++}if(!d)throw i.stop("Simulator boot timed out."),new Error("Simulator boot timed out.");i.stop("Simulator booted.")}i.start("Installing on iOS Simulator..."),await De("xcrun",["simctl","install","booted",e],process.cwd(),{},t),i.stop("Installation complete."),E.info(S.blue(`\u{1F680} Launching ${n}...`)),await De("xcrun",["simctl","launch","booted",n],process.cwd(),{},t)}catch(o){i.stop("Installation failed."),E.error(S.red(`Failed to install on Simulator: ${o.message}`))}},go=async(e,n,t)=>{let i=St();i.start("Scanning for connected iOS devices...");try{let o=F("xcrun devicectl list devices --json-output -").toString(),a=(JSON.parse(o).result?.devices||[]).filter(s=>s.connectionProperties?.transportType==="wired"||s.connectionProperties?.transportType==="localNetwork");if(a.length===0)throw i.stop("No connected iOS devices found."),new Error("Please connect your iPhone via USB or ensure it is on the same Wi-Fi for wireless debugging.");let c=a[0].identifier;if(a.length>1){i.stop();let s=await Ht({message:"Select a device to install on:",options:a.map(l=>({value:l.identifier,label:`${l.deviceProperties?.name||l.name||l.model?.name} (${l.model?.name||"iPhone"}) - ${l.identifier}`}))});if(At(s))return;c=s,i.start(`Installing on ${c}...`)}else i.message(`Installing on ${a[0].model.name}...`);await De("xcrun",["devicectl","device","install","app","--device",c,e],process.cwd(),{},t),i.stop("Installation complete."),E.info(S.blue(`\u{1F680} Launching ${n}...`)),await De("xcrun",["devicectl","device","launch","app","--device",c,n],process.cwd(),{},t)}catch(o){i.stop("Installation failed."),E.error(S.red(`Failed to install on device: ${o.message}`)),E.info(S.dim('Make sure your device is unlocked and "Developer Mode" is enabled in Settings -> Privacy & Security.'))}};import Et from"fs";function ke(e){if(e){if(!Et.existsSync(e))return null;try{return JSON.parse(Et.readFileSync(e,"utf-8"))}catch{return null}}if(!Et.existsSync(`./${f.configFileName}`))return null;try{return JSON.parse(Et.readFileSync(`./${f.configFileName}`,"utf-8"))}catch{return null}}function Me(e,n,t=new Set){if(t.has(n))throw new Error(`Circular inheritance detected in profile: ${n}`);t.add(n);let i=e.build?.[n];if(!i)return null;let o={...i};if(i.extends){let r=Me(e,i.extends,t);r&&(o={...r,...i,env:{...r.env,...i.env},ios:{...r.ios,...i.ios},android:{...r.android,...i.android}})}if(o.envGroups&&Array.isArray(o.envGroups)){let r={};for(let a of o.envGroups){let c=e.envGroups?.[a];c?Object.assign(r,c):log.warn(`Environment group not found: ${a}`)}o.env={...r,...o.env}}return o}var Be=(e,n=`${f.envPrefix}`)=>{let t={},i=(o,r)=>{if(o)for(let a in o){let c=o[a],s=`${r}${a.toUpperCase().replace(/[^A-Z0-9]/g,"_")}`;c!==null&&typeof c=="object"&&!Array.isArray(c)?i(c,`${s}_`):t[s]=String(c)}};return i(e,n),t};var It=async e=>{e.platform!=="android"&&e.platform!=="ios"&&(w.error(`Platform ${e.platform} is not supported. Use 'android' or 'ios'.`),process.exit(1));let n=jt(),t=e.buildId||ho(),i=e.projectId,o=Date.now(),r=!!i,a=async c=>{if(i)try{await D.patch(`/builds/${i}/${t}`,{status:"failed",error:c})}catch{}};if(e.local&&e.buildId){e.quiet||n.start(`Preparing isolated workspace for build: ${e.buildId}`);try{let c=await D.get(`/builds/${i}/${e.buildId}/source-url`);if(c.data.status!=="success")throw new Error("Failed to get source download URL from API");let s=await tt.get(c.data.downloadUrl,{responseType:"stream"}),l=(i||e.projectId||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),d=we.join(yo.homedir(),f.workspacesDir,l);ce.mkdirSync(d,{recursive:!0});let u=new Set(["node_modules",`.${f.nameLower}-cache-meta`]),p=new Set(["Pods"]);if(ce.existsSync(d)){let k=ce.readdirSync(d);for(let C of k){if(u.has(C))continue;if(C==="ios"){let H=we.join(d,"ios");try{let Z=ce.readdirSync(H);for(let y of Z)if(!p.has(y))try{ce.rmSync(we.join(H,y),{recursive:!0,force:!0})}catch{}}catch{}continue}let x=we.join(d,C);try{ce.rmSync(x,{recursive:!0,force:!0})}catch{}}}let g=we.join(d,"source.zip"),m=s.data,h=ce.createWriteStream(g);await new Promise((k,C)=>{m.pipe(h),m.on("error",x=>C(x)),h.on("finish",()=>k())}),new Ri(g).extractAllTo(d,!0);try{ce.unlinkSync(g)}catch{}process.chdir(d),w.info(R.green(`\u2713 Persistent workspace ready: ${d}`)),w.info(R.dim(` \u{1F4E6} Cached dirs preserved: node_modules=${ce.existsSync(we.join(d,"node_modules"))?"\u2705":"\u274C"}, Pods=${ce.existsSync(we.join(d,"ios","Pods"))?"\u2705":"\u274C"}`)),n.stop()}catch(c){n.stop(`Failed to prepare isolated workspace: ${c.message}`),i&&await a(`Setup Error: ${c.message}`),process.exit(1)}}try{let c=e.repo;if(!c)try{c=vi("git config --get remote.origin.url").toString().trim()}catch{w.warn("Could not detect git repository URL.")}!c&&e.dryRun,c||(c="https://github.com/placeholder/repo.git"),w.info(`Build ID: ${R.cyan(t)}`);let s={},l={},d=ke(`./${f.configFileName}`);if(d){i=d.projectId;let y=e.buildProfile||"production",v=Me(d,y);!v&&e.buildProfile&&(w.error(`Build profile '${y}' not found in ${f.configFileName}`),process.exit(1));let I=v||{};process.env.MACH_DEBUG&&w.info(R.dim(`Build profile: ${y} | Platform: ${e.platform} | Distribution: ${I.distribution||"store"} | Environment: ${I.environment||y}`)),I.env&&(l=I.env,w.info(R.blue(`Use Build Profile: ${y}`)));let b=e.platform,O=I[b]||{},G=["developmentClient","simulator","distribution","buildCommand","apk","iosScheme","preBuild","postBuild","scheme","environment","androidPackage","iosBundleIdentifier","name","iosDeploymentTarget","iosApiKeyId","iosApiKeyIssuer","iosApiKeyPath","iosTeamId","iosConfiguration","iosExportMethod","branch","repo","instanceType","ami","bucket","region","nodeVersion"];e.name=d.name,e.appName=d.name,e.androidPackage=d.android?.package,e.iosBundleIdentifier=d.ios?.bundleIdentifier,e.iosScheme=d.ios?.iosScheme,!e.nodeVersion&&d.nodeVersion&&(e.nodeVersion=d.nodeVersion);for(let N of G){let q=O[N]!==void 0?O[N]:I[N];q!==void 0&&e[N]===void 0&&(e[N]=q)}e.branch=e.branch||"main",e.iosConfiguration=e.iosConfiguration||(e.developmentClient||e.simulator?"Debug":"Release"),e.sshUser=e.sshUser||process.env.USER||"ubuntu",e.simulator===void 0&&(e.simulator=!1),e.local===void 0&&(e.local=!1),e.verbose===void 0&&(e.verbose=!1);let M=N=>{if(!N)return N;if(N.startsWith("scripts.")){let q=N.split(".")[1],z=d.scripts?.[q];if(z)return z;w.warn(`Script reference not found: ${N}`)}return N};e.buildCommand=M(e.buildCommand),e.preBuild=M(e.preBuild),e.postBuild=M(e.postBuild),!e.scheme&&d.scheme&&(e.scheme=d.scheme);let T={...Be(d,f.envPrefix),...Be(I,`${f.envPrefix}PROFILE_`)};s={...s,...l,...T},process.env.IOS_P12_PASSWORD&&!s.IOS_P12_PASSWORD&&(s.IOS_P12_PASSWORD=process.env.IOS_P12_PASSWORD),process.env.MATCH_PASSWORD&&!s.MATCH_PASSWORD&&(s.MATCH_PASSWORD=process.env.MATCH_PASSWORD),e.platform==="ios"&&(!e.iosTeamId&&I.ios?.appleTeamId&&(e.iosTeamId=I.ios.appleTeamId),!e.iosTeamId&&d.submit?.[y]?.ios?.appleTeamId&&(e.iosTeamId=d.submit[y].ios.appleTeamId),!e.iosTeamId&&d.submit?.production?.ios?.appleTeamId&&(w.warn(R.yellow(`Check: Using 'production' Team ID for '${y}' build.`)),e.iosTeamId=d.submit.production.ios.appleTeamId),e.iosTeamId?w.info(R.magenta(`\u2713 Injected iOS Team ID from config: ${e.iosTeamId}`)):w.warn(R.yellow("\u26A0\uFE0F No iOS Team ID found. Signing might fail if not managed automatically via Expo.")))}let u="unknown";try{u=vi("git rev-parse --abbrev-ref HEAD").toString().trim()}catch{w.warn("Failed to detect git branch.")}let p="1.0.0";try{ce.existsSync("./package.json")&&(p=JSON.parse(ce.readFileSync("./package.json","utf-8")).version||"1.0.0")}catch{}let g=e.buildProfile||"production",m="Internal";e.developmentClient?m="DevelopmentClient":g.toLowerCase().includes("store")||g.toLowerCase()==="production"?m="Store":g.toLowerCase().includes("preview")||g.toLowerCase().includes("staging")?m="Staging":(g.toLowerCase().includes("development")||g.toLowerCase().includes("dev"))&&(m="Development");let h=e.platform==="ios"?"iOS":"Android",P=e.platform==="ios"&&e.simulator?" (Simulator)":"",k=`${h}${P} v${p} (${m})`;if(i){try{let y=e.buildProfile||"production";w.info(R.blue(`Fetching managed secrets for profile: ${y}...`));let v=e.environment||y,b=(await D.get(`/projects/${i}/secrets/export?env=${v}`)).data;b.status==="success"&&b.secrets&&(s={...s,...b.secrets},Object.keys(b.secrets).length>0&&w.info(R.magenta(`\u2713 Injected ${Object.keys(b.secrets).length} secrets from Dashboard.`)))}catch(y){w.warn(`Failed to load managed secrets from Dashboard: ${y.message}`)}try{w.info(R.blue("Fetching managed credentials..."));let y="development";e.distribution==="store"?y="store":e.distribution==="internal"&&(y=e.platform==="ios"?"adhoc":"internal"),m==="Staging"&&e.developmentClient&&(y="development");let v=await D.get("/credentials/resolve",{params:{projectId:i,platform:e.platform,bundleId:e.iosBundleIdentifier||e.androidPackage,distributionType:y}});if(v.data.status==="success"&&v.data.credentials){let I=v.data.credentials;w.info(R.magenta(`\u2713 Found ${I.length} relevant credentials.`));let b=I.filter(T=>{if(T.distributionType){let N=y==="internal"?"adhoc":y;return T.distributionType===N||T.distributionType===y}return!0});w.info(R.dim(` Filtered to ${b.length} credentials for distributionType: ${y}`));let O=!1,G=!1,M=!1;for(let T of b)if(T.downloadUrl)try{let N="",q=5;for(;q>0;)try{let z=await tt.get(T.downloadUrl,{responseType:"arraybuffer",timeout:3e4,headers:{Connection:"close"}});N=Buffer.from(z.data).toString("base64");break}catch(z){if(q--,q===0)throw z;w.warn(R.dim(` - Temporary network error downloading ${T.name}. Retrying... (${5-q}/5)`)),await new Promise(W=>setTimeout(W,2e3))}if(T.type==="ios_cert"&&!O)s.IOS_DIST_P12=N,T.password?(s.IOS_P12_PASSWORD=T.password,w.info(R.dim(` - Injected ${T.name} as IOS_DIST_P12 with password from credential record`))):w.info(R.dim(` - Injected ${T.name} as IOS_DIST_P12`)),O=!0;else if(T.type==="ios_profile"&&!G)s.IOS_PROVISIONING_PROFILE=N,w.info(R.dim(` - Injected ${T.name} as IOS_PROVISIONING_PROFILE`)),G=!0;else if(T.type==="android_keystore"&&!M){s.ANDROID_KEYSTORE_BASE64=N;let z=T.password,W=T.alias||T.meta?.alias;if(z)s.ANDROID_KEY_PASSWORD=z,s.ANDROID_STORE_PASSWORD=z,w.info(R.dim(" - Injected keystore password from credential record"));else{let Q=["ANDROID_KEY_PASSWORD",...[y==="store"?"PRODUCTION":y==="internal"?"STAGING":"DEVELOPMENT",y.toUpperCase(),"PRODUCTION","STORE","INTERNAL","STAGING","RELEASE","DEBUG"].map(Ee=>`KEYSTORE_PASSWORD_${Ee}`),"KEYSTORE_PASSWORD"].find(Ee=>!!s[Ee]);Q&&s[Q]&&(s.ANDROID_KEY_PASSWORD=s[Q],s.ANDROID_STORE_PASSWORD=s[Q])}if(W)s.ANDROID_KEY_ALIAS=W;else{let ee=["ANDROID_KEY_ALIAS","KEYSTORE_ALIAS"].find(le=>!!s[le]);ee&&(s.ANDROID_KEY_ALIAS=s[ee])}w.info(R.dim(` - Injected ${T.name} as ANDROID_KEYSTORE_BASE64`)),M=!0}}catch(N){w.warn(`Failed to download credential ${T.name}: ${N.message}`)}}if(e.platform==="android"){let I=d.android?.versionCode==="auto"||d.expo?.android?.versionCode==="auto";if(e.autoVersion||I){n.start("Resolving latest versionCode from Google Play...");try{let b=(v.data.credentials||[]).find(z=>z.type==="google_service_account");if(b||(b=((await D.get(`/credentials/${i}`)).data.credentials||[]).find(W=>W.type==="google_service_account")),!b)throw new Error("Google Service Account not found. Upload it via Dashboard to use auto-versioning.");let O=await D.get(`/credentials/${b.credentialId}/download`,{params:{projectId:i}});if(O.data.status!=="success"||!O.data.downloadUrl)throw new Error("Failed to get secure download URL for service account");let M=(await tt.get(O.data.downloadUrl,{headers:{Connection:"close"}})).data,T=e.androidPackage||d.android?.package||d.expo?.android?.package||d.name,N=await bi(T,M);if(N==null)throw new Error("Could not retrieve any version information from Google Play.");let q=N+1;s.ANDROID_VERSION_CODE=q.toString(),n.stop(`\u2713 Resolved versionCode: ${R.green(q)} (Latest on Play Store: ${N})`)}catch(b){n.stop("Version resolution failed");let O=b.response?.data?.error?.message||b.message;w.warn(R.yellow(` \u26A0\uFE0F Auto-versioning failed: ${O}`)),w.warn(R.dim(' Falling back to version code from config. To fix: ensure Service Account has "View App Metadata" and "View App Information" permissions in Google Play Console.'))}}}if(e.platform==="ios"&&!e.simulator){let I=!!s.IOS_DIST_P12,b=!!s.IOS_PROVISIONING_PROFILE;if(!I||!b){let O=[...I?[]:["Distribution Certificate"],...b?[]:["Provisioning Profile"]].join(" and ");w.error(R.red(`Missing iOS credentials: ${O}`)),e.quiet&&process.exit(1);let G=e.yes||await Di({message:"Would you like to generate these credentials now?",initialValue:!0});if(G&&!wi(G))return await qe({platform:"ios",profile:g}),e.quiet||w.info(R.green("\u2713 Credentials setup complete! Restarting build phase...")),It(e);e.quiet||w.info(R.yellow(`Run \`${f.nameLower} credentials\` to set up signing credentials manually.`)),process.exit(1)}}if(e.platform==="android"&&(e.distribution==="internal"||e.distribution==="store")&&!(!!s.ANDROID_KEYSTORE_BASE64||!!s.ANDROID_KEYSTORE)){w.error(R.red("Missing Android credentials: Signing Keystore")),e.quiet&&process.exit(1);let b=e.yes||await Di({message:"Would you like to automatically create and upload an Android Keystore for this profile now?",initialValue:!0});if(b&&!wi(b))return await qe({platform:"android",profile:g}),e.quiet||w.info(R.green("\u2713 Android Keystore setup complete! Restarting build phase...")),It(e);e.quiet||w.info(R.yellow(`Run \`${f.nameLower} credentials --platform android\` to set up a signing keystore manually.`)),process.exit(1)}}catch(y){w.warn(`Failed to resolve credentials: ${y.message}`)}}let C=!!(e.local&&e.buildId),x=!!(e.local||e.sshHost),H=!x&&!C;if(C){w.info(R.magenta("\u{1F3D7}\uFE0F Runner Mode: Executing isolated build task..."));let y=await Gt({...e,interactive:!1},t,s,i,{branch:u,version:p,summary:k,buildType:m});await Z(y),process.exit(0)}async function Z(y){if(i&&y.length>0){let v=jt(),I=[];e.quiet||v.start("Uploading artifacts to Dashboard...");try{for(let b of y){let O=we.basename(b),G=ce.readFileSync(b),M=we.extname(O).toLowerCase(),T="application/octet-stream",N=await D.post(`/builds/${i}/${t}/artifact-upload-url`,{fileName:O,fileType:T});if(N.data.status!=="success")throw new Error(`Failed to get upload URL for ${O}`);let q=!1;for(let z=1;z<=3;z++)try{await tt.put(N.data.uploadUrl,G,{headers:{"Content-Type":T},maxBodyLength:1/0,maxContentLength:1/0,timeout:12e4}),q=!0;break}catch(W){if(w.warn(R.yellow(`Artifact upload attempt ${z}/3 failed (${W.code||W.message})`)),z<3)await new Promise(ee=>setTimeout(ee,3e3*z));else throw W}q&&I.push({name:O,url:N.data.downloadUrl,size:G.length,type:M.substring(1)})}e.quiet||v.stop("Artifacts uploaded.")}catch(b){e.quiet||v.stop("Failed to upload artifacts."),w.error(R.red(`Upload error: ${b.message}`));try{await D.patch(`/builds/${i}/${t}`,{status:"completed",artifacts:y.map(O=>we.basename(O)),endTime:Date.now()})}catch(O){w.warn(R.yellow(`Could not set fallback build status: ${O.message}`))}return}if(i&&I.length>0)try{w.info(R.cyan(`
792
+ \u{1F517} Download Links:`));for(let b of I)w.info(R.dim(` - ${b.name}: `)+R.blue.underline(b.url));await D.patch(`/builds/${i}/${t}`,{status:"success",artifacts:I,endTime:Date.now()}),w.success(R.green(`
793
+ \u2713 Build completed and reported to dashboard.`))}catch(b){w.warn(R.yellow(`
794
+ \u26A0\uFE0F Could not report to dashboard: ${b.message}`))}}else if(i)try{await D.patch(`/builds/${i}/${t}`,{status:"completed",endTime:Date.now()})}catch{}}if(x){if(w.info(R.cyan(`\u{1F680} Direct Build Mode: Executing on ${e.sshHost||"local"}...`)),i&&!r){let y=process.argv.slice(3).join(" ");await D.post("/builds",{projectId:i,buildId:t,platform:e.platform,status:"building",branch:u,version:p,summary:k,startTime:o,buildType:m,buildProfile:g,buildArgs:y,simulator:!!e.simulator})}if(e.sshHost&&e.platform==="ios"){let y=await Ii(e,t,s,i)}else{let y=await Gt({...e,interactive:!!e.local},t,s,i,{branch:u,version:p,summary:k,buildType:m});await Z(y)}return}if(H&&(w.info(R.blue("\u{1F6F0}\uFE0F Cloud Initiator Mode: Preparing orchestration...")),!e.dryRun)){e.quiet||n.start("Zipping and uploading local source...");let y=await D.post("/builds/source-upload-url",{projectId:i,buildId:t});if(y.data.status!=="success")throw n.stop("Failed to get upload URL."),new Error("Failed to get source upload URL from API");let v=new Ri,I=ce.readdirSync("."),b=["node_modules",".git","dist","build","builds",".gradle",".idea","android/build","ios/build","ios/Pods",`.${f.nameLower}_cli`];for(let M of I){if(b.includes(M))continue;ce.statSync(M).isDirectory()?v.addLocalFolder(M,M):v.addLocalFile(M)}let O=v.toBuffer();e.quiet||n.message(`Uploading source (${(O.length/1024/1024).toFixed(1)} MB)...`);let G=!1;for(let M=1;M<=3;M++)try{await tt.put(y.data.uploadUrl,O,{headers:{"Content-Type":"application/zip"},maxBodyLength:1/0,maxContentLength:1/0,timeout:12e4}),G=!0;break}catch(T){if(M<3)n.message(`Upload attempt ${M} failed (${T.code||T.message}), retrying...`),await new Promise(N=>setTimeout(N,2e3*M));else throw T}if(e.quiet||n.stop("Source uploaded"),i){let M=process.argv.slice(3).join(" ");await D.post("/builds",{projectId:i,buildId:t,platform:e.platform,status:"pending",branch:u,version:p,summary:k,startTime:o,buildType:m,buildProfile:g,buildArgs:M,simulator:!!e.simulator}),w.info(R.green("\u2713 Cloud build registered."))}e.platform==="android"&&await Ai(e,t,s,i),e.quiet||w.info(R.cyan("\u{1F4E1} Connecting to build stream...")),await So(i,t,e);return}}catch(c){let s=c.message||"Build failed";c.response?.data?.message?s=c.response.data.message:c.message.includes("status code 402")?s="Insufficient wallet balance. Please add credits in the Dashboard.":c.message.includes("status code 403")&&(s="Monthly build quota exceeded. Upgrade your plan in the Dashboard."),i&&!e.local&&await a(s),w.error(R.red(`\u2717 Build failed: ${s}`)),process.exit(1)}};async function So(e,n,t){let i=jt(),o="pending",r=0,a=0;for(t.quiet||i.start("Connecting to build stream...");;){try{let s=(await D.get(`/builds/${e}/${n}`)).data.build;if(s){if(o=s.status,o==="building")t.quiet||i.message("Building on M4 Mac Mini...");else if(o==="failed")t.quiet||i.stop("Build failed."),w.error(R.red(`
795
+ \u2717 Build failed: ${s.error||"Unknown error"}`)),process.exit(1);else if(o==="completed"||o==="success"){t.quiet||i.stop("Build successful!"),w.success(R.green(`
796
+ \u2713 Build completed successfully!`));try{t.quiet||(w.info(R.magenta(`
797
+ \u{1F4F1} Installation Hub:`)),w.info(R.dim(" - View & Install Build: ")+R.white.underline(`${ci}/build/${n}`)))}catch{}return}else if(o!=="pending"){t.quiet||i.stop(`Build status: ${o}`);return}}try{let d=(await D.get(`/builds/${e}/${n}/logs`)).data;if(d&&typeof d=="string"&&!t.quiet){let u=d.split(`
798
+ `);if(u.length>r){for(let p=r;p<u.length;p++)u[p].trim()&&console.log(R.dim(` ${u[p]}`));r=u.length}}}catch{}a=0}catch{a++,a>10&&(i.stop("Connection lost."),w.error(R.red(`
799
+ \u2717 Lost connection to Dashboard API.`)),process.exit(1))}await new Promise(c=>setTimeout(c,3e3))}}import Ao from"http";import{execSync as bt}from"child_process";import Bt from"chalk";import{log as Ke}from"@clack/prompts";var Pt=7070;function Eo(){let e=[];try{let n=bt("adb devices -l",{stdio:"pipe"}).toString(),t=new Set;n.split(`
800
+ `).forEach(i=>{if(i.includes("List of devices")||!i.trim())return;let o=i.split(/\s+/);if(o.length<2||o[1]!=="device")return;let r=o[0];t.add(r);let a=i.match(/model:([^\s]+)/);e.push({id:r,platform:"android",type:r.startsWith("emulator-")?"emulator":"physical",name:a?a[1].replace(/_/g," "):r,status:"online",details:i.trim()})})}catch{}try{let n=`${process.env.ANDROID_HOME||`${process.env.HOME}/Library/Android/sdk`}/emulator/emulator`,i=bt(`${n} -list-avds`,{stdio:"pipe"}).toString().split(`
801
+ `).filter(r=>!!r.trim()),o=e.some(r=>r.platform==="android"&&r.id.startsWith("emulator-"));i.forEach(r=>{o||e.push({id:r,platform:"android",type:"emulator",name:r.replace(/_/g," "),status:"offline",details:`Android Virtual Device: ${r}`})})}catch{}if(process.platform!=="darwin")return e;try{let n=bt("/usr/bin/xcrun simctl list devices --json",{stdio:"pipe"}).toString(),t=JSON.parse(n);Object.entries(t.devices).forEach(([i,o])=>{o.forEach(r=>{r.isAvailable&&e.push({id:r.udid,platform:"ios",type:"simulator",name:r.name,status:r.state?.toLowerCase()==="booted"?"online":"offline",runtime:i,details:`${r.name} (${i})`})})})}catch{}try{let n=bt("/usr/bin/xcrun devicectl list devices --json-output -",{stdio:"pipe"}).toString();(JSON.parse(n).result?.devices||[]).forEach(i=>{let o=i.connectionProperties?.transportType;(o==="wired"||o==="localNetwork")&&e.push({id:i.identifier,platform:"ios",type:"physical",name:i.deviceProperties?.name||"iPhone",status:"online",details:`${i.deviceProperties?.name||"iPhone"} (${i.model?.name||i.hardwareModel||""}) - ${o}`})})}catch{}return e}async function Oi(){process.platform!=="darwin"&&Ke.warn("Running on non-macOS \u2014 iOS discovery unavailable, Android only.");let e=Ao.createServer((n,t)=>{if(t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Access-Control-Allow-Methods","GET, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),n.method==="OPTIONS"){t.writeHead(204),t.end();return}let i=new URL(n.url||"/",`http://localhost:${Pt}`);if(n.method==="GET"&&i.pathname==="/local/devices"){try{let o=Eo();t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({status:"success",targets:o}))}catch(o){t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({status:"error",message:o.message}))}return}t.writeHead(404),t.end()});e.listen(Pt,"127.0.0.1",()=>{Ke.success(Bt.green(`Local device agent running on http://localhost:${Pt}`)),Ke.info(Bt.dim("Keep this running while using the Install Hub on the dashboard.")),Ke.info(Bt.dim("Press Ctrl+C to stop."))}),e.on("error",n=>{n.code==="EADDRINUSE"?Ke.error(`Port ${Pt} is already in use \u2014 agent may already be running.`):Ke.error(`Agent error: ${n.message}`),process.exit(1)}),await new Promise(()=>{})}import{createRequire as Qr}from"module";import{text as bo,password as Po,spinner as $o,isCancel as Ni}from"@clack/prompts";import Wt from"chalk";import it from"fs";import Ci from"path";import Io from"os";var Kt=Ci.join(Io.homedir(),f.configDir),Vt=Ci.join(Kt,"config.json");function zt(){if(!it.existsSync(Vt))return{};try{return JSON.parse(it.readFileSync(Vt,"utf-8"))}catch{return{}}}function Ti(e){it.existsSync(Kt)||it.mkdirSync(Kt,{recursive:!0});let t={...zt(),...e};it.writeFileSync(Vt,JSON.stringify(t,null,2))}async function ki(){let e=zt(),n=await bo({message:"Enter your email:",placeholder:"user@example.com",initialValue:e.lastLoginEmail,validate(o){if(o.length===0)return"Email is required!"}});if(Ni(n))return;let t=await Po({message:"Enter your password:",validate(o){if(o.length===0)return"Password is required!"}});if(Ni(t))return;let i=$o();i.start("Authenticating...");try{let r=await(await fetch(`${yt}/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:n,password:t})})).json();r.status==="success"&&r.user.token?(si({id:r.user.id,email:n,token:r.user.token,refreshToken:r.user.refreshToken}),Ti({lastLoginEmail:n}),i.stop(Wt.green("Login successful!"))):i.stop(Wt.red("Login failed: "+(r.message||"Unknown error")))}catch(o){i.stop(Wt.red("Network error: "+o.message))}}import{outro as _o,select as Do,spinner as wo,isCancel as vo}from"@clack/prompts";import $t from"chalk";import Yt from"fs";import Ro from"path";async function xi(){if(!fe()){console.log($t.red(`You are not logged in. Run \`${f.nameLower} login\` first.`));return}let n=wo();n.start("Fetching projects...");try{let{data:t}=await D.get("/projects");if(n.stop("Projects loaded."),t.status!=="success"||!t.projects||t.projects.length===0){console.log($t.yellow(`No projects found. Run \`${f.nameLower} init\` to create one.`));return}let i=t.projects.map(u=>({value:u.projectId,label:`${u.name} (${u.slug})`})),o=await Do({message:"Select a project to link:",options:i});if(vo(o))return;let r=Ro.join(process.cwd(),f.configFileName),a={};if(Yt.existsSync(r))try{a=JSON.parse(Yt.readFileSync(r,"utf-8"))}catch{}let c=t.projects.find(u=>u.projectId===o),s=a.android?.package||Oe("android"),l=a.ios?.bundleIdentifier||Oe("ios"),d={projectId:o,name:c?.name,slug:c?.slug,scheme:c?.slug?.toLowerCase()||"app",android:{package:s||""},ios:{bundleIdentifier:l||""},build:{development:{environment:"development",distribution:"internal"},staging:{environment:"staging",distribution:"internal"},production:{environment:"production",distribution:"store"}},submit:{production:{android:a.submit?.production?.android||{track:"internal"},ios:{ascAppId:a.submit?.production?.ios?.ascAppId||"1234567890",appleTeamId:a.submit?.production?.ios?.appleTeamId||"ABC123DEFG"}}}};Yt.writeFileSync(r,JSON.stringify(d,null,2)),_o($t.green(`Linked to project ${d.name} (${d.slug})`))}catch(t){n.stop($t.red("Error fetching projects: "+t.message))}}import{outro as Oo,text as _t,select as Co,spinner as To,isCancel as nt}from"@clack/prompts";import ot from"chalk";import No from"fs";import ko from"path";import{randomUUID as xo}from"crypto";async function Li(){if(!fe()){console.log(ot.red(`You are not logged in. Run \`${f.nameLower} login\` first.`));return}let n=await _t({message:"Project Name:",placeholder:"My Awesome App",validate(c){if(c.length===0)return"Name is required!"}});if(nt(n))return;let t=await _t({message:"Project Slug (URL friendly):",placeholder:"my-awesome-app",validate(c){if(c.length===0)return"Slug is required!";if(!/^[a-z0-9-]+$/.test(c))return"Slug must be lowercase alphanumeric with dashes."}});if(nt(t))return;let i=await Co({message:"Platform:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"},{value:"web",label:"Web"},{value:"all",label:"All Platforms"}]});if(nt(i))return;let o="";if(i==="android"||i==="all"){let c=Oe("android");if(o=await _t({message:"Android Package Name:",initialValue:c||"",placeholder:"com.example.app",validate(s){if(s.length===0)return"Package name is required for Android!"}}),nt(o))return}let r="";if(i==="ios"||i==="all"){let c=Oe("ios");if(r=await _t({message:"iOS Bundle Identifier:",initialValue:c||"",placeholder:"com.example.app",validate(s){if(s.length===0)return"Bundle ID is required for iOS!"}}),nt(r))return}let a=To();a.start("Creating project...");try{let c=xo(),l={projectId:c,name:n,slug:t,storageType:"managed",platforms:i==="all"?["android","ios","web"]:[i]},{data:d}=await D.post("/projects",l);if(d.status==="success"){a.stop(ot.green("Project created successfully!"));let u=ko.join(process.cwd(),f.configFileName);No.writeFileSync(u,JSON.stringify({projectId:c,name:n,slug:t,...o?{android:{package:o}}:{},...r?{ios:{bundleIdentifier:r}}:{},build:{development:{environment:"development",distribution:"internal"},staging:{environment:"staging",distribution:"internal"},production:{environment:"production",distribution:"store"}},submit:{production:{android:{track:"internal"},ios:{ascAppId:"1234567890",appleTeamId:"ABC123DEFG",...r?{bundleId:r}:{}}}}},null,2)),Oo(ot.green(`Initialized project ${n} and linked locally!`))}else a.stop(ot.red("creation failed: "+d.message))}catch(c){a.stop(ot.red("Network error: "+c.message))}}import{spinner as Mi,log as he}from"@clack/prompts";import Dt from"chalk";import Ui from"fs";import Lo from"path";async function Fi(e,n){let t=fe();if(!t){he.error(`You are not logged in. Run \`${f.nameLower} login\` first.`);return}let i=Lo.join(process.cwd(),f.configFileName);if(!Ui.existsSync(i)){he.error(`No ${f.configFileName} found. Run \`${f.nameLower} init\` or \`${f.nameLower} link\` first.`);return}let o;try{o=JSON.parse(Ui.readFileSync(i,"utf-8"))}catch{he.error(`Failed to parse ${f.configFileName}`);return}let{projectId:r}=o;if(!r){he.error(`${f.configFileName} is missing projectId.`);return}e==="set"?await Uo(r,n,t):e==="list"?await Mo(r,t):he.error(`Unknown env action: ${e}. Use 'set' or 'list'.`)}async function Uo(e,n,t){if(n.length===0){he.error(`Usage: ${f.nameLower} env set KEY=VALUE [KEY2=VALUE2 ...]`);return}let i=Mi();i.start("Setting environment variables...");let o=0,r=0;for(let a of n){let[c,...s]=a.split("="),l=s.join("=");if(!c||l===void 0){he.warn(`Invalid format for argument: ${a}. Expected KEY=VALUE.`),r++;continue}try{let d={key:c.trim(),value:l,type:"env",environment:"global",visibility:"secret"},{data:u}=await D.post(`/projects/${e}/secrets`,d);u.status==="success"?o++:(he.error(`Failed to set ${c}: ${u.message}`),r++)}catch(d){he.error(`Network error setting ${c}: ${d.message}`),r++}}i.stop(`Set ${o} variable(s). ${r>0?`${r} failed.`:""}`)}async function Mo(e,n){let t=Mi();t.start("Fetching environment variables...");try{let{data:i}=await D.get(`/projects/${e}/secrets`);if(i.status==="success"){t.stop("Fetched variables.");let o=i.secrets||[];o.length===0?he.info("No environment variables found for this project."):(he.info(Dt.bold("Environment Variables (Global & Scoped):")),o.forEach(r=>{let a=r.visibility==="plain"?r.value:"********";console.log(` ${Dt.cyan(r.key)} = ${a} ${Dt.gray(`[${r.environment}]`)}`)}))}else t.stop(Dt.red(`Failed to fetch variables: ${i.message}`))}catch(i){t.stop("Failed to fetch variables."),he.error(`Network error: ${i.message}`)}}import{spinner as st,text as rt,select as qt,isCancel as xe,cancel as Xt}from"@clack/prompts";import re from"chalk";import de from"fs";import Ve from"path";import{spawn as Fo,spawnSync as Ho}from"child_process";import Gi from"axios";import Zt from"os";import Go from"crypto";async function ji(e){let n=st(),t=fe(),i=`./${f.configFileName}`;if(!de.existsSync(i)){ye(`No ${f.configFileName} found. Run \`${f.nameLower} init\` or \`${f.nameLower} link\` first.`);return}let o=JSON.parse(de.readFileSync(i,"utf-8")),{projectId:r}=o;if(!r){ye(`${f.configFileName} is missing projectId.`);return}ve(re.dim(`Submit for project: ${o.name||r} `));let a=e.platform;if(!a){let h=await qt({message:"Select platform to submit:",options:[{value:"ios",label:"iOS (App Store Connect / TestFlight)"},{value:"android",label:"Android (Google Play Console)"}]});if(xe(h)){Xt("Operation cancelled");return}a=h}let c=await jo(r,a,e,t?.token);if(!c)return;ve(`Using artifact: ${re.green(Ve.basename(c))} `),n.start("Fetching submission credentials from Dashboard...");let s;try{let k=((await D.get(`/credentials/${r}`)).data.credentials||[]).filter(C=>a==="ios"?C.type==="asc_api_key":C.type==="google_service_account");if(k.length===0){n.stop("Credentials missing"),ye(`No Service Credentials found for ${a}.`),ve(`Use '${f.nameLower} credentials:service --platform ${a}' or use the Dashboard to upload them.`);return}if(k.length===1)s=k[0],n.stop(`Using: ${s.name}`);else{n.stop("Multiple credentials found");let C=await qt({message:`Choose a ${a==="ios"?"App Store Connect":"Google Play"} credential:`,options:k.map(x=>({value:x.credentialId,label:x.name,hint:`${x.keyId?`ID: ${x.keyId}`:""} ${x.issuerId?`(Issuer: ${x.issuerId.substring(0,8)}...)`:""}`}))});if(xe(C)){Xt("Submission cancelled");return}s=k.find(x=>x.credentialId===C),ve(`Using selected: ${re.green(s.name)}`)}}catch(h){n.stop("Failed to fetch credentials"),ye(`API Error: ${h.message} `);return}let l=de.mkdtempSync(Ve.join(Zt.tmpdir(),`${f.nameLower}-submit-`)),d=s.keyId||s.meta?.keyId,u=s.issuerId||s.meta?.issuerId,p=s.type==="asc_api_key"?`AuthKey_${d}.p8`:"service-account.json",g=Ve.join(l,p);n.start("Downloading secure key...");try{let h=await D.get(`/credentials/${s.credentialId}/download`,{params:{projectId:r}});if(h.data.status!=="success"||!h.data.downloadUrl)throw new Error("Failed to get secure download URL");let P=await Gi.get(h.data.downloadUrl,{responseType:"arraybuffer"});de.writeFileSync(g,Buffer.from(P.data)),n.stop("Key downloaded to secure temp storage")}catch(h){n.stop("Download failed"),ye(`Failed to download key: ${h.message}`);try{de.rmSync(l,{recursive:!0,force:!0})}catch{}return}ve(re.blue(`Initiating ${a==="ios"?"TestFlight":"Google Play"} submission...`));let m=a==="android"?e.track||o.submit?.production?.android?.track||"internal":void 0;try{if(a==="ios"){if(!d){let k=await rt({message:"Enter App Store Connect Key ID (e.g. 2X948D...):",validate:C=>C.length>0?void 0:"Key ID is required"});if(xe(k))return;d=k}if(!u||u==="undefined"){let k=await rt({message:"Enter App Store Connect Issuer ID (Found on ASC Keys page):",validate:C=>C.length>0?void 0:"Issuer ID is required"});if(xe(k))return;u=k}ve(`Using ASC Key ID: ${d}`),ve(`Using ASC Issuer ID: ${u}`);let h=o.ios?.bundleIdentifier,P=await Bo(c,g,u,d,h);if(P&&P.apiKeyJsonPath)throw ve(re.cyan(`
802
+ [DIAGNOSTIC] API key written to: ${P.apiKeyJsonPath}
803
+ `)),new Error("fastlane pilot execution failed");Hi(`${a==="ios"?"App Store":"Google Play"} submission successful!`)}else{let h=o.android?.package||s.bundleId;await Ko(c,g,m,h),Hi("Google Play submission successful!")}}catch(h){ye(`Submission failed: ${h.message}`)}finally{Vo(l),c.includes(`${f.nameLower}-artifact-`)}}async function jo(e,n,t,i){let o=t.buildId?"id":t.latest?"latest":null;if(!o&&(o=await qt({message:"Select artifact source:",options:[{value:"latest",label:`Latest Production Build (${f.name})`},{value:"id",label:`Input Build ID (${f.name})`},{value:"url",label:"Remote URL"},{value:"local",label:"Local File Path"}]}),xe(o)))return Xt("Operation cancelled"),null;if(o==="local"){let a=await rt({message:"Enter path to artifact (.ipa/.aab):",validate:c=>{if(!de.existsSync(c))return"File not found";if(n==="ios"&&!c.endsWith(".ipa"))return"Must be an .ipa file";if(n==="android"&&!c.endsWith(".aab"))return"Must be an .aab file"}});return xe(a)?null:a}let r=st();if(o==="latest"){r.start("Fetching latest build...");try{let a=await D.get(`/builds/${e}`,{params:{limit:50}});if(a.data.status!=="success")throw new Error(a.data.message);let c=a.data.builds||[],s=c.find(m=>m.platform?.toLowerCase()===n.toLowerCase()&&m.status?.toLowerCase()==="success"&&m.buildType?.toLowerCase()==="store")||c.find(m=>m.platform?.toLowerCase()===n.toLowerCase()&&m.status?.toLowerCase()==="success");if(!s)return r.stop("No suitable build found"),ye("No successful builds found for this platform."),null;r.stop(`Found build: ${s.buildId}`);let l=s.artifacts||[];if(l.length===0||l.every(m=>!(m.url||m.downloadUrl)))try{let m=await D.get(`/builds/${e}/${s.buildId}/artifacts`);m.data.status==="success"&&m.data.artifacts?.length>0?(l=m.data.artifacts.map(h=>({...h,url:h.url||h.downloadUrl})),console.log(re.cyan(` [RECOVERY] Fetched ${l.length} artifact(s) with download URLs.`))):console.log(re.yellow(" [RECOVERY] /artifacts endpoint returned 0 artifacts."))}catch(m){console.log(re.red(` [RECOVERY] /artifacts fetch failed: ${m.message}`))}let u=n==="ios",p=l.find(m=>{let h=(m.type||"").toLowerCase(),P=(m.name||"").toLowerCase();if(console.log(re.dim(` - Checking: ${m.name} (Type: ${m.type}, HasLink: ${!!(m.url||m.downloadUrl)})`)),h)return h===(u?"ipa":"aab");let k=u?".ipa":".aab",C=(m.url||m.downloadUrl||"").toLowerCase();return P.endsWith(k)||C.includes(k)});if(!p||!(p.url||p.downloadUrl))return ye("Build found but artifact URL is missing."),null;let g=p.url||p.downloadUrl;return await Jt(g,u?"ios":"android")}catch(a){return r.stop("Fetch failed"),ye(`API Error: ${a.message}`),null}}if(o==="id"){let a=t.buildId||await rt({message:"Enter Build ID:",validate:c=>c.length<5?"Invalid ID":void 0});if(xe(a))return null;r.start("Fetching build...");try{let c=await D.get(`/build/${a}`);if(c.data.status!=="success")throw new Error(c.data.message);let s=c.data.build;if(!s)throw new Error("Build not found");let l=n==="ios",d=s.artifacts?.find(u=>{if(u.type)return u.type===(l?"ipa":"aab");let p=l?".ipa":".aab";return u.name&&u.name.endsWith(p)||u.url&&u.url.includes(p)});return!d||!d.url?(r.stop("Missing artifact"),ye("Artifact URL not found on build record."),null):(r.stop(`Found build: ${s.buildId}`),await Jt(d.url,l?"ios":"android"))}catch(c){return r.stop("Fetch failed"),ye(c.message),null}}if(o==="url"){let a=await rt({message:"Enter Artifact URL:",validate:c=>c.startsWith("http")?void 0:"Must be a valid URL"});return xe(a)?null:await Jt(a,n)}return null}async function Jt(e,n,t=3){let i=st();i.start("Downloading artifact...");let o=de.mkdtempSync(Ve.join(Zt.tmpdir(),`${f.nameLower}-artifact-`)),r=`app.${n==="ios"?"ipa":"aab"}`,a=Ve.join(o,r);for(let c=1;c<=t;c++)try{c>1&&(i.message(`Downloading artifact (Retry ${c}/${t})...`),await new Promise(d=>setTimeout(d,2e3*c)));let s=de.createWriteStream(a),l=await Gi({url:e,method:"GET",responseType:"stream",timeout:6e4});return await new Promise((d,u)=>{l.data.pipe(s);let p=!1;l.data.on("error",g=>{p||(p=!0,s.close(),u(g))}),s.on("finish",()=>{p||d()}),s.on("error",g=>{p||(p=!0,u(g))})}),i.stop("Download complete"),a}catch(s){if(c===t)throw i.stop("Download failed"),s}throw new Error("Download failed after retries")}async function Bo(e,n,t,i,o){let r=st();if(o&&ve(`Bundled ID: ${re.green(o)}`),!t||!i)throw ye(`Missing credentials: issuerId=${t}, keyId=${i}. Check your Dashboard.`),new Error("Missing ASC API Key Metadata (IssuerID or KeyID)");let a=de.readFileSync(n,"utf8"),c;try{c=Go.createPrivateKey(a).export({type:"pkcs8",format:"pem"})}catch{ve("Key normalization failed, falling back to manual re-wrapping..."),c=`-----BEGIN PRIVATE KEY-----
803
804
  ${(a.replace(/-----BEGIN[^-]*-----/g,"").replace(/-----END[^-]*-----/g,"").replace(/\s+/g,"").match(/.{1,64}/g)||[]).join(`
804
805
  `)}
805
- -----END PRIVATE KEY-----`}console.log(ne.yellow(`
806
- [DIAGNOSTIC] Key ID: ${i}`)),console.log(ne.yellow(`[DIAGNOSTIC] Issuer ID: ${t}`)),console.log(ne.yellow(`[DIAGNOSTIC] Key Checksum (Start): ${c.substring(0,45).replace(/\n/g,"\\n")}`)),console.log(ne.yellow(`[DIAGNOSTIC] Key Checksum (End): ${c.substring(c.length-28).replace(/\n/g,"\\n")}
807
- `)),r.start("Uploading to TestFlight (pilot)...");let s=Ke.join(Xt.tmpdir(),`api_key_${i}.json`),l={key_id:i,issuer_id:t,key:c,in_house:!1};le.writeFileSync(s,JSON.stringify(l,null,2));let d={...process.env};return new Promise((u,p)=>{let g=Mo("fastlane",["pilot","upload","--ipa",e,"--api_key_path",s,"--skip_submission","true","--skip_waiting_for_build_processing","true"],{stdio:"inherit",env:d});g.on("close",m=>{if(m!==0)r.stop("Pilot failed"),u({apiKeyJsonPath:s});else{r.stop("IPA uploaded to TestFlight");try{le.unlinkSync(s)}catch{}u({apiKeyJsonPath:null})}}),g.on("error",m=>{try{le.unlinkSync(s)}catch{}r.stop("Pilot execution error"),p(m)})})}async function Bo(e,n,t="internal",i){let o=st();o.start(`Uploading to Google Play ${t} track (supply)...`);let r=["supply","--aab",e,"--json_key",n,"--track",t];if(i&&i!=="*"&&r.push("--package_name",i),Fo("fastlane",r,{stdio:"inherit",env:process.env}).status!==0)throw o.stop("Supply failed"),new Error("fastlane supply execution failed");o.stop(`AAB uploaded to ${t} track`)}function Ko(e){try{le.existsSync(e)&&le.rmSync(e,{recursive:!0,force:!0})}catch{}}function ge(e){console.log(ne.red(`\u274C ${e}`))}function ve(e){console.log(ne.gray(`\u2022 ${e}`))}function Fi(e){console.log(ne.green(`\u2713 ${e}`))}import{spinner as Vo,log as Me,outro as zo}from"@clack/prompts";import Zt from"chalk";import ji from"fs";import Wo from"path";import{execSync as Yo}from"child_process";import qo from"adm-zip";import Jo from"axios";import{randomUUID as Xo}from"crypto";async function Bi(e){Me.info(Zt.magenta("\u{1F680} Starting Over-The-Air (OTA) Update via Mach..."));let n=Ne();(!n||!n.projectId)&&(Me.error(`No ${f.configFileName} found or missing projectId. Run \`mach link\` first.`),process.exit(1));let t=n.projectId,i=e.branch||"production",o="1.0.0";try{o=JSON.parse(ji.readFileSync("./package.json","utf-8")).version||"1.0.0"}catch{Me.warn("Could not read package.json version. Defaulting to 1.0.0")}let r=Vo();r.start(`Compiling JavaScript bundles for OTA (Channel: ${i}, Runtime: ${o})...`);try{Yo("npx expo export --platform all",{stdio:"ignore"})}catch(l){r.stop("Compilation failed."),Me.error(`Failed to export JS bundles using Expo: ${l.message}`),process.exit(1)}r.message("Zipping artifact payload...");let a=Wo.join(process.cwd(),"dist");ji.existsSync(a)||(r.stop("Missing dist folder."),Me.error("The `dist` directory was not created. Export failed."),process.exit(1));let c=new qo;c.addLocalFolder(a,"dist");let s=c.toBuffer();r.message("Uploading payload to Mach Cloud...");try{let l=Xo(),d=await _.post("/builds/source-upload-url",{projectId:t,buildId:l});if(d.data.status!=="success")throw new Error("Could not secure upload bucket URL");let{uploadUrl:u,key:p}=d.data;await Jo.put(u,s,{headers:{"Content-Type":"application/zip"},maxBodyLength:1/0,maxContentLength:1/0}),r.message(`Promoting Update to ${i}...`),await _.post("/updates/publish",{projectId:t,channelName:i,runtimeVersion:o,platform:"android",updateId:`${l}-android`,manifestKey:p}),await _.post("/updates/publish",{projectId:t,channelName:i,runtimeVersion:o,platform:"ios",updateId:`${l}-ios`,manifestKey:p}),r.stop("Update Live!"),zo(Zt.green(`\u2713 OTA Update natively shipped to the '${i}' channel.`)),Me.info(Zt.dim(`Any app running runtime '${o}' will download this bundle smoothly.`))}catch(l){r.stop("Update failed during Cloud Sync."),Me.error(`Upload error: ${l.message}`),process.exit(1)}}import{intro as Zo,outro as Ki,log as Ve}from"@clack/prompts";import Re from"chalk";async function Vi(){Zo(Re.blue(`${f.name} CLI - User Profile`));let e=ue();if(!e){Ve.warn(Re.yellow("You are not logged in.")),Ve.info(`Run \`${f.nameLower} login\` to authenticate.`),Ki();return}Ve.info(`${Re.bold("Logged in as:")} ${Re.green(e.email)}`);try{await _.get("/projects");let t=ue().token.split(".");if(t.length===3){let i=JSON.parse(Buffer.from(t[1],"base64").toString());if(i.exp){let o=new Date(i.exp*1e3),r=new Date,a=o.getTime()-r.getTime();if(a>0){let c=Math.round(a/6e4),s=(c/60).toFixed(1);Ve.info(`${Re.bold("Token status:")} Valid (Expires in ~${s}h / ${c}m)`)}else Ve.warn(`${Re.bold("Token status:")} ${Re.red("Expired")} (Auto-refresh failed)`)}}}catch{Ve.warn(`${Re.bold("Token status:")} ${Re.red("Unreachable")} (Session might be truly expired)${gt}`)}Ki(Re.blue("---"))}import{spawn as ir}from"child_process";import{log as xe}from"@clack/prompts";import ze from"chalk";import nr from"fs";import Qo from"net";async function er(e){return new Promise(n=>{let t=Qo.createServer();t.once("error",i=>{i.code==="EADDRINUSE"?n(!0):n(!1)}),t.once("listening",()=>{t.close(),n(!1)}),t.listen(e,"0.0.0.0")})}async function zi(e,n=20){let t=e;for(;t<e+n;){if(!await er(t))return t;t++}throw new Error(`Could not find an available port after ${n} attempts starting from ${e}.`)}import{execSync as at}from"child_process";import{log as Qt}from"@clack/prompts";import ei from"chalk";async function Wi(e){return e.platform==="ios"?Yi(e.url):tr(e.url)}async function Yi(e){try{let n=at("xcrun simctl list devices booted --json").toString(),t=JSON.parse(n),i=null;for(let o in t.devices){let r=t.devices[o].find(a=>a.state==="Booted");if(r){i=r.udid;break}}if(!i)return Qt.info(ei.dim("No booted simulator found. Launching default simulator...")),at("open -a Simulator"),await new Promise(o=>setTimeout(o,3e3)),Yi(e);Qt.info(ei.dim(`Opening deep link on iOS Simulator (${i})...`)),at(`xcrun simctl openurl ${i} "${e}"`)}catch(n){throw new Error(`Failed to launch iOS Simulator: ${n.message}`)}}async function tr(e){try{let n=at("adb devices").toString().split(`
808
- `).filter(o=>o.includes(" device")).map(o=>o.split(" ")[0]);if(n.length===0)throw new Error("No Android devices or emulators found.");let t=n[0];Qt.info(ei.dim(`Opening deep link on Android Device (${t})...`));let i=`adb -s ${t} shell am start -a android.intent.action.VIEW -d "${e}"`;at(i)}catch(n){throw new Error(`Failed to launch Android: ${n.message}`)}}var qi=async e=>{xe.info(ze.blue(`Starting ${f.name} Dev Orchestrator...`));let n=Ne(),t=e.buildProfile||"development",i=n?Ue(n,t):null,o={...process.env};if(n?.projectId)try{xe.info(ze.dim(`Fetching managed secrets for profile: ${t}...`));let m=await _.get(`/projects/${n.projectId}/secrets/export?env=${t}`);m.data?.status==="success"&&m.data.secrets&&(Object.assign(o,m.data.secrets),xe.info(ze.magenta(`\u2713 Injected secrets from ${f.name} Dashboard.`)))}catch{xe.warn("Could not fetch managed secrets. Running with local env only.")}n&&Object.assign(o,je(n,f.envPrefix)),i&&(Object.assign(o,je(i,`${f.envPrefix}PROFILE_`)),i.env&&Object.assign(o,i.env));let r=!1;try{let m=JSON.parse(nr.readFileSync("package.json","utf-8"));r=!!(m.dependencies?.expo||m.devDependencies?.expo)}catch{xe.warn("Could not parse package.json. Defaulting to Bare React Native mode.")}let a=Number(e.port||i?.port||8081),c=await zi(a);c!==a&&xe.info(ze.yellow(`Port ${a} is busy. ${f.name} is using ${c} instead.`));let s="npx",l=[];r?(l=["expo","start","--port",String(c)],e.clear&&l.push("--clear"),e.tunnel&&l.push("--tunnel"),e.lan&&l.push("--lan"),e.localhost&&l.push("--localhost")):(l=["react-native","start","--port",String(c)],e.clear&&l.push("--clear"));let d=ir(s,l,{stdio:["inherit","pipe","pipe"],shell:!0,env:o}),u=!1,p="127.0.0.1",g=m=>{let h=m.toString(),$=h.match(/http:\/\/(.+):(\d+)/);if($&&!u&&(p=$[1],u=!0,e.ios||e.android)){let N=e.ios?"ios":"android",x=`exp+${n?.scheme||f.nameLower}://expo-development-client/?url=http%3A%2F%2F${p}%3A${c}`;xe.info(ze.magenta(`\u{1F680} ${f.name} is launching ${n?.name||"app"} on ${N==="ios"?"iOS":"Android"}...`)),Wi({platform:N,url:x}).catch(H=>xe.error(ze.red(`Launch failed: ${H.message}`)))}return h.includes("Starting project")||h.includes("Using src/app")||h.includes("Starting Metro Bundler")||h.includes("Opening exp+")||h.includes("Input is required")?null:h};return d.stdout?.on("data",m=>{let h=g(m);h&&process.stdout.write(h)}),d.stderr?.on("data",m=>{let h=g(m);h&&process.stderr.write(h)}),new Promise((m,h)=>{d.on("exit",$=>{$===0?m():h(new Error(`Dev server exited with code ${$}`))}),d.on("error",$=>{h($)})})};import{log as pe}from"@clack/prompts";import Ie from"chalk";var Ji=async e=>{let n=Ne();n||(pe.error(Ie.red(`No ${f.configFileName} found in the current directory.`)),process.exit(1));let t=e.profile||"development",i=Ue(n,t);if(e.json){console.log(JSON.stringify({project:n,resolved:i},null,2));return}pe.info(Ie.bgBlue.white(` Resolved ${f.name} Config [${t}] `)),pe.info(Ie.dim("----------------------------------------")),pe.info(`${Ie.blue("Project ID:")} ${n.projectId}`),pe.info(`${Ie.blue("Name:")} ${n.name}`),pe.info(`${Ie.blue("Scheme:")} ${n.scheme}`),i?(pe.info(Ie.dim(`
809
- Profile Settings:`)),pe.info(`${Ie.cyan("Distribution:")} ${i.distribution||"none"}`),pe.info(`${Ie.cyan("Development Client:")} ${i.developmentClient||"false"}`),i.env&&Object.keys(i.env).length>0&&(pe.info(Ie.dim(`
810
- Environment Variables:`)),Object.entries(i.env).forEach(([o,r])=>{pe.info(` ${o}=${r}`)}))):pe.warn(`Profile '${t}' not found.`),pe.info(Ie.dim("----------------------------------------"))};import{log as be,spinner as dt,text as Xi,select as Zi,confirm as or,isCancel as ct,cancel as lt,outro as ut,note as rr}from"@clack/prompts";import z from"chalk";import{execSync as sr}from"child_process";async function ar(){try{let e=sr("xcrun devicectl list devices --json-output -",{stdio:["pipe","pipe","pipe"]}).toString();return(JSON.parse(e).result?.devices||[]).filter(i=>i.connectionProperties?.transportType==="wired"||i.connectionProperties?.transportType==="localNetwork").map(i=>({udid:i.identifier,name:i.deviceProperties?.name||"Unknown Device",model:i.hardwareProperties?.marketingName||"iPhone"}))}catch{return[]}}async function cr(e){let n=e.udid,t=e.name,i="";if(!n){let r=dt();r.start("Scanning for connected iOS devices...");let a=await ar();if(r.stop(a.length>0?`Found ${a.length} device(s)`:"No devices detected"),a.length===1)n=a[0].udid,t=t||a[0].name,i=a[0].model,be.info(`Detected: ${z.bold(t)} (${z.dim(n.substring(0,12)+"...")})`);else if(a.length>1){let c=await Zi({message:"Select a device to register:",options:a.map(l=>({value:l.udid,label:`${l.name} (${l.model})`,hint:l.udid.substring(0,12)+"..."}))});if(ct(c)){lt("Cancelled");return}n=c;let s=a.find(l=>l.udid===n);t=t||s.name,i=s.model}else{be.info(z.dim("No connected devices found. Enter UDID manually."));let c=await Xi({message:"Device UDID:",placeholder:"00008101-XXXXXXXXXXXX",validate(s){if(s.length<10)return"UDID seems too short"}});if(ct(c)){lt("Cancelled");return}n=c}}if(!t){let r=await Xi({message:"Device name:",placeholder:"Nitesh's iPhone",validate(a){if(a.length===0)return"Name is required"}});if(ct(r)){lt("Cancelled");return}t=r}let o=dt();o.start("Registering device...");try{await _.post("/devices",{udid:n,name:t,platform:"ios",model:i||void 0,addedVia:"cli"}),o.stop(z.green("Device registered!")),be.info(` ${z.bold("Name:")} ${t}`),be.info(` ${z.bold("UDID:")} ${z.dim(n)}`)}catch(r){o.stop(z.red("Failed to register device")),be.error(r.response?.data?.message||r.message)}ut(z.blue("---"))}async function lr(){let e=dt();e.start("Fetching registered devices...");try{let t=(await _.get("/devices")).data.devices||[];if(e.stop(`${t.length} device(s) registered`),t.length===0){be.info(z.dim(`No devices registered yet. Run \`${f.nameLower} device register\` to add one.`)),ut(z.blue("---"));return}let i=t.map(o=>{let r=new Date(o.createdAt).toLocaleDateString();return` ${z.bold(o.name.padEnd(24))} ${z.dim(o.udid.padEnd(28))} ${z.cyan(o.addedVia.padEnd(10))} ${z.dim(r)}`});rr(` ${z.bold("Name".padEnd(24))} ${"UDID".padEnd(28)} ${"Via".padEnd(10)} Date
806
+ -----END PRIVATE KEY-----`}console.log(re.yellow(`
807
+ [DIAGNOSTIC] Key ID: ${i}`)),console.log(re.yellow(`[DIAGNOSTIC] Issuer ID: ${t}`)),console.log(re.yellow(`[DIAGNOSTIC] Key Checksum (Start): ${c.substring(0,45).replace(/\n/g,"\\n")}`)),console.log(re.yellow(`[DIAGNOSTIC] Key Checksum (End): ${c.substring(c.length-28).replace(/\n/g,"\\n")}
808
+ `)),r.start("Uploading to TestFlight (pilot)...");let s=Ve.join(Zt.tmpdir(),`api_key_${i}.json`),l={key_id:i,issuer_id:t,key:c,in_house:!1};de.writeFileSync(s,JSON.stringify(l,null,2));let d={...process.env};return new Promise((u,p)=>{let g=Fo("fastlane",["pilot","upload","--ipa",e,"--api_key_path",s,"--skip_submission","true","--skip_waiting_for_build_processing","true"],{stdio:"inherit",env:d});g.on("close",m=>{if(m!==0)r.stop("Pilot failed"),u({apiKeyJsonPath:s});else{r.stop("IPA uploaded to TestFlight");try{de.unlinkSync(s)}catch{}u({apiKeyJsonPath:null})}}),g.on("error",m=>{try{de.unlinkSync(s)}catch{}r.stop("Pilot execution error"),p(m)})})}async function Ko(e,n,t="internal",i){let o=st();o.start(`Uploading to Google Play ${t} track (supply)...`);let r=["supply","--aab",e,"--json_key",n,"--track",t];if(i&&i!=="*"&&r.push("--package_name",i),Ho("fastlane",r,{stdio:"inherit",env:process.env}).status!==0)throw o.stop("Supply failed"),new Error("fastlane supply execution failed");o.stop(`AAB uploaded to ${t} track`)}function Vo(e){try{de.existsSync(e)&&de.rmSync(e,{recursive:!0,force:!0})}catch{}}function ye(e){console.log(re.red(`\u274C ${e}`))}function ve(e){console.log(re.gray(`\u2022 ${e}`))}function Hi(e){console.log(re.green(`\u2713 ${e}`))}import{spinner as zo,log as Fe,outro as Wo}from"@clack/prompts";import Qt from"chalk";import Bi from"fs";import Yo from"path";import{execSync as Jo}from"child_process";import qo from"adm-zip";import Xo from"axios";import{randomUUID as Zo}from"crypto";async function Ki(e){Fe.info(Qt.magenta("\u{1F680} Starting Over-The-Air (OTA) Update via Mach..."));let n=ke();(!n||!n.projectId)&&(Fe.error(`No ${f.configFileName} found or missing projectId. Run \`mach link\` first.`),process.exit(1));let t=n.projectId,i=e.branch||"production",o="1.0.0";try{o=JSON.parse(Bi.readFileSync("./package.json","utf-8")).version||"1.0.0"}catch{Fe.warn("Could not read package.json version. Defaulting to 1.0.0")}let r=zo();r.start(`Compiling JavaScript bundles for OTA (Channel: ${i}, Runtime: ${o})...`);try{Jo("npx expo export --platform all",{stdio:"ignore"})}catch(l){r.stop("Compilation failed."),Fe.error(`Failed to export JS bundles using Expo: ${l.message}`),process.exit(1)}r.message("Zipping artifact payload...");let a=Yo.join(process.cwd(),"dist");Bi.existsSync(a)||(r.stop("Missing dist folder."),Fe.error("The `dist` directory was not created. Export failed."),process.exit(1));let c=new qo;c.addLocalFolder(a,"dist");let s=c.toBuffer();r.message("Uploading payload to Mach Cloud...");try{let l=Zo(),d=await D.post("/builds/source-upload-url",{projectId:t,buildId:l});if(d.data.status!=="success")throw new Error("Could not secure upload bucket URL");let{uploadUrl:u,key:p}=d.data;await Xo.put(u,s,{headers:{"Content-Type":"application/zip"},maxBodyLength:1/0,maxContentLength:1/0}),r.message(`Promoting Update to ${i}...`),await D.post("/updates/publish",{projectId:t,channelName:i,runtimeVersion:o,platform:"android",updateId:`${l}-android`,manifestKey:p}),await D.post("/updates/publish",{projectId:t,channelName:i,runtimeVersion:o,platform:"ios",updateId:`${l}-ios`,manifestKey:p}),r.stop("Update Live!"),Wo(Qt.green(`\u2713 OTA Update natively shipped to the '${i}' channel.`)),Fe.info(Qt.dim(`Any app running runtime '${o}' will download this bundle smoothly.`))}catch(l){r.stop("Update failed during Cloud Sync."),Fe.error(`Upload error: ${l.message}`),process.exit(1)}}import{intro as Qo,outro as Vi,log as ze}from"@clack/prompts";import Re from"chalk";async function zi(){Qo(Re.blue(`${f.name} CLI - User Profile`));let e=fe();if(!e){ze.warn(Re.yellow("You are not logged in.")),ze.info(`Run \`${f.nameLower} login\` to authenticate.`),Vi();return}ze.info(`${Re.bold("Logged in as:")} ${Re.green(e.email)}`);try{await D.get("/projects");let t=fe().token.split(".");if(t.length===3){let i=JSON.parse(Buffer.from(t[1],"base64").toString());if(i.exp){let o=new Date(i.exp*1e3),r=new Date,a=o.getTime()-r.getTime();if(a>0){let c=Math.round(a/6e4),s=(c/60).toFixed(1);ze.info(`${Re.bold("Token status:")} Valid (Expires in ~${s}h / ${c}m)`)}else ze.warn(`${Re.bold("Token status:")} ${Re.red("Expired")} (Auto-refresh failed)`)}}}catch{ze.warn(`${Re.bold("Token status:")} ${Re.red("Unreachable")} (Session might be truly expired)${yt}`)}Vi(Re.blue("---"))}import{spawn as nr}from"child_process";import{log as Le}from"@clack/prompts";import We from"chalk";import or from"fs";import er from"net";async function tr(e){return new Promise(n=>{let t=er.createServer();t.once("error",i=>{i.code==="EADDRINUSE"?n(!0):n(!1)}),t.once("listening",()=>{t.close(),n(!1)}),t.listen(e,"0.0.0.0")})}async function Wi(e,n=20){let t=e;for(;t<e+n;){if(!await tr(t))return t;t++}throw new Error(`Could not find an available port after ${n} attempts starting from ${e}.`)}import{execSync as at}from"child_process";import{log as ei}from"@clack/prompts";import ti from"chalk";async function Yi(e){return e.platform==="ios"?Ji(e.url):ir(e.url)}async function Ji(e){try{let n=at("xcrun simctl list devices booted --json").toString(),t=JSON.parse(n),i=null;for(let o in t.devices){let r=t.devices[o].find(a=>a.state==="Booted");if(r){i=r.udid;break}}if(!i)return ei.info(ti.dim("No booted simulator found. Launching default simulator...")),at("open -a Simulator"),await new Promise(o=>setTimeout(o,3e3)),Ji(e);ei.info(ti.dim(`Opening deep link on iOS Simulator (${i})...`)),at(`xcrun simctl openurl ${i} "${e}"`)}catch(n){throw new Error(`Failed to launch iOS Simulator: ${n.message}`)}}async function ir(e){try{let n=at("adb devices").toString().split(`
809
+ `).filter(o=>o.includes(" device")).map(o=>o.split(" ")[0]);if(n.length===0)throw new Error("No Android devices or emulators found.");let t=n[0];ei.info(ti.dim(`Opening deep link on Android Device (${t})...`));let i=`adb -s ${t} shell am start -a android.intent.action.VIEW -d "${e}"`;at(i)}catch(n){throw new Error(`Failed to launch Android: ${n.message}`)}}var qi=async e=>{Le.info(We.blue(`Starting ${f.name} Dev Orchestrator...`));let n=ke(),t=e.buildProfile||"development",i=n?Me(n,t):null,o={...process.env};if(n?.projectId)try{Le.info(We.dim(`Fetching managed secrets for profile: ${t}...`));let m=await D.get(`/projects/${n.projectId}/secrets/export?env=${t}`);m.data?.status==="success"&&m.data.secrets&&(Object.assign(o,m.data.secrets),Le.info(We.magenta(`\u2713 Injected secrets from ${f.name} Dashboard.`)))}catch{Le.warn("Could not fetch managed secrets. Running with local env only.")}n&&Object.assign(o,Be(n,f.envPrefix)),i&&(Object.assign(o,Be(i,`${f.envPrefix}PROFILE_`)),i.env&&Object.assign(o,i.env));let r=!1;try{let m=JSON.parse(or.readFileSync("package.json","utf-8"));r=!!(m.dependencies?.expo||m.devDependencies?.expo)}catch{Le.warn("Could not parse package.json. Defaulting to Bare React Native mode.")}let a=Number(e.port||i?.port||8081),c=await Wi(a);c!==a&&Le.info(We.yellow(`Port ${a} is busy. ${f.name} is using ${c} instead.`));let s="npx",l=[];r?(l=["expo","start","--port",String(c)],e.clear&&l.push("--clear"),e.tunnel&&l.push("--tunnel"),e.lan&&l.push("--lan"),e.localhost&&l.push("--localhost")):(l=["react-native","start","--port",String(c)],e.clear&&l.push("--clear"));let d=nr(s,l,{stdio:["inherit","pipe","pipe"],shell:!0,env:o}),u=!1,p="127.0.0.1",g=m=>{let h=m.toString(),P=h.match(/http:\/\/(.+):(\d+)/);if(P&&!u&&(p=P[1],u=!0,e.ios||e.android)){let k=e.ios?"ios":"android",x=`exp+${n?.scheme||f.nameLower}://expo-development-client/?url=http%3A%2F%2F${p}%3A${c}`;Le.info(We.magenta(`\u{1F680} ${f.name} is launching ${n?.name||"app"} on ${k==="ios"?"iOS":"Android"}...`)),Yi({platform:k,url:x}).catch(H=>Le.error(We.red(`Launch failed: ${H.message}`)))}return h.includes("Starting project")||h.includes("Using src/app")||h.includes("Starting Metro Bundler")||h.includes("Opening exp+")||h.includes("Input is required")?null:h};return d.stdout?.on("data",m=>{let h=g(m);h&&process.stdout.write(h)}),d.stderr?.on("data",m=>{let h=g(m);h&&process.stderr.write(h)}),new Promise((m,h)=>{d.on("exit",P=>{P===0?m():h(new Error(`Dev server exited with code ${P}`))}),d.on("error",P=>{h(P)})})};import{log as me}from"@clack/prompts";import Ie from"chalk";var Xi=async e=>{let n=ke();n||(me.error(Ie.red(`No ${f.configFileName} found in the current directory.`)),process.exit(1));let t=e.profile||"development",i=Me(n,t);if(e.json){console.log(JSON.stringify({project:n,resolved:i},null,2));return}me.info(Ie.bgBlue.white(` Resolved ${f.name} Config [${t}] `)),me.info(Ie.dim("----------------------------------------")),me.info(`${Ie.blue("Project ID:")} ${n.projectId}`),me.info(`${Ie.blue("Name:")} ${n.name}`),me.info(`${Ie.blue("Scheme:")} ${n.scheme}`),i?(me.info(Ie.dim(`
810
+ Profile Settings:`)),me.info(`${Ie.cyan("Distribution:")} ${i.distribution||"none"}`),me.info(`${Ie.cyan("Development Client:")} ${i.developmentClient||"false"}`),i.env&&Object.keys(i.env).length>0&&(me.info(Ie.dim(`
811
+ Environment Variables:`)),Object.entries(i.env).forEach(([o,r])=>{me.info(` ${o}=${r}`)}))):me.warn(`Profile '${t}' not found.`),me.info(Ie.dim("----------------------------------------"))};import{log as be,spinner as dt,text as Zi,select as Qi,confirm as rr,isCancel as ct,cancel as lt,outro as ut,note as sr}from"@clack/prompts";import Y from"chalk";import{execSync as ar}from"child_process";async function cr(){try{let e=ar("xcrun devicectl list devices --json-output -",{stdio:["pipe","pipe","pipe"]}).toString();return(JSON.parse(e).result?.devices||[]).filter(i=>i.connectionProperties?.transportType==="wired"||i.connectionProperties?.transportType==="localNetwork").map(i=>({udid:i.identifier,name:i.deviceProperties?.name||"Unknown Device",model:i.hardwareProperties?.marketingName||"iPhone"}))}catch{return[]}}async function lr(e){let n=e.udid,t=e.name,i="";if(!n){let r=dt();r.start("Scanning for connected iOS devices...");let a=await cr();if(r.stop(a.length>0?`Found ${a.length} device(s)`:"No devices detected"),a.length===1)n=a[0].udid,t=t||a[0].name,i=a[0].model,be.info(`Detected: ${Y.bold(t)} (${Y.dim(n.substring(0,12)+"...")})`);else if(a.length>1){let c=await Qi({message:"Select a device to register:",options:a.map(l=>({value:l.udid,label:`${l.name} (${l.model})`,hint:l.udid.substring(0,12)+"..."}))});if(ct(c)){lt("Cancelled");return}n=c;let s=a.find(l=>l.udid===n);t=t||s.name,i=s.model}else{be.info(Y.dim("No connected devices found. Enter UDID manually."));let c=await Zi({message:"Device UDID:",placeholder:"00008101-XXXXXXXXXXXX",validate(s){if(s.length<10)return"UDID seems too short"}});if(ct(c)){lt("Cancelled");return}n=c}}if(!t){let r=await Zi({message:"Device name:",placeholder:"Nitesh's iPhone",validate(a){if(a.length===0)return"Name is required"}});if(ct(r)){lt("Cancelled");return}t=r}let o=dt();o.start("Registering device...");try{await D.post("/devices",{udid:n,name:t,platform:"ios",model:i||void 0,addedVia:"cli"}),o.stop(Y.green("Device registered!")),be.info(` ${Y.bold("Name:")} ${t}`),be.info(` ${Y.bold("UDID:")} ${Y.dim(n)}`)}catch(r){o.stop(Y.red("Failed to register device")),be.error(r.response?.data?.message||r.message)}ut(Y.blue("---"))}async function dr(){let e=dt();e.start("Fetching registered devices...");try{let t=(await D.get("/devices")).data.devices||[];if(e.stop(`${t.length} device(s) registered`),t.length===0){be.info(Y.dim(`No devices registered yet. Run \`${f.nameLower} device register\` to add one.`)),ut(Y.blue("---"));return}let i=t.map(o=>{let r=new Date(o.createdAt).toLocaleDateString();return` ${Y.bold(o.name.padEnd(24))} ${Y.dim(o.udid.padEnd(28))} ${Y.cyan(o.addedVia.padEnd(10))} ${Y.dim(r)}`});sr(` ${Y.bold("Name".padEnd(24))} ${"UDID".padEnd(28)} ${"Via".padEnd(10)} Date
811
812
  `+i.join(`
812
- `),"Registered Devices")}catch(n){e.stop(z.red("Failed to fetch devices")),be.error(n.response?.data?.message||n.message)}ut(z.blue("---"))}async function dr(e){let n=e.udid;if(!n){let o=dt();o.start("Fetching registered devices...");try{let a=(await _.get("/devices")).data.devices||[];if(o.stop(`${a.length} device(s) found`),a.length===0){be.info(z.dim("No devices to remove.")),ut(z.blue("---"));return}let c=await Zi({message:"Select device to remove:",options:a.map(s=>({value:s.udid,label:s.name,hint:s.udid.substring(0,12)+"..."}))});if(ct(c)){lt("Cancelled");return}n=c}catch(r){o.stop(z.red("Failed to fetch devices")),be.error(r.response?.data?.message||r.message);return}}let t=await or({message:`Remove device ${z.dim(n.substring(0,12)+"...")}?`});if(ct(t)||!t){lt("Cancelled");return}let i=dt();i.start("Removing device...");try{await _.delete(`/devices/${encodeURIComponent(n)}`),i.stop(z.green("Device removed"))}catch(o){i.stop(z.red("Failed to remove device")),be.error(o.response?.data?.message||o.message)}ut(z.blue("---"))}async function _t(e,n){switch(e){case"register":await cr(n);break;case"list":await lr();break;case"remove":await dr(n);break;default:be.error(`Unknown action: ${e}`)}}import{log as ye,spinner as vn}from"@clack/prompts";import Pe from"chalk";import xt from"path";import mt from"fs";import Kr from"os";import Vr from"axios";var he=(r=>(r.CRITICAL="critical",r.HIGH="high",r.MEDIUM="medium",r.LOW="low",r.INFO="info",r))(he||{}),$e=(s=>(s.PERMISSIONS="permissions",s.SECRETS="secrets",s.DEPENDENCIES="dependencies",s.STORAGE="storage",s.NETWORK="network",s.DEBUG="debug",s.MANIFEST="manifest",s.ATS="ats",s))($e||{});import{spinner as Sn,log as ft}from"@clack/prompts";import fe from"chalk";import{execSync as kr}from"child_process";import An from"fs";import En from"path";import Le from"fs";import pt from"path";import{execSync as ur}from"child_process";var Qi={"android.permission.READ_PHONE_STATE":{severity:"high",description:"Can read phone number, IMEI, carrier info"},"android.permission.CALL_PHONE":{severity:"high",description:"Can make calls without user interaction"},"android.permission.SEND_SMS":{severity:"high",description:"Can send SMS without user interaction"},"android.permission.READ_SMS":{severity:"high",description:"Can read user SMS messages"},"android.permission.READ_CONTACTS":{severity:"medium",description:"Can read user contacts"},"android.permission.WRITE_CONTACTS":{severity:"medium",description:"Can modify user contacts"},"android.permission.READ_CALL_LOG":{severity:"high",description:"Can read call history"},"android.permission.CAMERA":{severity:"medium",description:"Camera access"},"android.permission.RECORD_AUDIO":{severity:"medium",description:"Microphone access"},"android.permission.ACCESS_FINE_LOCATION":{severity:"medium",description:"Precise GPS location"},"android.permission.ACCESS_COARSE_LOCATION":{severity:"medium",description:"Approximate location"},"android.permission.ACCESS_BACKGROUND_LOCATION":{severity:"high",description:"Background location tracking"},"android.permission.READ_EXTERNAL_STORAGE":{severity:"medium",description:"Read files on device"},"android.permission.WRITE_EXTERNAL_STORAGE":{severity:"medium",description:"Write files on device"},"android.permission.READ_MEDIA_IMAGES":{severity:"low",description:"Read photos"},"android.permission.READ_MEDIA_VIDEO":{severity:"low",description:"Read videos"},"android.permission.SYSTEM_ALERT_WINDOW":{severity:"high",description:"Draw overlays on other apps"},"android.permission.REQUEST_INSTALL_PACKAGES":{severity:"high",description:"Can install APKs"}},pr={NSCameraUsageDescription:{severity:"medium",description:"Camera access declared"},NSMicrophoneUsageDescription:{severity:"medium",description:"Microphone access declared"},NSLocationWhenInUseUsageDescription:{severity:"medium",description:"Location (in-use) declared"},NSLocationAlwaysUsageDescription:{severity:"high",description:"Background location declared"},NSContactsUsageDescription:{severity:"medium",description:"Contacts access declared"},NSCalendarsUsageDescription:{severity:"low",description:"Calendar access declared"},NSPhotoLibraryUsageDescription:{severity:"low",description:"Photo library access declared"}};function fr(e){try{let t=ur("npx expo config --type introspect --json 2>/dev/null",{cwd:e,encoding:"utf-8",timeout:3e4});return JSON.parse(t)}catch{}let n=pt.join(e,"app.json");if(Le.existsSync(n))try{let t=JSON.parse(Le.readFileSync(n,"utf-8"));return t.expo||t}catch{}return null}function mr(e){let n=[],t=pt.join(e,"node_modules");if(!Le.existsSync(t))return n;let i=/<uses-permission\s+android:name="([^"]+)"/g;function o(r,a){let c=pt.join(r,"android","src","main","AndroidManifest.xml");if(!Le.existsSync(c))return;let s=Le.readFileSync(c,"utf-8"),l;for(;(l=i.exec(s))!==null;)n.push({pkg:a,permission:l[1]});i.lastIndex=0}for(let r of Le.readdirSync(t)){if(r.startsWith("."))continue;let a=pt.join(t,r);if(r.startsWith("@")){if(!Le.statSync(a).isDirectory())continue;for(let c of Le.readdirSync(a))o(pt.join(a,c),`${r}/${c}`)}else o(a,r)}return n}async function en(e,n){let t=[],i=1,o=fr(e),r=o?.android?.permissions||[],a=o?.android?.blockedPermissions||[];for(let l of r){let d=Qi[l];d&&t.push({id:`PERM-${String(i++).padStart(3,"0")}`,title:`${l.split(".").pop()} declared`,description:d.description,severity:d.severity,category:"permissions",file:"app.config.ts",recommendation:"Remove from permissions if not needed, or add justification."})}let c=mr(e);for(let{pkg:l,permission:d}of c){let u=Qi[d];u&&(a.includes(d)||r.includes(d)||t.push({id:`PERM-${String(i++).padStart(3,"0")}`,title:`${d.split(".").pop()} injected by ${l}`,description:`${u.description}. Auto-injected via ${l} AndroidManifest.xml`,severity:u.severity,category:"permissions",file:`node_modules/${l}/android/src/main/AndroidManifest.xml`,recommendation:`Add "${d}" to blockedPermissions if not needed.`,autoFixable:!0}))}let s=o?.ios?.infoPlist||{};for(let[l,d]of Object.entries(pr))l in s&&t.push({id:`PERM-${String(i++).padStart(3,"0")}`,title:`iOS: ${l} declared`,description:d.description,severity:d.severity,category:"permissions",file:"app.config.ts",recommendation:`Remove ${l} from infoPlist if the app does not use this capability.`});return{category:"permissions",label:"Permission Audit",findings:t,durationMs:0}}import ti from"fs";import Dt from"path";var gr=[{id:"SEC-001",pattern:/(['"`])(?:sk|pk)_(?:live|test)_[a-zA-Z0-9]{20,}\1/g,severity:"critical",label:"Stripe API Key"},{id:"SEC-002",pattern:/(['"`])AIza[0-9A-Za-z\-_]{35}\1/g,severity:"high",label:"Google API Key"},{id:"SEC-003",pattern:/(['"`])AKIA[0-9A-Z]{16}\1/g,severity:"critical",label:"AWS Access Key ID"},{id:"SEC-004",pattern:/-----BEGIN (?:RSA |EC )?PRIVATE KEY-----/g,severity:"critical",label:"Private key in source"},{id:"SEC-005",pattern:/(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9_]{36,}/g,severity:"high",label:"GitHub Token"},{id:"SEC-006",pattern:/xox[bpors]-[a-zA-Z0-9-]{10,}/g,severity:"high",label:"Slack Token"},{id:"SEC-007",pattern:/(?:password|secret|apikey|api_key)\s*[:=]\s*['"`][^'"`\n]{8,}['"`]/gi,severity:"high",label:"Hardcoded credential"}],hr=new Set([".ts",".tsx",".js",".jsx"]),yr=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function tn(e){let n=[],t=ti.readdirSync(e,{withFileTypes:!0});for(let i of t){if(yr.has(i.name))continue;let o=Dt.join(e,i.name);i.isDirectory()?n.push(...tn(o)):hr.has(Dt.extname(i.name))&&n.push(o)}return n}function Sr(e){let n=e.trim();return n.startsWith("//")||n.startsWith("*")||n.startsWith("/*")}function Ar(e){return/process\.env\./i.test(e)||/import\.meta\.env/i.test(e)}async function nn(e,n){let t=[],i=Dt.join(e,"src"),o=ti.existsSync(i)?i:e,r=tn(o);for(let a of r){let s=ti.readFileSync(a,"utf-8").split(`
813
- `),l=Dt.relative(e,a);for(let d=0;d<s.length;d++){let u=s[d];if(!Sr(u)&&!Ar(u))for(let{id:p,pattern:g,severity:m,label:h}of gr)g.lastIndex=0,g.test(u)&&t.push({id:p,title:h,description:`Potential ${h.toLowerCase()} found in source code`,severity:m,category:"secrets",file:l,line:d+1,recommendation:`Move to environment variables or a secrets manager. Use \`${f.nameLower} env set\` for managed secrets.`})}}return{category:"secrets",label:"Secrets Detection",findings:t,durationMs:0}}import{execSync as Er}from"child_process";var Ir={critical:"critical",high:"high",moderate:"medium",low:"low",info:"info"};async function on(e,n){let t=[],i=1,o;try{o=Er("npm audit --json 2>/dev/null",{cwd:e,encoding:"utf-8",timeout:6e4})}catch(c){if(o=c.stdout||"",!o)return{category:"dependencies",label:"Dependency CVEs",findings:[],durationMs:0,error:"Failed to run npm audit. Ensure npm is available and dependencies are installed."}}let r;try{r=JSON.parse(o)}catch{return{category:"dependencies",label:"Dependency CVEs",findings:[],durationMs:0,error:"Failed to parse npm audit output."}}let a=r.vulnerabilities||{};for(let[c,s]of Object.entries(a)){let l=Ir[s.severity]||"info",d=Array.isArray(s.via)?s.via.map(u=>typeof u=="string"?u:u.title||u.name).join(", "):String(s.via);t.push({id:`DEP-${String(i++).padStart(3,"0")}`,title:`${c} \u2014 ${s.severity}`,description:`Via: ${d}. Range: ${s.range||"unknown"}`,severity:l,category:"dependencies",recommendation:s.fixAvailable?`Run \`npm audit fix\` or update ${c} to a patched version.`:"No fix available yet. Monitor for updates or evaluate alternatives.",autoFixable:!!s.fixAvailable})}return{category:"dependencies",label:"Dependency CVEs",findings:t,durationMs:0}}import wt from"fs";import vt from"path";var br=/(?:token|password|credential|secret|apiKey|api_key|session|auth|jwt|refresh_token|access_token|private_key|pin|otp)/i,rn=/AsyncStorage\s*\.\s*(?:setItem|mergeItem)\s*\(\s*['"`]([^'"`]+)['"`]/g,$r=/from\s+['"]@react-native-async-storage\/async-storage['"]|from\s+['"]react-native['"].*AsyncStorage/,Pr=new Set([".ts",".tsx",".js",".jsx"]),_r=new Set(["node_modules",".expo",".git","android","ios","dist","build"]);function sn(e){let n=[];if(!wt.existsSync(e))return n;let t=wt.readdirSync(e,{withFileTypes:!0});for(let i of t){if(_r.has(i.name))continue;let o=vt.join(e,i.name);i.isDirectory()?n.push(...sn(o)):Pr.has(vt.extname(i.name))&&n.push(o)}return n}async function an(e,n){let t=[],i=1,o=vt.join(e,"src"),r=wt.existsSync(o)?o:e,a=sn(r);for(let c of a){let s=wt.readFileSync(c,"utf-8");if(!$r.test(s))continue;let l=s.split(`
814
- `),d=vt.relative(e,c);for(let u=0;u<l.length;u++){let p=l[u];rn.lastIndex=0;let g;for(;(g=rn.exec(p))!==null;){let m=g[1];br.test(m)&&t.push({id:`STOR-${String(i++).padStart(3,"0")}`,title:`AsyncStorage used for "${m}"`,description:`Sensitive data key "${m}" stored in AsyncStorage (unencrypted).`,severity:"high",category:"storage",file:d,line:u+1,recommendation:"Use expo-secure-store (SecureStore) for sensitive data instead of AsyncStorage."})}}}return{category:"storage",label:"Insecure Storage",findings:t,durationMs:0}}import Rt from"fs";import Ot from"path";var cn=/['"`](http:\/\/(?!localhost|127\.0\.0\.1|10\.|192\.168\.|0\.0\.0\.0|172\.(?:1[6-9]|2\d|3[01])\.)[^'"`\s]+)['"`]/g,Dr=/\/api\/|\/v[0-9]+\/|\/graphql|\/rest\//i,wr=new Set([".ts",".tsx",".js",".jsx"]),vr=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function ln(e){let n=[];if(!Rt.existsSync(e))return n;let t=Rt.readdirSync(e,{withFileTypes:!0});for(let i of t){if(vr.has(i.name))continue;let o=Ot.join(e,i.name);i.isDirectory()?n.push(...ln(o)):wr.has(Ot.extname(i.name))&&n.push(o)}return n}async function dn(e,n){let t=[],i=1,o=Ot.join(e,"src"),r=Rt.existsSync(o)?o:e,a=ln(r);for(let c of a){let l=Rt.readFileSync(c,"utf-8").split(`
815
- `),d=Ot.relative(e,c);for(let u=0;u<l.length;u++){let p=l[u],g=p.trim();if(g.startsWith("//")||g.startsWith("*"))continue;cn.lastIndex=0;let m;for(;(m=cn.exec(p))!==null;){let h=m[1],$=Dr.test(h);t.push({id:`NET-${String(i++).padStart(3,"0")}`,title:`Insecure HTTP URL${$?" (API endpoint)":""}`,description:`Plain HTTP URL found: ${h}`,severity:$?"high":"medium",category:"network",file:d,line:u+1,recommendation:"Use HTTPS instead of HTTP for all network requests."})}}}return{category:"network",label:"HTTP URLs",findings:t,durationMs:0}}import Ct from"fs";import Tt from"path";var un=/(?:debug|debugMode|devMode|enableDebug)\s*[:=]\s*true/gi,pn=/console\.(?:log|warn|info|debug)\s*\([^)]*(?:token|password|secret|credential|key|auth)/gi,Rr=new Set([".ts",".tsx",".js",".jsx"]),Or=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function fn(e){let n=[];if(!Ct.existsSync(e))return n;let t=Ct.readdirSync(e,{withFileTypes:!0});for(let i of t){if(Or.has(i.name))continue;let o=Tt.join(e,i.name);i.isDirectory()?n.push(...fn(o)):Rr.has(Tt.extname(i.name))&&n.push(o)}return n}async function mn(e,n){let t=[],i=1,o=Tt.join(e,"src"),r=Ct.existsSync(o)?o:e,a=fn(r);for(let c of a){let l=Ct.readFileSync(c,"utf-8").split(`
816
- `),d=Tt.relative(e,c);for(let u=0;u<l.length;u++){let p=l[u],g=p.trim();if(!(g.startsWith("//")||g.startsWith("*"))&&(un.lastIndex=0,un.test(p)&&t.push({id:`DBG-${String(i++).padStart(3,"0")}`,title:"Hardcoded debug flag",description:"Debug/dev mode enabled in source code",severity:"medium",category:"debug",file:d,line:u+1,recommendation:"Use __DEV__ or environment variables instead of hardcoded debug flags."}),pn.lastIndex=0,pn.test(p))){let m=l.slice(Math.max(0,u-3),u).join(`
817
- `);/__DEV__/.test(m)||t.push({id:`DBG-${String(i++).padStart(3,"0")}`,title:"Sensitive data in console log",description:"Console log may expose sensitive data (token, password, etc.) in production",severity:"medium",category:"debug",file:d,line:u+1,recommendation:"Wrap in __DEV__ check or remove sensitive data from console output."})}}}return{category:"debug",label:"Debug/Dev Flags",findings:t,durationMs:0}}import gn from"fs";import ii from"path";var Cr=new Set(["androidx.work.impl.background.systemjob.SystemJobService","androidx.work.impl.diagnostics.DiagnosticsReceiver","com.google.firebase.iid.FirebaseInstanceIdReceiver","com.google.android.gms.auth.api.signin.RevocationBoundService","androidx.profileinstaller.ProfileInstallReceiver","com.google.firebase.messaging.FirebaseMessagingService","com.google.android.gms.measurement.AppMeasurementService","com.google.android.gms.measurement.AppMeasurementJobService"]);function Tr(e){let n=[ii.join(e,"android","app","src","main","AndroidManifest.xml"),ii.join(e,"android","AndroidManifest.xml")];for(let t of n)if(gn.existsSync(t))return t;return null}async function hn(e,n){let t=[],i=1,o=Tr(e);if(!o)return{category:"manifest",label:"Android Manifest",findings:[],durationMs:0,error:"No AndroidManifest.xml found. Run with --prebuild or run `expo prebuild` first."};let r=gn.readFileSync(o,"utf-8"),a=ii.relative(e,o),c=/<(activity|service|receiver|provider)\s+([^>]*?)(?:\/>|>)/gs,s;for(;(s=c.exec(r))!==null;){let l=s[1],d=s[2],p=d.match(/android:name="([^"]+)"/)?.[1]||"unknown";if(Cr.has(p))continue;let g=/android:exported="true"/.test(d),m=/android:permission="/.test(d);g&&!m&&t.push({id:`MAN-${String(i++).padStart(3,"0")}`,title:`Exported ${l}: ${p.split(".").pop()}`,description:`${p} is exported=true without android:permission protection`,severity:"medium",category:"manifest",file:a,recommendation:'Set android:exported="false" or add an android:permission attribute.'})}return/android:allowBackup="true"/.test(r)&&t.push({id:`MAN-${String(i++).padStart(3,"0")}`,title:"allowBackup is enabled",description:'android:allowBackup="true" allows data extraction via ADB backup',severity:"medium",category:"manifest",file:a,recommendation:'Set android:allowBackup="false" via expo-build-properties plugin.',autoFixable:!0}),/android:debuggable="true"/.test(r)&&t.push({id:`MAN-${String(i++).padStart(3,"0")}`,title:"App is debuggable",description:'android:debuggable="true" allows attaching a debugger in production',severity:"critical",category:"manifest",file:a,recommendation:"Ensure debuggable is false for production builds. This is usually set automatically for release builds."}),{category:"manifest",label:"Android Manifest",findings:t,durationMs:0}}import Nt from"fs";import ni from"path";function Nr(e){let n=ni.join(e,"ios");if(!Nt.existsSync(n))return null;let t=Nt.readdirSync(n,{withFileTypes:!0});for(let i of t){if(!i.isDirectory()||i.name==="Pods"||i.name.startsWith("."))continue;let o=ni.join(n,i.name,"Info.plist");if(Nt.existsSync(o))return o}return null}async function yn(e,n){let t=[],i=1,o=Nr(e);if(!o)return{category:"ats",label:"iOS ATS Config",findings:[],durationMs:0,error:"No Info.plist found. Run with --prebuild or run `expo prebuild` first."};let r=Nt.readFileSync(o,"utf-8"),a=ni.relative(e,o),c=r.match(/<key>NSAppTransportSecurity<\/key>\s*<dict>([\s\S]*?)<\/dict>/);if(c){let s=c[1];/<key>NSAllowsArbitraryLoads<\/key>\s*<true\s*\/>/.test(s)&&t.push({id:`ATS-${String(i++).padStart(3,"0")}`,title:"ATS disabled \u2014 NSAllowsArbitraryLoads",description:"App Transport Security is completely disabled. All HTTP connections are allowed.",severity:"critical",category:"ats",file:a,recommendation:"Remove NSAllowsArbitraryLoads or set to false. Use domain-specific exceptions only if absolutely necessary."});let l=s.match(/<key>NSExceptionDomains<\/key>\s*<dict>([\s\S]*?)<\/dict>/);if(l){let d=l[1].match(/<key>([^<]+)<\/key>/g);if(d)for(let u of d){let p=u.replace(/<\/?key>/g,"");p!=="NSExceptionDomains"&&t.push({id:`ATS-${String(i++).padStart(3,"0")}`,title:`ATS exception: ${p}`,description:`ATS exception configured for ${p}`,severity:"low",category:"ats",file:a,recommendation:`Verify that the ATS exception for ${p} is necessary. Use HTTPS where possible.`})}}}return{category:"ats",label:"iOS ATS Config",findings:t,durationMs:0}}var xr=[{category:"permissions",label:"Permission Audit",fn:en,requiresPrebuild:!1},{category:"secrets",label:"Secrets Detection",fn:nn,requiresPrebuild:!1},{category:"dependencies",label:"Dependency CVEs",fn:on,requiresPrebuild:!1},{category:"storage",label:"Insecure Storage",fn:an,requiresPrebuild:!1},{category:"network",label:"HTTP URLs",fn:dn,requiresPrebuild:!1},{category:"debug",label:"Debug/Dev Flags",fn:mn,requiresPrebuild:!1},{category:"manifest",label:"Android Manifest",fn:hn,requiresPrebuild:!0},{category:"ats",label:"iOS ATS Config",fn:yn,requiresPrebuild:!0}];async function In(e,n){let t=xr;n.category&&(t=t.filter(a=>a.category===n.category),t.length===0&&(ft.error(fe.red(`Unknown category: ${n.category}`)),ft.info(fe.dim(`Available: ${Object.values($e).join(", ")}`)),process.exit(1)));let i=t.filter(a=>!a.requiresPrebuild),o=t.filter(a=>a.requiresPrebuild),r=[];for(let a of i){let c=Sn();c.start(fe.dim(`Running ${a.label}...`));try{let s=Date.now(),l=await a.fn(e,n);l.durationMs=Date.now()-s,r.push(l);let d=l.findings.length;c.stop(d>0?fe.yellow(`${a.label} \u2014 ${d} finding(s)`):fe.green(`${a.label} \u2014 clean`))}catch(s){c.stop(fe.red(`${a.label} \u2014 error`)),r.push({category:a.category,label:a.label,findings:[],durationMs:0,error:s.message})}}if(o.length>0){let a=En.join(e,"android"),c=En.join(e,"ios"),s=An.existsSync(a)||An.existsSync(c);if(!s&&n.prebuild){n.json||ft.info(fe.dim(`
818
- Running expo prebuild for deeper analysis...`));try{kr("npx expo prebuild --no-install",{cwd:e,stdio:"pipe"})}catch{return ft.warn(fe.yellow("Prebuild failed \u2014 skipping manifest/plist checks.")),r}}else if(!s)return n.json||ft.info(fe.dim(`
819
- Skipping manifest/plist checks \u2014 no android/ios dirs. Use --prebuild to generate them.`)),r;for(let l of o){let d=Sn();d.start(fe.dim(`Running ${l.label}...`));try{let u=Date.now(),p=await l.fn(e,n);p.durationMs=Date.now()-u,r.push(p);let g=p.findings.length;d.stop(g>0?fe.yellow(`${l.label} \u2014 ${g} finding(s)`):fe.green(`${l.label} \u2014 clean`))}catch(u){d.stop(fe.red(`${l.label} \u2014 error`)),r.push({category:l.category,label:l.label,findings:[],durationMs:0,error:u.message})}}}return r}import ie from"chalk";import{log as ee}from"@clack/prompts";var We={critical:ie.bgRed.white.bold,high:ie.red.bold,medium:ie.yellow.bold,low:ie.blue,info:ie.dim},kt={critical:0,high:1,medium:2,low:3,info:4};function Lr(e,n){if(!n)return!0;let t=kt[n];return t===void 0?!0:kt[e]<=t}function bn(e,n){let t=0,i={critical:0,high:0,medium:0,low:0,info:0};for(let a of e){let c=a.findings.filter(l=>Lr(l.severity,n));if(c.length===0&&!a.error)continue;if(ee.info(""),ee.info(ie.bold(` ${a.label}`)+ie.dim(` ${c.length} finding(s)`)),ee.info(ie.dim(" "+"\u2500".repeat(60))),a.error){ee.error(ie.red(` Error: ${a.error}`));continue}let s=[...c].sort((l,d)=>kt[l.severity]-kt[d.severity]);for(let l of s){let d=We[l.severity](` ${l.severity.toUpperCase()} `);ee.info(` ${d} ${ie.bold(l.id)} ${l.title}`),ee.info(ie.dim(` ${l.description}`)),l.file&&ee.info(ie.dim(` File: ${l.file}${l.line?`:${l.line}`:""}`)),ee.info(ie.cyan(` Fix: ${l.recommendation}`)),ee.info(""),i[l.severity]++,t++}}ee.info(""),ee.info(ie.bold(" Summary")),ee.info(ie.dim(" "+"\u2500".repeat(60))),ee.info(` Total: ${ie.bold(String(t))} finding(s)`),ee.info(` ${We.critical(` ${i.critical} Critical `)} ${We.high(` ${i.high} High `)} ${We.medium(` ${i.medium} Medium `)} ${We.low(` ${i.low} Low `)} ${We.info(` ${i.info} Info `)}`);let o=i.critical>0,r=i.high>0;o||r?(ee.info(""),ee.error(ie.red.bold(` FAIL \u2014 ${i.critical} critical, ${i.high} high issue(s) found`))):t>0?(ee.info(""),ee.warn(ie.yellow(" PASS (with warnings) \u2014 no critical or high issues"))):(ee.info(""),ee.success(ie.green.bold(" PASS \u2014 no issues found")))}function $n(e,n){let t=e.flatMap(o=>o.findings),i={};for(let o of Object.values(he))i[o]=t.filter(r=>r.severity===o).length;return{version:"1.0.0",timestamp:new Date().toISOString(),project:n.name||"unknown",projectVersion:n.version||"0.0.0",summary:{total:t.length,...i},passed:i.critical===0&&i.high===0,checks:e.map(o=>({category:o.category,label:o.label,findingCount:o.findings.length,durationMs:o.durationMs,error:o.error||null})),findings:t}}import{log as te,spinner as Ur}from"@clack/prompts";import J from"chalk";import Ce from"fs";import Mr from"os";import Ye from"path";import{execSync as Fr}from"child_process";var Pn=16384,Hr=1,Gr=Buffer.from([127,69,76,70]);async function _n(e){te.info(J.bold.underline("16KB Page Alignment Check")),console.log("");let n=Ye.resolve(e);if(!Ce.existsSync(n))return te.error(J.red(`APK file not found: ${n}`)),!1;if(!n.endsWith(".apk"))return te.error(J.red("The provided file is not an APK file.")),!1;let t=Ur();t.start("Extracting and analyzing native libraries...");let i=Ce.mkdtempSync(Ye.join(Mr.tmpdir(),"mach-16kb-"));try{try{Fr(`unzip -o -q "${n}" "lib/arm64-v8a/*.so" "lib/x86_64/*.so" -d "${i}" 2>/dev/null`,{encoding:"utf-8",maxBuffer:50*1024*1024})}catch{}let o=Dn(Ye.join(i,"lib"));if(o.length===0)return t.stop("Analysis complete."),te.info(J.yellow("No arm64-v8a or x86_64 native libraries found in the APK.")),te.info(J.dim("16KB alignment check only applies to arm64-v8a and x86_64 architectures.")),!0;let r=[];for(let s of o){let l=Ye.relative(i,s),d=Br(l),u=Ye.basename(s),p=jr(s);p!==null&&r.push({name:u,filePath:l,arch:d,align:p,compatible:p>=Pn})}if(t.stop("Analysis complete."),r.length===0)return te.info(J.yellow("No valid ELF shared libraries found.")),!0;let a=r.filter(s=>!s.compatible),c=r.filter(s=>s.compatible);if(te.info(J.dim(`Checked ${r.length} native librar${r.length===1?"y":"ies"}
820
- `)),a.length>0){te.info(J.red.bold(`Incompatible libraries:
821
- `));for(let s of a)te.error(J.red(`${J.bold(s.name)} ${J.dim(`(${s.arch})`)}`)),te.info(J.dim(` PT_LOAD alignment: 2**${Math.log2(s.align)} (${s.align} bytes, needs 2**14 = ${Pn})`))}return c.length>0&&(console.log(""),te.success(J.green(`${c.length} librar${c.length===1?"y":"ies"} correctly aligned (2**14 or higher).`))),console.log(""),a.length===0?(te.success(J.green.bold("ELF Verification Successful. APK is 16KB compatible.")),!0):(te.error(J.red.bold(`Found ${a.length} unaligned lib${a.length===1?"":"s"} (arm64-v8a/x86_64 libs need to be aligned).`)),console.log(""),te.info(J.yellow("To fix this:")),te.info(J.dim(" 1. Rebuild with NDK r28+ which defaults to 16KB page alignment")),te.info(J.dim(" 2. Or set -DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON in CMake")),te.info(J.dim(" 3. Update third-party libraries that ship prebuilt .so files")),te.info(J.dim(" 4. After rebuilding: zipalign -p -f -v 16 input.apk output.apk")),console.log(""),te.info(J.dim("Reference: https://developer.android.com/guide/practices/page-sizes")),!1)}catch(o){return t.stop("Analysis failed."),te.error(J.red(`Failed to analyze APK: ${o.message}`)),!1}finally{try{Ce.rmSync(i,{recursive:!0,force:!0})}catch{}}}function jr(e){let n=Ce.openSync(e,"r");try{let t=Buffer.alloc(64);if(Ce.readSync(n,t,0,64,0),!t.subarray(0,4).equals(Gr))return null;let i=t[4]===2,o=t[5]===1,r=(p,g)=>o?p.readUInt16LE(g):p.readUInt16BE(g),a=(p,g)=>o?p.readUInt32LE(g):p.readUInt32BE(g),c=(p,g)=>Number(o?p.readBigUInt64LE(g):p.readBigUInt64BE(g)),s,l,d;i?(s=c(t,32),l=r(t,54),d=r(t,56)):(s=a(t,28),l=r(t,42),d=r(t,44));let u=null;for(let p=0;p<d;p++){let g=Buffer.alloc(l);if(Ce.readSync(n,g,0,l,s+p*l),a(g,0)!==Hr)continue;let h;i?h=c(g,48):h=a(g,28),h>0&&(u===null||h<u)&&(u=h)}return u??0}catch{return null}finally{Ce.closeSync(n)}}function Dn(e){let n=[];if(!Ce.existsSync(e))return n;let t=Ce.readdirSync(e,{withFileTypes:!0});for(let i of t){let o=Ye.join(e,i.name);i.isDirectory()?n.push(...Dn(o)):i.name.endsWith(".so")&&n.push(o)}return n}function Br(e){return e.includes("arm64-v8a")?"arm64-v8a":e.includes("x86_64")?"x86_64":"unknown"}var Rn=async e=>{if(ue()||(ye.error(Pe.red(`You are not logged in. Run \`${f.nameLower} login\` first.`)),process.exit(1)),e.apk){await zr(e);return}let t=process.cwd(),i=xt.join(t,"package.json");mt.existsSync(i)||(ye.error(Pe.red("No package.json found. Run this command from a project root.")),process.exit(1));let o=JSON.parse(mt.readFileSync(i,"utf-8")),r=!!(o.dependencies?.expo||o.devDependencies?.expo);e.json||(ye.info(Pe.dim(`Project: ${o.name||"unknown"} v${o.version||"0.0.0"}`)),ye.info(Pe.dim(`Type: ${r?"Expo":"Bare React Native"}`)),ye.info(""));let a={json:e.json,fix:e.fix,category:e.category,severity:e.severity,prebuild:e.prebuild},c=await In(t,a);e.json?console.log(JSON.stringify($n(c,o),null,2)):bn(c,e.severity);let s=c.some(d=>d.findings.some(u=>u.severity==="critical")),l=c.some(d=>d.findings.some(u=>u.severity==="high"));(s||l)&&process.exit(1)},wn=["16kb"];async function zr(e){let n=e.category?.toLowerCase();n&&!wn.includes(n)&&(ye.error(Pe.red(`Unknown APK check category: "${n}"`)),ye.info(Pe.dim(`Available APK checks: ${wn.join(", ")}`)),process.exit(1));let t=await Wr(e.apk);t||process.exit(1);let i=!n,o=!1;(i||n==="16kb")&&(await _n(t)||(o=!0)),o&&process.exit(1)}async function Wr(e){if(e.startsWith("build:")){let t=e.slice(6);return await Yr(t)}if(e.startsWith("http://")||e.startsWith("https://"))return await On(e);let n=xt.resolve(e);return mt.existsSync(n)?n:(ye.error(Pe.red(`APK file not found: ${n}`)),null)}async function Yr(e){let n=vn();n.start(`Fetching APK from build ${e}...`);try{let t=await _.get(`/build/${e}`);if(t.data.status!=="success")throw new Error(t.data.message);let i=t.data.build;if(!i)throw new Error("Build not found");let o=i.artifacts?.find(r=>r.type?r.type==="apk":r.name?.endsWith(".apk")||r.url?.includes(".apk"));return!o||!o.url?(n.stop("No APK artifact found"),ye.error(Pe.red("This build does not have an APK artifact.")),ye.info(Pe.dim("Make sure the build produced an APK (not just an AAB).")),null):(n.stop(`Found build: ${i.buildId||e}`),await On(o.url))}catch(t){return n.stop("Failed to fetch build"),ye.error(Pe.red(t.message)),null}}async function On(e){let n=vn();n.start("Downloading APK...");try{let t=mt.mkdtempSync(xt.join(Kr.tmpdir(),`${f.nameLower}-audit-`)),i=xt.join(t,"app.apk"),o=await Vr.get(e,{responseType:"arraybuffer"});mt.writeFileSync(i,o.data);let r=(o.data.length/(1024*1024)).toFixed(1);return n.stop(`Downloaded APK (${r} MB)`),i}catch(t){return n.stop("Download failed"),ye.error(Pe.red(`Failed to download APK: ${t.message}`)),null}}var Xr=console.log;console.log=()=>{};Jr();console.log=Xr;de(re.bgCyan.black(f.cliTag("Production Build Orchestrator")));var Qr=Zr(import.meta.url),es=Qr("../package.json"),W=new qr;W.name(f.nameLower).description(`${f.name} CLI: Powerful Cloud Infrastructure Tools`).version(es.version).option("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1);W.command("agent").description("Start local device discovery agent for the Install Hub (port 7070)").action(async()=>{await Ri()});W.command("host").description("Setup AWS S3 static hosting and CloudFront").action(async()=>{de(re.bgCyan.black(f.cliTag("Hosting"))),await di()});W.command("sitemap").description("Generate sitemap.xml from Expo Router app structure").option("-o, --output <path>","Output path for sitemap.xml","./public/sitemap.xml").action(async e=>{de(re.bgCyan.black(f.cliTag("Sitemap Generator"))),await mi(e)});W.command("build").description("Run a build on a cloud provider (AWS Spot Instances)").argument("[platform]","Target platform (android, ios)").option("--platform <os>","Target platform alias (android, ios) [Optional]").option("--repo <url>","Git Repository URL").option("--branch <name>","Git Branch").option("--ami <id>","AMI ID").option("--bucket <name>","S3 Bucket for artifacts").option("--region <region>","AWS Region").option("--aws-profile <name>","AWS Credentials Profile").option("-p, --build-profile <name>","Build Profile (e.g. production, staging)","production").option("--profile <name>","Build Profile (alias for --build-profile)").option("--dry-run","Generate User Data script without launching").option("--keep-instance","Do not terminate the instance after build").option("--subnet <id>","VPC Subnet ID to launch the instance in").option("--security-group <id>","VPC Security Group ID to use").option("--ssh-host <host>","Remote host for iOS build (SSH)").option("--ssh-user <user>","SSH username for remote host").option("--ssh-key <path>","Path to private SSH key for remote host").option("--ios-scheme <scheme>","iOS Scheme to build").option("--ios-team-id <id>","Apple Development Team ID").option("--ios-configuration <config>","Xcode configuration (Release/Debug)").option("--ios-export-method <method>","Export method (ad-hoc, app-store, development, enterprise)").option("--ios-api-key-id <id>","App Store Connect API Key ID").option("--ios-api-key-issuer <id>","App Store Connect API Key Issuer ID").option("--ios-api-key-path <path>","Path to App Store Connect API Key (.p8) file").option("--simulator","Build for iOS Simulator (no signing required)").addOption(new Cn("--build-id <id>","Internal build ID").hideHelp()).addOption(new Cn("--project-id <id>","Internal project ID").hideHelp()).option("--local","Run build on local machine").option("--auto-version","Automatically fetch and increment versionCode from Google Play").option("--verbose","Enable verbose logging").option("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1).action(async(e,n)=>{let t=W.opts();n.yes=n.yes||t.yes,n.quiet=n.quiet||t.quiet,n.platform=e||n.platform,n.buildProfile=n.profile||n.buildProfile,n.quiet||de(re.bgCyan.black(f.cliTag("Cloud Build"))),await At(n)});W.command("update").description("Deploy an Over-The-Air (OTA) update to your live channel").option("--branch <name>","Channel or Branch to deploy to (e.g., production)","production").action(async e=>{de(re.bgCyan.black(f.cliTag("OTA Update"))),await Bi(e)});W.command("submit").description("Automated Store Submission (App Store / Google Play)").option("--platform <os>","Target platform (ios/android)").option("--track <track>","Google Play Track (internal, alpha, beta, production)","internal").option("--latest","Use the latest successful build for submission").option("--build-id <id>","Use a specific build ID for submission").action(async e=>{de(re.bgCyan.black(f.cliTag("Store Submission"))),await Gi(e)});W.command("login").description(`Login to ${f.name} Dashboard`).action(async()=>{de(re.bgCyan.black(f.cliTag("Login"))),await Ni()});W.command("link").description(`Link local directory to a ${f.name} Project`).action(async()=>{de(re.bgCyan.black(f.cliTag("Link Project"))),await ki()});W.command("me").description("Display currently logged in user details").action(async()=>{await Vi()});W.command("init").description(`Create a new ${f.name} Project`).action(async()=>{de(re.bgCyan.black(f.cliTag("Init Project"))),await xi()});W.command("env").description("Manage Environment Variables").argument("<action>","Action to perform: set or list").argument("[args...]","Key=Value pairs for set action").action(async(e,n)=>{de(re.bgCyan.black(f.cliTag("Env Manager"))),await Mi(e,n)});W.command("start").description("Start the development server (Metro)").option("-p, --build-profile <name>","Build profile (e.g. development, staging)","development").option("--tunnel","Use ngrok tunnel").option("--lan","Use LAN IP").option("--localhost","Use localhost").option("-c, --clear","Clear Metro cache").option("--port <number>","Port to listen on").option("--ios","Start on iOS").option("--android","Start on Android").option("--web","Start on Web").action(async e=>{de(re.bgCyan.black(f.cliTag("Dev Server"))),await qi(e)});W.command("config").description("Show resolved configuration for a profile").option("-p, --profile <name>","Build profile to resolve","development").option("--json","Output as JSON").action(async e=>{await Ji(e)});W.command("credentials").description("Unified, interactive credential management (iOS/Android)").option("-p, --profile <name>","Build profile (production, staging, development)").option("--force","Force recreate certificates (nuke existing on Apple Portal)",!1).action(async e=>{let{credentialsMainCommand:n}=await import("./credentials-WL7JKLF4.js");await n(e)});W.command("credentials:setup").description("Automated credential provisioning (iOS/Android) [Legacy]").requiredOption("--platform <os>","Platform: ios or android").option("--profile <name>","Build profile (production, staging, development)").option("--bundle-id <id>","Bundle ID / Package Name (optional, auto-detected)").option("--team-id <id>","Apple Team ID (iOS only)").option("--key-alias <alias>","Android keystore alias (optional, auto-generated)").option("--aws-profile <name>","AWS Credentials Profile (for S3 storage)").option("--force","Force recreate certificates (nuke existing on Apple Portal)",!1).action(async e=>{de(re.bgCyan.black(f.cliTag("Credentials Setup"))),await Je(e),Tn(re.green("Done!"))});W.command("credentials:service").description("Upload Service Credentials (ASC API Key / Google Service JSON) [Legacy]").requiredOption("--platform <os>","Platform: ios or android").option("--file <path>","Path to credential file (.p8 or .json)").option("--issuer-id <id>","ASC API Key Issuer ID (iOS only)").option("--key-id <id>","ASC API Key ID (iOS only)").action(async e=>{de(re.bgCyan.black(f.cliTag("Service Credentials"))),await ci(e),Tn(re.green("Done!"))});var oi=W.command("device").description("Manage registered iOS test devices");oi.command("register").description("Register a connected iOS device or enter UDID manually").option("--udid <udid>","Device UDID (skip auto-detection)").option("--name <name>","Device name").action(async e=>{await _t("register",e)});oi.command("list").description("List all registered devices").action(async()=>{await _t("list",{})});oi.command("remove").description("Remove a registered device").option("--udid <udid>","Device UDID to remove").action(async e=>{await _t("remove",e)});W.command("audit").description("Run automated security audit on the project or APK").option("--apk <path>","Path to APK file (runs APK diagnostics like 16KB alignment)").option("--json","Output results as JSON (for CI/CD)").option("--fix","Auto-apply fixes where possible").option("--category <name>","Run only a specific check category (e.g. 16kb, permissions, secrets)").option("--severity <level>","Minimum severity to display (critical, high, medium, low, info)").option("--prebuild","Run expo prebuild for deeper manifest/plist analysis").action(async e=>{de(re.bgCyan.black(f.cliTag(e.apk?"APK Audit":"Security Audit"))),await Rn(e)});var ts=new Set(["login"]);W.hook("preAction",(e,n)=>{let t=n.name();ts.has(t)||si()});W.on("command:*",()=>{console.error(`Invalid command: %s
822
- See --help for a list of available commands.`,W.args.join(" ")),process.exit(1)});process.argv.slice(2).length||W.help();W.parse(process.argv);
813
+ `),"Registered Devices")}catch(n){e.stop(Y.red("Failed to fetch devices")),be.error(n.response?.data?.message||n.message)}ut(Y.blue("---"))}async function ur(e){let n=e.udid;if(!n){let o=dt();o.start("Fetching registered devices...");try{let a=(await D.get("/devices")).data.devices||[];if(o.stop(`${a.length} device(s) found`),a.length===0){be.info(Y.dim("No devices to remove.")),ut(Y.blue("---"));return}let c=await Qi({message:"Select device to remove:",options:a.map(s=>({value:s.udid,label:s.name,hint:s.udid.substring(0,12)+"..."}))});if(ct(c)){lt("Cancelled");return}n=c}catch(r){o.stop(Y.red("Failed to fetch devices")),be.error(r.response?.data?.message||r.message);return}}let t=await rr({message:`Remove device ${Y.dim(n.substring(0,12)+"...")}?`});if(ct(t)||!t){lt("Cancelled");return}let i=dt();i.start("Removing device...");try{await D.delete(`/devices/${encodeURIComponent(n)}`),i.stop(Y.green("Device removed"))}catch(o){i.stop(Y.red("Failed to remove device")),be.error(o.response?.data?.message||o.message)}ut(Y.blue("---"))}async function wt(e,n){switch(e){case"register":await lr(n);break;case"list":await dr();break;case"remove":await ur(n);break;default:be.error(`Unknown action: ${e}`)}}import{log as Ae,spinner as Rn}from"@clack/prompts";import $e from"chalk";import Ut from"path";import mt from"fs";import Vr from"os";import zr from"axios";var Se=(r=>(r.CRITICAL="critical",r.HIGH="high",r.MEDIUM="medium",r.LOW="low",r.INFO="info",r))(Se||{}),Pe=(s=>(s.PERMISSIONS="permissions",s.SECRETS="secrets",s.DEPENDENCIES="dependencies",s.STORAGE="storage",s.NETWORK="network",s.DEBUG="debug",s.MANIFEST="manifest",s.ATS="ats",s))(Pe||{});import{spinner as An,log as ft}from"@clack/prompts";import ge from"chalk";import{execSync as xr}from"child_process";import En from"fs";import In from"path";import Ue from"fs";import pt from"path";import{execSync as pr}from"child_process";var en={"android.permission.READ_PHONE_STATE":{severity:"high",description:"Can read phone number, IMEI, carrier info"},"android.permission.CALL_PHONE":{severity:"high",description:"Can make calls without user interaction"},"android.permission.SEND_SMS":{severity:"high",description:"Can send SMS without user interaction"},"android.permission.READ_SMS":{severity:"high",description:"Can read user SMS messages"},"android.permission.READ_CONTACTS":{severity:"medium",description:"Can read user contacts"},"android.permission.WRITE_CONTACTS":{severity:"medium",description:"Can modify user contacts"},"android.permission.READ_CALL_LOG":{severity:"high",description:"Can read call history"},"android.permission.CAMERA":{severity:"medium",description:"Camera access"},"android.permission.RECORD_AUDIO":{severity:"medium",description:"Microphone access"},"android.permission.ACCESS_FINE_LOCATION":{severity:"medium",description:"Precise GPS location"},"android.permission.ACCESS_COARSE_LOCATION":{severity:"medium",description:"Approximate location"},"android.permission.ACCESS_BACKGROUND_LOCATION":{severity:"high",description:"Background location tracking"},"android.permission.READ_EXTERNAL_STORAGE":{severity:"medium",description:"Read files on device"},"android.permission.WRITE_EXTERNAL_STORAGE":{severity:"medium",description:"Write files on device"},"android.permission.READ_MEDIA_IMAGES":{severity:"low",description:"Read photos"},"android.permission.READ_MEDIA_VIDEO":{severity:"low",description:"Read videos"},"android.permission.SYSTEM_ALERT_WINDOW":{severity:"high",description:"Draw overlays on other apps"},"android.permission.REQUEST_INSTALL_PACKAGES":{severity:"high",description:"Can install APKs"}},fr={NSCameraUsageDescription:{severity:"medium",description:"Camera access declared"},NSMicrophoneUsageDescription:{severity:"medium",description:"Microphone access declared"},NSLocationWhenInUseUsageDescription:{severity:"medium",description:"Location (in-use) declared"},NSLocationAlwaysUsageDescription:{severity:"high",description:"Background location declared"},NSContactsUsageDescription:{severity:"medium",description:"Contacts access declared"},NSCalendarsUsageDescription:{severity:"low",description:"Calendar access declared"},NSPhotoLibraryUsageDescription:{severity:"low",description:"Photo library access declared"}};function mr(e){try{let t=pr("npx expo config --type introspect --json 2>/dev/null",{cwd:e,encoding:"utf-8",timeout:3e4});return JSON.parse(t)}catch{}let n=pt.join(e,"app.json");if(Ue.existsSync(n))try{let t=JSON.parse(Ue.readFileSync(n,"utf-8"));return t.expo||t}catch{}return null}function gr(e){let n=[],t=pt.join(e,"node_modules");if(!Ue.existsSync(t))return n;let i=/<uses-permission\s+android:name="([^"]+)"/g;function o(r,a){let c=pt.join(r,"android","src","main","AndroidManifest.xml");if(!Ue.existsSync(c))return;let s=Ue.readFileSync(c,"utf-8"),l;for(;(l=i.exec(s))!==null;)n.push({pkg:a,permission:l[1]});i.lastIndex=0}for(let r of Ue.readdirSync(t)){if(r.startsWith("."))continue;let a=pt.join(t,r);if(r.startsWith("@")){if(!Ue.statSync(a).isDirectory())continue;for(let c of Ue.readdirSync(a))o(pt.join(a,c),`${r}/${c}`)}else o(a,r)}return n}async function tn(e,n){let t=[],i=1,o=mr(e),r=o?.android?.permissions||[],a=o?.android?.blockedPermissions||[];for(let l of r){let d=en[l];d&&t.push({id:`PERM-${String(i++).padStart(3,"0")}`,title:`${l.split(".").pop()} declared`,description:d.description,severity:d.severity,category:"permissions",file:"app.config.ts",recommendation:"Remove from permissions if not needed, or add justification."})}let c=gr(e);for(let{pkg:l,permission:d}of c){let u=en[d];u&&(a.includes(d)||r.includes(d)||t.push({id:`PERM-${String(i++).padStart(3,"0")}`,title:`${d.split(".").pop()} injected by ${l}`,description:`${u.description}. Auto-injected via ${l} AndroidManifest.xml`,severity:u.severity,category:"permissions",file:`node_modules/${l}/android/src/main/AndroidManifest.xml`,recommendation:`Add "${d}" to blockedPermissions if not needed.`,autoFixable:!0}))}let s=o?.ios?.infoPlist||{};for(let[l,d]of Object.entries(fr))l in s&&t.push({id:`PERM-${String(i++).padStart(3,"0")}`,title:`iOS: ${l} declared`,description:d.description,severity:d.severity,category:"permissions",file:"app.config.ts",recommendation:`Remove ${l} from infoPlist if the app does not use this capability.`});return{category:"permissions",label:"Permission Audit",findings:t,durationMs:0}}import ii from"fs";import vt from"path";var hr=[{id:"SEC-001",pattern:/(['"`])(?:sk|pk)_(?:live|test)_[a-zA-Z0-9]{20,}\1/g,severity:"critical",label:"Stripe API Key"},{id:"SEC-002",pattern:/(['"`])AIza[0-9A-Za-z\-_]{35}\1/g,severity:"high",label:"Google API Key"},{id:"SEC-003",pattern:/(['"`])AKIA[0-9A-Z]{16}\1/g,severity:"critical",label:"AWS Access Key ID"},{id:"SEC-004",pattern:/-----BEGIN (?:RSA |EC )?PRIVATE KEY-----/g,severity:"critical",label:"Private key in source"},{id:"SEC-005",pattern:/(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9_]{36,}/g,severity:"high",label:"GitHub Token"},{id:"SEC-006",pattern:/xox[bpors]-[a-zA-Z0-9-]{10,}/g,severity:"high",label:"Slack Token"},{id:"SEC-007",pattern:/(?:password|secret|apikey|api_key)\s*[:=]\s*['"`][^'"`\n]{8,}['"`]/gi,severity:"high",label:"Hardcoded credential"}],yr=new Set([".ts",".tsx",".js",".jsx"]),Sr=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function nn(e){let n=[],t=ii.readdirSync(e,{withFileTypes:!0});for(let i of t){if(Sr.has(i.name))continue;let o=vt.join(e,i.name);i.isDirectory()?n.push(...nn(o)):yr.has(vt.extname(i.name))&&n.push(o)}return n}function Ar(e){let n=e.trim();return n.startsWith("//")||n.startsWith("*")||n.startsWith("/*")}function Er(e){return/process\.env\./i.test(e)||/import\.meta\.env/i.test(e)}async function on(e,n){let t=[],i=vt.join(e,"src"),o=ii.existsSync(i)?i:e,r=nn(o);for(let a of r){let s=ii.readFileSync(a,"utf-8").split(`
814
+ `),l=vt.relative(e,a);for(let d=0;d<s.length;d++){let u=s[d];if(!Ar(u)&&!Er(u))for(let{id:p,pattern:g,severity:m,label:h}of hr)g.lastIndex=0,g.test(u)&&t.push({id:p,title:h,description:`Potential ${h.toLowerCase()} found in source code`,severity:m,category:"secrets",file:l,line:d+1,recommendation:`Move to environment variables or a secrets manager. Use \`${f.nameLower} env set\` for managed secrets.`})}}return{category:"secrets",label:"Secrets Detection",findings:t,durationMs:0}}import{execSync as Ir}from"child_process";var br={critical:"critical",high:"high",moderate:"medium",low:"low",info:"info"};async function rn(e,n){let t=[],i=1,o;try{o=Ir("npm audit --json 2>/dev/null",{cwd:e,encoding:"utf-8",timeout:6e4})}catch(c){if(o=c.stdout||"",!o)return{category:"dependencies",label:"Dependency CVEs",findings:[],durationMs:0,error:"Failed to run npm audit. Ensure npm is available and dependencies are installed."}}let r;try{r=JSON.parse(o)}catch{return{category:"dependencies",label:"Dependency CVEs",findings:[],durationMs:0,error:"Failed to parse npm audit output."}}let a=r.vulnerabilities||{};for(let[c,s]of Object.entries(a)){let l=br[s.severity]||"info",d=Array.isArray(s.via)?s.via.map(u=>typeof u=="string"?u:u.title||u.name).join(", "):String(s.via);t.push({id:`DEP-${String(i++).padStart(3,"0")}`,title:`${c} \u2014 ${s.severity}`,description:`Via: ${d}. Range: ${s.range||"unknown"}`,severity:l,category:"dependencies",recommendation:s.fixAvailable?`Run \`npm audit fix\` or update ${c} to a patched version.`:"No fix available yet. Monitor for updates or evaluate alternatives.",autoFixable:!!s.fixAvailable})}return{category:"dependencies",label:"Dependency CVEs",findings:t,durationMs:0}}import Rt from"fs";import Ot from"path";var Pr=/(?:token|password|credential|secret|apiKey|api_key|session|auth|jwt|refresh_token|access_token|private_key|pin|otp)/i,sn=/AsyncStorage\s*\.\s*(?:setItem|mergeItem)\s*\(\s*['"`]([^'"`]+)['"`]/g,$r=/from\s+['"]@react-native-async-storage\/async-storage['"]|from\s+['"]react-native['"].*AsyncStorage/,_r=new Set([".ts",".tsx",".js",".jsx"]),Dr=new Set(["node_modules",".expo",".git","android","ios","dist","build"]);function an(e){let n=[];if(!Rt.existsSync(e))return n;let t=Rt.readdirSync(e,{withFileTypes:!0});for(let i of t){if(Dr.has(i.name))continue;let o=Ot.join(e,i.name);i.isDirectory()?n.push(...an(o)):_r.has(Ot.extname(i.name))&&n.push(o)}return n}async function cn(e,n){let t=[],i=1,o=Ot.join(e,"src"),r=Rt.existsSync(o)?o:e,a=an(r);for(let c of a){let s=Rt.readFileSync(c,"utf-8");if(!$r.test(s))continue;let l=s.split(`
815
+ `),d=Ot.relative(e,c);for(let u=0;u<l.length;u++){let p=l[u];sn.lastIndex=0;let g;for(;(g=sn.exec(p))!==null;){let m=g[1];Pr.test(m)&&t.push({id:`STOR-${String(i++).padStart(3,"0")}`,title:`AsyncStorage used for "${m}"`,description:`Sensitive data key "${m}" stored in AsyncStorage (unencrypted).`,severity:"high",category:"storage",file:d,line:u+1,recommendation:"Use expo-secure-store (SecureStore) for sensitive data instead of AsyncStorage."})}}}return{category:"storage",label:"Insecure Storage",findings:t,durationMs:0}}import Ct from"fs";import Tt from"path";var ln=/['"`](http:\/\/(?!localhost|127\.0\.0\.1|10\.|192\.168\.|0\.0\.0\.0|172\.(?:1[6-9]|2\d|3[01])\.)[^'"`\s]+)['"`]/g,wr=/\/api\/|\/v[0-9]+\/|\/graphql|\/rest\//i,vr=new Set([".ts",".tsx",".js",".jsx"]),Rr=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function dn(e){let n=[];if(!Ct.existsSync(e))return n;let t=Ct.readdirSync(e,{withFileTypes:!0});for(let i of t){if(Rr.has(i.name))continue;let o=Tt.join(e,i.name);i.isDirectory()?n.push(...dn(o)):vr.has(Tt.extname(i.name))&&n.push(o)}return n}async function un(e,n){let t=[],i=1,o=Tt.join(e,"src"),r=Ct.existsSync(o)?o:e,a=dn(r);for(let c of a){let l=Ct.readFileSync(c,"utf-8").split(`
816
+ `),d=Tt.relative(e,c);for(let u=0;u<l.length;u++){let p=l[u],g=p.trim();if(g.startsWith("//")||g.startsWith("*"))continue;ln.lastIndex=0;let m;for(;(m=ln.exec(p))!==null;){let h=m[1],P=wr.test(h);t.push({id:`NET-${String(i++).padStart(3,"0")}`,title:`Insecure HTTP URL${P?" (API endpoint)":""}`,description:`Plain HTTP URL found: ${h}`,severity:P?"high":"medium",category:"network",file:d,line:u+1,recommendation:"Use HTTPS instead of HTTP for all network requests."})}}}return{category:"network",label:"HTTP URLs",findings:t,durationMs:0}}import Nt from"fs";import kt from"path";var pn=/(?:debug|debugMode|devMode|enableDebug)\s*[:=]\s*true/gi,fn=/console\.(?:log|warn|info|debug)\s*\([^)]*(?:token|password|secret|credential|key|auth)/gi,Or=new Set([".ts",".tsx",".js",".jsx"]),Cr=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function mn(e){let n=[];if(!Nt.existsSync(e))return n;let t=Nt.readdirSync(e,{withFileTypes:!0});for(let i of t){if(Cr.has(i.name))continue;let o=kt.join(e,i.name);i.isDirectory()?n.push(...mn(o)):Or.has(kt.extname(i.name))&&n.push(o)}return n}async function gn(e,n){let t=[],i=1,o=kt.join(e,"src"),r=Nt.existsSync(o)?o:e,a=mn(r);for(let c of a){let l=Nt.readFileSync(c,"utf-8").split(`
817
+ `),d=kt.relative(e,c);for(let u=0;u<l.length;u++){let p=l[u],g=p.trim();if(!(g.startsWith("//")||g.startsWith("*"))&&(pn.lastIndex=0,pn.test(p)&&t.push({id:`DBG-${String(i++).padStart(3,"0")}`,title:"Hardcoded debug flag",description:"Debug/dev mode enabled in source code",severity:"medium",category:"debug",file:d,line:u+1,recommendation:"Use __DEV__ or environment variables instead of hardcoded debug flags."}),fn.lastIndex=0,fn.test(p))){let m=l.slice(Math.max(0,u-3),u).join(`
818
+ `);/__DEV__/.test(m)||t.push({id:`DBG-${String(i++).padStart(3,"0")}`,title:"Sensitive data in console log",description:"Console log may expose sensitive data (token, password, etc.) in production",severity:"medium",category:"debug",file:d,line:u+1,recommendation:"Wrap in __DEV__ check or remove sensitive data from console output."})}}}return{category:"debug",label:"Debug/Dev Flags",findings:t,durationMs:0}}import hn from"fs";import ni from"path";var Tr=new Set(["androidx.work.impl.background.systemjob.SystemJobService","androidx.work.impl.diagnostics.DiagnosticsReceiver","com.google.firebase.iid.FirebaseInstanceIdReceiver","com.google.android.gms.auth.api.signin.RevocationBoundService","androidx.profileinstaller.ProfileInstallReceiver","com.google.firebase.messaging.FirebaseMessagingService","com.google.android.gms.measurement.AppMeasurementService","com.google.android.gms.measurement.AppMeasurementJobService"]);function Nr(e){let n=[ni.join(e,"android","app","src","main","AndroidManifest.xml"),ni.join(e,"android","AndroidManifest.xml")];for(let t of n)if(hn.existsSync(t))return t;return null}async function yn(e,n){let t=[],i=1,o=Nr(e);if(!o)return{category:"manifest",label:"Android Manifest",findings:[],durationMs:0,error:"No AndroidManifest.xml found. Run with --prebuild or run `expo prebuild` first."};let r=hn.readFileSync(o,"utf-8"),a=ni.relative(e,o),c=/<(activity|service|receiver|provider)\s+([^>]*?)(?:\/>|>)/gs,s;for(;(s=c.exec(r))!==null;){let l=s[1],d=s[2],p=d.match(/android:name="([^"]+)"/)?.[1]||"unknown";if(Tr.has(p))continue;let g=/android:exported="true"/.test(d),m=/android:permission="/.test(d);g&&!m&&t.push({id:`MAN-${String(i++).padStart(3,"0")}`,title:`Exported ${l}: ${p.split(".").pop()}`,description:`${p} is exported=true without android:permission protection`,severity:"medium",category:"manifest",file:a,recommendation:'Set android:exported="false" or add an android:permission attribute.'})}return/android:allowBackup="true"/.test(r)&&t.push({id:`MAN-${String(i++).padStart(3,"0")}`,title:"allowBackup is enabled",description:'android:allowBackup="true" allows data extraction via ADB backup',severity:"medium",category:"manifest",file:a,recommendation:'Set android:allowBackup="false" via expo-build-properties plugin.',autoFixable:!0}),/android:debuggable="true"/.test(r)&&t.push({id:`MAN-${String(i++).padStart(3,"0")}`,title:"App is debuggable",description:'android:debuggable="true" allows attaching a debugger in production',severity:"critical",category:"manifest",file:a,recommendation:"Ensure debuggable is false for production builds. This is usually set automatically for release builds."}),{category:"manifest",label:"Android Manifest",findings:t,durationMs:0}}import xt from"fs";import oi from"path";function kr(e){let n=oi.join(e,"ios");if(!xt.existsSync(n))return null;let t=xt.readdirSync(n,{withFileTypes:!0});for(let i of t){if(!i.isDirectory()||i.name==="Pods"||i.name.startsWith("."))continue;let o=oi.join(n,i.name,"Info.plist");if(xt.existsSync(o))return o}return null}async function Sn(e,n){let t=[],i=1,o=kr(e);if(!o)return{category:"ats",label:"iOS ATS Config",findings:[],durationMs:0,error:"No Info.plist found. Run with --prebuild or run `expo prebuild` first."};let r=xt.readFileSync(o,"utf-8"),a=oi.relative(e,o),c=r.match(/<key>NSAppTransportSecurity<\/key>\s*<dict>([\s\S]*?)<\/dict>/);if(c){let s=c[1];/<key>NSAllowsArbitraryLoads<\/key>\s*<true\s*\/>/.test(s)&&t.push({id:`ATS-${String(i++).padStart(3,"0")}`,title:"ATS disabled \u2014 NSAllowsArbitraryLoads",description:"App Transport Security is completely disabled. All HTTP connections are allowed.",severity:"critical",category:"ats",file:a,recommendation:"Remove NSAllowsArbitraryLoads or set to false. Use domain-specific exceptions only if absolutely necessary."});let l=s.match(/<key>NSExceptionDomains<\/key>\s*<dict>([\s\S]*?)<\/dict>/);if(l){let d=l[1].match(/<key>([^<]+)<\/key>/g);if(d)for(let u of d){let p=u.replace(/<\/?key>/g,"");p!=="NSExceptionDomains"&&t.push({id:`ATS-${String(i++).padStart(3,"0")}`,title:`ATS exception: ${p}`,description:`ATS exception configured for ${p}`,severity:"low",category:"ats",file:a,recommendation:`Verify that the ATS exception for ${p} is necessary. Use HTTPS where possible.`})}}}return{category:"ats",label:"iOS ATS Config",findings:t,durationMs:0}}var Lr=[{category:"permissions",label:"Permission Audit",fn:tn,requiresPrebuild:!1},{category:"secrets",label:"Secrets Detection",fn:on,requiresPrebuild:!1},{category:"dependencies",label:"Dependency CVEs",fn:rn,requiresPrebuild:!1},{category:"storage",label:"Insecure Storage",fn:cn,requiresPrebuild:!1},{category:"network",label:"HTTP URLs",fn:un,requiresPrebuild:!1},{category:"debug",label:"Debug/Dev Flags",fn:gn,requiresPrebuild:!1},{category:"manifest",label:"Android Manifest",fn:yn,requiresPrebuild:!0},{category:"ats",label:"iOS ATS Config",fn:Sn,requiresPrebuild:!0}];async function bn(e,n){let t=Lr;n.category&&(t=t.filter(a=>a.category===n.category),t.length===0&&(ft.error(ge.red(`Unknown category: ${n.category}`)),ft.info(ge.dim(`Available: ${Object.values(Pe).join(", ")}`)),process.exit(1)));let i=t.filter(a=>!a.requiresPrebuild),o=t.filter(a=>a.requiresPrebuild),r=[];for(let a of i){let c=An();c.start(ge.dim(`Running ${a.label}...`));try{let s=Date.now(),l=await a.fn(e,n);l.durationMs=Date.now()-s,r.push(l);let d=l.findings.length;c.stop(d>0?ge.yellow(`${a.label} \u2014 ${d} finding(s)`):ge.green(`${a.label} \u2014 clean`))}catch(s){c.stop(ge.red(`${a.label} \u2014 error`)),r.push({category:a.category,label:a.label,findings:[],durationMs:0,error:s.message})}}if(o.length>0){let a=In.join(e,"android"),c=In.join(e,"ios"),s=En.existsSync(a)||En.existsSync(c);if(!s&&n.prebuild){n.json||ft.info(ge.dim(`
819
+ Running expo prebuild for deeper analysis...`));try{xr("npx expo prebuild --no-install",{cwd:e,stdio:"pipe"})}catch{return ft.warn(ge.yellow("Prebuild failed \u2014 skipping manifest/plist checks.")),r}}else if(!s)return n.json||ft.info(ge.dim(`
820
+ Skipping manifest/plist checks \u2014 no android/ios dirs. Use --prebuild to generate them.`)),r;for(let l of o){let d=An();d.start(ge.dim(`Running ${l.label}...`));try{let u=Date.now(),p=await l.fn(e,n);p.durationMs=Date.now()-u,r.push(p);let g=p.findings.length;d.stop(g>0?ge.yellow(`${l.label} \u2014 ${g} finding(s)`):ge.green(`${l.label} \u2014 clean`))}catch(u){d.stop(ge.red(`${l.label} \u2014 error`)),r.push({category:l.category,label:l.label,findings:[],durationMs:0,error:u.message})}}}return r}import ne from"chalk";import{log as te}from"@clack/prompts";var Ye={critical:ne.bgRed.white.bold,high:ne.red.bold,medium:ne.yellow.bold,low:ne.blue,info:ne.dim},Lt={critical:0,high:1,medium:2,low:3,info:4};function Ur(e,n){if(!n)return!0;let t=Lt[n];return t===void 0?!0:Lt[e]<=t}function Pn(e,n){let t=0,i={critical:0,high:0,medium:0,low:0,info:0};for(let a of e){let c=a.findings.filter(l=>Ur(l.severity,n));if(c.length===0&&!a.error)continue;if(te.info(""),te.info(ne.bold(` ${a.label}`)+ne.dim(` ${c.length} finding(s)`)),te.info(ne.dim(" "+"\u2500".repeat(60))),a.error){te.error(ne.red(` Error: ${a.error}`));continue}let s=[...c].sort((l,d)=>Lt[l.severity]-Lt[d.severity]);for(let l of s){let d=Ye[l.severity](` ${l.severity.toUpperCase()} `);te.info(` ${d} ${ne.bold(l.id)} ${l.title}`),te.info(ne.dim(` ${l.description}`)),l.file&&te.info(ne.dim(` File: ${l.file}${l.line?`:${l.line}`:""}`)),te.info(ne.cyan(` Fix: ${l.recommendation}`)),te.info(""),i[l.severity]++,t++}}te.info(""),te.info(ne.bold(" Summary")),te.info(ne.dim(" "+"\u2500".repeat(60))),te.info(` Total: ${ne.bold(String(t))} finding(s)`),te.info(` ${Ye.critical(` ${i.critical} Critical `)} ${Ye.high(` ${i.high} High `)} ${Ye.medium(` ${i.medium} Medium `)} ${Ye.low(` ${i.low} Low `)} ${Ye.info(` ${i.info} Info `)}`);let o=i.critical>0,r=i.high>0;o||r?(te.info(""),te.error(ne.red.bold(` FAIL \u2014 ${i.critical} critical, ${i.high} high issue(s) found`))):t>0?(te.info(""),te.warn(ne.yellow(" PASS (with warnings) \u2014 no critical or high issues"))):(te.info(""),te.success(ne.green.bold(" PASS \u2014 no issues found")))}function $n(e,n){let t=e.flatMap(o=>o.findings),i={};for(let o of Object.values(Se))i[o]=t.filter(r=>r.severity===o).length;return{version:"1.0.0",timestamp:new Date().toISOString(),project:n.name||"unknown",projectVersion:n.version||"0.0.0",summary:{total:t.length,...i},passed:i.critical===0&&i.high===0,checks:e.map(o=>({category:o.category,label:o.label,findingCount:o.findings.length,durationMs:o.durationMs,error:o.error||null})),findings:t}}import{log as ie,spinner as Mr}from"@clack/prompts";import X from"chalk";import Ce from"fs";import Fr from"os";import Je from"path";import{execSync as Hr}from"child_process";var _n=16384,Gr=1,jr=Buffer.from([127,69,76,70]);async function Dn(e){ie.info(X.bold.underline("16KB Page Alignment Check")),console.log("");let n=Je.resolve(e);if(!Ce.existsSync(n))return ie.error(X.red(`APK file not found: ${n}`)),!1;if(!n.endsWith(".apk"))return ie.error(X.red("The provided file is not an APK file.")),!1;let t=Mr();t.start("Extracting and analyzing native libraries...");let i=Ce.mkdtempSync(Je.join(Fr.tmpdir(),"mach-16kb-"));try{try{Hr(`unzip -o -q "${n}" "lib/arm64-v8a/*.so" "lib/x86_64/*.so" -d "${i}" 2>/dev/null`,{encoding:"utf-8",maxBuffer:50*1024*1024})}catch{}let o=wn(Je.join(i,"lib"));if(o.length===0)return t.stop("Analysis complete."),ie.info(X.yellow("No arm64-v8a or x86_64 native libraries found in the APK.")),ie.info(X.dim("16KB alignment check only applies to arm64-v8a and x86_64 architectures.")),!0;let r=[];for(let s of o){let l=Je.relative(i,s),d=Kr(l),u=Je.basename(s),p=Br(s);p!==null&&r.push({name:u,filePath:l,arch:d,align:p,compatible:p>=_n})}if(t.stop("Analysis complete."),r.length===0)return ie.info(X.yellow("No valid ELF shared libraries found.")),!0;let a=r.filter(s=>!s.compatible),c=r.filter(s=>s.compatible);if(ie.info(X.dim(`Checked ${r.length} native librar${r.length===1?"y":"ies"}
821
+ `)),a.length>0){ie.info(X.red.bold(`Incompatible libraries:
822
+ `));for(let s of a)ie.error(X.red(`${X.bold(s.name)} ${X.dim(`(${s.arch})`)}`)),ie.info(X.dim(` PT_LOAD alignment: 2**${Math.log2(s.align)} (${s.align} bytes, needs 2**14 = ${_n})`))}return c.length>0&&(console.log(""),ie.success(X.green(`${c.length} librar${c.length===1?"y":"ies"} correctly aligned (2**14 or higher).`))),console.log(""),a.length===0?(ie.success(X.green.bold("ELF Verification Successful. APK is 16KB compatible.")),!0):(ie.error(X.red.bold(`Found ${a.length} unaligned lib${a.length===1?"":"s"} (arm64-v8a/x86_64 libs need to be aligned).`)),console.log(""),ie.info(X.yellow("To fix this:")),ie.info(X.dim(" 1. Rebuild with NDK r28+ which defaults to 16KB page alignment")),ie.info(X.dim(" 2. Or set -DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON in CMake")),ie.info(X.dim(" 3. Update third-party libraries that ship prebuilt .so files")),ie.info(X.dim(" 4. After rebuilding: zipalign -p -f -v 16 input.apk output.apk")),console.log(""),ie.info(X.dim("Reference: https://developer.android.com/guide/practices/page-sizes")),!1)}catch(o){return t.stop("Analysis failed."),ie.error(X.red(`Failed to analyze APK: ${o.message}`)),!1}finally{try{Ce.rmSync(i,{recursive:!0,force:!0})}catch{}}}function Br(e){let n=Ce.openSync(e,"r");try{let t=Buffer.alloc(64);if(Ce.readSync(n,t,0,64,0),!t.subarray(0,4).equals(jr))return null;let i=t[4]===2,o=t[5]===1,r=(p,g)=>o?p.readUInt16LE(g):p.readUInt16BE(g),a=(p,g)=>o?p.readUInt32LE(g):p.readUInt32BE(g),c=(p,g)=>Number(o?p.readBigUInt64LE(g):p.readBigUInt64BE(g)),s,l,d;i?(s=c(t,32),l=r(t,54),d=r(t,56)):(s=a(t,28),l=r(t,42),d=r(t,44));let u=null;for(let p=0;p<d;p++){let g=Buffer.alloc(l);if(Ce.readSync(n,g,0,l,s+p*l),a(g,0)!==Gr)continue;let h;i?h=c(g,48):h=a(g,28),h>0&&(u===null||h<u)&&(u=h)}return u??0}catch{return null}finally{Ce.closeSync(n)}}function wn(e){let n=[];if(!Ce.existsSync(e))return n;let t=Ce.readdirSync(e,{withFileTypes:!0});for(let i of t){let o=Je.join(e,i.name);i.isDirectory()?n.push(...wn(o)):i.name.endsWith(".so")&&n.push(o)}return n}function Kr(e){return e.includes("arm64-v8a")?"arm64-v8a":e.includes("x86_64")?"x86_64":"unknown"}var On=async e=>{if(fe()||(Ae.error($e.red(`You are not logged in. Run \`${f.nameLower} login\` first.`)),process.exit(1)),e.apk){await Wr(e);return}let t=process.cwd(),i=Ut.join(t,"package.json");mt.existsSync(i)||(Ae.error($e.red("No package.json found. Run this command from a project root.")),process.exit(1));let o=JSON.parse(mt.readFileSync(i,"utf-8")),r=!!(o.dependencies?.expo||o.devDependencies?.expo);e.json||(Ae.info($e.dim(`Project: ${o.name||"unknown"} v${o.version||"0.0.0"}`)),Ae.info($e.dim(`Type: ${r?"Expo":"Bare React Native"}`)),Ae.info(""));let a={json:e.json,fix:e.fix,category:e.category,severity:e.severity,prebuild:e.prebuild},c=await bn(t,a);e.json?console.log(JSON.stringify($n(c,o),null,2)):Pn(c,e.severity);let s=c.some(d=>d.findings.some(u=>u.severity==="critical")),l=c.some(d=>d.findings.some(u=>u.severity==="high"));(s||l)&&process.exit(1)},vn=["16kb"];async function Wr(e){let n=e.category?.toLowerCase();n&&!vn.includes(n)&&(Ae.error($e.red(`Unknown APK check category: "${n}"`)),Ae.info($e.dim(`Available APK checks: ${vn.join(", ")}`)),process.exit(1));let t=await Yr(e.apk);t||process.exit(1);let i=!n,o=!1;(i||n==="16kb")&&(await Dn(t)||(o=!0)),o&&process.exit(1)}async function Yr(e){if(e.startsWith("build:")){let t=e.slice(6);return await Jr(t)}if(e.startsWith("http://")||e.startsWith("https://"))return await Cn(e);let n=Ut.resolve(e);return mt.existsSync(n)?n:(Ae.error($e.red(`APK file not found: ${n}`)),null)}async function Jr(e){let n=Rn();n.start(`Fetching APK from build ${e}...`);try{let t=await D.get(`/build/${e}`);if(t.data.status!=="success")throw new Error(t.data.message);let i=t.data.build;if(!i)throw new Error("Build not found");let o=i.artifacts?.find(r=>r.type?r.type==="apk":r.name?.endsWith(".apk")||r.url?.includes(".apk"));return!o||!o.url?(n.stop("No APK artifact found"),Ae.error($e.red("This build does not have an APK artifact.")),Ae.info($e.dim("Make sure the build produced an APK (not just an AAB).")),null):(n.stop(`Found build: ${i.buildId||e}`),await Cn(o.url))}catch(t){return n.stop("Failed to fetch build"),Ae.error($e.red(t.message)),null}}async function Cn(e){let n=Rn();n.start("Downloading APK...");try{let t=mt.mkdtempSync(Ut.join(Vr.tmpdir(),`${f.nameLower}-audit-`)),i=Ut.join(t,"app.apk"),o=await zr.get(e,{responseType:"arraybuffer"});mt.writeFileSync(i,o.data);let r=(o.data.length/(1024*1024)).toFixed(1);return n.stop(`Downloaded APK (${r} MB)`),i}catch(t){return n.stop("Download failed"),Ae.error($e.red(`Failed to download APK: ${t.message}`)),null}}var Zr=console.log;console.log=()=>{};Xr();console.log=Zr;ue(se.bgCyan.black(f.cliTag("Production Build Orchestrator")));var es=Qr(import.meta.url),ts=es("../package.json"),J=new qr;J.name(f.nameLower).description(`${f.name} CLI: Powerful Cloud Infrastructure Tools`).version(ts.version).option("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1);J.command("agent").description("Start local device discovery agent for the Install Hub (port 7070)").action(async()=>{await Oi()});J.command("host").description("Setup AWS S3 static hosting and CloudFront").action(async()=>{ue(se.bgCyan.black(f.cliTag("Hosting"))),await ui()});J.command("sitemap").description("Generate sitemap.xml from Expo Router app structure").option("-o, --output <path>","Output path for sitemap.xml","./public/sitemap.xml").action(async e=>{ue(se.bgCyan.black(f.cliTag("Sitemap Generator"))),await gi(e)});J.command("build").description("Run a build on a cloud provider (AWS Spot Instances)").argument("[platform]","Target platform (android, ios)").option("--platform <os>","Target platform alias (android, ios) [Optional]").option("--repo <url>","Git Repository URL").option("--branch <name>","Git Branch").option("--ami <id>","AMI ID").option("--bucket <name>","S3 Bucket for artifacts").option("--region <region>","AWS Region").option("--aws-profile <name>","AWS Credentials Profile").option("-p, --build-profile <name>","Build Profile (e.g. production, staging)","production").option("--profile <name>","Build Profile (alias for --build-profile)").option("--dry-run","Generate User Data script without launching").option("--keep-instance","Do not terminate the instance after build").option("--subnet <id>","VPC Subnet ID to launch the instance in").option("--security-group <id>","VPC Security Group ID to use").option("--ssh-host <host>","Remote host for iOS build (SSH)").option("--ssh-user <user>","SSH username for remote host").option("--ssh-key <path>","Path to private SSH key for remote host").option("--ios-scheme <scheme>","iOS Scheme to build").option("--ios-team-id <id>","Apple Development Team ID").option("--ios-configuration <config>","Xcode configuration (Release/Debug)").option("--ios-export-method <method>","Export method (ad-hoc, app-store, development, enterprise)").option("--ios-api-key-id <id>","App Store Connect API Key ID").option("--ios-api-key-issuer <id>","App Store Connect API Key Issuer ID").option("--ios-api-key-path <path>","Path to App Store Connect API Key (.p8) file").option("--simulator","Build for iOS Simulator (no signing required)").addOption(new Tn("--build-id <id>","Internal build ID").hideHelp()).addOption(new Tn("--project-id <id>","Internal project ID").hideHelp()).option("--local","Run build on local machine").option("--auto-version","Automatically fetch and increment versionCode from Google Play").option("--verbose","Enable verbose logging").option("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1).action(async(e,n)=>{let t=J.opts();n.yes=n.yes||t.yes,n.quiet=n.quiet||t.quiet,n.platform=e||n.platform,n.buildProfile=n.profile||n.buildProfile,n.quiet||ue(se.bgCyan.black(f.cliTag("Cloud Build"))),await It(n)});J.command("update").description("Deploy an Over-The-Air (OTA) update to your live channel").option("--branch <name>","Channel or Branch to deploy to (e.g., production)","production").action(async e=>{ue(se.bgCyan.black(f.cliTag("OTA Update"))),await Ki(e)});J.command("submit").description("Automated Store Submission (App Store / Google Play)").option("--platform <os>","Target platform (ios/android)").option("--track <track>","Google Play Track (internal, alpha, beta, production)","internal").option("--latest","Use the latest successful build for submission").option("--build-id <id>","Use a specific build ID for submission").action(async e=>{ue(se.bgCyan.black(f.cliTag("Store Submission"))),await ji(e)});J.command("login").description(`Login to ${f.name} Dashboard`).action(async()=>{ue(se.bgCyan.black(f.cliTag("Login"))),await ki()});J.command("link").description(`Link local directory to a ${f.name} Project`).action(async()=>{ue(se.bgCyan.black(f.cliTag("Link Project"))),await xi()});J.command("me").description("Display currently logged in user details").action(async()=>{await zi()});J.command("init").description(`Create a new ${f.name} Project`).action(async()=>{ue(se.bgCyan.black(f.cliTag("Init Project"))),await Li()});J.command("env").description("Manage Environment Variables").argument("<action>","Action to perform: set or list").argument("[args...]","Key=Value pairs for set action").action(async(e,n)=>{ue(se.bgCyan.black(f.cliTag("Env Manager"))),await Fi(e,n)});J.command("start").description("Start the development server (Metro)").option("-p, --build-profile <name>","Build profile (e.g. development, staging)","development").option("--tunnel","Use ngrok tunnel").option("--lan","Use LAN IP").option("--localhost","Use localhost").option("-c, --clear","Clear Metro cache").option("--port <number>","Port to listen on").option("--ios","Start on iOS").option("--android","Start on Android").option("--web","Start on Web").action(async e=>{ue(se.bgCyan.black(f.cliTag("Dev Server"))),await qi(e)});J.command("config").description("Show resolved configuration for a profile").option("-p, --profile <name>","Build profile to resolve","development").option("--json","Output as JSON").action(async e=>{await Xi(e)});J.command("credentials").description("Unified, interactive credential management (iOS/Android)").option("-p, --profile <name>","Build profile (production, staging, development)").option("--force","Force recreate certificates (nuke existing on Apple Portal)",!1).action(async e=>{let{credentialsMainCommand:n}=await import("./credentials-WL7JKLF4.js");await n(e)});J.command("credentials:setup").description("Automated credential provisioning (iOS/Android) [Legacy]").requiredOption("--platform <os>","Platform: ios or android").option("--profile <name>","Build profile (production, staging, development)").option("--bundle-id <id>","Bundle ID / Package Name (optional, auto-detected)").option("--team-id <id>","Apple Team ID (iOS only)").option("--key-alias <alias>","Android keystore alias (optional, auto-generated)").option("--aws-profile <name>","AWS Credentials Profile (for S3 storage)").option("--force","Force recreate certificates (nuke existing on Apple Portal)",!1).action(async e=>{ue(se.bgCyan.black(f.cliTag("Credentials Setup"))),await qe(e),Nn(se.green("Done!"))});J.command("credentials:service").description("Upload Service Credentials (ASC API Key / Google Service JSON) [Legacy]").requiredOption("--platform <os>","Platform: ios or android").option("--file <path>","Path to credential file (.p8 or .json)").option("--issuer-id <id>","ASC API Key Issuer ID (iOS only)").option("--key-id <id>","ASC API Key ID (iOS only)").action(async e=>{ue(se.bgCyan.black(f.cliTag("Service Credentials"))),await li(e),Nn(se.green("Done!"))});var ri=J.command("device").description("Manage registered iOS test devices");ri.command("register").description("Register a connected iOS device or enter UDID manually").option("--udid <udid>","Device UDID (skip auto-detection)").option("--name <name>","Device name").action(async e=>{await wt("register",e)});ri.command("list").description("List all registered devices").action(async()=>{await wt("list",{})});ri.command("remove").description("Remove a registered device").option("--udid <udid>","Device UDID to remove").action(async e=>{await wt("remove",e)});J.command("audit").description("Run automated security audit on the project or APK").option("--apk <path>","Path to APK file (runs APK diagnostics like 16KB alignment)").option("--json","Output results as JSON (for CI/CD)").option("--fix","Auto-apply fixes where possible").option("--category <name>","Run only a specific check category (e.g. 16kb, permissions, secrets)").option("--severity <level>","Minimum severity to display (critical, high, medium, low, info)").option("--prebuild","Run expo prebuild for deeper manifest/plist analysis").action(async e=>{ue(se.bgCyan.black(f.cliTag(e.apk?"APK Audit":"Security Audit"))),await On(e)});var is=new Set(["login"]);J.hook("preAction",(e,n)=>{let t=n.name();is.has(t)||ai()});J.on("command:*",()=>{console.error(`Invalid command: %s
823
+ See --help for a list of available commands.`,J.args.join(" ")),process.exit(1)});process.argv.slice(2).length||J.help();J.parse(process.argv);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@radhya/mach",
3
- "version": "1.4.22",
3
+ "version": "1.4.23",
4
4
  "description": "Mach CLI: Cloud Build Orchestrator for React Native & Expo",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",