@radhya/mach 2.0.2 → 2.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -1
- package/dist/chunk-UZNUPNFP.js +61 -0
- package/dist/{credentials-G45XNNRU.js → credentials-KDH6HGWP.js} +1 -1
- package/dist/index.js +139 -137
- package/package.json +1 -1
- package/dist/chunk-K7ILUOUP.js +0 -61
package/dist/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as
|
|
3
|
-
`;s+=`Region: ${
|
|
4
|
-
`,s+=`S3 Website URL: ${
|
|
5
|
-
|
|
6
|
-
CloudFront ID: ${
|
|
7
|
-
CloudFront URL: ${
|
|
8
|
-
${s.map(
|
|
9
|
-
`)}`,"Sitemap Summary"),
|
|
2
|
+
import{a as qi,b as Pe,c as Qe,d as Xi,e as Zi,f as St,g as Qi,i as Ct}from"./chunk-UZNUPNFP.js";import{a as f,b as Wi,c as Re,d as Yi,e as Ji,f as yt,g as Ke,h as R}from"./chunk-HIP5BA3H.js";import{Command as Hu,Option as Le}from"commander";import{configDotenv as ju}from"dotenv";import{intro as we,outro as Fs}from"@clack/prompts";import be from"chalk";import{text as er,confirm as Hs,spinner as js,isCancel as Vn,cancel as Nt,note as Gs,outro as Ks}from"@clack/prompts";import Tt from"chalk";async function tr(){try{let e=await er({message:"Enter Bucket Name:",placeholder:"e.g. my-app-dev",validate(r){if(r.length===0)return"Bucket name is required"}});Vn(e)&&(Nt("Operation cancelled."),process.exit(0));let t=await er({message:"Enter Region:",initialValue:"ap-south-1"});Vn(t)&&(Nt("Operation cancelled."),process.exit(0));let n=await Hs({message:"Do you want to create a CloudFront Distribution for this bucket?",initialValue:!0});Vn(n)&&(Nt("Operation cancelled."),process.exit(0));let i=js();i.start("Setting up hosting infrastructure...");try{let r=await R.post("/hosting/setup",{bucketName:e,region:t,createCloudFront:n});if(r.data.status!=="success")throw new Error(r.data.message||"Hosting setup failed");i.stop("Hosting setup complete!");let o=r.data,s=`Bucket Name: ${Tt.cyan(o.bucketName)}
|
|
3
|
+
`;s+=`Region: ${Tt.cyan(o.region)}
|
|
4
|
+
`,s+=`S3 Website URL: ${Tt.blue(o.s3WebsiteUrl)}`,o.cloudFrontId&&(s+=`
|
|
5
|
+
|
|
6
|
+
CloudFront ID: ${Tt.cyan(o.cloudFrontId)}`,s+=`
|
|
7
|
+
CloudFront URL: ${Tt.blue(o.cloudFrontUrl)}`),Gs(s,"Setup Complete!"),Ks("You are all set!")}catch(r){i.stop("Setup failed"),Nt(`Error: ${r.response?.data?.message||r.message}`)}}catch(e){Nt(`An unexpected error occurred: ${e.message}`)}}import{readdir as Vs,writeFile as zs,access as Ws,mkdir as Ys}from"fs/promises";import{join as nr}from"path";import{spinner as Js,text as ir,isCancel as rr,cancel as zn,note as qs,outro as Xs}from"@clack/prompts";import Zs from"chalk";async function Qs(){let e=["./app","./src/app"];for(let t of e)try{return await Ws(t),t}catch{}return null}async function or(e){try{let n=await Qs()||"./app",i=await ir({message:"Enter path to your app directory:",placeholder:n,initialValue:n,validate(c){if(c.length===0)return"Path is required"}});rr(i)&&(zn("Operation cancelled."),process.exit(0));let r=await ir({message:"Enter your website base URL:",placeholder:"https://example.com",validate(c){if(c.length===0)return"Base URL is required";if(!c.startsWith("http"))return"URL must start with http:// or https://"}});rr(r)&&(zn("Operation cancelled."),process.exit(0));let o=Js();o.start("Scanning app directory for routes...");let s=await sr(i);o.stop(`Found ${s.length} routes`);let l=ea(s,r),a=e.output||"./public/sitemap.xml";o.start(`Writing sitemap to ${a}...`);let d=a.substring(0,a.lastIndexOf("/"));if(d)try{await Ys(d,{recursive:!0})}catch{}await zs(a,l,"utf-8"),o.stop("Sitemap generated successfully!"),qs(`Routes included:
|
|
8
|
+
${s.map(c=>` \u2022 ${c.path}`).join(`
|
|
9
|
+
`)}`,"Sitemap Summary"),Xs(`Sitemap saved to ${Zs.cyan(a)}`)}catch(t){zn(`An error occurred: ${t.message}`)}}async function sr(e,t=""){let n=[];try{let i=await Vs(e,{withFileTypes:!0});for(let r of i){let o=nr(e,r.name);if(!(r.name.startsWith("_")||r.name.startsWith("."))){if(r.isDirectory()){let s=await sr(o,nr(t,r.name));n.push(...s)}else if(r.isFile()){if(r.name==="index.tsx"||r.name==="index.ts"||r.name==="index.jsx"||r.name==="index.js"){let s=t===""?"/":`/${t}`;n.push({path:s,file:o})}else if(r.name.match(/\.(tsx|ts|jsx|js)$/)&&!r.name.includes("_layout")&&!r.name.includes("+")){let s=r.name.replace(/\.(tsx|ts|jsx|js)$/,""),l=`/${t}/${s}`.replace(/\/+/g,"/");n.push({path:l,file:o})}}}}}catch(i){throw new Error(`Failed to scan directory ${e}: ${i.message}`)}return n}function ea(e,t){let n=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(r=>{let o=r.path;return o=o.replace(/\/\([^)]+\)/g,""),o=o.replace(/\/\[.*?\]/g,"/:id"),o=o.replace(/\/+/g,"/"),o===""&&(o="/"),` <url>
|
|
12
12
|
<loc>${t}${o}</loc>
|
|
@@ -15,7 +15,7 @@ ${e.map(r=>{let o=r.path;return o=o.replace(/\/\([^)]+\)/g,""),o=o.replace(/\/\[
|
|
|
15
15
|
<priority>0.8</priority>
|
|
16
16
|
</url>`}).join(`
|
|
17
17
|
`)}
|
|
18
|
-
</urlset>`}import{randomUUID as
|
|
18
|
+
</urlset>`}import{randomUUID as Sd}from"crypto";import $e from"path";import yn from"axios";import bd from"os";import{spinner as _i,confirm as to,isCancel as no,log as _}from"@clack/prompts";import $ from"chalk";import de from"fs";import{execSync as io}from"child_process";import ro from"adm-zip";import{spinner as sa,log as sn}from"@clack/prompts";import lr from"chalk";import dr from"fs";import cr from"path";var ar=`#!/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}}"
|
|
@@ -530,15 +530,15 @@ for pid in "\${cache_pids[@]}"; do wait "$pid" || true; done
|
|
|
530
530
|
echo "Build orchestrator finished. Auto-terminating instance in 5 seconds..."
|
|
531
531
|
sleep 5
|
|
532
532
|
sudo shutdown -h now
|
|
533
|
-
`;import
|
|
534
|
-
`):"",p;if(r){let
|
|
535
|
-
export MACH_APP_NAME="${
|
|
536
|
-
export MACH_BUILD_PROFILE="${
|
|
537
|
-
export MACH_ANDROID_RELEASE_ABIS="${
|
|
538
|
-
export MACH_ENV_FINGERPRINT="${
|
|
533
|
+
`;import ta from"crypto";var na="mach-env-v2-js-bundle-cache",ia=new Set(["BUILD_ID","BUILD_NUMBER","ANDROID_VERSION_CODE","MACH_TOKEN","MACH_DEBUG","MACH_ENV_FINGERPRINT","CODEARTIFACT_AUTH_TOKEN","EXPO_ZQRN_BB_REPO_TOKEN","SENTRY_AUTH_TOKEN","IOS_DIST_P12","IOS_PROVISIONING_PROFILE","IOS_P12_PASSWORD","MATCH_ENCRYPTION_PASSPHRASE","MATCH_PASSWORD","MATCH_KEYCHAIN_NAME","MATCH_KEYCHAIN_PASSWORD","APPLE_TEAM_ID","FASTLANE_TEAM_ID","ANDROID_KEYSTORE","ANDROID_KEYSTORE_BASE64","ANDROID_STORE_PASSWORD","ANDROID_KEY_PASSWORD","ANDROID_KEY_ALIAS","KEYSTORE_PASSWORD","KEYSTORE_ALIAS","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","AWS_SECURITY_TOKEN","GITHUB_TOKEN","NPM_TOKEN"]),ra=["PRESIGNED_","KEYSTORE_PASSWORD_"],oa=e=>!e||ia.has(e)?!1:!ra.some(t=>e.startsWith(t)),dt=(e,t,n)=>({...e,EXPO_NO_DOTENV:"1",MACH_BUILD_PROFILE:t,MACH_APP_NAME:n.appName||n.name||"App"}),bt=e=>{let t=Object.entries(e).filter(([n])=>oa(n)).sort(([n],[i])=>n.localeCompare(i));return ta.createHash("sha256").update(JSON.stringify({version:na,entries:t})).digest("hex")};var Wn=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`"),Yn=e=>["1","true","yes","on"].includes(String(e||"").trim().toLowerCase()),aa=e=>/(^|[-_])(maestro|e2e|test|emulator)([-_]|$)/i.test(e),la=(e,t,n)=>{let i=n.MACH_ANDROID_RELEASE_ABIS||n.MACH_ANDROID_ABIS||n.MACH_PROFILE_ANDROID_RELEASE_ABIS||n.MACH_PROFILE_ANDROID_ABIS||n.MACH_PROFILE_ANDROID_ARCHITECTURES||n.MACH_PROFILE_ANDROID_REACT_NATIVE_ARCHITECTURES;return i||(!!e.maestro||aa(t)||Yn(n.MACH_PROFILE_ANDROID_EMULATOR)||Yn(n.MACH_ANDROID_INCLUDE_EMULATOR_ABIS)||Yn(n.MACH_PROFILE_ANDROID_INCLUDE_EMULATOR_ABIS)?"armeabi-v7a,arm64-v8a,x86_64":"armeabi-v7a,arm64-v8a")},ur=async(e,t,n={},i,r)=>{let o=sa(),s=e.buildProfile||"production",l=s==="production",a=e.apk===!0,d=e.developmentClient?"assembleDebug":l?"bundleRelease":"assembleRelease",c=e.buildCommand||(a?"assembleRelease":d),u=e.nodeVersion?[`echo "[NODE] Switching to Node ${e.nodeVersion}..."`,`CURRENT_MAJOR=$(node -e "process.stdout.write(process.version.split('.')[0].replace('v',''))" 2>/dev/null || echo "0")`,`if [ "$CURRENT_MAJOR" != "${e.nodeVersion}" ]; then`,` curl -fsSL https://deb.nodesource.com/setup_${e.nodeVersion}.x | bash - 2>&1`," apt-get install -y nodejs 2>&1",' echo "[NODE] Installed Node $(node -v)"',"else",' echo "[NODE] Already on Node $(node -v) \u2014 no switch needed"',"fi"].join(`
|
|
534
|
+
`):"",p;if(r){let M=cr.isAbsolute(r)?r:cr.resolve(process.cwd(),r);dr.existsSync(M)?(p=dr.readFileSync(M,"utf-8"),sn.info(lr.magenta(`\u2713 Loaded preBuild hook: ${r}`))):sn.warn(`preBuild script not found at ${M} \u2014 skipping`)}let m=la(e,s,n),y={...dt(n,s,e),MACH_ANDROID_RELEASE_ABIS:m},C=bt(y),N=ar.replace(/\{\{BUILD_ID\}\}/g,t).replace(/\{\{BUILD_COMMAND\}\}/g,c).replace("{{NODE_VERSION_SETUP}}",u).replace("{{ENV_VARS}}",`
|
|
535
|
+
export MACH_APP_NAME="${Wn(y.MACH_APP_NAME)}"
|
|
536
|
+
export MACH_BUILD_PROFILE="${Wn(s)}"
|
|
537
|
+
export MACH_ANDROID_RELEASE_ABIS="${Wn(m)}"
|
|
538
|
+
export MACH_ENV_FINGERPRINT="${C}"
|
|
539
539
|
export EXPO_NO_DOTENV=1
|
|
540
540
|
{{ENV_VARS}}
|
|
541
|
-
`);if(e.dryRun){
|
|
541
|
+
`);if(e.dryRun){sn.info("User Data Script (dry run):"),console.log(N);return}o.start("Requesting cloud build instance...");try{let M=await R.post("/builds/launch-android",{projectId:i,buildId:t,platform:e.platform,buildProfile:e.buildProfile,buildCommand:c,instanceType:e.instanceType,ami:e.ami,keepInstance:e.keepInstance,region:e.region,subnet:e.subnet,securityGroup:e.securityGroup,projectSecrets:n,dryRun:e.dryRun,userDataScript:N,preBuildScriptContent:p});if(M.data.status!=="success")throw new Error(M.data.message||"Failed to launch build instance");let P=M.data.instanceId;return o.stop("Build Started"),sn.success(lr.green(`Build initiated on cloud instance (${P}).`)),{instanceId:P}}catch(M){o.stop("Android Build Failed");let P=M.response?.data?.message||M.message;throw new Error(`Failed to launch Android build: ${P}`)}};import{spinner as da,log as Et}from"@clack/prompts";import et from"chalk";import ca from"fs";import{execSync as kt}from"child_process";var pr=`#!/bin/bash
|
|
542
542
|
# --- Mach Cloud Build Script (iOS) ---
|
|
543
543
|
# All S3 operations use presigned URLs via curl \u2014 zero AWS credentials on Mac.
|
|
544
544
|
|
|
@@ -1022,40 +1022,40 @@ touch done
|
|
|
1022
1022
|
if [ ! -z "$PRESIGNED_DONE_MARKER" ]; then
|
|
1023
1023
|
curl -X PUT -T done "$PRESIGNED_DONE_MARKER" --silent
|
|
1024
1024
|
fi
|
|
1025
|
-
`;var
|
|
1026
|
-
`:
|
|
1027
|
-
`);r.message("Generating macOS build script...");let
|
|
1028
|
-
`:"";if(n)for(let[
|
|
1029
|
-
`}let
|
|
1030
|
-
`),
|
|
1031
|
-
`):"",
|
|
1025
|
+
`;var fr=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`"),mr=async(e,t,n={},i)=>{let r=da();e.sshHost||(e.sshHost="localhost",Et.message(et.yellow("No SSH host provided, defaulting to localhost."))),r.start(`Connecting to remote Mac at ${et.cyan(e.sshHost)}...`);let o=e.sshUser||process.env.USER||"ubuntu",s=e.sshKey,l=`${o}@${e.sshHost}`,a=`ssh ${s?`-i ${s}`:""} -o StrictHostKeyChecking=no ${l}`,d=`scp ${s?`-i ${s}`:""} -o StrictHostKeyChecking=no`;try{let c=o==="ubuntu"?"/home/ubuntu":`/Users/${o}`,u=(n.PROJECT_ID||"default_project").replace(/[^a-zA-Z0-9-_]/g,"_"),p=`${c}/${f.remoteWorkspacesDir}/${u}`;r.message(`Preparing stable workspace: ${p}...`),kt(`${a} "mkdir -p ${p}"`,{stdio:"inherit"}),r.message("Transferring source code...");let m=`/tmp/${f.nameLower}-source-${t}.zip`;kt(`${d} ${m} ${l}:${p}/source.zip`,{stdio:"inherit"});let y=e.iosApiKeyPath?`${p}/api_key.p8`:"",C="";e.iosApiKeyPath&&(r.message("Uploading App Store Connect API key..."),kt(`${d} ${e.iosApiKeyPath} ${l}:${y}`),e.iosApiKeyId&&e.iosApiKeyIssuer&&(C=`-authenticationKeyID ${e.iosApiKeyId} -authenticationKeyIssuerID ${e.iosApiKeyIssuer} -authenticationKeyPath ${y}`));let N={};if(i)try{let v=await R.post(`/builds/${i}/${t}/build-urls`,{platform:"ios"});v.data.status==="success"&&(N=v.data.urls)}catch(v){Et.warn(et.yellow(`Could not fetch build URLs: ${v.message}`))}let M="";if(N.credentials&&N.credentials.length>0)for(let v of N.credentials)v.type==="p12"?M+=`curl -sf -o "$CERT_DIR/${v.name}" "${v.downloadUrl}" || true
|
|
1026
|
+
`:v.type==="mobileprovision"&&(M+=`curl -sf -o "$PROV_TEMP/${v.name}" "${v.downloadUrl}" || true
|
|
1027
|
+
`);r.message("Generating macOS build script...");let P=process.env.CODEARTIFACT_AUTH_TOKEN?`export CODEARTIFACT_AUTH_TOKEN="${process.env.CODEARTIFACT_AUTH_TOKEN}"
|
|
1028
|
+
`:"";if(n)for(let[v,E]of Object.entries(n)){let k=E.replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");P+=`export ${v}="${k}"
|
|
1029
|
+
`}let j=e.buildProfile||"production",S=dt(n,j,e),G=bt(S),Q=[P,N.logUpload?`export PRESIGNED_LOG_UPLOAD="${N.logUpload}"`:"",N.doneMarker?`export PRESIGNED_DONE_MARKER="${N.doneMarker}"`:"",N.cacheDerivedDataDownload?`export PRESIGNED_CACHE_DD_DOWNLOAD="${N.cacheDerivedDataDownload}"`:"",N.cacheDerivedDataUpload?`export PRESIGNED_CACHE_DD_UPLOAD="${N.cacheDerivedDataUpload}"`:"",N.cacheNodeModulesDownload?`export PRESIGNED_CACHE_NODE_DOWNLOAD="${N.cacheNodeModulesDownload}"`:"",N.cacheNodeModulesUpload?`export PRESIGNED_CACHE_NODE_UPLOAD="${N.cacheNodeModulesUpload}"`:"",N.cachePodsDownload?`export PRESIGNED_CACHE_PODS_DOWNLOAD="${N.cachePodsDownload}"`:"",N.cachePodsUpload?`export PRESIGNED_CACHE_PODS_UPLOAD="${N.cachePodsUpload}"`:"",N.artifactIpaUpload?`export PRESIGNED_ARTIFACT_IPA_UPLOAD="${N.artifactIpaUpload}"`:"",N.artifactAppZipUpload?`export PRESIGNED_ARTIFACT_APP_ZIP_UPLOAD="${N.artifactAppZipUpload}"`:"",`export BUILD_ID="${t}"`,`export MACH_BUILD_PROFILE="${fr(j)}"`,`export MACH_APP_NAME="${fr(S.MACH_APP_NAME)}"`,`export MACH_ENV_FINGERPRINT="${G}"`,"export EXPO_NO_DOTENV=1",`export ${f.envPrefix}PROJECT_ID="${u}"`,n.MATCH_ENCRYPTION_PASSPHRASE?`export MATCH_PASSWORD="${n.MATCH_ENCRYPTION_PASSPHRASE}"`:"",n.APPLE_TEAM_ID?`export FASTLANE_TEAM_ID="${n.APPLE_TEAM_ID}"`:"",`export MATCH_KEYCHAIN_NAME="${f.credentialsKeychain}"`,`export MATCH_KEYCHAIN_PASSWORD="${f.keychainPassword}"`].filter(Boolean).join(`
|
|
1030
|
+
`),g=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(`
|
|
1031
|
+
`):"",T=pr,I={"{{REMOTE_DIR}}":p,"{{ENV_VARS}}":Q,"{{CREDENTIAL_DOWNLOADS}}":M,"{{IOS_SCHEME}}":e.iosScheme||"","{{IOS_CONFIG}}":e.iosConfiguration||"Release","{{TEAM_ID}}":e.iosTeamId||"","{{AUTH_PARAMS}}":C,"{{IS_SIMULATOR}}":e.simulator?"true":"false","{{BUILD_ID}}":t,"{{EXPORT_METHOD}}":e.iosExportMethod||"ad-hoc","{{NODE_VERSION_SETUP}}":g};Object.entries(I).forEach(([v,E])=>{T=T.split(v).join(E)});let L=`/tmp/${f.nameLower}-mac-build-${t}.sh`;if(ca.writeFileSync(L,T),kt(`${d} ${L} ${l}:${p}/build.sh`),r.stop("Remote script uploaded."),Et.info(et.cyan("Executing remote build. This might take a while...")),kt(`${a} "bash ${p}/build.sh"`,{stdio:"inherit"}),r.stop("Remote build finished!"),i){r.start("Fetching artifact links...");try{let E=(await R.get(`/builds/${i}/${t}/artifacts`)).data.artifacts||[],k=e.simulator===!0;if(E.length===0&&!k)throw r.stop("Build Failed!"),new Error("Build completed but no artifacts were generated. Check build logs for errors.");if(r.stop("Build Successful!"),E.length>0){Et.success("Build Artifacts Ready:");for(let K of E)console.log(`
|
|
1032
1032
|
${et.yellow(K.name)}:
|
|
1033
1033
|
${et.cyan(K.downloadUrl)}`);console.log(`
|
|
1034
|
-
${et.dim("Note: Links are valid for 7 days.")}`)}else
|
|
1034
|
+
${et.dim("Note: Links are valid for 7 days.")}`)}else k&&Et.warn("Simulator build completed. No artifacts uploaded.")}catch(v){r.stop("Could not fetch artifacts"),Et.warn(et.yellow(`Artifact listing failed: ${v.message}`))}}}catch(c){throw r.stop("iOS Build Failed"),c}};import ua from"crypto";import Me from"axios";import gr from"fs";var Ve=6e4,pa=12e4,Jn=4,Je=e=>encodeURIComponent(e),fa=e=>new Promise(t=>setTimeout(t,e));async function Ue(e,t){let n;for(let i=1;i<=Jn;i++)try{return await t()}catch(r){if(n=r,i>=Jn||!ma(r))throw r;let o=Number(r.response?.headers?.["retry-after"]),s=Number.isFinite(o)&&o>0?o*1e3:Math.min(2e3*i*i,15e3);console.log(`[Google Play] ${e} failed (attempt ${i}/${Jn}); retrying in ${Math.round(s/1e3)}s...`),await fa(s)}throw n}function ma(e){let t=e.response?.status;return t?t===408||t===409||t===425||t===429||t>=500:!0}async function hr(e,t){let n;try{let i=await an(t),r=Je(e);if(n=(await Ue("create edit",()=>Me.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits`,{},{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Ve}))).data.id,!n)throw new Error("Google Play edit insert succeeded but did not return an edit id.");let s=Je(n),l=0,d=(await Ue("list tracks",()=>Me.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits/${s}/tracks`,{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Ve}))).data.tracks||[];for(let c of d)if(c.releases){for(let u of c.releases)if(u.versionCodes)for(let p of u.versionCodes){let m=parseInt(p,10);m>l&&(l=m)}}try{let u=(await Ue("list bundles",()=>Me.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits/${s}/bundles`,{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Ve}))).data.bundles||[];for(let p of u)p.versionCode&&p.versionCode>l&&(l=p.versionCode)}catch{}try{let u=(await Ue("list APKs",()=>Me.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits/${s}/apks`,{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Ve}))).data.apks||[];for(let p of u)p.versionCode&&p.versionCode>l&&(l=p.versionCode)}catch{}return l}catch(i){let r=i.response?.data?.error?.message||i.message;throw new Error(`Google Play API Error: ${r}`)}finally{if(n)try{let i=await an(t);await Ue("delete edit",()=>Me.delete(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${Je(e)}/edits/${Je(n)}`,{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Ve}))}catch{}}}async function yr(e){let{packageName:t,serviceAccount:n,aabPath:i,track:r,releaseStatus:o,userFraction:s,changesNotSentForReview:l}=e,a;try{let c={Authorization:`Bearer ${await an(n)}`,Connection:"close"},u=Je(t);if(a=(await Ue("create edit",()=>Me.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${u}/edits`,{},{headers:c,timeout:Ve}))).data.id,!a)throw new Error("Google Play edit insert succeeded but did not return an edit id.");let m=Je(a),y=gr.statSync(i),C=await Ue("upload AAB",()=>Me.post(`https://androidpublisher.googleapis.com/upload/androidpublisher/v3/applications/${u}/edits/${m}/bundles`,gr.createReadStream(i),{headers:{...c,"Content-Type":"application/octet-stream","Content-Length":y.size},maxBodyLength:1/0,maxContentLength:1/0,params:{uploadType:"media"},timeout:pa})),N=Number(C.data.versionCode);if(!N)throw new Error("Google Play upload succeeded but did not return a versionCode.");let M={versionCodes:[String(N)],status:o};return(o==="inProgress"||o==="halted")&&typeof s=="number"&&(M.userFraction=s),await Ue("update track",()=>Me.put(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${u}/edits/${m}/tracks/${Je(r)}`,{releases:[M]},{headers:c,timeout:Ve})),await Ue("commit edit",()=>Me.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${u}/edits/${m}:commit`,{},{headers:c,params:l?{changesNotSentForReview:!0}:void 0,timeout:Ve})),{editId:a,versionCode:N,track:r,releaseStatus:o,userFraction:s}}catch(d){if(a)try{let u=await an(n);await Ue("delete edit",()=>Me.delete(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${Je(t)}/edits/${Je(a)}`,{headers:{Authorization:`Bearer ${u}`,Connection:"close"},timeout:Ve}))}catch{}let c=d.response?.data?.error?.message||d.message;throw new Error(`Google Play API Error: ${c}`)}}async function an(e){let t=Math.floor(Date.now()/1e3),n=t+3600,i={alg:"RS256",typ:"JWT"},r={iss:e.client_email,sub:e.client_email,aud:"https://oauth2.googleapis.com/token",iat:t,exp:n,scope:"https://www.googleapis.com/auth/androidpublisher"},o=Buffer.from(JSON.stringify(i)).toString("base64url"),s=Buffer.from(JSON.stringify(r)).toString("base64url"),l=`${o}.${s}`,a=ua.createSign("RSA-SHA256");a.update(l);let d=a.sign(e.private_key,"base64url"),c=`${l}.${d}`;return(await Ue("OAuth token exchange",()=>Me.post("https://oauth2.googleapis.com/token",{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:c},{headers:{Connection:"close"},timeout:Ve}))).data.access_token}import ga from"crypto";import Sr from"axios";var Xn="https://api.appstoreconnect.apple.com/v1",br=6e4,qn=4,ha=e=>new Promise(t=>setTimeout(t,e));function ya(e,t,n){let i=Math.floor(Date.now()/1e3),r=Buffer.from(JSON.stringify({alg:"ES256",kid:e,typ:"JWT"})).toString("base64url"),o=Buffer.from(JSON.stringify({iss:t,iat:i,exp:i+1200,aud:"appstoreconnect-v1"})).toString("base64url"),s=`${r}.${o}`,l=ga.createSign("SHA256");l.update(s);let a=l.sign({key:n,dsaEncoding:"ieee-p1363"}).toString("base64url");return`${s}.${a}`}function Sa(e){let t=e.response?.status;return t?t===408||t===409||t===425||t===429||t>=500:!0}async function Er(e,t){let n;for(let i=1;i<=qn;i++)try{return await t()}catch(r){if(n=r,i>=qn||!Sa(r))throw r;let o=Number(r.response?.headers?.["retry-after"]),s=Number.isFinite(o)&&o>0?o*1e3:Math.min(2e3*i*i,15e3);console.log(`[App Store Connect] ${e} failed (attempt ${i}/${qn}); retrying in ${Math.round(s/1e3)}s...`),await ha(s)}throw n}function Ar(e){return{Authorization:`Bearer ${ya(e.keyId,e.issuerId,e.privateKey)}`,"Content-Type":"application/json",Connection:"close"}}function ba(e){let t=e.response?.data?.errors;return Array.isArray(t)&&t.length>0?t.map(n=>n.detail||n.title||n.code).filter(Boolean).join("; "):e.response?.data?.error?.message||e.message||"Unknown App Store Connect error"}function ln(e){let t=String(e||"").trim();if(/^\d+(?:\.\d+){0,2}$/.test(t))return t.split(".").map(n=>Number(n))}function Ea(e,t){let n=ln(e),i=ln(t);if(!n&&!i)return 0;if(!n)return-1;if(!i)return 1;let r=Math.max(n.length,i.length);for(let o=0;o<r;o++){let s=n[o]||0,l=i[o]||0;if(s!==l)return s>l?1:-1}return 0}function Aa(e){let t=ln(e);return!t||t.length===0?"1":(t[t.length-1]+=1,t.join("."))}async function Ia(e,t,n){if(t)return t;if(!n)throw new Error("Set ios.ascAppId or ios.bundleIdentifier so Mach can find the App Store Connect app.");let r=(await Er("lookup app by bundle ID",()=>Sr.get(`${Xn}/apps`,{headers:Ar(e),params:{"filter[bundleId]":n,limit:1},timeout:br}))).data?.data?.[0];if(!r?.id)throw new Error(`No App Store Connect app found for bundle ID ${n}. Set ios.ascAppId in mach.config.json if the app exists.`);return r.id}async function Ir(e){let t={keyId:e.keyId,issuerId:e.issuerId,privateKey:e.privateKey};try{let n=await Ia(t,e.ascAppId,e.bundleId),i=`${Xn}/builds`,r="0",o,s=0;for(;i&&s<10;){s+=1;let l=await Er("list builds",()=>Sr.get(i,{headers:Ar(t),params:i===`${Xn}/builds`?{"filter[app]":n,"fields[builds]":"version,uploadedDate",sort:"-uploadedDate",limit:200}:void 0,timeout:br})),a=l.data?.data||[];for(let d of a){let c=String(d.attributes?.version||"").trim();ln(c)&&Ea(c,r)>0&&(r=c,o=d.attributes?.uploadedDate)}i=l.data?.links?.next}return{appId:n,latestBuildNumber:r,nextBuildNumber:Aa(r),latestUploadedDate:o}}catch(n){throw new Error(`App Store Connect API Error: ${ba(n)}`)}}import{spinner as dn,log as A,isCancel as cn,confirm as wa,select as Qn}from"@clack/prompts";import b from"chalk";import h from"fs";import w from"path";import{execFileSync as Zn,execSync as te,spawn as vr}from"child_process";import Ae from"os";import _a from"crypto";var Rr=(e,t)=>t.filter(n=>h.existsSync(w.join(e,n))).reduce((n,i)=>n.update(h.readFileSync(w.join(e,i))),_a.createHash("sha256")).digest("hex").slice(0,16),$a=e=>Rr(e,["package.json","yarn.lock","package-lock.json","bun.lockb"]),va=e=>Rr(e,["Podfile","Podfile.lock"]),Ra=e=>{let t=w.join(e,"fingerprint.json");try{return JSON.parse(h.readFileSync(t,"utf-8"))}catch{return{}}},wr=(e,t)=>{h.mkdirSync(e,{recursive:!0}),h.writeFileSync(w.join(e,"fingerprint.json"),JSON.stringify(t,null,2))},Pa=7200*1e3,Da=(e,t)=>{h.mkdirSync(e,{recursive:!0});let n=w.join(e,"build.lock");if(h.existsSync(n))try{let i=JSON.parse(h.readFileSync(n,"utf-8")),r=Date.now()-(i.timestamp||0);if(r<Pa)throw new Error(`Another build is already running for this project (build ${i.buildId}, started ${Math.round(r/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}h.writeFileSync(n,JSON.stringify({buildId:t,pid:process.pid,timestamp:Date.now()}))},Oa=(e,t)=>{let n=w.join(e,"build.lock");try{h.existsSync(n)&&JSON.parse(h.readFileSync(n,"utf-8")).buildId===t&&h.unlinkSync(n)}catch{}},_r=2e5,$r=(e,t)=>{let n=e+t;return n.length>_r?n.slice(-_r):n},Pr=e=>e.replace(/\u001b\[[0-9;]*m/g,""),Ca=(e,t,n,i)=>{let r=Pr(i).replace(/\r/g,`
|
|
1035
1035
|
`).split(`
|
|
1036
1036
|
`).map(a=>a.trimEnd()).filter(Boolean),o=r.filter(a=>/\berror:|fatal error:|xcodebuild: error|The following build commands failed|Command PhaseScriptExecution failed|CodeSign|Provisioning profile|No profiles|requires a provisioning profile|Undefined symbols|ld:|clang: error|SwiftCompile|CompileC/i.test(a)),s=o.length>0?o.slice(-40):r.slice(-80),l=o.length>0?"Key failure output":"Last command output";return[`Command failed with code ${n}: ${e} ${t.join(" ")}`,s.length>0?`
|
|
1037
1037
|
${l}:
|
|
1038
1038
|
${s.join(`
|
|
1039
|
-
`)}`:""].join("")},
|
|
1040
|
-
`)),r(
|
|
1041
|
-
`)),r(
|
|
1042
|
-
`)));let
|
|
1043
|
-
`)))}let
|
|
1039
|
+
`)}`:""].join("")},Na=e=>e==="xcodebuild"&&process.env.MACH_XCODE_FULL_LOGS!=="1",Ta=e=>{let t=Pr(e).trim();return t?/\berror:|fatal error:|xcodebuild: error|The following build commands failed|Command PhaseScriptExecution failed|CodeSign|Provisioning profile|No profiles|requires a provisioning profile|Undefined symbols|ld:|clang: error|SwiftCompile|CompileC|CFBundleVersion|ARCHIVE SUCCEEDED|ARCHIVE FAILED|EXPORT SUCCEEDED|EXPORT FAILED|Exported .* to:|\[IPA VALID\]/i.test(t):!1},ct=e=>{try{h.existsSync(e)&&h.rmSync(e,{recursive:!0,force:!0})}catch{}},ka=(e,t)=>{try{if(!h.existsSync(e))return;for(let n of h.readdirSync(e))t(n)&&ct(w.join(e,n))}catch{}},Dr=e=>{A.info(b.dim("Clearing Metro/Hermes JS transform caches..."));let t=Ae.tmpdir();ka(t,n=>n==="metro-cache"||n.startsWith("metro-")||n.startsWith("haste-map-")||n.startsWith("react-native-packager-cache-")),ct(w.join(e,".expo")),ct(w.join(e,"node_modules/.cache/metro")),ct(w.join(Ae.homedir(),".cache/metro")),ct(w.join(Ae.homedir(),".cache/react-native-packager")),ct(w.join(Ae.homedir(),"Library/Caches/metro")),ct(w.join(Ae.homedir(),"Library/Caches/react-native-packager"))},ze=(e,t,n=process.cwd(),i={},r,o)=>new Promise((s,l)=>{let a="",d=Na(e),c=Date.now(),u=["/opt/homebrew/bin","/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin",w.join(Ae.homedir(),".npm-global/bin")],m=[...(process.env.PATH||"").split(":"),...u].filter((P,j,S)=>P&&S.indexOf(P)===j).join(":");process.env[`${f.envPrefix}DEBUG`]&&console.log(b.magenta(`[${f.nameUpper}_DEBUG] Execution PATH: ${m}`));let y={...process.env,...i,PATH:m,LANG:"en_US.UTF-8",LC_ALL:"en_US.UTF-8"};r&&process.env[`${f.envPrefix}DEBUG`]&&(r(b.magenta(`[ENVIRONMENT] node: ${process.execPath}
|
|
1040
|
+
`)),r(b.magenta(`[ENVIRONMENT] PATH: ${m}
|
|
1041
|
+
`)),r(b.magenta(`[ENVIRONMENT] command: ${e} ${t.join(" ")}
|
|
1042
|
+
`)));let C=e;if(["node","npm","npx","pod"].includes(e)){let P=w.dirname(process.execPath),j=w.join(P,e);h.existsSync(j)&&(C=j,r&&r(b.dim(`[EXEC] Using absolute path: ${C}
|
|
1043
|
+
`)))}let N=vr(C,t,{stdio:"pipe",cwd:n,shell:!0,env:y,detached:process.platform!=="win32"});if(o){if(o.aborted){if(N.pid)try{process.kill(-N.pid,"SIGTERM")}catch{N.kill()}return l(new Error("Command aborted"))}o.addEventListener("abort",()=>{if(N.pid)try{process.kill(-N.pid,"SIGTERM")}catch{N.kill()}l(new Error("Command aborted"))})}let M=(P,j)=>{if(!d){j.write(P);return}let S=P.replace(/\r/g,`
|
|
1044
1044
|
`).split(`
|
|
1045
|
-
`).filter(
|
|
1045
|
+
`).filter(Ta);if(S.length>0){j.write(`${S.join(`
|
|
1046
1046
|
`)}
|
|
1047
|
-
`),
|
|
1048
|
-
`),
|
|
1049
|
-
`).find(r=>/^Payload\/[^/]+\.app\/Info\.plist$/.test(r.trim()));if(!n)throw new Error(`Could not validate iOS build number: ${
|
|
1050
|
-
\u{1F6D1} Build cancelled from dashboard. Terminating...`)),u.abort(),
|
|
1051
|
-
`)},
|
|
1052
|
-
`);else if(i&&l==="ios"&&!e.simulator)try{let
|
|
1053
|
-
`)),n.BUILD_NUMBER=
|
|
1054
|
-
`)}}catch(
|
|
1055
|
-
`)}if(await
|
|
1056
|
-
`),A.info(
|
|
1057
|
-
`),A.warn(
|
|
1058
|
-
`),
|
|
1047
|
+
`),c=Date.now();return}let G=Date.now();G-c>3e4&&(j.write(`[xcodebuild] still running; detailed output is streamed to Mach logs.
|
|
1048
|
+
`),c=G)};N.stdout.on("data",P=>{let j=P.toString();a=$r(a,j),M(j,process.stdout),r&&r(j)}),N.stderr.on("data",P=>{let j=P.toString();a=$r(a,j),M(j,process.stderr),r&&r(j)}),N.on("close",P=>{P===0?s(P):l(new Error(Ca(e,t,P,a)))}),N.on("error",P=>l(P))}),La=e=>{let t=Math.floor(e/1e3%60),n=Math.floor(e/(1e3*60)%60),i=Math.floor(e/(1e3*60*60)%24),r=[];return i>0&&r.push(`${i}h`),n>0&&r.push(`${n}m`),(t>0||r.length===0)&&r.push(`${t}s`),r.join(" ")},ut=(e,t)=>{let n=[];try{if(!h.existsSync(e))return n;let i=h.readdirSync(e);for(let r of i){let o=w.join(e,r);try{let s=h.statSync(o);if(t.some(a=>r.endsWith(a))){n.push(w.resolve(o));continue}s.isDirectory()&&(n=n.concat(ut(o,t)))}catch{}}}catch{}return n},xa=/^\d+(?:\.\d+){0,2}$/,ei=e=>{let t=String(e||"").trim();return!t||t==="undefined"||t==="null"?null:xa.test(t)?t:null},Or=(e,t)=>{let n=ei(e);if(!n)throw new Error(`Invalid iOS CFBundleVersion from ${t}: "${e||""}". Apple requires one to three period-separated integers, for example "42" or "1.2.3". If you see "[Decryption Failed]", fix/remove the broken BUILD_NUMBER secret and rebuild.`);return n},Cr=(e,t)=>Zn("/usr/libexec/PlistBuddy",["-c",`Print :${t}`,e],{encoding:"utf-8"}).trim(),Ma=e=>{let t=w.join(e,"Info.plist");if(!h.existsSync(t))throw new Error(`Could not validate iOS build number: ${t} not found.`);return Or(Cr(t,"CFBundleVersion"),t)},Ua=e=>{let n=Zn("unzip",["-Z1",e],{encoding:"utf-8"}).split(`
|
|
1049
|
+
`).find(r=>/^Payload\/[^/]+\.app\/Info\.plist$/.test(r.trim()));if(!n)throw new Error(`Could not validate iOS build number: ${w.basename(e)} has no Payload/*.app/Info.plist.`);let i=h.mkdtempSync(w.join(Ae.tmpdir(),`${f.nameLower}-ipa-plist-`));try{let r=w.join(i,"Info.plist"),o=Zn("unzip",["-p",e,n.trim()]);return h.writeFileSync(r,o),Or(Cr(r,"CFBundleVersion"),`${w.basename(e)}:${n.trim()}`)}finally{h.rmSync(i,{recursive:!0,force:!0})}},ti=async(e,t,n={},i,r={})=>{let o=dn(),s=Date.now(),l=e.platform,a=e.buildProfile||"production",d=()=>dt(n,a,e),c=async(g,T={})=>{if(i)for(let I=1;I<=3;I++)try{await R.patch(`/builds/${i}/${t}`,{status:g,...T});return}catch(L){let v=L?.response?.data?.message||L?.message||String(L);console.error(`[reportStatus] attempt ${I}/3 failed (status=${g}): ${v}`),I<3&&await new Promise(E=>setTimeout(E,2e3))}},u=new AbortController,{signal:p}=u,m=null;i&&(m=setInterval(async()=>{try{(await R.get(`/builds/${i}/${t}`)).data.status==="cancelled"&&(A.warn(b.yellow(`
|
|
1050
|
+
\u{1F6D1} Build cancelled from dashboard. Terminating...`)),u.abort(),m&&clearInterval(m))}catch{}},5e3));let y=w.join(process.cwd(),".mach-cache"),C="setup",N="",M=null,P=async()=>{if(!N||!i)return;let g=N;N="";try{let T=g;Object.values(n).forEach(I=>{if(I&&I.length>5){let L=I.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");T=T.replace(new RegExp(L,"g"),"[SECRET]")}}),await R.post(`/builds/${i}/${t}/logs`,{log:T,step:C})}catch{}},j=async()=>{M&&(clearTimeout(M),M=null),await P(),Oa(y,t),m&&(clearInterval(m),m=null);try{let g=w.join(Ae.tmpdir(),`${f.buildPrefix}-${t}.keychain-db`);h.existsSync(g)&&(te(`security delete-keychain "${g}"`,{stdio:"ignore"}),A.info(b.dim("\u{1F511} Build keychain deleted.")))}catch{}try{let g=w.join(Ae.homedir(),"Library/MobileDevice/Provisioning Profiles");if(h.existsSync(g)){let T=h.readdirSync(g).filter(I=>I.includes(t)||I.startsWith(`${f.nameLower}-temp-${t}`));for(let I of T)h.unlinkSync(w.join(g,I))}}catch{}},S=async g=>{i&&(N+=g,N.length>=8192?(M&&(clearTimeout(M),M=null),await P()):M||(M=setTimeout(()=>{M=null,P()},2e3)))},G=async g=>{C=g,await S(`[STEP_START:${g}] ${Math.floor(Date.now()/1e3)}
|
|
1051
|
+
`)},Q=async(g,T,I,L)=>await ze(g,T,I,L,v=>{S(v)},p);A.info(b.blue(`\u{1F680} Starting local build for ${l} (${a})...`));try{Da(y,t)}catch(g){throw await c("failed",{error:g.message}),g}if(await c("building"),await G("setup"),l==="ios"&&!e.simulator&&n.MACH_IOS_BUILD_NUMBER_LOCKED==="1"&&n.BUILD_NUMBER)A.info(b.dim(`Auto build number: ${n.BUILD_NUMBER}`)),await S(`[BUILD_NUMBER] ${n.BUILD_NUMBER}
|
|
1052
|
+
`);else if(i&&l==="ios"&&!e.simulator)try{let g=parseInt(n.BUILD_NUMBER||"0",10),T=Number.isFinite(g)?g:0,I=await R.post(`/projects/${i}/next-build-number`,{platform:"ios",startFrom:T});if(I.data.status==="success"){let L=ei(String(I.data.buildNumber||""));if(!L)throw new Error(`Dashboard returned invalid iOS build number: "${I.data.buildNumber||""}"`);let v=parseInt(L,10),E=T>0&&Number.isFinite(v)&&v<T?String(T):L;E!==L&&(A.warn(b.yellow(`Dashboard build counter returned ${L}; using minimum ${E}.`)),await S(`[BUILD_NUMBER] Dashboard returned ${L}; using minimum ${E}
|
|
1053
|
+
`)),n.BUILD_NUMBER=E,A.info(b.dim(`Auto build number: ${n.BUILD_NUMBER}`)),await S(`[BUILD_NUMBER] ${n.BUILD_NUMBER}
|
|
1054
|
+
`)}}catch(g){A.warn(b.yellow(`Could not fetch auto build number: ${g.message}`))}await G("lock"),e.developmentClient?(A.info(b.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(b.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 G("clone"),A.info(b.dim("Preparing source...")),await G("read_config");let g=w.join(process.cwd(),f.configFileName);if(h.existsSync(g)){let U=JSON.parse(h.readFileSync(g,"utf-8"))?.build?.[a]||{};await S(`[CONFIG] Profile: ${a}, distribution: ${U.distribution||"not set"}, simulator: ${U.simulator||!1}
|
|
1055
|
+
`)}if(await G("read_package"),e.nodeVersion){let B=process.env.NVM_DIR||w.join(Ae.homedir(),".nvm"),U=w.join(B,"versions","node"),q;if(h.existsSync(U)){let O=h.readdirSync(U).sort().reverse(),F=e.nodeVersion.startsWith("v")?e.nodeVersion:`v${e.nodeVersion}`,X=O.find(ae=>ae===F||ae.startsWith(F+".")||ae.startsWith(`v${e.nodeVersion}.`));X&&(q=w.join(U,X,"bin"))}if(q&&h.existsSync(q)){let O=process.env.PATH||"";process.env.PATH=`${q}:${O}`,await S(`[NODE] Switched to Node ${e.nodeVersion} \u2014 using ${q}
|
|
1056
|
+
`),A.info(b.green(`\u2713 Node switched to ${e.nodeVersion} (${q})`))}else await S(`[NODE] Warning: Node ${e.nodeVersion} not found in nvm. Run: nvm install ${e.nodeVersion} on the build machine.
|
|
1057
|
+
`),A.warn(b.yellow(`Node ${e.nodeVersion} not found in nvm \u2014 using system default`))}await G("deps"),o.start("Checking dependencies...");let T=Ra(y),I=$a(process.cwd()),L=h.existsSync("node_modules"),v=h.existsSync("yarn.lock"),E=h.existsSync("bun.lockb");L&&T.node&&T.node!==I&&(o.stop("Dependency fingerprint changed \u2014 clearing node_modules for clean install..."),await S(`[CACHE] package.json/lockfile changed \u2014 wiping node_modules
|
|
1058
|
+
`),h.rmSync(w.join(process.cwd(),"node_modules"),{recursive:!0,force:!0}),L=!1);let k="npm",K=["install","--prefer-offline"];v?(k="yarn",K=["install","--prefer-offline"]):E&&(k="bun",K=["install"]),L?o.stop("Cached node_modules found. Syncing dependencies..."):o.stop("No cached dependencies. Running fresh install..."),e.preBuild&&(A.info(b.blue("Running pre-install hook...")),A.info(b.dim(`> ${e.preBuild}`)),await G("prebuild"),await Q("bash",[e.preBuild],process.cwd(),d())),A.info(b.dim(`Running ${k} ${K.join(" ")}...`)),await Q(k,K,process.cwd(),d()),T.node=I,wr(y,T);let W=JSON.parse(h.readFileSync("package.json","utf-8")),x=W.dependencies?.expo||W.devDependencies?.expo,z=e.iosBundleIdentifier||"",D=e.name||"";if(x){o.start(`Enforcing ${f.name} configuration...`);let B=w.join(process.cwd(),"app.json"),U=null;if(h.existsSync(B)){U=h.readFileSync(B,"utf-8");let O=JSON.parse(U);O.expo=O.expo||{},D||(D=O.expo.name||""),l==="ios"&&!z&&(z=O.expo?.ios?.bundleIdentifier||""),e.name&&(O.expo.name=e.name),e.scheme&&(O.expo.scheme=e.scheme),l==="ios"&&e.iosBundleIdentifier?(O.expo.ios=O.expo.ios||{},O.expo.ios.bundleIdentifier=e.iosBundleIdentifier):l==="android"&&e.androidPackage&&(O.expo.android=O.expo.android||{},O.expo.android.package=e.androidPackage),h.writeFileSync(B,JSON.stringify(O,null,2))}let q=["exec","--","expo","prebuild","--platform",l,"--no-install"];try{if(await G("prebuild"),await Q("npm",q,process.cwd(),d()),l==="ios"&&h.existsSync("ios")){await G("pods"),A.info(b.blue("Running pod install..."));try{let O=w.resolve("ios"),F=w.join(O,"Podfile");if(!h.existsSync(F))throw new Error("ios/Podfile not found. Skipping pod install.");let X=h.readFileSync(F,"utf-8"),ae=e.iosDeploymentTarget||"13.4";if(!e.developmentClient&&(A.info(b.blue("\u2139\uFE0F Patching Podfile to EXCLUDE expo-dev-client...")),X.includes("use_expo_modules!")&&!X.includes("exclude:"))){let lt=/use_expo_modules!(\s*)$/m;lt.test(X)?X=X.replace(lt,'use_expo_modules!(exclude: ["expo-dev-client"])$1'):X=X.replace("use_expo_modules!",'use_expo_modules!(exclude: ["expo-dev-client"])')}let Se=`
|
|
1059
1059
|
installer.generated_projects.each do |project|
|
|
1060
1060
|
project.targets.each do |target|
|
|
1061
1061
|
target.build_configurations.each do |config|
|
|
@@ -1068,72 +1068,72 @@ ${s.join(`
|
|
|
1068
1068
|
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '${ae}'
|
|
1069
1069
|
end
|
|
1070
1070
|
end
|
|
1071
|
-
`,
|
|
1072
|
-
${Se}`),
|
|
1071
|
+
`,Ye=/post_install\s+do\s+\|installer\|/;if(Ye.test(X))A.info(b.dim(`Injecting deployment target (${ae}) into existing post_install hook...`)),X=X.replace(Ye,`post_install do |installer|
|
|
1072
|
+
${Se}`),h.writeFileSync(F,X);else{A.info(b.dim(`Appending new post_install hook for deployment target (${ae})...`));let lt=`
|
|
1073
1073
|
post_install do |installer|
|
|
1074
1074
|
${Se}
|
|
1075
1075
|
end
|
|
1076
|
-
`;
|
|
1077
|
-
`),A.info(
|
|
1078
|
-
\u2713 Local build completed successfully in ${
|
|
1079
|
-
\u{1F4E6} Generated Artifacts:`)),
|
|
1080
|
-
\u274C Build aborted.`)),await
|
|
1081
|
-
\u2717 Local build failed: ${
|
|
1082
|
-
`)[0]||"unknown"}`))}if(!Dt)throw new Error("Failed to import P12.");
|
|
1083
|
-
`).map(_e=>_e.trim().replace(/^"|"$/g,"")).filter(_e=>_e.length>0),
|
|
1076
|
+
`;h.appendFileSync(F,lt)}let Dt="/opt/homebrew/bin/pod",nn=h.existsSync(Dt)?Dt:"pod",rn=va(O);h.existsSync(w.join(O,"Pods"))&&T.pods&&T.pods!==rn&&(await S(`[CACHE] Podfile/Podfile.lock changed \u2014 wiping ios/Pods
|
|
1077
|
+
`),A.info(b.dim("Podfile fingerprint changed \u2014 clearing Pods for clean install...")),h.rmSync(w.join(O,"Pods"),{recursive:!0,force:!0})),A.info(b.dim(`Using pod command: ${nn} in ${O}`)),await Q(nn,["install"],O,d()),T.pods=rn,wr(y,T)}catch(O){let F=O.message||"Unknown error";A.warn(b.yellow(`Native "pod" command failed: ${F}`)),A.info(b.dim("Falling back to npm exec pod-install...")),A.info(b.magenta(`${f.nameUpper}_DEBUG: Executing pod-install override via npx --yes pod-install@latest`)),await Q("npx",["--yes","pod-install@latest","ios"],process.cwd(),d())}if(h.existsSync("ios/Pods")){A.info(b.dim("Disabling signing for Pod targets to prevent conflicts..."));try{te(`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&&h.writeFileSync(B,U)}o.stop(`Expo prebuild complete (${f.name} config enforced).`)}let J=[];if(l==="android")await G("build"),J=await Ba(e,a,n,B=>S(B),p);else if(l==="ios"){await G("signing"),A.info(b.dim("Preparing credentials..."));let B=r?.distributionType;J=await Fa(e,t,a,n,i,U=>S(U),p,B,U=>G(U))}e.postBuild&&(A.info(b.blue("Running post-build hook...")),A.info(b.dim(`> ${e.postBuild}`)),await Q(e.postBuild,[],process.cwd(),d()));let ye=La(Date.now()-s);if(A.success(b.green(`
|
|
1078
|
+
\u2713 Local build completed successfully in ${ye}`)),await c("building",{...z&&{bundleId:z},...D&&{appName:D}}),J.length>0&&(A.info(b.cyan(`
|
|
1079
|
+
\u{1F4E6} Generated Artifacts:`)),J.forEach(B=>{let U=w.resolve(B);A.info(b.dim(` - ${B}`)),A.info(b.gray(` Path: ${U}`))}),e.interactive)){let B=await wa({message:"Install on connected device?"});if(!cn(B)&&B){if(l==="android"){let U=J.find(q=>q.endsWith(".apk"))||J[0];await ja(U,q=>S(q))}else if(l==="ios"){let U=J.find(O=>O.endsWith(".ipa"))||J.find(O=>O.endsWith(".app"))||J[0],q=qe("ios");e.simulator?await Ga(U,q||"",O=>S(O)):await Ka(U,q||"",O=>S(O))}}}await G("upload");let Ee=[];for(let B of J)try{let U=w.join(Ae.tmpdir(),`${t}-${w.basename(B)}`);h.copyFileSync(B,U),Ee.push(U),A.info(b.dim(` \u{1F4CB} Preserved artifact: ${w.basename(B)}`))}catch{A.warn(b.yellow(` Failed to preserve artifact: ${w.basename(B)}`))}J=Ee,A.info(b.dim("\u{1F9F9} Cleaning workspace (preserving dependency cache)..."));try{let B=process.cwd(),U=new Set(["node_modules"]),q=h.readdirSync(B),O=0;for(let F of q)if(!U.has(F)){if(F==="ios"){let X=w.join(B,"ios"),ae=h.readdirSync(X);for(let Se of ae)if(Se!=="Pods")try{h.rmSync(w.join(X,Se),{recursive:!0,force:!0}),O++}catch{}continue}try{h.rmSync(w.join(B,F),{recursive:!0,force:!0}),O++}catch{}}A.info(b.dim(` Cleaned ${O} items. Cached: node_modules${h.existsSync(w.join(B,"ios","Pods"))?", ios/Pods":""}`)),A.info(b.green("\u{1F512} Security: No source code retained on build server. Only public dependencies cached."))}catch{A.warn(b.yellow("Post-build cleanup encountered errors (non-fatal)."))}try{let U=w.join(Ae.homedir(),f.workspacesDir),q=te(`df -k "${U}" | tail -1 | awk '{print $4}'`,{encoding:"utf8"}).trim(),O=parseInt(q,10)*1024;if(O<53687091200&&h.existsSync(U)){A.info(b.dim(` \u26A0\uFE0F Low disk space (${(O/1024/1024/1024).toFixed(0)} GB free). Running cache eviction...`));let F=w.basename(process.cwd()),X=h.readdirSync(U).filter(ae=>ae!==F).map(ae=>{let Se=w.join(U,ae);try{let Ye=h.statSync(Se);return Ye.isDirectory()?{name:ae,dir:Se,mtime:Ye.mtimeMs}:null}catch{return null}}).filter(Boolean);X.sort((ae,Se)=>ae.mtime-Se.mtime);for(let ae of X){if(O>=53687091200)break;try{h.rmSync(ae.dir,{recursive:!0,force:!0}),A.info(b.dim(` \u{1F5D1}\uFE0F Evicted stale workspace: ${ae.name}`));let Se=te(`df -k "${U}" | tail -1 | awk '{print $4}'`,{encoding:"utf8"}).trim();if(parseInt(Se,10)*1024>=53687091200)break}catch{}}}}catch{}return await j(),J}catch(g){throw await j(),g.message==="Command aborted"?(A.warn(b.yellow(`
|
|
1080
|
+
\u274C Build aborted.`)),await c("failed",{error:"Aborted by user"}),g):(A.error(b.red(`
|
|
1081
|
+
\u2717 Local build failed: ${g.message}`)),await c("failed",{error:g.message}),g)}},Ba=async(e,t,n={},i,r)=>{let o=h.existsSync("android/gradlew")?"android/gradlew":h.existsSync("gradlew")?"./gradlew":null;if(!o)throw new Error("Could not find gradlew. Is this an Android project?");let s=e.developmentClient?"assembleDebug":"assembleRelease";!e.developmentClient&&e.distribution==="store"?s="bundleRelease":!e.developmentClient&&e.distribution==="internal"&&(s="assembleRelease");let l=e.buildCommand||s;A.info(b.blue(`Running Android build: ${l}...`));let a=o.includes("android/")?"android":".",d=(o.includes("android/"),"./gradlew"),c=[l],u={...n,EXPO_NO_DOTENV:"1",MACH_BUILD_PROFILE:t,MACH_APP_NAME:e.appName||e.name||"App"};if(n.ANDROID_VERSION_CODE){let m=w.join(a,"app/build.gradle");if(h.existsSync(m)){let y=n.ANDROID_VERSION_CODE,C=h.readFileSync(m,"utf-8");C=C.replace(/versionCode\s+\d+/,`versionCode ${y}`),h.writeFileSync(m,C),A.info(b.green(`\u2713 Applied Android versionCode ${y}`))}c.push(`-Pandroid.injected.version.code=${n.ANDROID_VERSION_CODE}`)}for(let m of["app/build","build",".cxx"]){let y=w.join(a,m);h.existsSync(y)&&h.rmSync(y,{recursive:!0,force:!0})}Dr(process.cwd()),await ze(d,c,a,u,i,r);let p=w.join(a,"app/build/outputs");return ut(p,[".apk",".aab"])},Fa=async(e,t,n,i={},r,o,s,l,a)=>{if(process.platform!=="darwin")throw new Error("iOS builds can only be run on macOS.");let d=w.resolve(process.cwd(),h.existsSync("ios")?"ios":"."),c=h.readdirSync(d),u=c.find(I=>I.endsWith(".xcworkspace")),p=c.find(I=>I.endsWith(".xcodeproj")),m=dt(i,n,e),y=ei(m.BUILD_NUMBER||m.CURRENT_PROJECT_VERSION);if((m.BUILD_NUMBER||m.CURRENT_PROJECT_VERSION)&&!y)throw new Error(`Invalid iOS BUILD_NUMBER/CURRENT_PROJECT_VERSION: "${m.BUILD_NUMBER||m.CURRENT_PROJECT_VERSION}". Apple requires one to three period-separated integers. Fix the Dashboard secret or remove it so Mach can use its auto build number.`);let C=y?[`BUILD_NUMBER=${y}`,`CURRENT_PROJECT_VERSION=${y}`]:[];if(y&&(m.BUILD_NUMBER=y,m.CURRENT_PROJECT_VERSION=y,A.info(b.dim(`Using iOS build number: ${y}`))),!u&&!p)throw new Error("Could not find Xcode workspace or project in ios/ directory.");try{let I=te("xcode-select -p").toString().trim();A.info(b.dim(`Using Xcode at: ${I}`))}catch{A.warn(b.dim("Could not detect Xcode path."))}A.info(b.blue("Running iOS build via xcodebuild..."));let N=u?u.replace(".xcworkspace",""):p?.replace(".xcodeproj",""),M=e.iosScheme||N||e.scheme,P=e.developmentClient?"Debug":e.iosConfiguration||"Release",j=(r||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),S=w.join(Ae.homedir(),`Library/Developer/Xcode/DerivedData/${f.nameLower}`,j);h.mkdirSync(S,{recursive:!0});let G=bt(m),Q=w.join(S,".mach-env-hash"),g=w.join(S,"Build"),T=h.existsSync(Q)?h.readFileSync(Q,"utf-8").trim():"";if(h.existsSync(g)){let I=T&&T!==G?"Build environment changed \u2014 clearing iOS DerivedData build products.":T?"Clearing iOS DerivedData build products to force a fresh JS bundle.":"DerivedData has no environment stamp \u2014 clearing iOS build products.";A.info(b.dim(I)),h.rmSync(g,{recursive:!0,force:!0})}if(h.writeFileSync(Q,G),Dr(process.cwd()),e.simulator){A.info(b.dim(`Building for simulator (Scheme: ${M}, Config: ${P})...`)),await ze("xcodebuild",[u?"-workspace":"-project",u||p,"-scheme",M,"-configuration",P,"-sdk","iphonesimulator","-derivedDataPath",S,...C,"CODE_SIGNING_ALLOWED=NO","CODE_SIGNING_REQUIRED=NO"],d,m,o,s);let I=w.join(S,"Build/Products",`${P}-iphonesimulator`),L=ut(I,[".app"]);if(L.length>0){let v=L[0],E=w.basename(v,".app"),k=w.join(I,`${E}_simulator.zip`);return A.info(b.dim(`Creating simulator artifact: ${k}...`)),te(`cd "${I}" && zip -r "${k}" "${w.basename(v)}"`),[k]}return[]}else{A.info(b.dim(`Archiving (Scheme: ${M}, Config: ${P})...`));let I=w.join(d,"build.xcarchive"),L=w.join(d,"export");h.rmSync(I,{recursive:!0,force:!0}),h.rmSync(L,{recursive:!0,force:!0});let v=i.IOS_DIST_P12,E=i.IOS_PROVISIONING_PROFILE,k=i.IOS_P12_PASSWORD||"",K=[],W,x,z={isAppStore:!1,isDevelopment:!1};if(v&&E){A.info(b.blue("\u{1F510} CI/CD Signing: Importing certificates..."));try{let O=`${f.buildPrefix}-${t}.keychain-db`,F=w.join(Ae.tmpdir(),O),X=f.keychainPassword;te(`security create-keychain -p "${X}" "${F}" 2>/dev/null || true`),te(`security set-keychain-settings -t 3600 -l "${F}"`),te(`security unlock-keychain -p "${X}" "${F}"`);let ae=w.join(Ae.tmpdir(),`cert-${t}.p12`),Se=Buffer.from(v,"base64");h.writeFileSync(ae,Se),A.info(b.dim(`P12 data size: ${Se.length} bytes, first bytes: ${Se.slice(0,4).toString("hex")}`)),(Se.length<100||Se[0]!==48)&&(A.warn(b.yellow("\u26A0\uFE0F P12 data looks corrupted or was not decrypted correctly.")),A.warn(b.yellow(" This usually means MACH_ENCRYPTION_KEY on the Remote API differs from when credentials were uploaded.")));let Ye=[k,"",f.keychainPassword],Dt=!1;for(let _e of Ye)try{te(`security import "${ae}" -k "${F}" -P "${_e}" -A -T /usr/bin/codesign -T /usr/bin/security`,{stdio:"pipe"}),Dt=!0,A.info(b.dim(`\u2713 P12 imported successfully with password: ${_e?"[set]":"[empty]"}`));break}catch(xe){A.info(b.dim(` P12 import attempt with password ${_e?`"${_e.substring(0,3)}..."`:"[empty]"} failed: ${xe.message?.split(`
|
|
1082
|
+
`)[0]||"unknown"}`))}if(!Dt)throw new Error("Failed to import P12.");h.unlinkSync(ae),te(`security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "${X}" "${F}"`);let nn=te("security list-keychains -d user",{encoding:"utf-8"}).split(`
|
|
1083
|
+
`).map(_e=>_e.trim().replace(/^"|"$/g,"")).filter(_e=>_e.length>0),rn=[F,...nn].map(_e=>`"${_e}"`).join(" ");te(`security list-keychains -d user -s ${rn}`),te(`security default-keychain -s "${F}"`);let on=w.join(Ae.homedir(),"Library/MobileDevice/Provisioning Profiles");h.mkdirSync(on,{recursive:!0});let lt=Buffer.from(E,"base64"),jn=w.join(on,`${f.nameLower}-temp-${t}.mobileprovision`);h.writeFileSync(jn,lt);let Gn=lt.toString("utf-8"),Ki=/<key>get-task-allow<\/key>\s*<true\/>/.test(Gn);z={isAppStore:!Gn.includes("<key>ProvisionedDevices</key>")&&!Ki,isDevelopment:Ki};try{let xe=te(`security cms -D -i "${jn}"`,{encoding:"utf-8"}).match(/<key>UUID<\/key>\s*<string>([^<]+)<\/string>/);x=xe?xe[1]:void 0}catch{let xe=Gn.match(/<key>UUID<\/key>\s*<string>([^<]+)<\/string>/);x=xe?xe[1]:void 0}x||(A.warn("Could not extract UUID from provisioning profile. Using fallback."),x=`${f.nameLower}-${t}`);let Kn=w.join(on,`${x}.mobileprovision`);h.existsSync(Kn)&&h.unlinkSync(Kn),h.renameSync(jn,Kn);try{let _e=te(`security find-identity -v -p codesigning "${F}"`,{encoding:"utf-8"}),xe=Array.from(_e.matchAll(/"((?:Apple|iPhone) (?:Distribution|Developer|Development)[^"]*)"/g),Ot=>Ot[1]),Vi=z.isDevelopment?xe.find(Ot=>/\b(Development|Developer)\b/.test(Ot)):xe.find(Ot=>/\bDistribution\b/.test(Ot)),zi=xe[0];(Vi||zi)&&(W=Vi||zi,A.info(b.blue(`Identity auto-detected from keychain: "${W}"`)))}catch{}W||(W=z.isDevelopment?"Apple Development":"Apple Distribution",A.info(b.blue(`Identity fallback (profile heuristic): "${W}"`))),A.info(b.dim(`Profile type: ${z.isDevelopment?"Development":z.isAppStore?"App Store":"Ad-Hoc"}`)),A.info(b.dim(`Identity Detection: get-task-allow=${z.isDevelopment}, Selected Identity="${W}"`)),K.push("CODE_SIGN_STYLE=Manual"),K.push(`CODE_SIGN_IDENTITY="${W}"`),K.push(`PROVISIONING_PROFILE_SPECIFIER=${x}`),e.iosTeamId&&K.push(`DEVELOPMENT_TEAM=${e.iosTeamId}`)}catch(O){throw A.error(`Signing setup failed: ${O.message}`),O}}else K.push("-allowProvisioningUpdates"),e.iosTeamId&&K.push(`DEVELOPMENT_TEAM=${e.iosTeamId}`);a&&await a("archive"),A.info(b.blue(`Archive detected Identity: "${W}"`)),A.info(b.blue(`Archive detected UUID: "${x}"`)),await ze("xcodebuild",["archive",u?"-workspace":"-project",u||p,"-scheme",M,"-configuration",P,"-archivePath",I,"-derivedDataPath",S,...C,...K],d,m,o,s);let D=ut(w.join(I,"Products","Applications"),[".app"]);for(let O of D){let F=Ma(O);A.info(b.dim(`Validated iOS CFBundleVersion ${F} in ${w.basename(O)}`))}let J;x?(z.isAppStore?J="app-store":z.isDevelopment?J="development":J="ad-hoc",A.info(b.blue(`Export method from profile: "${J}"`))):(J=e.distribution==="store"?"app-store":e.distribution==="internal"?"ad-hoc":"development",A.warn(b.yellow(`No profile UUID detected. Export method from distribution flag: "${J}"`)));let ye=e.iosExportMethod||J,Ee=e.iosBundleIdentifier||qe("ios"),B=w.join(d,"ExportOptions.plist"),U=`<?xml version="1.0" encoding="UTF-8"?>
|
|
1084
1084
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
1085
1085
|
<plist version="1.0">
|
|
1086
1086
|
<dict>
|
|
1087
1087
|
<key>method</key>
|
|
1088
|
-
<string>${
|
|
1088
|
+
<string>${ye}</string>
|
|
1089
1089
|
<key>destination</key>
|
|
1090
1090
|
<string>export</string>
|
|
1091
1091
|
<key>signingStyle</key>
|
|
1092
|
-
<string>${
|
|
1092
|
+
<string>${x?"manual":"automatic"}</string>
|
|
1093
1093
|
<key>thinning</key>
|
|
1094
1094
|
<string><none></string>
|
|
1095
1095
|
${e.iosTeamId?`<key>teamID</key><string>${e.iosTeamId}</string>`:""}
|
|
1096
|
-
${
|
|
1096
|
+
${Ee&&x?`
|
|
1097
1097
|
<key>provisioningProfiles</key>
|
|
1098
1098
|
<dict>
|
|
1099
|
-
<key>${
|
|
1100
|
-
<string>${
|
|
1099
|
+
<key>${Ee}</key>
|
|
1100
|
+
<string>${x}</string>
|
|
1101
1101
|
</dict>`:""}
|
|
1102
1102
|
</dict>
|
|
1103
|
-
</plist>`;if(
|
|
1104
|
-
${
|
|
1103
|
+
</plist>`;if(h.writeFileSync(B,U),process.env[`${f.envPrefix}DEBUG`]&&A.info(b.magenta(`[${f.nameUpper}_DEBUG] ExportOptions.plist:
|
|
1104
|
+
${U}`)),a&&await a("export"),A.info(b.blue(`Exporting with Bundle ID: "${Ee}"`)),A.info(b.blue(`Exporting with Method: "${ye}"`)),o){o(b.magenta(`
|
|
1105
1105
|
[DIAGNOSTIC] Checking available signing identities...
|
|
1106
|
-
`));try{let
|
|
1107
|
-
`))}catch(
|
|
1108
|
-
`))}}await
|
|
1109
|
-
`),o&&o(`[IPA VALID] CFBundleVersion ${
|
|
1110
|
-
`)}catch(
|
|
1111
|
-
`),new Error(
|
|
1112
|
-
`).slice(1).map(s=>s.trim()).filter(s=>s.length>0&&!s.startsWith("*")).map(s=>s.split(" ")[0]).length===0){A.warn(
|
|
1113
|
-
`).filter(a=>a.trim().length>0)}catch{}if(l.length>0){let a=await
|
|
1114
|
-
`).find(a=>a.includes("android.intent.action.MAIN")&&a.includes("android.intent.category.LAUNCHER"))?
|
|
1106
|
+
`));try{let O=te("security find-identity -v -p codesigning",{encoding:"utf-8"});o(b.magenta(`${O}
|
|
1107
|
+
`))}catch(O){o(b.red(`[DIAGNOSTIC] Failed to list identities: ${O.message}
|
|
1108
|
+
`))}}await ze("xcodebuild",["-exportArchive","-archivePath",I,"-exportPath",L,"-exportOptionsPlist",B],d,m,o,s),a&&await a("validate");let q=ut(L,[".ipa"]);for(let O of q)try{te(`unzip -t "${O}"`,{stdio:"pipe"});let F=Ua(O);o&&o(`[IPA VALID] ${w.basename(O)} \u2014 archive integrity OK
|
|
1109
|
+
`),o&&o(`[IPA VALID] CFBundleVersion ${F}
|
|
1110
|
+
`)}catch(F){let X=`IPA validation failed for ${w.basename(O)}: ${F.message||"archive may be corrupt"}`;throw o&&o(`[IPA CORRUPT] ${X}
|
|
1111
|
+
`),new Error(X)}return q}},qe=e=>{try{let t=w.join(process.cwd(),f.configFileName);if(h.existsSync(t)){let n=JSON.parse(h.readFileSync(t,"utf-8"));if(e==="android"&&n.android?.package)return n.android.package;if(e==="ios"&&n.ios?.bundleIdentifier)return n.ios.bundleIdentifier}if(e==="android"){let n=["android/app/build.gradle","app/build.gradle","build.gradle"];for(let i of n)if(h.existsSync(i)){let o=h.readFileSync(i,"utf-8").match(/applicationId\s+['"]([^'"]+)['"]/);if(o)return o[1]}}else{let n=w.resolve(process.cwd(),h.existsSync("ios")?"ios":"."),i=ut(n,["Info.plist"]).filter(s=>!s.includes("/Pods/")&&!s.includes("/build/")&&!s.includes("/DerivedData/"));i.sort((s,l)=>l.split("/").length-s.split("/").length);for(let s of i){let a=h.readFileSync(s,"utf-8").match(/<key>CFBundleIdentifier<\/key>\s*<string>([^<]+)<\/string>/);if(a&&!a[1].includes("$"))return a[1]}let r=ut(n,[".xcodeproj"]);if(r.length>0){let s=w.join(r[0],"project.pbxproj");if(h.existsSync(s)){let a=h.readFileSync(s,"utf-8").match(/PRODUCT_BUNDLE_IDENTIFIER\s*=\s*"?([^";\s]+)"?;/);if(a)return a[1]}}let o=["app.json","app.config.json","app.config.js","app.config.ts"];for(let s of o)if(h.existsSync(s)){let a=h.readFileSync(s,"utf-8").match(/"bundleIdentifier":\s*"([^"]+)"/);if(a)return a[1]}}}catch{return null}return null},Ha=()=>{try{return te("emulator -version",{stdio:"ignore"}),"emulator"}catch{let t=Ae.homedir(),n=[w.join(t,"Library/Android/sdk/emulator/emulator"),w.join(t,"Android/Sdk/emulator/emulator"),"/usr/local/lib/android/sdk/emulator/emulator"];for(let i of n)if(h.existsSync(i))return i}return"emulator"},ja=async(e,t)=>{let n=dn();try{if(te("adb devices").toString().split(`
|
|
1112
|
+
`).slice(1).map(s=>s.trim()).filter(s=>s.length>0&&!s.startsWith("*")).map(s=>s.split(" ")[0]).length===0){A.warn(b.yellow("No Android devices or emulators found."));let s=Ha(),l=[];try{l=te(`${s} -list-avds`).toString().split(`
|
|
1113
|
+
`).filter(a=>a.trim().length>0)}catch{}if(l.length>0){let a=await Qn({message:"Select an emulator to launch:",options:l.map(u=>({value:u,label:u}))});if(cn(a))return;n.start(`Launching emulator ${a}...`),vr(s,["-avd",a],{detached:!0,stdio:"ignore"}).unref();let d=0,c=!1;for(;d<60;){try{if(te("adb shell getprop sys.boot_completed",{stdio:"pipe"}).toString().trim()==="1"){c=!0;break}}catch{}await new Promise(u=>setTimeout(u,2e3)),d++}if(!c)throw n.stop("Emulator launch timed out."),new Error("Emulator launch timed out. Please try launching it manually.");n.stop("Emulator launched.")}else throw new Error("No devices found and no emulators available to launch. (Make sure Android SDK is installed)")}n.start("Installing APK on device..."),await ze("adb",["install","-r",e],process.cwd(),{},t),n.stop("Installation complete.");let o=qe("android");if(o){A.info(b.blue(`\u{1F680} Launching ${o}...`));try{te(`adb shell dumpsys package ${o}`).toString().split(`
|
|
1114
|
+
`).find(a=>a.includes("android.intent.action.MAIN")&&a.includes("android.intent.category.LAUNCHER"))?te(`adb shell monkey -p ${o} -c android.intent.category.LAUNCHER 1`,{stdio:"ignore"}):te(`adb shell monkey -p ${o} -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){n.stop("Installation failed."),A.error(b.red(`Failed to install APK: ${i.message}`))}},Ga=async(e,t,n)=>{let i=dn();try{if(!te("xcrun simctl list devices booted").toString().includes("(Booted)")){A.warn(b.yellow("No iOS Simulator is currently booted."));let o=te("xcrun simctl list devices --json").toString(),s=JSON.parse(o).devices,l=[];Object.keys(s).forEach(u=>{s[u].forEach(p=>{p.isAvailable&&l.push({...p,runtime:u})})});let a=await Qn({message:"Select a simulator to launch:",options:l.map(u=>({value:u.udid,label:`${u.name} (${u.runtime.split(".").pop()})`}))});if(cn(a))return;i.start(`Booting ${a}...`),te(`xcrun simctl boot ${a}`),te(`open -a Simulator --args -CurrentDeviceUDID ${a}`);let d=0,c=!1;for(;d<30;){try{if(te("xcrun simctl list devices booted").toString().includes(a)){c=!0;break}}catch{}await new Promise(u=>setTimeout(u,2e3)),d++}if(!c)throw i.stop("Simulator boot timed out."),new Error("Simulator boot timed out.");i.stop("Simulator booted.")}i.start("Installing on iOS Simulator..."),await ze("xcrun",["simctl","install","booted",e],process.cwd(),{},n),i.stop("Installation complete."),A.info(b.blue(`\u{1F680} Launching ${t}...`)),await ze("xcrun",["simctl","launch","booted",t],process.cwd(),{},n)}catch(r){i.stop("Installation failed."),A.error(b.red(`Failed to install on Simulator: ${r.message}`))}},Ka=async(e,t,n)=>{let i=dn();i.start("Scanning for connected iOS devices...");try{let r=te("xcrun devicectl list devices --json-output -").toString(),s=(JSON.parse(r).result?.devices||[]).filter(a=>a.connectionProperties?.transportType==="wired"||a.connectionProperties?.transportType==="localNetwork");if(s.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 l=s[0].identifier;if(s.length>1){i.stop();let a=await Qn({message:"Select a device to install on:",options:s.map(d=>({value:d.identifier,label:`${d.deviceProperties?.name||d.name||d.model?.name} (${d.model?.name||"iPhone"}) - ${d.identifier}`}))});if(cn(a))return;l=a,i.start(`Installing on ${l}...`)}else i.message(`Installing on ${s[0].model.name}...`);await ze("xcrun",["devicectl","device","install","app","--device",l,e],process.cwd(),{},n),i.stop("Installation complete."),A.info(b.blue(`\u{1F680} Launching ${t}...`)),await ze("xcrun",["devicectl","device","launch","app","--device",l,t],process.cwd(),{},n)}catch(r){i.stop("Installation failed."),A.error(b.red(`Failed to install on device: ${r.message}`)),A.info(b.dim('Make sure your device is unlocked and "Developer Mode" is enabled in Settings -> Privacy & Security.'))}};import Y from"fs";import si from"os";import ee from"path";import{spawnSync as tt}from"child_process";import{randomUUID as Va}from"crypto";import{pipeline as za}from"stream/promises";import{isCancel as ii,log as H,select as Lr,spinner as xt,text as Wa}from"@clack/prompts";import Lt from"axios";import V from"chalk";import un from"adm-zip";async function xr(e){if(e.localRunner){let n=await qa(e);process.exitCode=n?n.exitCode:1;return}if(e.local){let n=await Xa(e);n&&(process.exitCode=n.exitCode);return}let t=await ai(e);if(t&&(H.success(V.green(`Maestro run ${t.status||"queued"}: ${t.testRunId}`)),t.launchDeferredReason&&H.warn(V.yellow(t.launchDeferredReason)),t.dashboardUrl&&H.info(V.dim("View test run: ")+V.white.underline(t.dashboardUrl)),e.wait)){let n=await Za(e,t);n&&(process.exitCode=n.status==="passed"?0:1)}}var Ya=new Set(["passed","failed","cancelled","interrupted"]),Nr=Number(process.env.MACH_FLOW_UPLOAD_MAX_ATTEMPTS||4),Ja=Number(process.env.MACH_FLOW_UPLOAD_TIMEOUT_MS||12e4);async function qa(e){let t=e.projectId,n=e.testRunId,i=e.runnerToken||process.env.MACH_RUNNER_TOKEN||process.env.MACH_TOKEN,r=(process.env.MACH_API_URL||yt).replace(/\/$/,""),o=Y.mkdtempSync(ee.join(si.tmpdir(),"mach-maestro-runner-")),s=ee.join(o,"mach-maestro-output"),l=ee.join(o,"runner.log");if(Y.mkdirSync(s,{recursive:!0}),!t||!n||!i)return H.error(V.red("--local-runner requires --project-id, --test-run-id, and a runner token.")),{status:"failed",exitCode:1,attempts:0,flows:".maestro",platform:e.platform};let a=null,d=u=>{Y.appendFileSync(l,`${u}${u.endsWith(`
|
|
1115
1115
|
`)?"":`
|
|
1116
|
-
`}`)},d=async(u,p)=>{try{await kt.post(`${r}/internal/tests/${encodeURIComponent(n)}/runner`,{projectId:t,runnerToken:i,status:u,error:p,logPreview:Ja(l),junitUrl:a?.urls?.junitDownloadUrl,logsUrl:a?.urls?.logsDownloadUrl,artifactsUrl:a?.urls?.artifactsDownloadUrl})}catch(f){c(`[WARN] Could not post runner update: ${f.message||f}`)}};try{c(`Mach Maestro local runner starting for ${n}`);let u=await kt.post(`${r}/internal/tests/${encodeURIComponent(n)}/runner-payload`,{projectId:t,runnerToken:i});if(u.data?.status!=="success"||!u.data?.payload)throw new Error(u.data?.message||"Runner payload was not returned.");a=u.data.payload,await d("running");let p=a.platform==="android"?"app.apk":"app.zip",f=X.join(o,p),S=X.join(o,"source.zip"),L=X.join(o,"source");W.mkdirSync(L,{recursive:!0}),c("Downloading app artifact..."),await ni(a.artifactUrl,f),c("Downloading Maestro source..."),await ni(a.urls.sourceUrl,S),new cn(S).extractAllTo(L,!0);let k=qa(L,a.flowPath||".maestro");if(!W.existsSync(k))throw new Error(`Maestro flow path not found: ${a.flowPath||".maestro"}`);if(a.platform==="ios"){await el(a.device||"iphone_15",l);let b=tl(f,o);il(b,l),ii("xcrun",["simctl","install","booted",b],l)}else ii("adb",["install","-r",f],l);let O=Math.max(0,Math.min(10,Number(a.retries??1)))+1,G=X.join(s,"report.xml"),h=Za(l);if(!h)throw new Error("Maestro CLI not found on this runner. Install Maestro or set MAESTRO_BIN to the full maestro path.");let H=1;for(let b=1;b<=O&&(c(`Running Maestro attempt ${b}/${O}...`),H=xt(h,["test","--platform",a.platform,k,"--format","junit","--output",G,"--test-output-dir",s],l),H!==0);b+=1);return await Rr(a.urls,o,s,l),H===0?(await d("passed"),F.success(V.green(`Managed Maestro run passed: ${n}`)),{status:"passed",exitCode:0,attempts:O,flows:a.flowPath,platform:a.platform}):(await d("failed",`Maestro exited with code ${H}`),F.error(V.red(`Managed Maestro run failed with exit code ${H}`)),{status:"failed",exitCode:H,attempts:O,flows:a.flowPath,platform:a.platform})}catch(u){let p=u.message||String(u);return c(`MACH_MAESTRO_RUN_FAILED: ${p}`),a?.urls&&await Rr(a.urls,o,s,l),await d("failed",p),F.error(V.red(`Managed Maestro runner failed: ${p}`)),{status:"failed",exitCode:1,attempts:0,flows:a?.flowPath||".maestro",platform:a?.platform||e.platform}}}async function Fa(e){let t=e.maestroFlows||".maestro",n=Cr(e.maestroRetries);if(n===null)return null;let i=X.resolve(t);if(!W.existsSync(i))return F.error(V.red(`Maestro flows not found: ${t}`)),{status:"failed",exitCode:1,attempts:0,flows:t,platform:e.platform};let r=await za(e);if(r?.url){if(!await Ya(r))return{status:"failed",exitCode:1,attempts:0,flows:t,platform:r.platform||e.platform}}else if(e.buildId||e.buildUrl||e.artifactUrl||e.latest)return{status:"failed",exitCode:1,attempts:0,flows:t,platform:e.platform};e.maestroRecord&&F.warn(V.yellow("--maestro-record is managed-runner only and is ignored in --local mode."));let o=r?.platform||e.platform,s=["test"];o&&s.push("--platform",o),e.maestroDevice&&s.push("--device",String(e.maestroDevice)),s.push(t);let l=n+1,a=1;for(let u=1;u<=l;u+=1){F.info(V.dim(`Running local Maestro attempt ${u}/${l}...`));let p=tt("maestro",s,{cwd:process.cwd(),stdio:"inherit",env:process.env});if(p.error){let f=p.error.message||"Failed to run Maestro";F.error(V.red(`Local Maestro failed to start: ${f}`)),F.info(V.dim("Install Maestro locally, then retry: https://maestro.mobile.dev/getting-started/installing-maestro")),a=1;break}if(a=typeof p.status=="number"?p.status:1,a===0)break}let c=a===0?"passed":"failed",d={status:c,exitCode:a,attempts:l,flows:t,platform:o};return ll(e,d),c==="passed"?F.success(V.green("Local Maestro run passed")):F.error(V.red(`Local Maestro run failed with exit code ${a}`)),d}async function oi(e){let t=Te(`./${m.configFileName}`),n=e.projectId||t?.projectId,i=String(e.profile||e.buildProfile||"production").toLowerCase();if(!n)return F.error(`No projectId found. Run \`${m.nameLower} link\` first or pass an internal project id.`),null;let r=e.platform;if(!r&&e.latest){let c=await vr({message:"Select platform for the latest build:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"}]});if(ti(c))return null;r=c}let o=await Va(e);if(!o)return null;if(o.kind==="latest"&&!r)return F.error("Pass --platform when using --latest."),null;if(o.kind==="artifact-url"&&!r)return F.error("Pass --platform when using --artifact-url."),null;let s=Cr(e.maestroRetries);if(s===null)return null;let l=await ja(e,n);if(l===null)return null;let a=Lt();e.quiet||a.start("Queuing Maestro run...");try{let c=await v.post("/tests/maestro",{projectId:n,platform:r,profile:i,latest:o.kind==="latest",buildId:o.kind==="build-id"?o.value:e.buildId,buildUrl:o.kind==="build-url"?o.value:e.buildUrl,artifactUrl:o.kind==="artifact-url"?o.value:e.artifactUrl,flowSourceKey:l,flows:e.maestroFlows||".maestro",device:e.maestroDevice||(r==="ios"?"iphone_15":"pixel_6"),retries:s,record:!!e.maestroRecord});if(c.data.status!=="success")throw new Error(c.data.message||"Failed to queue Maestro run");let d=c.data.testRun,u={testRunId:d.testRunId,status:d.status,projectId:n,buildId:d.buildId,platform:d.platform,dashboardUrl:d.dashboardUrl||`${Ye}/tests/${d.testRunId}`,launchDeferredReason:d.launchDeferredReason};return kr(e,u),e.quiet||a.stop("Maestro run queued"),u}catch(c){e.quiet||a.stop("Could not queue Maestro run");let d=c.response?.data?.message||c.message||"Unknown error";return F.error(V.red(`Maestro queue failed: ${d}`)),null}}async function Ha(e,t){let n=Pr(e.waitTimeout,60,"--wait-timeout"),i=Pr(e.waitInterval,15,"--wait-interval");if(n===null||i===null)return null;let r=n*60*1e3,o=Math.max(5,i)*1e3,s=Date.now(),l=t.status||"queued";for(F.info(V.dim(`Waiting for Maestro run ${t.testRunId} to finish...`));Date.now()-s<=r;){let a=await Ka(t.projectId,t.testRunId);if(!a)return null;if(a.status&&a.status!==l&&(l=a.status,F.info(V.dim(`Maestro status: ${l}`))),Ma.has(String(a.status)))return kr(e,a),a.status==="passed"?F.success(V.green(`Maestro run passed: ${a.testRunId}`)):(F.error(V.red(`Maestro run ${a.status}: ${a.testRunId}`)),a.error&&F.error(V.red(String(a.error)))),a;await si(o)}return F.error(V.red(`Timed out waiting for Maestro run ${t.testRunId} after ${n} minute(s).`)),{...t,status:"timeout"}}async function ja(e,t){if(e.maestroUseBuildSource)return;let n=e.maestroFlows||".maestro",i=X.resolve(n);if(!W.existsSync(i))return e.maestroFlows?(F.error(V.red(`Maestro flows not found: ${n}`)),null):void 0;let r=X.relative(process.cwd(),i);if(!r||r.startsWith("..")||X.isAbsolute(r))return F.error(V.red("Managed Maestro flow uploads must be inside the current project directory.")),null;let o=Lt();e.quiet||o.start(`Uploading Maestro flows from ${r}...`);try{let s=await v.post("/tests/maestro/source-upload-url",{projectId:t,uploadId:ka()});if(s.data.status!=="success"||!s.data.uploadUrl||!s.data.key)throw new Error(s.data.message||"Failed to get Maestro flow upload URL");let l=new cn;if(W.statSync(i).isDirectory())l.addLocalFolder(i,r);else{let d=X.dirname(r);l.addLocalFile(i,d==="."?void 0:d,X.basename(r))}let c=l.toBuffer();return await Ga(s.data.uploadUrl,c,"application/zip","Maestro flow upload",d=>{e.quiet||o.message(d)}),e.quiet||o.stop("Maestro flows uploaded"),s.data.key}catch(s){e.quiet||o.stop("Could not upload Maestro flows");let l=s.response?.data?.message||s.message||"Unknown error";return F.error(V.red(`Maestro flow upload failed: ${l}`)),null}}function Or(e){let t=e.response?.status,n=e.code||"",i=e.message||"";return t&&![408,409,425,429].includes(t)&&t<500?!1:/ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|ECONNABORTED|socket hang up|network|timeout/i.test(`${n} ${i}`)||!t}async function Ga(e,t,n,i,r){let o;for(let s=1;s<=$r;s+=1)try{await kt.put(e,t,{headers:{"Content-Type":n},maxBodyLength:1/0,maxContentLength:1/0,timeout:Ua});return}catch(l){if(o=l,!Or(l)||s>=$r)break;let a=Math.min(2e4,2e3*s),c=l.code||l.response?.status||l.message||"network error";r?.(`${i} attempt ${s} failed (${c}), retrying...`),await si(a)}throw o}async function Ka(e,t){try{let n=await v.get(`/tests/${encodeURIComponent(t)}`,{params:{projectId:e}});if(n.data.status!=="success")throw new Error(n.data.message||"Failed to fetch Maestro run");let i=n.data.testRun;return{testRunId:i.testRunId,status:i.status,projectId:e,buildId:i.buildId,platform:i.platform,dashboardUrl:i.dashboardUrl||`${Ye}/tests/${i.testRunId}`,launchDeferredReason:i.launchDeferredReason,...i.error?{error:i.error}:{}}}catch(n){let i=n.response?.data?.message||n.message||"Unknown error";return F.error(V.red(`Could not fetch Maestro run status: ${i}`)),null}}async function Va(e){if(e.buildId)return{kind:"build-id",value:e.buildId};if(e.buildUrl)return{kind:"build-url",value:e.buildUrl};if(e.artifactUrl)return{kind:"artifact-url",value:e.artifactUrl};if(e.latest)return{kind:"latest"};let t=await vr({message:"Select app artifact source for Maestro:",options:[{value:"latest",label:"Latest successful build"},{value:"build-id",label:"Build ID"},{value:"build-url",label:`${m.name} build URL`},{value:"artifact-url",label:"Direct artifact URL"}]});if(ti(t))return null;if(t==="latest")return{kind:"latest"};let n=await xa({message:t==="build-id"?"Enter build ID:":t==="build-url"?`Enter ${m.name} build URL:`:"Enter artifact URL:",validate:i=>{let r=String(i||"").trim();if(!r)return"Value is required";if((t==="build-url"||t==="artifact-url")&&!r.startsWith("http"))return"Must be a URL"}});return ti(n)?null:{kind:t,value:String(n).trim()}}function Pr(e,t,n){if(e==null||e==="")return t;let i=Number(e);return!Number.isFinite(i)||i<=0?(F.error(`${n} must be a positive number.`),null):i}function si(e){return new Promise(t=>setTimeout(t,e))}function Cr(e){if(e==null||e==="")return 1;let t=Number(e);return!Number.isInteger(t)||t<0||t>10?(F.error("--maestro-retries must be an integer between 0 and 10."),null):t}async function za(e){if(e.artifactUrl)return{url:e.artifactUrl,platform:e.platform||li(e.artifactUrl),name:Tr(e.artifactUrl)};let t=e.buildId||al(e.buildUrl);return t?Nr(t,e.platform):e.latest?Wa(e):null}async function Nr(e,t){let n=Lt();n.start(`Resolving build ${e}...`);try{let i=await v.get(`/public/builds/${encodeURIComponent(e)}`);if(i.data.status!=="success")throw new Error(i.data.message||"Build lookup failed");let r=t||i.data.build?.platform,o=sl(i.data.artifacts||[],r);if(!o?.downloadUrl)throw new Error("No installable APK or simulator app artifact found for this build.");return n.stop("Build artifact resolved"),{url:o.downloadUrl,platform:r||li(o.name||o.downloadUrl),name:o.name}}catch(i){n.stop("Could not resolve build artifact");let r=i.response?.data?.message||i.message||"Unknown error";return F.error(V.red(`Local Maestro artifact lookup failed: ${r}`)),null}}async function Wa(e){let t=Te(`./${m.configFileName}`),n=e.projectId||t?.projectId,i=String(e.profile||e.buildProfile||"production").toLowerCase();if(!n)return F.error(`No projectId found. Run \`${m.nameLower} link\` first or pass --build-id/--artifact-url.`),null;if(!e.platform)return F.error("Pass --platform when using --latest with --local."),null;let r=Lt();r.start("Resolving latest build...");try{let o=await v.get(`/builds/${n}`,{params:{limit:100}}),l=(Array.isArray(o.data.builds)?o.data.builds:[]).find(a=>a.status==="success"&&a.platform===e.platform&&String(a.buildProfile||a.buildType||"production").toLowerCase()===i);if(!l?.buildId)throw new Error(`No successful ${e.platform} build found for profile ${i}.`);return r.stop(`Latest build resolved: ${l.buildId}`),Nr(l.buildId,e.platform)}catch(o){r.stop("Could not resolve latest build");let s=o.response?.data?.message||o.message||"Unknown error";return F.error(V.red(`Latest build lookup failed: ${s}`)),null}}async function Ya(e){let t=e.platform||li(e.url);if(!t)return F.error(V.red("Could not infer platform for local install. Pass --platform android or --platform ios.")),!1;let n=W.mkdtempSync(X.join(ri.tmpdir(),"mach-maestro-")),i=e.name||Tr(e.url)||(t==="android"?"app.apk":"app.zip"),r=X.join(n,i),o=Lt();o.start(`Downloading ${i}...`);try{await ni(e.url,r),o.stop("Artifact downloaded")}catch(s){return o.stop("Artifact download failed"),F.error(V.red(s.message||"Failed to download artifact")),!1}return t==="android"?rl(r):ol(r,n)}async function ni(e,t){let n=await kt.get(e,{responseType:"stream"});await La(n.data,W.createWriteStream(t))}function Ja(e,t=12e3){try{return W.readFileSync(e,"utf-8").slice(-t)}catch{return""}}function qa(e,t){let n=X.resolve(e,t||".maestro"),i=X.relative(e,n);if(i.startsWith("..")||X.isAbsolute(i))throw new Error("Maestro flow path must stay inside the build source.");return n}function xt(e,t,n,i){W.appendFileSync(n,`
|
|
1116
|
+
`}`)},c=async(u,p)=>{try{await Lt.post(`${r}/internal/tests/${encodeURIComponent(n)}/runner`,{projectId:t,runnerToken:i,status:u,error:p,logPreview:sl(l),junitUrl:a?.urls?.junitDownloadUrl,logsUrl:a?.urls?.logsDownloadUrl,artifactsUrl:a?.urls?.artifactsDownloadUrl})}catch(m){d(`[WARN] Could not post runner update: ${m.message||m}`)}};try{d(`Mach Maestro local runner starting for ${n}`);let u=await Lt.post(`${r}/internal/tests/${encodeURIComponent(n)}/runner-payload`,{projectId:t,runnerToken:i});if(u.data?.status!=="success"||!u.data?.payload)throw new Error(u.data?.message||"Runner payload was not returned.");a=u.data.payload,await c("running");let p=a.platform==="android"?"app.apk":"app.zip",m=ee.join(o,p),y=ee.join(o,"source.zip"),C=ee.join(o,"source");Y.mkdirSync(C,{recursive:!0}),d("Downloading app artifact..."),await ri(a.artifactUrl,m),d("Downloading Maestro source..."),await ri(a.urls.sourceUrl,y),new un(y).extractAllTo(C,!0);let N=al(C,a.flowPath||".maestro");if(!Y.existsSync(N))throw new Error(`Maestro flow path not found: ${a.flowPath||".maestro"}`);if(a.platform==="ios"){await ul(a.device||"iphone_15",l);let Q=pl(m,o);ml(Q,l),oi("xcrun",["simctl","install","booted",Q],l)}else oi("adb",["install","-r",m],l);let P=Math.max(0,Math.min(10,Number(a.retries??1)))+1,j=ee.join(s,"report.xml"),S=dl(l);if(!S)throw new Error("Maestro CLI not found on this runner. Install Maestro or set MAESTRO_BIN to the full maestro path.");let G=1;for(let Q=1;Q<=P&&(d(`Running Maestro attempt ${Q}/${P}...`),G=Mt(S,["test","--platform",a.platform,N,"--format","junit","--output",j,"--test-output-dir",s],l),G!==0);Q+=1);return await kr(a.urls,o,s,l),G===0?(await c("passed"),H.success(V.green(`Managed Maestro run passed: ${n}`)),{status:"passed",exitCode:0,attempts:P,flows:a.flowPath,platform:a.platform}):(await c("failed",`Maestro exited with code ${G}`),H.error(V.red(`Managed Maestro run failed with exit code ${G}`)),{status:"failed",exitCode:G,attempts:P,flows:a.flowPath,platform:a.platform})}catch(u){let p=u.message||String(u);return d(`MACH_MAESTRO_RUN_FAILED: ${p}`),a?.urls&&await kr(a.urls,o,s,l),await c("failed",p),H.error(V.red(`Managed Maestro runner failed: ${p}`)),{status:"failed",exitCode:1,attempts:0,flows:a?.flowPath||".maestro",platform:a?.platform||e.platform}}}async function Xa(e){let t=e.maestroFlows||".maestro",n=Ur(e.maestroRetries);if(n===null)return null;let i=ee.resolve(t);if(!Y.existsSync(i))return H.error(V.red(`Maestro flows not found: ${t}`)),{status:"failed",exitCode:1,attempts:0,flows:t,platform:e.platform};let r=await il(e);if(r?.url){if(!await ol(r))return{status:"failed",exitCode:1,attempts:0,flows:t,platform:r.platform||e.platform}}else if(e.buildId||e.buildUrl||e.artifactUrl||e.latest)return{status:"failed",exitCode:1,attempts:0,flows:t,platform:e.platform};e.maestroRecord&&H.warn(V.yellow("--maestro-record is managed-runner only and is ignored in --local mode."));let o=r?.platform||e.platform,s=["test"];o&&s.push("--platform",o),e.maestroDevice&&s.push("--device",String(e.maestroDevice)),s.push(t);let l=n+1,a=1;for(let u=1;u<=l;u+=1){H.info(V.dim(`Running local Maestro attempt ${u}/${l}...`));let p=tt("maestro",s,{cwd:process.cwd(),stdio:"inherit",env:process.env});if(p.error){let m=p.error.message||"Failed to run Maestro";H.error(V.red(`Local Maestro failed to start: ${m}`)),H.info(V.dim("Install Maestro locally, then retry: https://maestro.mobile.dev/getting-started/installing-maestro")),a=1;break}if(a=typeof p.status=="number"?p.status:1,a===0)break}let d=a===0?"passed":"failed",c={status:d,exitCode:a,attempts:l,flows:t,platform:o};return bl(e,c),d==="passed"?H.success(V.green("Local Maestro run passed")):H.error(V.red(`Local Maestro run failed with exit code ${a}`)),c}async function ai(e){let t=Pe(`./${f.configFileName}`),n=e.projectId||t?.projectId,i=String(e.profile||e.buildProfile||"production").toLowerCase();if(!n)return H.error(`No projectId found. Run \`${f.nameLower} link\` first or pass an internal project id.`),null;let r=e.platform;if(!r&&e.latest){let d=await Lr({message:"Select platform for the latest build:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"}]});if(ii(d))return null;r=d}let o=await nl(e);if(!o)return null;if(o.kind==="latest"&&!r)return H.error("Pass --platform when using --latest."),null;if(o.kind==="artifact-url"&&!r)return H.error("Pass --platform when using --artifact-url."),null;let s=Ur(e.maestroRetries);if(s===null)return null;let l=await Qa(e,n);if(l===null)return null;let a=xt();e.quiet||a.start("Queuing Maestro run...");try{let d=await R.post("/tests/maestro",{projectId:n,platform:r,profile:i,latest:o.kind==="latest",buildId:o.kind==="build-id"?o.value:e.buildId,buildUrl:o.kind==="build-url"?o.value:e.buildUrl,artifactUrl:o.kind==="artifact-url"?o.value:e.artifactUrl,flowSourceKey:l,flows:e.maestroFlows||".maestro",device:e.maestroDevice||(r==="ios"?"iphone_15":"pixel_6"),retries:s,record:!!e.maestroRecord});if(d.data.status!=="success")throw new Error(d.data.message||"Failed to queue Maestro run");let c=d.data.testRun,u={testRunId:c.testRunId,status:c.status,projectId:n,buildId:c.buildId,platform:c.platform,dashboardUrl:c.dashboardUrl||`${Ke}/tests/${c.testRunId}`,launchDeferredReason:c.launchDeferredReason};return Hr(e,u),e.quiet||a.stop("Maestro run queued"),u}catch(d){e.quiet||a.stop("Could not queue Maestro run");let c=d.response?.data?.message||d.message||"Unknown error";return H.error(V.red(`Maestro queue failed: ${c}`)),null}}async function Za(e,t){let n=Tr(e.waitTimeout,60,"--wait-timeout"),i=Tr(e.waitInterval,15,"--wait-interval");if(n===null||i===null)return null;let r=n*60*1e3,o=Math.max(5,i)*1e3,s=Date.now(),l=t.status||"queued";for(H.info(V.dim(`Waiting for Maestro run ${t.testRunId} to finish...`));Date.now()-s<=r;){let a=await tl(t.projectId,t.testRunId);if(!a)return null;if(a.status&&a.status!==l&&(l=a.status,H.info(V.dim(`Maestro status: ${l}`))),Ya.has(String(a.status)))return Hr(e,a),a.status==="passed"?H.success(V.green(`Maestro run passed: ${a.testRunId}`)):(H.error(V.red(`Maestro run ${a.status}: ${a.testRunId}`)),a.error&&H.error(V.red(String(a.error)))),a;await li(o)}return H.error(V.red(`Timed out waiting for Maestro run ${t.testRunId} after ${n} minute(s).`)),{...t,status:"timeout"}}async function Qa(e,t){if(e.maestroUseBuildSource)return;let n=e.maestroFlows||".maestro",i=ee.resolve(n);if(!Y.existsSync(i))return e.maestroFlows?(H.error(V.red(`Maestro flows not found: ${n}`)),null):void 0;let r=ee.relative(process.cwd(),i);if(!r||r.startsWith("..")||ee.isAbsolute(r))return H.error(V.red("Managed Maestro flow uploads must be inside the current project directory.")),null;let o=xt();e.quiet||o.start(`Uploading Maestro flows from ${r}...`);try{let s=await R.post("/tests/maestro/source-upload-url",{projectId:t,uploadId:Va()});if(s.data.status!=="success"||!s.data.uploadUrl||!s.data.key)throw new Error(s.data.message||"Failed to get Maestro flow upload URL");let l=new un;if(Y.statSync(i).isDirectory())l.addLocalFolder(i,r);else{let c=ee.dirname(r);l.addLocalFile(i,c==="."?void 0:c,ee.basename(r))}let d=l.toBuffer();return await el(s.data.uploadUrl,d,"application/zip","Maestro flow upload",c=>{e.quiet||o.message(c)}),e.quiet||o.stop("Maestro flows uploaded"),s.data.key}catch(s){e.quiet||o.stop("Could not upload Maestro flows");let l=s.response?.data?.message||s.message||"Unknown error";return H.error(V.red(`Maestro flow upload failed: ${l}`)),null}}function Mr(e){let t=e.response?.status,n=e.code||"",i=e.message||"";return t&&![408,409,425,429].includes(t)&&t<500?!1:/ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|ECONNABORTED|socket hang up|network|timeout/i.test(`${n} ${i}`)||!t}async function el(e,t,n,i,r){let o;for(let s=1;s<=Nr;s+=1)try{await Lt.put(e,t,{headers:{"Content-Type":n},maxBodyLength:1/0,maxContentLength:1/0,timeout:Ja});return}catch(l){if(o=l,!Mr(l)||s>=Nr)break;let a=Math.min(2e4,2e3*s),d=l.code||l.response?.status||l.message||"network error";r?.(`${i} attempt ${s} failed (${d}), retrying...`),await li(a)}throw o}async function tl(e,t){try{let n=await R.get(`/tests/${encodeURIComponent(t)}`,{params:{projectId:e}});if(n.data.status!=="success")throw new Error(n.data.message||"Failed to fetch Maestro run");let i=n.data.testRun;return{testRunId:i.testRunId,status:i.status,projectId:e,buildId:i.buildId,platform:i.platform,dashboardUrl:i.dashboardUrl||`${Ke}/tests/${i.testRunId}`,launchDeferredReason:i.launchDeferredReason,...i.error?{error:i.error}:{}}}catch(n){let i=n.response?.data?.message||n.message||"Unknown error";return H.error(V.red(`Could not fetch Maestro run status: ${i}`)),null}}async function nl(e){if(e.buildId)return{kind:"build-id",value:e.buildId};if(e.buildUrl)return{kind:"build-url",value:e.buildUrl};if(e.artifactUrl)return{kind:"artifact-url",value:e.artifactUrl};if(e.latest)return{kind:"latest"};let t=await Lr({message:"Select app artifact source for Maestro:",options:[{value:"latest",label:"Latest successful build"},{value:"build-id",label:"Build ID"},{value:"build-url",label:`${f.name} build URL`},{value:"artifact-url",label:"Direct artifact URL"}]});if(ii(t))return null;if(t==="latest")return{kind:"latest"};let n=await Wa({message:t==="build-id"?"Enter build ID:":t==="build-url"?`Enter ${f.name} build URL:`:"Enter artifact URL:",validate:i=>{let r=String(i||"").trim();if(!r)return"Value is required";if((t==="build-url"||t==="artifact-url")&&!r.startsWith("http"))return"Must be a URL"}});return ii(n)?null:{kind:t,value:String(n).trim()}}function Tr(e,t,n){if(e==null||e==="")return t;let i=Number(e);return!Number.isFinite(i)||i<=0?(H.error(`${n} must be a positive number.`),null):i}function li(e){return new Promise(t=>setTimeout(t,e))}function Ur(e){if(e==null||e==="")return 1;let t=Number(e);return!Number.isInteger(t)||t<0||t>10?(H.error("--maestro-retries must be an integer between 0 and 10."),null):t}async function il(e){if(e.artifactUrl)return{url:e.artifactUrl,platform:e.platform||ci(e.artifactUrl),name:Fr(e.artifactUrl)};let t=e.buildId||Sl(e.buildUrl);return t?Br(t,e.platform):e.latest?rl(e):null}async function Br(e,t){let n=xt();n.start(`Resolving build ${e}...`);try{let i=await R.get(`/public/builds/${encodeURIComponent(e)}`);if(i.data.status!=="success")throw new Error(i.data.message||"Build lookup failed");let r=t||i.data.build?.platform,o=yl(i.data.artifacts||[],r);if(!o?.downloadUrl)throw new Error("No installable APK or simulator app artifact found for this build.");return n.stop("Build artifact resolved"),{url:o.downloadUrl,platform:r||ci(o.name||o.downloadUrl),name:o.name}}catch(i){n.stop("Could not resolve build artifact");let r=i.response?.data?.message||i.message||"Unknown error";return H.error(V.red(`Local Maestro artifact lookup failed: ${r}`)),null}}async function rl(e){let t=Pe(`./${f.configFileName}`),n=e.projectId||t?.projectId,i=String(e.profile||e.buildProfile||"production").toLowerCase();if(!n)return H.error(`No projectId found. Run \`${f.nameLower} link\` first or pass --build-id/--artifact-url.`),null;if(!e.platform)return H.error("Pass --platform when using --latest with --local."),null;let r=xt();r.start("Resolving latest build...");try{let o=await R.get(`/builds/${n}`,{params:{limit:100}}),l=(Array.isArray(o.data.builds)?o.data.builds:[]).find(a=>a.status==="success"&&a.platform===e.platform&&String(a.buildProfile||a.buildType||"production").toLowerCase()===i);if(!l?.buildId)throw new Error(`No successful ${e.platform} build found for profile ${i}.`);return r.stop(`Latest build resolved: ${l.buildId}`),Br(l.buildId,e.platform)}catch(o){r.stop("Could not resolve latest build");let s=o.response?.data?.message||o.message||"Unknown error";return H.error(V.red(`Latest build lookup failed: ${s}`)),null}}async function ol(e){let t=e.platform||ci(e.url);if(!t)return H.error(V.red("Could not infer platform for local install. Pass --platform android or --platform ios.")),!1;let n=Y.mkdtempSync(ee.join(si.tmpdir(),"mach-maestro-")),i=e.name||Fr(e.url)||(t==="android"?"app.apk":"app.zip"),r=ee.join(n,i),o=xt();o.start(`Downloading ${i}...`);try{await ri(e.url,r),o.stop("Artifact downloaded")}catch(s){return o.stop("Artifact download failed"),H.error(V.red(s.message||"Failed to download artifact")),!1}return t==="android"?gl(r):hl(r,n)}async function ri(e,t){let n=await Lt.get(e,{responseType:"stream"});await za(n.data,Y.createWriteStream(t))}function sl(e,t=12e3){try{return Y.readFileSync(e,"utf-8").slice(-t)}catch{return""}}function al(e,t){let n=ee.resolve(e,t||".maestro"),i=ee.relative(e,n);if(i.startsWith("..")||ee.isAbsolute(i))throw new Error("Maestro flow path must stay inside the build source.");return n}function Mt(e,t,n,i){Y.appendFileSync(n,`
|
|
1117
1117
|
$ ${[e,...t].join(" ")}
|
|
1118
|
-
`);let r=tt(e,t,{cwd:i,encoding:"utf-8",env:process.env});return r.stdout&&
|
|
1119
|
-
`),1):typeof r.status=="number"?r.status:1}function
|
|
1120
|
-
`)[0]?.trim():"";i&&t.unshift(i);for(let r of t)if(r&&
|
|
1121
|
-
`),r;return e&&
|
|
1122
|
-
`),null}function
|
|
1123
|
-
`);return}let i=
|
|
1124
|
-
`),
|
|
1125
|
-
`),
|
|
1126
|
-
`),null;let i=tt("/usr/bin/plutil",["-extract","CFBundleIdentifier","raw","-o","-",n],{encoding:"utf-8",env:process.env}),r=String(i.stdout||"").trim();return i.status!==0||!r?(
|
|
1127
|
-
`),null):r}function
|
|
1128
|
-
`),
|
|
1129
|
-
`)}async function
|
|
1130
|
-
`)}try{await
|
|
1131
|
-
`)}try{
|
|
1132
|
-
`)}}function rl(e){if(!e.endsWith(".apk"))return F.error(V.red("Local Android Maestro runs need an APK artifact.")),!1;F.info(V.dim("Installing APK on local Android device/emulator..."));let t=tt("adb",["install","-r",e],{stdio:"inherit",env:process.env});return t.error?(F.error(V.red(`adb failed to start: ${t.error.message}`)),!1):t.status!==0?(F.error(V.red(`adb install failed with exit code ${t.status??1}`)),!1):!0}function ol(e,t){if(e.endsWith(".ipa"))return F.error(V.red("Local iOS Maestro runs need an iOS Simulator .app.zip artifact, not an App Store .ipa.")),!1;let n=e;if(e.endsWith(".zip")){let r=X.join(t,"ios-app");W.mkdirSync(r,{recursive:!0}),new cn(e).extractAllTo(r,!0);let o=ai(r);if(!o)return F.error(V.red("Could not find a .app bundle inside the downloaded zip.")),!1;n=o}if(!n.endsWith(".app"))return F.error(V.red("Local iOS Maestro runs need an iOS Simulator .app bundle or .app.zip artifact.")),!1;F.info(V.dim("Installing app on booted iOS Simulator..."));let i=tt("xcrun",["simctl","install","booted",n],{stdio:"inherit",env:process.env});return i.error?(F.error(V.red(`xcrun failed to start: ${i.error.message}`)),!1):i.status!==0?(F.error(V.red(`iOS Simulator install failed with exit code ${i.status??1}`)),!1):!0}function ai(e){let t=W.readdirSync(e,{withFileTypes:!0});for(let n of t){let i=X.join(e,n.name);if(n.isDirectory()&&n.name.endsWith(".app"))return i;if(n.isDirectory()){let r=ai(i);if(r)return r}}return null}function sl(e,t){let n=String(t||"").toLowerCase();return n==="android"?e.find(i=>At(i,".apk")):n==="ios"?e.find(i=>At(i,".app.zip"))||e.find(i=>At(i,".zip")):e.find(i=>At(i,".apk"))||e.find(i=>At(i,".app.zip"))||e.find(i=>At(i,".zip"))}function At(e,t){return String(e?.name||e?.downloadUrl||e?.url||"").toLowerCase().endsWith(t)}function li(e){let t=String(e||"").toLowerCase();if(t.includes(".apk"))return"android";if(t.includes(".app.zip")||t.endsWith(".app")||t.includes(".ipa"))return"ios"}function Tr(e){if(e)try{return X.basename(new URL(e).pathname)||void 0}catch{return X.basename(e)||void 0}}function al(e){return e?e.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i)?.[0]:void 0}function kr(e,t){if(!e.jsonOutput)return;let n=X.resolve(e.jsonOutput),i={...t,updatedAt:new Date().toISOString()};try{let r=X.dirname(n);r&&r!=="."&&W.mkdirSync(r,{recursive:!0}),W.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){F.warn(V.yellow(`Could not write Maestro metadata JSON: ${r.message}`))}}function ll(e,t){if(!e.jsonOutput)return;let n=X.resolve(e.jsonOutput),i={mode:"local",...t,updatedAt:new Date().toISOString()};try{let r=X.dirname(n);r&&r!=="."&&W.mkdirSync(r,{recursive:!0}),W.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){F.warn(V.yellow(`Could not write Maestro metadata JSON: ${r.message}`))}}import{spinner as it,text as Mt,select as fi,isCancel as nt,cancel as mi,log as Hr}from"@clack/prompts";import ee from"chalk";import oe from"fs";import Ae from"path";import{spawn as cl,spawnSync as pt}from"child_process";import jr from"axios";import mt from"os";import yi from"crypto";var dl=5e3,ul=12,Gr=100,ci=24,Lr=8e3,pl={completed:"completed",draft:"draft",halted:"halted",inprogress:"inProgress","in-progress":"inProgress"},fl=e=>e?.type==="google_service_account",un=e=>e?.bundleId||e?.packageName||e?.meta?.packageName||e?.meta?.bundleId,Kr=e=>e.submitArgs||process.argv.slice(3).join(" ");async function pn(e){let t=it(),n=Pe(),i=ml(e);if(!i){process.exitCode=1;return}let r=e.projectId||i.projectId,o=e.profile||e.buildProfile||"production";if(!r){le(`${m.configFileName} is missing projectId. Pass --project-id in runner mode.`),process.exitCode=1;return}i.projectId=r,fe(ee.dim(`Submit for project: ${i.name||r} | Profile: ${o}`));let s=e.platform;if(!s){let w=await fi({message:"Select platform to submit:",options:[{value:"ios",label:"iOS (App Store Connect / TestFlight)"},{value:"android",label:"Android (Google Play Console)"}]});if(nt(w)){mi("Operation cancelled");return}s=w}if(s=String(s).toLowerCase(),s!=="ios"&&s!=="android"){le(`Platform ${s} is not supported. Use 'ios' or 'android'.`),process.exitCode=1;return}let l=s==="ios"&&!e.local&&e.sshHost?Ol(i,o,e):null;if(s==="ios"&&!e.local&&!l){await gl(i,o,e);return}let a=e.submitId,c=!!(e.local&&a),d=a||null,u=async(w,U={})=>{d&&await bl(r,d,{status:w,...U})},p=s==="android"?Rl(i,o):void 0,f=s==="ios"?Dl(i,o):void 0,S,L,k,x=!1;try{s==="android"&&(S=e.track||i.submit?.[o]?.android?.track||i.submit?.production?.android?.track||"internal",L=Cl(i,o,e.releaseStatus),k=Tl(i,o,e.rollout),x=kl(i,o,e.changesNotSentForReview),Ll(L,k))}catch(w){le(w.message),process.exitCode=1;return}if(s==="android"&&!c&&(d=await hl(i,r,s,o,e,{packageName:p,track:S,releaseStatus:L,rollout:k,changesNotSentForReview:x}),!d)){le("Could not create submission tracking record. Submission was not started."),process.exitCode=1;return}await u("running",{platform:s,profile:o,packageName:p,track:S,releaseStatus:L,rollout:k,startTime:Date.now(),...c?Al():{}});let O=null,G=null;try{G=await xl(r,s,e,n?.token),O=G?.filePath||null}catch(w){await u("failed",{error:`Failed to resolve submission artifact: ${w.message}`,endTime:Date.now()}),le(`Failed to resolve submission artifact: ${w.message}`),process.exitCode=1;return}if(!O){let w=Ul(s,e);await u("failed",{error:w,endTime:Date.now()}),le(w),process.exitCode=1;return}await u("running",{buildId:G?.buildId,artifactName:G?.artifactName,artifactSource:G?.source}),fe(`Using artifact: ${ee.green(Ae.basename(O))} `),t.start("Fetching submission credentials from Dashboard...");let h;try{let U=(await v.get(`/credentials/${r}`)).data.credentials||[];if(s==="android"&&!p){t.stop("Package name missing"),le("Could not resolve Android package name. Set android.package in mach.config.json/app.json."),await u("failed",{error:"Could not resolve Android package name.",endTime:Date.now()}),process.exitCode=1;return}let K=U.filter(fl),M=s==="ios"?U.filter(Y=>Y.type==="asc_api_key"):vl(K,p);if(M.length===0){if(t.stop("Credentials missing"),le(s==="android"?`No Google Play service credential found for package ${p}.`:`No Service Credentials found for ${s}.`),s==="android"){let Y=K.map(un).filter(Boolean).join(", ");Y&&fe(`Found Google Play service credential(s) for: ${Y}`),fe(`Use '${m.nameLower} credentials:service --platform android --package-name ${p}' or upload it under that package in the Dashboard.`)}else fe(`Use '${m.nameLower} credentials:service --platform ${s}' or use the Dashboard to upload them.`);await u("failed",{error:`No submission credentials found for ${s}.`,endTime:Date.now()}),process.exitCode=1;return}if(h=wl(M,e.credentialId),!h&&s==="ios"&&f&&(h=_l(M,f)),h||M.length===1)h=h||M[0],t.stop(`Using: ${h.name}`),s==="android"&&un(h)==="*"&&fe(ee.yellow(`Using legacy wildcard Google Play credential for ${p}. Upload a package-scoped credential when possible.`));else{if(t.stop("Multiple credentials found"),$l()){let E=M.map(re=>`${re.name||"credential"} (${re.credentialId||re.id||"no-id"})`).join(", ");le(`Multiple ${s==="ios"?"App Store Connect":"Google Play"} credentials found. Use --credential-id in CI. Available: ${E}`),await u("failed",{error:"Multiple submission credentials found; --credential-id is required in CI.",endTime:Date.now()}),process.exitCode=1;return}let Y=await fi({message:`Choose a ${s==="ios"?"App Store Connect":"Google Play"} credential:`,options:M.map(E=>({value:E.credentialId,label:E.name,hint:`${E.keyId?`ID: ${E.keyId}`:""} ${E.issuerId?`(Issuer: ${E.issuerId.substring(0,8)}...)`:""}`}))});if(nt(Y)){mi("Submission cancelled"),await u("failed",{error:"Submission cancelled while selecting credential.",endTime:Date.now()}),process.exitCode=1;return}h=M.find(E=>E.credentialId===Y),fe(`Using selected: ${ee.green(h.name)}`)}}catch(w){t.stop("Failed to fetch credentials"),le(`API Error: ${w.message} `),await u("failed",{error:`Failed to fetch credentials: ${w.message}`,endTime:Date.now()}),process.exitCode=1;return}let H=oe.mkdtempSync(Ae.join(mt.tmpdir(),`${m.nameLower}-submit-`)),b=h.keyId||h.meta?.keyId,I=h.issuerId||h.meta?.issuerId,N=h.type==="asc_api_key"?`AuthKey_${b}.p8`:"service-account.json",P=Ae.join(H,N);t.start("Downloading secure key...");try{let w=await v.get(`/credentials/${h.credentialId}/download`,{params:{projectId:r,format:"raw"}});if(w.data.status!=="success"||!w.data.downloadUrl)throw new Error("Failed to get secure download URL");let U=await jr.get(w.data.downloadUrl,{responseType:"arraybuffer"});oe.writeFileSync(P,Buffer.from(U.data)),t.stop("Key downloaded to secure temp storage")}catch(w){t.stop("Download failed"),le(`Failed to download key: ${w.message}`);try{oe.rmSync(H,{recursive:!0,force:!0})}catch{}await u("failed",{error:`Failed to download credential key: ${w.message}`,endTime:Date.now()}),process.exitCode=1;return}fe(ee.blue(`Initiating ${s==="ios"?"TestFlight":"Google Play"} submission...`));let T=!1,R;try{if(s==="ios"){if(!b){let U=await Mt({message:"Enter App Store Connect Key ID (e.g. 2X948D...):",validate:K=>K.length>0?void 0:"Key ID is required"});if(nt(U)){await u("failed",{error:"Submission cancelled while entering ASC Key ID.",endTime:Date.now()}),process.exitCode=1;return}b=U}if(!I||I==="undefined"){let U=await Mt({message:"Enter App Store Connect Issuer ID (Found on ASC Keys page):",validate:K=>K.length>0?void 0:"Issuer ID is required"});if(nt(U)){await u("failed",{error:"Submission cancelled while entering ASC Issuer ID.",endTime:Date.now()}),process.exitCode=1;return}I=U}fe(`Using ASC Key ID: ${b}`),fe(`Using ASC Issuer ID: ${I}`);let w=l?await Fl(O,P,I,b,f,l):await Bl(O,P,I,b,f);hi(`${s==="ios"?"App Store":"Google Play"} submission successful!`),T=!0}else R=await Vl(O,P,S||"internal",p,L||"completed",k,x,o),hi("Google Play submission successful!"),T=!0}catch(w){le(`Submission failed: ${w.message}`),await u("failed",{error:w.message,endTime:Date.now()}),It(e,{status:"failed",projectId:r,submitId:d,platform:s,profile:o,buildId:G?.buildId||e.buildId,artifactName:G?.artifactName,error:w.message,dashboardUrl:d?ft(d,r):void 0}),process.exitCode=1}finally{T&&(await u("success",{endTime:Date.now(),versionCode:R?.versionCode,track:S,releaseStatus:L}),It(e,{status:"success",projectId:r,submitId:d,platform:s,profile:o,buildId:G?.buildId||e.buildId,artifactName:G?.artifactName,versionCode:R?.versionCode,track:S,releaseStatus:L,dashboardUrl:d?ft(d,r):void 0})),sc(H),O&&O.includes(`${m.nameLower}-artifact-`)}}function ml(e){let t=`./${m.configFileName}`;if(oe.existsSync(t))try{return JSON.parse(oe.readFileSync(t,"utf-8"))}catch(n){return le(`Failed to read ${m.configFileName}: ${n.message}`),null}return e.projectId?{projectId:e.projectId}:(le(`No ${m.configFileName} found. Run \`${m.nameLower} init\` or \`${m.nameLower} link\` first.`),null)}async function gl(e,t,n){let i=n.projectId||e.projectId;if(!i){le(`${m.configFileName} is missing projectId.`),process.exitCode=1;return}let r=n.submitId||yi.randomUUID(),o=!!n.latest||!n.buildId,s=yl({...n,latest:o,profile:t,projectId:i,submitId:r}),l={projectId:i,submitId:r,platform:"ios",profile:t,latest:o,buildId:n.buildId,credentialId:n.credentialId,status:"pending",source:"cli",submitArgs:Kr(n),runnerArgs:s,runnerCommand:[m.nameLower,"submit",...s].map(Pl).join(" "),appName:e.name,startTime:Date.now()},a=it();a.start("Queuing iOS submit on macOS runner...");try{let c=await v.post("/submissions",l),d=c.data?.submission||c.data?.submit||{},u=c.data?.dashboardUrl||ft(r,i);a.stop("iOS submit queued"),fe(`Submission ID: ${ee.cyan(r)}`),fe(`Dashboard: ${ee.blue.underline(u)}`),It(n,{status:"pending",projectId:i,submitId:r,platform:"ios",profile:t,latest:o,buildId:n.buildId,dashboardUrl:u}),await Sl(i,r,n)}catch(c){a.stop("Could not queue iOS submit"),le(Il(c)),process.exitCode=1}}async function hl(e,t,n,i,r,o={}){let s=r.submitId||yi.randomUUID(),l=!!r.latest||!r.buildId,a={projectId:t,submitId:s,platform:n,profile:i,latest:l,buildId:r.buildId,credentialId:r.credentialId,status:"running",source:"cli-direct",submitArgs:Kr(r),appName:e.name,startTime:Date.now(),...o};try{let c=await v.post("/submissions",a),d=c.data?.submission||c.data?.submit||{},u=c.data?.dashboardUrl||d.dashboardUrl||ft(s,t);return fe(`Submission ID: ${ee.cyan(s)}`),fe(`Dashboard: ${ee.blue.underline(u)}`),It(r,{status:"running",projectId:t,submitId:s,platform:n,profile:i,latest:l,buildId:r.buildId,dashboardUrl:u}),s}catch(c){let d=c.response?.data?.message||c.response?.data?.error||c.message;return fe(ee.yellow(`Could not create submission tracking record: ${d}`)),null}}function yl(e){let t=["--local","--submit-id",e.submitId,"--project-id",e.projectId,"--platform","ios","--profile",e.profile||"production"];return e.buildId?t.push("--build-id",e.buildId):t.push("--latest"),e.credentialId&&t.push("--credential-id",e.credentialId),e.quiet&&t.push("--quiet"),e.jsonOutput&&t.push("--json-output",e.jsonOutput),t.filter(n=>n!=null&&n!=="")}async function Sl(e,t,n){let i=it(),r=0,o=0;for(n.quiet||i.start("Waiting for iOS submit runner...");;)try{let s=await v.get(`/submissions/${e}/${t}`),l=s.data?.submission||s.data?.submit||s.data,a=String(l?.status||"pending").toLowerCase();r=0;let c=Array.isArray(l?.logs)?l.logs:[];for(let d=o;d<c.length;d++){let u=c[d];u&&console.log(ee.dim(String(u)))}if(o=c.length,["success","completed","succeeded"].includes(a)){n.quiet||i.stop("iOS submit completed"),hi("App Store submission successful!"),It(n,{status:"success",projectId:e,submitId:t,platform:"ios",profile:l?.profile||n.profile||"production",buildId:l?.buildId||n.buildId,artifactName:l?.artifactName,dashboardUrl:l?.dashboardUrl||ft(t,e)});return}if(["failed","error","cancelled","canceled"].includes(a)){n.quiet||i.stop("iOS submit failed");let d=l?.error||l?.message||"Unknown iOS submit failure.";le(d),It(n,{status:"failed",projectId:e,submitId:t,platform:"ios",profile:l?.profile||n.profile||"production",buildId:l?.buildId||n.buildId,artifactName:l?.artifactName,error:d,dashboardUrl:l?.dashboardUrl||ft(t,e)}),process.exitCode=1;return}n.quiet||i.message(`iOS submit ${a}...`),await gi(dl)}catch(s){if(r++,r>=ul){n.quiet||i.stop("Lost connection to iOS submit status"),le(`Could not fetch iOS submit status after ${r} attempts: ${s.message}`),process.exitCode=1;return}await gi(Math.min(2e3*r,15e3))}}async function bl(e,t,n){let i;for(let r=1;r<=3;r++)try{await v.patch(`/submissions/${e}/${t}`,n);return}catch(o){if(i=o,r>=3||!El(o))break;await gi(1e3*r)}Hr.warn(ee.dim(`Could not report submission status: ${i?.message||i}`))}function El(e){let t=e.response?.status;return!t||t===408||t===409||t===425||t===429||t>=500}function Al(){let e={gitlabJobId:process.env.CI_JOB_ID,gitlabJobUrl:process.env.CI_JOB_URL,gitlabPipelineId:process.env.CI_PIPELINE_ID,gitlabProjectId:process.env.CI_PROJECT_ID,gitlabProjectPath:process.env.CI_PROJECT_PATH};return Object.fromEntries(Object.entries(e).filter(([,t])=>!!t))}function Il(e){let t=e.response?.status,n=e.response?.data?.message||e.response?.data?.error;return t===404||t===405?["Managed iOS submit is not enabled on this Mach API yet.","Deploy the API/dashboard submission orchestration endpoint, then retry the same command.","Expected API: POST /submissions and GET/PATCH /submissions/:projectId/:submitId."].join(`
|
|
1133
|
-
`):n||e.message||String(e)}function ft(e,t){if(!e)return Ye;let n=t?`?projectId=${encodeURIComponent(t)}`:"";return`${Ye}/submissions/${e}${n}`}function It(e,t){if(!e.jsonOutput)return;let n=Ae.resolve(e.jsonOutput),i={...t,url:t.url||t.dashboardUrl||ft(t.submitId,t.projectId),updatedAt:new Date().toISOString()};try{let r=Ae.dirname(n);r&&r!=="."&&oe.mkdirSync(r,{recursive:!0}),oe.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){Hr.warn(ee.yellow(`Could not write submission metadata JSON: ${r.message}`))}}function wl(e,t){return t&&e.find(n=>n.credentialId===t||n.id===t||n.keyId===t||n.meta?.keyId===t)||null}function _l(e,t){let n=e.filter(i=>[i.bundleId,i.bundleIdentifier,i.appIdentifier,i.meta?.bundleId,i.meta?.bundleIdentifier,i.meta?.appIdentifier].filter(Boolean).map(String).includes(t));return n.length===1?n[0]:null}function $l(){return process.env.CI==="true"||process.env.CI==="1"||!process.stdin.isTTY}function gi(e){return new Promise(t=>setTimeout(t,e))}function Pl(e){return/^[a-zA-Z0-9_./:=@-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function Rl(e,t){if(e.submit?.[t]?.android?.package)return e.submit[t].android.package;let n=Ki(e,t);if(n)return n;let i=Ae.join(process.cwd(),"app.json");if(oe.existsSync(i))try{return JSON.parse(oe.readFileSync(i,"utf-8")).expo?.android?.package}catch{}let r=Ae.join(process.cwd(),"app.config.json");if(oe.existsSync(r))try{let o=JSON.parse(oe.readFileSync(r,"utf-8"));return o.expo?.android?.package||o.android?.package}catch{}}function vl(e,t){let n=e.filter(o=>un(o)===t);if(n.length>0)return n;let i=e.filter(o=>{let s=un(o);return!s||s==="*"});return e.length>0&&e.length===i.length?i:[]}function Dl(e,t){return e.submit?.[t]?.ios?.bundleIdentifier?e.submit[t].ios.bundleIdentifier:e.submit?.[t]?.ios?.bundleId?e.submit[t].ios.bundleId:Vi(e,t)}function Ol(e,t,n){let i=e.submit?.[t]?.ios||{},r=e.submit?.production?.ios||{},o=n.sshHost||i.sshHost||r.sshHost||process.env.MACH_IOS_SUBMIT_SSH_HOST;return o?{sshHost:o,sshUser:n.sshUser||i.sshUser||r.sshUser||process.env.MACH_IOS_SUBMIT_SSH_USER||process.env.USER||"ubuntu",sshKey:n.sshKey||i.sshKey||r.sshKey||process.env.MACH_IOS_SUBMIT_SSH_KEY}:null}function Cl(e,t,n){let i=n||e.submit?.[t]?.android?.releaseStatus||e.submit?.production?.android?.releaseStatus||"completed";return Nl(i)}function Nl(e){let t=pl[String(e).trim().toLowerCase()];if(!t)throw new Error(`Invalid Android release status "${e}". Use completed, draft, halted, or inProgress.`);return t}function Tl(e,t,n){let i=n??e.submit?.[t]?.android?.rollout??e.submit?.[t]?.android?.userFraction??e.submit?.[t]?.android?.rolloutFraction??e.submit?.production?.android?.rollout??e.submit?.production?.android?.userFraction??e.submit?.production?.android?.rolloutFraction;if(i==null||i==="")return;let r=Number(i);if(!Number.isFinite(r)||r<=0||r>=1)throw new Error(`Invalid Android rollout fraction "${i}". Use a number greater than 0 and less than 1, for example 0.1.`);return r}function kl(e,t,n){let i=n??e.submit?.[t]?.android?.changesNotSentForReview??e.submit?.[t]?.android?.changes_not_sent_for_review??e.submit?.production?.android?.changesNotSentForReview??e.submit?.production?.android?.changes_not_sent_for_review??!1;return i===!0||i==="true"||i==="1"}function Ll(e,t){if(e==="inProgress"&&t===void 0)throw new Error("Google Play staged rollout requires --rollout <fraction> when --release-status inProgress is used.");if(e!=="inProgress"&&e!=="halted"&&t!==void 0)throw new Error("Android rollout fraction can only be used with --release-status inProgress or halted.")}async function xl(e,t,n,i){let r=n.buildId?"id":n.latest?"latest":null;if(!r){let s=await fi({message:"Select artifact source:",options:[{value:"latest",label:`Latest Production Build (${m.name})`},{value:"id",label:`Input Build ID (${m.name})`},{value:"url",label:"Remote URL"},{value:"local",label:"Local File Path"}]});if(nt(s))return mi("Operation cancelled"),null;r=s}if(r==="local"){let s=await Mt({message:"Enter path to artifact (.ipa/.aab):",validate:l=>{if(!oe.existsSync(l))return"File not found";if(t==="ios"&&!l.endsWith(".ipa"))return"Must be an .ipa file";if(t==="android"&&!l.endsWith(".aab"))return"Must be an .aab file"}});return nt(s)?null:{filePath:s,source:"local"}}let o=it();if(r==="latest"){let s=n.profile||n.buildProfile;o.start(`Fetching latest${s?` ${s}`:""} build...`);try{let l=await v.get(`/builds/${e}`,{params:{limit:50}});if(l.data.status!=="success")throw new Error(l.data.message);let a=l.data.builds||[],c=s?.toLowerCase(),d=h=>h.platform?.toLowerCase()===t.toLowerCase()&&h.status?.toLowerCase()==="success",u=h=>c?[h.buildProfile,h.profile,h.profileName,h.buildType].filter(Boolean).some(H=>String(H).toLowerCase()===c):!0,p=a.filter(h=>d(h)&&u(h)),f=p.find(h=>h.buildType?.toLowerCase()==="store"||h.distribution?.toLowerCase()==="store")||p[0],S=a.some(h=>h.platform?.toLowerCase()===t.toLowerCase()&&h.status?.toLowerCase()==="success");if(!f)return o.stop("No suitable build found"),le(s&&S?`No successful ${t} builds found for profile "${s}".`:"No successful builds found for this platform."),null;o.stop(`Found build: ${f.buildId}`);let L=f.artifacts||[];if(L.length===0||L.every(h=>!(h.url||h.downloadUrl)))try{let h=await v.get(`/builds/${e}/${f.buildId}/artifacts`);h.data.status==="success"&&h.data.artifacts?.length>0?(L=h.data.artifacts.map(H=>({...H,url:H.url||H.downloadUrl})),console.log(ee.cyan(` [RECOVERY] Fetched ${L.length} artifact(s) with download URLs.`))):console.log(ee.yellow(" [RECOVERY] /artifacts endpoint returned 0 artifacts."))}catch(h){console.log(ee.red(` [RECOVERY] /artifacts fetch failed: ${h.message}`))}let x=t==="ios",O=L.find(h=>{let H=(h.type||"").toLowerCase(),b=(h.name||"").toLowerCase();if(console.log(ee.dim(` - Checking: ${h.name} (Type: ${h.type}, HasLink: ${!!(h.url||h.downloadUrl)})`)),H)return H===(x?"ipa":"aab");let I=x?".ipa":".aab",N=(h.url||h.downloadUrl||"").toLowerCase();return b.endsWith(I)||N.includes(I)});if(!O||!(O.url||O.downloadUrl))return le("Build found but artifact URL is missing."),null;let G=O.url||O.downloadUrl;return{filePath:await di(G,x?"ios":"android"),buildId:f.buildId,artifactName:O.name,source:"latest"}}catch(l){return o.stop("Fetch failed"),le(`API Error: ${l.message}`),null}}if(r==="id"){let s=n.buildId||await Mt({message:"Enter Build ID:",validate:a=>a.length<5?"Invalid ID":void 0});if(nt(s))return null;let l=String(s);o.start("Fetching build...");try{let a=null;try{let f=await v.get(`/builds/${e}/${l}`);f.data.status==="success"&&(a=f.data.build)}catch(f){f.response?.status!==404&&console.log(ee.dim(` [RECOVERY] Project build lookup skipped: ${f.message}`))}if(!a){let f=await v.get(`/build/${l}`);if(f.data.status!=="success")throw new Error(f.data.message);a=f.data.build}if(!a)throw new Error(`Build ${l} was not found.`);let c=t==="ios",d=dn(a.artifacts);Ml(d)||(d=await Mr(e,l,d));let u=xr(d,t);if(u||(d=await Mr(e,l,d),u=xr(d,t)),!u)throw new Error(`No ${c?".ipa":".aab"} artifact found for build ${l}. The build exists, but its artifact list does not contain a downloadable submission artifact.`);let p=u.url||u.downloadUrl;if(!p)throw new Error(`Artifact ${u.name||"(unnamed)"} for build ${l} has no download URL. Retry after the build artifact upload is visible in the Installation Hub.`);return o.stop(`Found build: ${a.buildId||l}`),{filePath:await di(p,c?"ios":"android"),buildId:a.buildId||l,artifactName:u.name,source:"id"}}catch(a){throw o.stop("Fetch failed"),a}}if(r==="url"){let s=await Mt({message:"Enter Artifact URL:",validate:l=>l.startsWith("http")?void 0:"Must be a valid URL"});return nt(s)?null:{filePath:await di(s,t),source:"url"}}return null}function dn(e){return(e||[]).map(t=>({...t,url:t.url||t.downloadUrl}))}function Ml(e){return e.some(t=>!!(t.url||t.downloadUrl))}function xr(e,t){let n=t==="ios",i=n?"ipa":"aab",r=n?".ipa":".aab";return e.find(o=>{let s=String(o.type||"").toLowerCase(),l=String(o.name||"").toLowerCase(),a=String(o.url||o.downloadUrl||"").toLowerCase();return s?s===i:l.endsWith(r)||a.includes(r)})||null}function Ul(e,t){let n=e==="ios"?".ipa":".aab";if(t.buildId)return`No downloadable ${n} artifact found for build ${t.buildId}. Check that the build finished artifact upload before submitting.`;if(t.latest){let i=t.profile||t.buildProfile;return`No latest successful ${e}${i?` ${i}`:""} build has a downloadable ${n} artifact.`}return`No downloadable ${n} artifact was selected for submission.`}async function Mr(e,t,n){try{let i=await v.get(`/builds/${e}/${t}/artifacts`);if(i.data.status==="success"&&i.data.artifacts?.length>0){let r=dn(i.data.artifacts);return console.log(ee.cyan(` [RECOVERY] Fetched ${r.length} artifact(s) with download URLs.`)),r}}catch(i){console.log(ee.dim(` [RECOVERY] Project artifact lookup skipped: ${i.message}`))}try{let i=await v.get(`/public/builds/${t}`);if(i.data.status==="success"&&i.data.artifacts?.length>0){let r=dn(i.data.artifacts);return console.log(ee.cyan(` [RECOVERY] Fetched ${r.length} public artifact(s) with download URLs.`)),r}}catch(i){console.log(ee.dim(` [RECOVERY] Public artifact lookup skipped: ${i.message}`))}return dn(n)}async function di(e,t,n=3){let i=it();i.start("Downloading artifact...");let r=oe.mkdtempSync(Ae.join(mt.tmpdir(),`${m.nameLower}-artifact-`)),o=`app.${t==="ios"?"ipa":"aab"}`,s=Ae.join(r,o);for(let l=1;l<=n;l++)try{l>1&&(i.message(`Downloading artifact (Retry ${l}/${n})...`),await new Promise(d=>setTimeout(d,2e3*l)));let a=oe.createWriteStream(s),c=await jr({url:e,method:"GET",responseType:"stream",timeout:6e4});return await new Promise((d,u)=>{c.data.pipe(a);let p=!1;c.data.on("error",f=>{p||(p=!0,a.close(),u(f))}),a.on("finish",()=>{p||d()}),a.on("error",f=>{p||(p=!0,u(f))})}),i.stop("Download complete"),s}catch(a){if(l===n)throw i.stop("Download failed"),a}throw new Error("Download failed after retries")}async function Bl(e,t,n,i,r){let o=it();if(r&&fe(`Bundle ID: ${ee.green(r)}`),!n||!i)throw le(`Missing credentials: issuerId=${n}, keyId=${i}. Check your Dashboard.`),new Error("Missing ASC API Key Metadata (IssuerID or KeyID)");let s=Vr(t,n,i),l=Wl();return o.start("Uploading to TestFlight (pilot)..."),new Promise((a,c)=>{let d=Jl(),u=cl(l.command,["pilot","upload","--ipa",e,"--api_key_path",s,"--skip_submission","true","--skip_waiting_for_build_processing","true"],{stdio:["ignore","pipe","pipe"],env:l.env});u.stdout?.on("data",p=>d.append(p,process.stdout)),u.stderr?.on("data",p=>d.append(p,process.stderr)),u.on("close",p=>{if(d.flush(),p!==0){o.stop("Pilot failed");try{oe.unlinkSync(s)}catch{}c(ql(p,d.lines()))}else{o.stop("IPA uploaded to TestFlight");try{oe.unlinkSync(s)}catch{}a({})}}),u.on("error",p=>{d.flush();try{oe.unlinkSync(s)}catch{}o.stop("Pilot execution error");let f=rc(p);f.logs=d.lines(),c(f)})})}async function Fl(e,t,n,i,r,o){let s=it();if(r&&fe(`Bundle ID: ${ee.green(r)}`),!n||!i)throw le(`Missing credentials: issuerId=${n}, keyId=${i}. Check your Dashboard.`),new Error("Missing ASC API Key Metadata (IssuerID or KeyID)");let l=Vr(t,n,i),a=`${o.sshUser}@${o.sshHost}`,c=Hl(o),d=jl(o),u="",p="";try{if(s.start(`Preparing remote iOS submit runner (${a})...`),u=Gl("ssh",[...c,"mktemp -d /tmp/mach-submit.XXXXXX"]).trim(),!u)throw new Error("Remote runner did not return a temp directory.");s.stop(`Remote runner ready: ${a}`),s.start("Uploading IPA and App Store Connect key to remote runner..."),ui("scp",[...d,e,`${a}:${u}/app.ipa`],"IPA upload to remote runner"),ui("scp",[...d,l,`${a}:${u}/api_key.json`],"ASC key upload to remote runner"),p=Ae.join(mt.tmpdir(),`${m.nameLower}-ios-submit-${Date.now()}.sh`),oe.writeFileSync(p,Kl(u)),ui("scp",[...d,p,`${a}:${u}/submit.sh`],"submit script upload to remote runner"),s.stop("Remote submit inputs uploaded"),s.start("Uploading to TestFlight on remote runner...");let f=`chmod +x ${Ut(`${u}/submit.sh`)} && bash ${Ut(`${u}/submit.sh`)}`,S=pt("ssh",[...c,f],{stdio:"inherit"});if(S.error)throw Si("ssh",S.error);if(S.status!==0)throw new Error(`Remote iOS submit failed with exit code ${S.status}.`);return s.stop("IPA uploaded to TestFlight"),{apiKeyJsonPath:null}}catch(f){throw s.stop("Remote iOS submit failed"),f}finally{try{oe.unlinkSync(l)}catch{}if(p)try{oe.unlinkSync(p)}catch{}if(u)try{pt("ssh",[...c,`rm -rf ${Ut(u)}`],{stdio:"ignore"})}catch{}}}function Vr(e,t,n){let i=oe.readFileSync(e,"utf8"),r;try{r=yi.createPrivateKey(i).export({type:"pkcs8",format:"pem"})}catch{fe("Key normalization failed, falling back to manual re-wrapping..."),r=`-----BEGIN PRIVATE KEY-----
|
|
1118
|
+
`);let r=tt(e,t,{cwd:i,encoding:"utf-8",env:process.env});return r.stdout&&Y.appendFileSync(n,r.stdout),r.stderr&&Y.appendFileSync(n,r.stderr),r.error?(Y.appendFileSync(n,`${r.error.message}
|
|
1119
|
+
`),1):typeof r.status=="number"?r.status:1}function oi(e,t,n,i){let r=Mt(e,t,n,i);if(r!==0)throw new Error(`${e} ${t.join(" ")} failed with exit code ${r}`)}function ll(e){try{return Y.accessSync(e,Y.constants.X_OK),!0}catch{return!1}}function dl(e){let t=[process.env.MAESTRO_BIN,ee.join(si.homedir(),".maestro","bin","maestro"),"/opt/homebrew/bin/maestro","/usr/local/bin/maestro"].filter(Boolean),n=tt("/usr/bin/env",["which","maestro"],{encoding:"utf-8",env:process.env}),i=n.status===0?String(n.stdout||"").split(`
|
|
1120
|
+
`)[0]?.trim():"";i&&t.unshift(i);for(let r of t)if(r&&ll(r))return e&&Y.appendFileSync(e,`Using Maestro CLI at ${r}
|
|
1121
|
+
`),r;return e&&Y.appendFileSync(e,`Maestro CLI not found. Checked: ${t.join(", ")}
|
|
1122
|
+
`),null}function cl(e){let t=String(e||"").trim();return t?t.replace(/_/g," ").replace(/\bios\b/gi,"").replace(/\biphone\b/i,"iPhone").replace(/\s+/g," ").trim():"iPhone 15"}async function ul(e,t){if((tt("xcrun",["simctl","list","devices","booted"],{encoding:"utf-8"}).stdout||"").includes("(Booted)")){Y.appendFileSync(t,`Using already booted iOS Simulator.
|
|
1123
|
+
`);return}let i=cl(e),r=tt("xcrun",["simctl","list","devices","--json"],{encoding:"utf-8"});if(r.status!==0||!r.stdout)throw new Error("Could not list iOS simulators.");let o=JSON.parse(r.stdout),s=Object.values(o.devices||{}).flatMap(d=>Array.isArray(d)?d:[]).filter(d=>d?.isAvailable),l=s.find(d=>d.name===i)||s.find(d=>String(d.name||"").toLowerCase().includes(i.toLowerCase()))||s.find(d=>String(d.name||"").startsWith("iPhone"));if(!l?.udid)throw new Error(`No available iOS Simulator found for ${i}.`);Y.appendFileSync(t,`Booting iOS Simulator ${l.name} (${l.udid})...
|
|
1124
|
+
`),Mt("xcrun",["simctl","boot",l.udid],t)!==0&&Y.appendFileSync(t,`simctl boot returned non-zero; continuing to bootstatus in case it was already booting.
|
|
1125
|
+
`),oi("xcrun",["simctl","bootstatus",l.udid,"-b"],t)}function pl(e,t){if(e.endsWith(".ipa"))throw new Error("iOS Maestro runs need a simulator .app.zip artifact, not an App Store .ipa.");if(e.endsWith(".zip")){let n=ee.join(t,"ios-app");Y.mkdirSync(n,{recursive:!0}),new un(e).extractAllTo(n,!0);let i=di(n);if(!i)throw new Error("Could not find a .app bundle inside the iOS artifact zip.");return i}if(e.endsWith(".app"))return e;throw new Error("iOS Maestro runs need a .app bundle or .app.zip artifact.")}function fl(e,t){let n=ee.join(e,"Info.plist");if(!Y.existsSync(n))return Y.appendFileSync(t,`Could not find Info.plist in ${e}; skipping uninstall.
|
|
1126
|
+
`),null;let i=tt("/usr/bin/plutil",["-extract","CFBundleIdentifier","raw","-o","-",n],{encoding:"utf-8",env:process.env}),r=String(i.stdout||"").trim();return i.status!==0||!r?(Y.appendFileSync(t,`Could not read CFBundleIdentifier from Info.plist; skipping uninstall.
|
|
1127
|
+
`),null):r}function ml(e,t){let n=fl(e,t);if(!n)return;Y.appendFileSync(t,`Uninstalling existing iOS app data for ${n} if present...
|
|
1128
|
+
`),Mt("xcrun",["simctl","uninstall","booted",n],t)!==0&&Y.appendFileSync(t,`No existing app install removed for ${n}; continuing.
|
|
1129
|
+
`)}async function ni(e,t,n){if(!Y.existsSync(e))return;let i=Y.readFileSync(e),r;for(let o=1;o<=3;o+=1)try{await Lt.put(t,i,{headers:{"Content-Type":n,"Content-Length":String(i.length)},maxBodyLength:1/0,maxContentLength:1/0,timeout:12e4});return}catch(s){if(r=s,!Mr(s)||o>=3)break;await li(2e3*o)}throw r}async function kr(e,t,n,i){let r=ee.join(n,"report.xml"),o=ee.join(t,"artifacts.tar.gz");try{await ni(r,e.junitUploadUrl,"application/xml")}catch(s){Y.appendFileSync(i,`[WARN] Failed to upload JUnit report: ${s.message||s}
|
|
1130
|
+
`)}try{await ni(i,e.logUploadUrl,"text/plain")}catch(s){Y.appendFileSync(i,`[WARN] Failed to upload runner log: ${s.message||s}
|
|
1131
|
+
`)}try{Mt("tar",["-czf",o,"-C",t,ee.basename(n)],i),await ni(o,e.artifactsUploadUrl,"application/gzip")}catch(s){Y.appendFileSync(i,`[WARN] Failed to upload Maestro artifacts: ${s.message||s}
|
|
1132
|
+
`)}}function gl(e){if(!e.endsWith(".apk"))return H.error(V.red("Local Android Maestro runs need an APK artifact.")),!1;H.info(V.dim("Installing APK on local Android device/emulator..."));let t=tt("adb",["install","-r",e],{stdio:"inherit",env:process.env});return t.error?(H.error(V.red(`adb failed to start: ${t.error.message}`)),!1):t.status!==0?(H.error(V.red(`adb install failed with exit code ${t.status??1}`)),!1):!0}function hl(e,t){if(e.endsWith(".ipa"))return H.error(V.red("Local iOS Maestro runs need an iOS Simulator .app.zip artifact, not an App Store .ipa.")),!1;let n=e;if(e.endsWith(".zip")){let r=ee.join(t,"ios-app");Y.mkdirSync(r,{recursive:!0}),new un(e).extractAllTo(r,!0);let o=di(r);if(!o)return H.error(V.red("Could not find a .app bundle inside the downloaded zip.")),!1;n=o}if(!n.endsWith(".app"))return H.error(V.red("Local iOS Maestro runs need an iOS Simulator .app bundle or .app.zip artifact.")),!1;H.info(V.dim("Installing app on booted iOS Simulator..."));let i=tt("xcrun",["simctl","install","booted",n],{stdio:"inherit",env:process.env});return i.error?(H.error(V.red(`xcrun failed to start: ${i.error.message}`)),!1):i.status!==0?(H.error(V.red(`iOS Simulator install failed with exit code ${i.status??1}`)),!1):!0}function di(e){let t=Y.readdirSync(e,{withFileTypes:!0});for(let n of t){let i=ee.join(e,n.name);if(n.isDirectory()&&n.name.endsWith(".app"))return i;if(n.isDirectory()){let r=di(i);if(r)return r}}return null}function yl(e,t){let n=String(t||"").toLowerCase();return n==="android"?e.find(i=>At(i,".apk")):n==="ios"?e.find(i=>At(i,".app.zip"))||e.find(i=>At(i,".zip")):e.find(i=>At(i,".apk"))||e.find(i=>At(i,".app.zip"))||e.find(i=>At(i,".zip"))}function At(e,t){return String(e?.name||e?.downloadUrl||e?.url||"").toLowerCase().endsWith(t)}function ci(e){let t=String(e||"").toLowerCase();if(t.includes(".apk"))return"android";if(t.includes(".app.zip")||t.endsWith(".app")||t.includes(".ipa"))return"ios"}function Fr(e){if(e)try{return ee.basename(new URL(e).pathname)||void 0}catch{return ee.basename(e)||void 0}}function Sl(e){return e?e.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i)?.[0]:void 0}function Hr(e,t){if(!e.jsonOutput)return;let n=ee.resolve(e.jsonOutput),i={...t,updatedAt:new Date().toISOString()};try{let r=ee.dirname(n);r&&r!=="."&&Y.mkdirSync(r,{recursive:!0}),Y.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){H.warn(V.yellow(`Could not write Maestro metadata JSON: ${r.message}`))}}function bl(e,t){if(!e.jsonOutput)return;let n=ee.resolve(e.jsonOutput),i={mode:"local",...t,updatedAt:new Date().toISOString()};try{let r=ee.dirname(n);r&&r!=="."&&Y.mkdirSync(r,{recursive:!0}),Y.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){H.warn(V.yellow(`Could not write Maestro metadata JSON: ${r.message}`))}}import{spinner as it,text as Ut,select as gi,isCancel as nt,cancel as hi,log as Yr}from"@clack/prompts";import ne from"chalk";import se from"fs";import Ie from"path";import{spawn as El,spawnSync as pt}from"child_process";import Jr from"axios";import mt from"os";import bi from"crypto";var Al=5e3,Il=12,qr=100,ui=24,jr=8e3,wl={completed:"completed",draft:"draft",halted:"halted",inprogress:"inProgress","in-progress":"inProgress"},_l=e=>e?.type==="google_service_account",fn=e=>e?.bundleId||e?.packageName||e?.meta?.packageName||e?.meta?.bundleId,Xr=e=>e.submitArgs||process.argv.slice(3).join(" ");async function mn(e){let t=it(),n=Re(),i=$l(e);if(!i){process.exitCode=1;return}let r=e.projectId||i.projectId,o=e.profile||e.buildProfile||"production";if(!r){le(`${f.configFileName} is missing projectId. Pass --project-id in runner mode.`),process.exitCode=1;return}i.projectId=r,pe(ne.dim(`Submit for project: ${i.name||r} | Profile: ${o}`));let s=e.platform;if(!s){let E=await gi({message:"Select platform to submit:",options:[{value:"ios",label:"iOS (App Store Connect / TestFlight)"},{value:"android",label:"Android (Google Play Console)"}]});if(nt(E)){hi("Operation cancelled");return}s=E}if(s=String(s).toLowerCase(),s!=="ios"&&s!=="android"){le(`Platform ${s} is not supported. Use 'ios' or 'android'.`),process.exitCode=1;return}let l=s==="ios"&&!e.local&&e.sshHost?Hl(i,o,e):null;if(s==="ios"&&!e.local&&!l){await vl(i,o,e);return}let a=e.submitId,d=!!(e.local&&a),c=a||null,u=async(E,k={})=>{c&&await Ol(r,c,{status:E,...k})},p=s==="android"?e.packageName||e.androidPackage||Ul(i,o):void 0,m=s==="ios"?e.bundleId||e.iosBundleIdentifier||Fl(i,o):void 0,y,C,N,M=!1;try{s==="android"&&(y=e.track||i.submit?.[o]?.android?.track||i.submit?.production?.android?.track||"internal",C=jl(i,o,e.releaseStatus),N=Kl(i,o,e.rollout),M=Vl(i,o,e.changesNotSentForReview),zl(C,N))}catch(E){le(E.message),process.exitCode=1;return}if(s==="android"&&!d&&(c=await Rl(i,r,s,o,e,{packageName:p,track:y,releaseStatus:C,rollout:N,changesNotSentForReview:M}),!c)){le("Could not create submission tracking record. Submission was not started."),process.exitCode=1;return}await u("running",{platform:s,profile:o,packageName:p,track:y,releaseStatus:C,rollout:N,startTime:Date.now(),...d?Nl():{}});let P=null,j=null;try{j=await Wl(r,s,e,n?.token),P=j?.filePath||null}catch(E){await u("failed",{error:`Failed to resolve submission artifact: ${E.message}`,endTime:Date.now()}),le(`Failed to resolve submission artifact: ${E.message}`),process.exitCode=1;return}if(!P){let E=Jl(s,e);await u("failed",{error:E,endTime:Date.now()}),le(E),process.exitCode=1;return}await u("running",{buildId:j?.buildId,artifactName:j?.artifactName,artifactSource:j?.source}),pe(`Using artifact: ${ne.green(Ie.basename(P))} `),t.start("Fetching submission credentials from Dashboard...");let S;try{let k=(await R.get(`/credentials/${r}`)).data.credentials||[];if(s==="android"&&!p){t.stop("Package name missing"),le("Could not resolve Android package name. Set android.package in mach.config.json/app.json."),await u("failed",{error:"Could not resolve Android package name.",endTime:Date.now()}),process.exitCode=1;return}let K=k.filter(_l),W=s==="ios"?k.filter(x=>x.type==="asc_api_key"):Bl(K,p);if(W.length===0){if(t.stop("Credentials missing"),le(s==="android"?`No Google Play service credential found for package ${p}.`:`No Service Credentials found for ${s}.`),s==="android"){let x=K.map(fn).filter(Boolean).join(", ");x&&pe(`Found Google Play service credential(s) for: ${x}`),pe(`Use '${f.nameLower} credentials:service --platform android --package-name ${p}' or upload it under that package in the Dashboard.`)}else pe(`Use '${f.nameLower} credentials:service --platform ${s}' or use the Dashboard to upload them.`);await u("failed",{error:`No submission credentials found for ${s}.`,endTime:Date.now()}),process.exitCode=1;return}if(S=kl(W,e.credentialId),!S&&s==="ios"&&m&&(S=Ll(W,m)),S||W.length===1)S=S||W[0],t.stop(`Using: ${S.name}`),s==="android"&&fn(S)==="*"&&pe(ne.yellow(`Using legacy wildcard Google Play credential for ${p}. Upload a package-scoped credential when possible.`));else{if(t.stop("Multiple credentials found"),xl()){let z=W.map(D=>`${D.name||"credential"} (${D.credentialId||D.id||"no-id"})`).join(", ");le(`Multiple ${s==="ios"?"App Store Connect":"Google Play"} credentials found. Use --credential-id in CI. Available: ${z}`),await u("failed",{error:"Multiple submission credentials found; --credential-id is required in CI.",endTime:Date.now()}),process.exitCode=1;return}let x=await gi({message:`Choose a ${s==="ios"?"App Store Connect":"Google Play"} credential:`,options:W.map(z=>({value:z.credentialId,label:z.name,hint:`${z.keyId?`ID: ${z.keyId}`:""} ${z.issuerId?`(Issuer: ${z.issuerId.substring(0,8)}...)`:""}`}))});if(nt(x)){hi("Submission cancelled"),await u("failed",{error:"Submission cancelled while selecting credential.",endTime:Date.now()}),process.exitCode=1;return}S=W.find(z=>z.credentialId===x),pe(`Using selected: ${ne.green(S.name)}`)}}catch(E){t.stop("Failed to fetch credentials"),le(`API Error: ${E.message} `),await u("failed",{error:`Failed to fetch credentials: ${E.message}`,endTime:Date.now()}),process.exitCode=1;return}let G=se.mkdtempSync(Ie.join(mt.tmpdir(),`${f.nameLower}-submit-`)),Q=S.keyId||S.meta?.keyId,g=S.issuerId||S.meta?.issuerId,T=S.type==="asc_api_key"?`AuthKey_${Q}.p8`:"service-account.json",I=Ie.join(G,T);t.start("Downloading secure key...");try{let E=await R.get(`/credentials/${S.credentialId}/download`,{params:{projectId:r,format:"raw"}});if(E.data.status!=="success"||!E.data.downloadUrl)throw new Error("Failed to get secure download URL");let k=await Jr.get(E.data.downloadUrl,{responseType:"arraybuffer"});se.writeFileSync(I,Buffer.from(k.data)),t.stop("Key downloaded to secure temp storage")}catch(E){t.stop("Download failed"),le(`Failed to download key: ${E.message}`);try{se.rmSync(G,{recursive:!0,force:!0})}catch{}await u("failed",{error:`Failed to download credential key: ${E.message}`,endTime:Date.now()}),process.exitCode=1;return}pe(ne.blue(`Initiating ${s==="ios"?"TestFlight":"Google Play"} submission...`));let L=!1,v;try{if(s==="ios"){if(!Q){let k=await Ut({message:"Enter App Store Connect Key ID (e.g. 2X948D...):",validate:K=>K.length>0?void 0:"Key ID is required"});if(nt(k)){await u("failed",{error:"Submission cancelled while entering ASC Key ID.",endTime:Date.now()}),process.exitCode=1;return}Q=k}if(!g||g==="undefined"){let k=await Ut({message:"Enter App Store Connect Issuer ID (Found on ASC Keys page):",validate:K=>K.length>0?void 0:"Issuer ID is required"});if(nt(k)){await u("failed",{error:"Submission cancelled while entering ASC Issuer ID.",endTime:Date.now()}),process.exitCode=1;return}g=k}pe(`Using ASC Key ID: ${Q}`),pe(`Using ASC Issuer ID: ${g}`);let E=l?await Xl(P,I,g,Q,m,l):await ql(P,I,g,Q,m);Si(`${s==="ios"?"App Store":"Google Play"} submission successful!`),L=!0}else v=await nd(P,I,y||"internal",p,C||"completed",N,M,o),Si("Google Play submission successful!"),L=!0}catch(E){le(`Submission failed: ${E.message}`),await u("failed",{error:E.message,endTime:Date.now()}),It(e,{status:"failed",projectId:r,submitId:c,platform:s,profile:o,buildId:j?.buildId||e.buildId,artifactName:j?.artifactName,error:E.message,dashboardUrl:c?ft(c,r):void 0}),process.exitCode=1}finally{L&&(await u("success",{endTime:Date.now(),versionCode:v?.versionCode,track:y,releaseStatus:C}),It(e,{status:"success",projectId:r,submitId:c,platform:s,profile:o,buildId:j?.buildId||e.buildId,artifactName:j?.artifactName,versionCode:v?.versionCode,track:y,releaseStatus:C,dashboardUrl:c?ft(c,r):void 0})),yd(G),P&&P.includes(`${f.nameLower}-artifact-`)}}function $l(e){let t=`./${f.configFileName}`;if(se.existsSync(t))try{return JSON.parse(se.readFileSync(t,"utf-8"))}catch(n){return le(`Failed to read ${f.configFileName}: ${n.message}`),null}return e.projectId?{projectId:e.projectId}:(le(`No ${f.configFileName} found. Run \`${f.nameLower} init\` or \`${f.nameLower} link\` first.`),null)}async function vl(e,t,n){let i=n.projectId||e.projectId;if(!i){le(`${f.configFileName} is missing projectId.`),process.exitCode=1;return}let r=n.submitId||bi.randomUUID(),o=!!n.latest||!n.buildId,s=Pl({...n,latest:o,profile:t,projectId:i,submitId:r}),l={projectId:i,submitId:r,platform:"ios",profile:t,latest:o,buildId:n.buildId,credentialId:n.credentialId,status:"pending",source:"cli",submitArgs:Xr(n),runnerArgs:s,runnerCommand:[f.nameLower,"submit",...s].map(Ml).join(" "),appName:e.name,startTime:Date.now()},a=it();a.start("Queuing iOS submit on macOS runner...");try{let d=await R.post("/submissions",l),c=d.data?.submission||d.data?.submit||{},u=d.data?.dashboardUrl||ft(r,i);a.stop("iOS submit queued"),pe(`Submission ID: ${ne.cyan(r)}`),pe(`Dashboard: ${ne.blue.underline(u)}`),It(n,{status:"pending",projectId:i,submitId:r,platform:"ios",profile:t,latest:o,buildId:n.buildId,dashboardUrl:u}),await Dl(i,r,n)}catch(d){a.stop("Could not queue iOS submit"),le(Tl(d)),process.exitCode=1}}async function Rl(e,t,n,i,r,o={}){let s=r.submitId||bi.randomUUID(),l=!!r.latest||!r.buildId,a={projectId:t,submitId:s,platform:n,profile:i,latest:l,buildId:r.buildId,credentialId:r.credentialId,status:"running",source:"cli-direct",submitArgs:Xr(r),appName:e.name,startTime:Date.now(),...o};try{let d=await R.post("/submissions",a),c=d.data?.submission||d.data?.submit||{},u=d.data?.dashboardUrl||c.dashboardUrl||ft(s,t);return pe(`Submission ID: ${ne.cyan(s)}`),pe(`Dashboard: ${ne.blue.underline(u)}`),It(r,{status:"running",projectId:t,submitId:s,platform:n,profile:i,latest:l,buildId:r.buildId,dashboardUrl:u}),s}catch(d){let c=d.response?.data?.message||d.response?.data?.error||d.message;return pe(ne.yellow(`Could not create submission tracking record: ${c}`)),null}}function Pl(e){let t=["--local","--submit-id",e.submitId,"--project-id",e.projectId,"--platform","ios","--profile",e.profile||"production"];return e.buildId?t.push("--build-id",e.buildId):t.push("--latest"),e.credentialId&&t.push("--credential-id",e.credentialId),e.bundleId&&t.push("--bundle-id",e.bundleId),e.packageName&&t.push("--package-name",e.packageName),e.quiet&&t.push("--quiet"),e.jsonOutput&&t.push("--json-output",e.jsonOutput),t.filter(n=>n!=null&&n!=="")}async function Dl(e,t,n){let i=it(),r=0,o=0;for(n.quiet||i.start("Waiting for iOS submit runner...");;)try{let s=await R.get(`/submissions/${e}/${t}`),l=s.data?.submission||s.data?.submit||s.data,a=String(l?.status||"pending").toLowerCase();r=0;let d=Array.isArray(l?.logs)?l.logs:[];for(let c=o;c<d.length;c++){let u=d[c];u&&console.log(ne.dim(String(u)))}if(o=d.length,["success","completed","succeeded"].includes(a)){n.quiet||i.stop("iOS submit completed"),Si("App Store submission successful!"),It(n,{status:"success",projectId:e,submitId:t,platform:"ios",profile:l?.profile||n.profile||"production",buildId:l?.buildId||n.buildId,artifactName:l?.artifactName,dashboardUrl:l?.dashboardUrl||ft(t,e)});return}if(["failed","error","cancelled","canceled"].includes(a)){n.quiet||i.stop("iOS submit failed");let c=l?.error||l?.message||"Unknown iOS submit failure.";le(c),It(n,{status:"failed",projectId:e,submitId:t,platform:"ios",profile:l?.profile||n.profile||"production",buildId:l?.buildId||n.buildId,artifactName:l?.artifactName,error:c,dashboardUrl:l?.dashboardUrl||ft(t,e)}),process.exitCode=1;return}n.quiet||i.message(`iOS submit ${a}...`),await yi(Al)}catch(s){if(r++,r>=Il){n.quiet||i.stop("Lost connection to iOS submit status"),le(`Could not fetch iOS submit status after ${r} attempts: ${s.message}`),process.exitCode=1;return}await yi(Math.min(2e3*r,15e3))}}async function Ol(e,t,n){let i;for(let r=1;r<=3;r++)try{await R.patch(`/submissions/${e}/${t}`,n);return}catch(o){if(i=o,r>=3||!Cl(o))break;await yi(1e3*r)}Yr.warn(ne.dim(`Could not report submission status: ${i?.message||i}`))}function Cl(e){let t=e.response?.status;return!t||t===408||t===409||t===425||t===429||t>=500}function Nl(){let e={gitlabJobId:process.env.CI_JOB_ID,gitlabJobUrl:process.env.CI_JOB_URL,gitlabPipelineId:process.env.CI_PIPELINE_ID,gitlabProjectId:process.env.CI_PROJECT_ID,gitlabProjectPath:process.env.CI_PROJECT_PATH};return Object.fromEntries(Object.entries(e).filter(([,t])=>!!t))}function Tl(e){let t=e.response?.status,n=e.response?.data?.message||e.response?.data?.error;return t===404||t===405?["Managed iOS submit is not enabled on this Mach API yet.","Deploy the API/dashboard submission orchestration endpoint, then retry the same command.","Expected API: POST /submissions and GET/PATCH /submissions/:projectId/:submitId."].join(`
|
|
1133
|
+
`):n||e.message||String(e)}function ft(e,t){if(!e)return Ke;let n=t?`?projectId=${encodeURIComponent(t)}`:"";return`${Ke}/submissions/${e}${n}`}function It(e,t){if(!e.jsonOutput)return;let n=Ie.resolve(e.jsonOutput),i={...t,url:t.url||t.dashboardUrl||ft(t.submitId,t.projectId),updatedAt:new Date().toISOString()};try{let r=Ie.dirname(n);r&&r!=="."&&se.mkdirSync(r,{recursive:!0}),se.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){Yr.warn(ne.yellow(`Could not write submission metadata JSON: ${r.message}`))}}function kl(e,t){return t&&e.find(n=>n.credentialId===t||n.id===t||n.keyId===t||n.meta?.keyId===t)||null}function Ll(e,t){let n=e.filter(i=>[i.bundleId,i.bundleIdentifier,i.appIdentifier,i.meta?.bundleId,i.meta?.bundleIdentifier,i.meta?.appIdentifier].filter(Boolean).map(String).includes(t));return n.length===1?n[0]:null}function xl(){return process.env.CI==="true"||process.env.CI==="1"||!process.stdin.isTTY}function yi(e){return new Promise(t=>setTimeout(t,e))}function Ml(e){return/^[a-zA-Z0-9_./:=@-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function Ul(e,t){if(e.submit?.[t]?.android?.package)return e.submit[t].android.package;let n=Xi(e,t);if(n)return n;let i=Ie.join(process.cwd(),"app.json");if(se.existsSync(i))try{return JSON.parse(se.readFileSync(i,"utf-8")).expo?.android?.package}catch{}let r=Ie.join(process.cwd(),"app.config.json");if(se.existsSync(r))try{let o=JSON.parse(se.readFileSync(r,"utf-8"));return o.expo?.android?.package||o.android?.package}catch{}}function Bl(e,t){let n=e.filter(o=>fn(o)===t);if(n.length>0)return n;let i=e.filter(o=>{let s=fn(o);return!s||s==="*"});return e.length>0&&e.length===i.length?i:[]}function Fl(e,t){return e.submit?.[t]?.ios?.bundleIdentifier?e.submit[t].ios.bundleIdentifier:e.submit?.[t]?.ios?.bundleId?e.submit[t].ios.bundleId:Zi(e,t)}function Hl(e,t,n){let i=e.submit?.[t]?.ios||{},r=e.submit?.production?.ios||{},o=n.sshHost||i.sshHost||r.sshHost||process.env.MACH_IOS_SUBMIT_SSH_HOST;return o?{sshHost:o,sshUser:n.sshUser||i.sshUser||r.sshUser||process.env.MACH_IOS_SUBMIT_SSH_USER||process.env.USER||"ubuntu",sshKey:n.sshKey||i.sshKey||r.sshKey||process.env.MACH_IOS_SUBMIT_SSH_KEY}:null}function jl(e,t,n){let i=n||e.submit?.[t]?.android?.releaseStatus||e.submit?.production?.android?.releaseStatus||"completed";return Gl(i)}function Gl(e){let t=wl[String(e).trim().toLowerCase()];if(!t)throw new Error(`Invalid Android release status "${e}". Use completed, draft, halted, or inProgress.`);return t}function Kl(e,t,n){let i=n??e.submit?.[t]?.android?.rollout??e.submit?.[t]?.android?.userFraction??e.submit?.[t]?.android?.rolloutFraction??e.submit?.production?.android?.rollout??e.submit?.production?.android?.userFraction??e.submit?.production?.android?.rolloutFraction;if(i==null||i==="")return;let r=Number(i);if(!Number.isFinite(r)||r<=0||r>=1)throw new Error(`Invalid Android rollout fraction "${i}". Use a number greater than 0 and less than 1, for example 0.1.`);return r}function Vl(e,t,n){let i=n??e.submit?.[t]?.android?.changesNotSentForReview??e.submit?.[t]?.android?.changes_not_sent_for_review??e.submit?.production?.android?.changesNotSentForReview??e.submit?.production?.android?.changes_not_sent_for_review??!1;return i===!0||i==="true"||i==="1"}function zl(e,t){if(e==="inProgress"&&t===void 0)throw new Error("Google Play staged rollout requires --rollout <fraction> when --release-status inProgress is used.");if(e!=="inProgress"&&e!=="halted"&&t!==void 0)throw new Error("Android rollout fraction can only be used with --release-status inProgress or halted.")}async function Wl(e,t,n,i){let r=n.buildId?"id":n.latest?"latest":null;if(!r){let s=await gi({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"}]});if(nt(s))return hi("Operation cancelled"),null;r=s}if(r==="local"){let s=await Ut({message:"Enter path to artifact (.ipa/.aab):",validate:l=>{if(!se.existsSync(l))return"File not found";if(t==="ios"&&!l.endsWith(".ipa"))return"Must be an .ipa file";if(t==="android"&&!l.endsWith(".aab"))return"Must be an .aab file"}});return nt(s)?null:{filePath:s,source:"local"}}let o=it();if(r==="latest"){let s=n.profile||n.buildProfile;o.start(`Fetching latest${s?` ${s}`:""} build...`);try{let l=await R.get(`/builds/${e}`,{params:{limit:50}});if(l.data.status!=="success")throw new Error(l.data.message);let a=l.data.builds||[],d=s?.toLowerCase(),c=S=>S.platform?.toLowerCase()===t.toLowerCase()&&S.status?.toLowerCase()==="success",u=S=>d?[S.buildProfile,S.profile,S.profileName,S.buildType].filter(Boolean).some(G=>String(G).toLowerCase()===d):!0,p=a.filter(S=>c(S)&&u(S)),m=p.find(S=>S.buildType?.toLowerCase()==="store"||S.distribution?.toLowerCase()==="store")||p[0],y=a.some(S=>S.platform?.toLowerCase()===t.toLowerCase()&&S.status?.toLowerCase()==="success");if(!m)return o.stop("No suitable build found"),le(s&&y?`No successful ${t} builds found for profile "${s}".`:"No successful builds found for this platform."),null;o.stop(`Found build: ${m.buildId}`);let C=m.artifacts||[];if(C.length===0||C.every(S=>!(S.url||S.downloadUrl)))try{let S=await R.get(`/builds/${e}/${m.buildId}/artifacts`);S.data.status==="success"&&S.data.artifacts?.length>0?(C=S.data.artifacts.map(G=>({...G,url:G.url||G.downloadUrl})),console.log(ne.cyan(` [RECOVERY] Fetched ${C.length} artifact(s) with download URLs.`))):console.log(ne.yellow(" [RECOVERY] /artifacts endpoint returned 0 artifacts."))}catch(S){console.log(ne.red(` [RECOVERY] /artifacts fetch failed: ${S.message}`))}let M=t==="ios",P=C.find(S=>{let G=(S.type||"").toLowerCase(),Q=(S.name||"").toLowerCase();if(console.log(ne.dim(` - Checking: ${S.name} (Type: ${S.type}, HasLink: ${!!(S.url||S.downloadUrl)})`)),G)return G===(M?"ipa":"aab");let g=M?".ipa":".aab",T=(S.url||S.downloadUrl||"").toLowerCase();return Q.endsWith(g)||T.includes(g)});if(!P||!(P.url||P.downloadUrl))return le("Build found but artifact URL is missing."),null;let j=P.url||P.downloadUrl;return{filePath:await pi(j,M?"ios":"android"),buildId:m.buildId,artifactName:P.name,source:"latest"}}catch(l){return o.stop("Fetch failed"),le(`API Error: ${l.message}`),null}}if(r==="id"){let s=n.buildId||await Ut({message:"Enter Build ID:",validate:a=>a.length<5?"Invalid ID":void 0});if(nt(s))return null;let l=String(s);o.start("Fetching build...");try{let a=null;try{let m=await R.get(`/builds/${e}/${l}`);m.data.status==="success"&&(a=m.data.build)}catch(m){m.response?.status!==404&&console.log(ne.dim(` [RECOVERY] Project build lookup skipped: ${m.message}`))}if(!a){let m=await R.get(`/build/${l}`);if(m.data.status!=="success")throw new Error(m.data.message);a=m.data.build}if(!a)throw new Error(`Build ${l} was not found.`);let d=t==="ios",c=pn(a.artifacts);Yl(c)||(c=await Kr(e,l,c));let u=Gr(c,t);if(u||(c=await Kr(e,l,c),u=Gr(c,t)),!u)throw new Error(`No ${d?".ipa":".aab"} artifact found for build ${l}. The build exists, but its artifact list does not contain a downloadable submission artifact.`);let p=u.url||u.downloadUrl;if(!p)throw new Error(`Artifact ${u.name||"(unnamed)"} for build ${l} has no download URL. Retry after the build artifact upload is visible in the Installation Hub.`);return o.stop(`Found build: ${a.buildId||l}`),{filePath:await pi(p,d?"ios":"android"),buildId:a.buildId||l,artifactName:u.name,source:"id"}}catch(a){throw o.stop("Fetch failed"),a}}if(r==="url"){let s=await Ut({message:"Enter Artifact URL:",validate:l=>l.startsWith("http")?void 0:"Must be a valid URL"});return nt(s)?null:{filePath:await pi(s,t),source:"url"}}return null}function pn(e){return(e||[]).map(t=>({...t,url:t.url||t.downloadUrl}))}function Yl(e){return e.some(t=>!!(t.url||t.downloadUrl))}function Gr(e,t){let n=t==="ios",i=n?"ipa":"aab",r=n?".ipa":".aab";return e.find(o=>{let s=String(o.type||"").toLowerCase(),l=String(o.name||"").toLowerCase(),a=String(o.url||o.downloadUrl||"").toLowerCase();return s?s===i:l.endsWith(r)||a.includes(r)})||null}function Jl(e,t){let n=e==="ios"?".ipa":".aab";if(t.buildId)return`No downloadable ${n} artifact found for build ${t.buildId}. Check that the build finished artifact upload before submitting.`;if(t.latest){let i=t.profile||t.buildProfile;return`No latest successful ${e}${i?` ${i}`:""} build has a downloadable ${n} artifact.`}return`No downloadable ${n} artifact was selected for submission.`}async function Kr(e,t,n){try{let i=await R.get(`/builds/${e}/${t}/artifacts`);if(i.data.status==="success"&&i.data.artifacts?.length>0){let r=pn(i.data.artifacts);return console.log(ne.cyan(` [RECOVERY] Fetched ${r.length} artifact(s) with download URLs.`)),r}}catch(i){console.log(ne.dim(` [RECOVERY] Project artifact lookup skipped: ${i.message}`))}try{let i=await R.get(`/public/builds/${t}`);if(i.data.status==="success"&&i.data.artifacts?.length>0){let r=pn(i.data.artifacts);return console.log(ne.cyan(` [RECOVERY] Fetched ${r.length} public artifact(s) with download URLs.`)),r}}catch(i){console.log(ne.dim(` [RECOVERY] Public artifact lookup skipped: ${i.message}`))}return pn(n)}async function pi(e,t,n=3){let i=it();i.start("Downloading artifact...");let r=se.mkdtempSync(Ie.join(mt.tmpdir(),`${f.nameLower}-artifact-`)),o=`app.${t==="ios"?"ipa":"aab"}`,s=Ie.join(r,o);for(let l=1;l<=n;l++)try{l>1&&(i.message(`Downloading artifact (Retry ${l}/${n})...`),await new Promise(c=>setTimeout(c,2e3*l)));let a=se.createWriteStream(s),d=await Jr({url:e,method:"GET",responseType:"stream",timeout:6e4});return await new Promise((c,u)=>{d.data.pipe(a);let p=!1;d.data.on("error",m=>{p||(p=!0,a.close(),u(m))}),a.on("finish",()=>{p||c()}),a.on("error",m=>{p||(p=!0,u(m))})}),i.stop("Download complete"),s}catch(a){if(l===n)throw i.stop("Download failed"),a}throw new Error("Download failed after retries")}async function ql(e,t,n,i,r){let o=it();if(r&&pe(`Bundle ID: ${ne.green(r)}`),!n||!i)throw le(`Missing credentials: issuerId=${n}, keyId=${i}. Check your Dashboard.`),new Error("Missing ASC API Key Metadata (IssuerID or KeyID)");let s=Zr(t,n,i),l=rd();return o.start("Uploading to TestFlight (pilot)..."),new Promise((a,d)=>{let c=sd(),u=El(l.command,["pilot","upload","--ipa",e,"--api_key_path",s,"--skip_submission","true","--skip_waiting_for_build_processing","true"],{stdio:["ignore","pipe","pipe"],env:l.env});u.stdout?.on("data",p=>c.append(p,process.stdout)),u.stderr?.on("data",p=>c.append(p,process.stderr)),u.on("close",p=>{if(c.flush(),p!==0){o.stop("Pilot failed");try{se.unlinkSync(s)}catch{}d(ad(p,c.lines()))}else{o.stop("IPA uploaded to TestFlight");try{se.unlinkSync(s)}catch{}a({})}}),u.on("error",p=>{c.flush();try{se.unlinkSync(s)}catch{}o.stop("Pilot execution error");let m=gd(p);m.logs=c.lines(),d(m)})})}async function Xl(e,t,n,i,r,o){let s=it();if(r&&pe(`Bundle ID: ${ne.green(r)}`),!n||!i)throw le(`Missing credentials: issuerId=${n}, keyId=${i}. Check your Dashboard.`),new Error("Missing ASC API Key Metadata (IssuerID or KeyID)");let l=Zr(t,n,i),a=`${o.sshUser}@${o.sshHost}`,d=Zl(o),c=Ql(o),u="",p="";try{if(s.start(`Preparing remote iOS submit runner (${a})...`),u=ed("ssh",[...d,"mktemp -d /tmp/mach-submit.XXXXXX"]).trim(),!u)throw new Error("Remote runner did not return a temp directory.");s.stop(`Remote runner ready: ${a}`),s.start("Uploading IPA and App Store Connect key to remote runner..."),fi("scp",[...c,e,`${a}:${u}/app.ipa`],"IPA upload to remote runner"),fi("scp",[...c,l,`${a}:${u}/api_key.json`],"ASC key upload to remote runner"),p=Ie.join(mt.tmpdir(),`${f.nameLower}-ios-submit-${Date.now()}.sh`),se.writeFileSync(p,td(u)),fi("scp",[...c,p,`${a}:${u}/submit.sh`],"submit script upload to remote runner"),s.stop("Remote submit inputs uploaded"),s.start("Uploading to TestFlight on remote runner...");let m=`chmod +x ${Bt(`${u}/submit.sh`)} && bash ${Bt(`${u}/submit.sh`)}`,y=pt("ssh",[...d,m],{stdio:"inherit"});if(y.error)throw Ei("ssh",y.error);if(y.status!==0)throw new Error(`Remote iOS submit failed with exit code ${y.status}.`);return s.stop("IPA uploaded to TestFlight"),{apiKeyJsonPath:null}}catch(m){throw s.stop("Remote iOS submit failed"),m}finally{try{se.unlinkSync(l)}catch{}if(p)try{se.unlinkSync(p)}catch{}if(u)try{pt("ssh",[...d,`rm -rf ${Bt(u)}`],{stdio:"ignore"})}catch{}}}function Zr(e,t,n){let i=se.readFileSync(e,"utf8"),r;try{r=bi.createPrivateKey(i).export({type:"pkcs8",format:"pem"})}catch{pe("Key normalization failed, falling back to manual re-wrapping..."),r=`-----BEGIN PRIVATE KEY-----
|
|
1134
1134
|
${(i.replace(/-----BEGIN[^-]*-----/g,"").replace(/-----END[^-]*-----/g,"").replace(/\s+/g,"").match(/.{1,64}/g)||[]).join(`
|
|
1135
1135
|
`)}
|
|
1136
|
-
-----END PRIVATE KEY-----`}let o=
|
|
1136
|
+
-----END PRIVATE KEY-----`}let o=Ie.join(mt.tmpdir(),`api_key_${n}_${Date.now()}.json`),s={key_id:n,issuer_id:t,key:r,in_house:!1};return se.writeFileSync(o,JSON.stringify(s,null,2)),o}function Zl(e){let t=["-o","StrictHostKeyChecking=no","-o","ServerAliveInterval=30"];return e.sshKey&&t.push("-i",e.sshKey),t.push(`${e.sshUser}@${e.sshHost}`),t}function Ql(e){let t=["-o","StrictHostKeyChecking=no","-o","ServerAliveInterval=30"];return e.sshKey&&t.push("-i",e.sshKey),t}function ed(e,t){let n=pt(e,t,{encoding:"utf-8",stdio:["ignore","pipe","inherit"]});if(n.error)throw Ei(e,n.error);if(n.status!==0)throw new Error(`${e} failed with exit code ${n.status}.`);return n.stdout||""}function fi(e,t,n){let i=pt(e,t,{stdio:"inherit"});if(i.error)throw Ei(e,i.error);if(i.status!==0)throw new Error(`${n} failed with exit code ${i.status}.`)}function Ei(e,t){return t?.code==="ENOENT"?new Error(`${e} was not found on this machine. Install OpenSSH client tools or run iOS submit directly on the macOS runner.`):t}function Bt(e){return`'${e.replace(/'/g,"'\\''")}'`}function td(e){let t=Bt(`${e}/app.ipa`),n=Bt(`${e}/api_key.json`);return`#!/bin/bash
|
|
1137
1137
|
set -euo pipefail
|
|
1138
1138
|
|
|
1139
1139
|
export PATH="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:$HOME/.local/share/fastlane/3.4.0/bin:$PATH"
|
|
@@ -1161,61 +1161,61 @@ fastlane pilot upload \\
|
|
|
1161
1161
|
--api_key_path ${n} \\
|
|
1162
1162
|
--skip_submission true \\
|
|
1163
1163
|
--skip_waiting_for_build_processing true
|
|
1164
|
-
`}async function
|
|
1164
|
+
`}async function nd(e,t,n="internal",i,r="completed",o,s=!1,l="production"){let a=it();if(!i||i==="*")throw new Error("Android package name is required for Google Play submission.");let d=o!==void 0?` (${o} rollout)`:"";a.start(`Uploading to Google Play ${n} track with ${r} release status${d}...`);try{let c=JSON.parse(se.readFileSync(t,"utf-8"));id(c);let u=await yr({packageName:i,serviceAccount:c,aabPath:e,track:n,releaseStatus:r,userFraction:o,changesNotSentForReview:s});return a.stop(`AAB uploaded to ${n} track (versionCode ${u.versionCode})`),u}catch(c){throw a.stop("Google Play upload failed"),new Error(hd(c,n,i,l))}}function id(e){if(!e?.client_email||!e?.private_key)throw new Error("Invalid Google service account JSON: missing client_email or private_key.")}function mi(){let e=process.env.HOME||mt.homedir(),t=process.env.FASTLANE_GEM_HOME||Ie.join(e,".local/share/fastlane/3.4.0"),n=[process.env.FASTLANE_BIN_DIR,"/usr/local/opt/ruby/bin","/opt/homebrew/opt/ruby/bin","/usr/local/bin","/opt/homebrew/bin","/usr/local/Cellar/fastlane/2.227.0/libexec/bin",Ie.join(t,"bin"),process.env.PATH].filter(Boolean).join(":");return{...process.env,PATH:n,GEM_HOME:t,GEM_PATH:[t,"/usr/local/Cellar/fastlane/2.227.0/libexec",process.env.GEM_PATH].filter(Boolean).join(":"),FASTLANE_INSTALLED_VIA_HOMEBREW:"true",FASTLANE_SKIP_UPDATE_CHECK:"1",FASTLANE_HIDE_CHANGELOG:"1",LANG:process.env.LANG||"en_US.UTF-8",LC_ALL:process.env.LC_ALL||"en_US.UTF-8",CI:process.env.CI||"1"}}function rd(){let e=mi(),t=Vr(e);if(t)return t;if(process.env.MACH_SKIP_FASTLANE_INSTALL!=="1"){od(e);let n=Vr(mi());if(n)return n}return{command:"fastlane",env:mi()}}function Vr(e){let t=process.env.HOME||mt.homedir(),n=[process.env.FASTLANE_BINARY,"/usr/local/bin/fastlane","/opt/homebrew/bin/fastlane","/usr/local/Cellar/fastlane/2.227.0/libexec/bin/fastlane",Ie.join(process.env.FASTLANE_GEM_HOME||Ie.join(t,".local/share/fastlane/3.4.0"),"bin/fastlane"),"fastlane"].filter(Boolean);for(let i of n){if(i.includes("/")&&!se.existsSync(i))continue;if(!pt(i,["--version"],{env:e,stdio:"ignore"}).error)return{command:i,env:e}}return null}function od(e){let t=pt("gem",["--version"],{env:e,stdio:"ignore"});if(t.error||t.status!==0)return;let n=process.env.HOME||mt.homedir(),i=process.env.FASTLANE_GEM_HOME||Ie.join(n,".local/share/fastlane/3.4.0"),r=Ie.join(i,"bin");se.mkdirSync(r,{recursive:!0}),pe(ne.dim("fastlane not found. Installing fastlane into the local Mach runner cache..."));let o=pt("gem",["install","fastlane","-NV","--install-dir",i,"--bindir",r],{env:{...e,GEM_HOME:i,GEM_PATH:[i,e.GEM_PATH].filter(Boolean).join(":")},stdio:"inherit"});(o.error||o.status!==0)&&pe(ne.yellow("Automatic fastlane install failed; Mach will try PATH resolution once more."))}function sd(e=qr){let t=[],n="",i=r=>{let o=eo(r);if(o)for(t.push(o);t.length>e;)t.shift()};return{append(r,o){let s=Buffer.isBuffer(r)?r.toString("utf8"):String(r);o.write(s),n+=s;let l=n.split(/\r?\n/);n=l.pop()||"";for(let a of l)i(a)},flush(){n.trim()&&i(n),n=""},lines(){return t.slice()}}}function ad(e,t){let n=new Error(ld(e,t));return n.logs=Qr(t),n.exitCode=e,n}function ld(e,t){let n=`fastlane pilot failed with exit code ${e??"unknown"}.`,i=dd(t);return i.length===0?n:`${n}
|
|
1165
1165
|
|
|
1166
1166
|
Fastlane output:
|
|
1167
1167
|
${i.join(`
|
|
1168
|
-
`)}`}function
|
|
1169
|
-
`);if(!/bundle version must be higher than the previously uploaded version/i.test(t))return null;let
|
|
1170
|
-
`))}function
|
|
1168
|
+
`)}`}function dd(e){let t=Qr(e);if(t.length===0)return[];let n=zr(t.filter(ud)),i=cd(t);if(i)return[i,...Wr(n,ui-1,jr)];let r=n.length>0?n:t.slice(-ui);return Wr(zr(r),ui,jr)}function cd(e){let t=e.join(`
|
|
1169
|
+
`),n=t.match(/CFBundleShortVersionString\s*\[([^\]]+)\]/i)?.[1]||t.match(/train version ['"]([^'"]+)['"]/i)?.[1];if(/Invalid Pre-Release Train/i.test(t)||/CFBundleShortVersionString[\s\S]*must contain a higher version/i.test(t))return[`App Store Connect rejected CFBundleShortVersionString${n?` ${n}`:""}: this App Store version train is closed or not higher than the approved version.`,'ios.buildNumber="auto" only changes CFBundleVersion; bump the marketing version (Expo app.json "expo.version" / iOS MARKETING_VERSION), rebuild, then submit the new build.'].join(" ");if(!/bundle version must be higher than the previously uploaded version/i.test(t))return null;let i=t.match(/previous(?:ly)?BundleVersion\s*:\s*([0-9.]+)/i)?.[1]||t.match(/previously uploaded version:\s*[‘'"]?([0-9.]+)/i)?.[1];return`App Store Connect rejected CFBundleVersion: the bundle version must be higher than the previously uploaded version.${i?` Previous uploaded build: ${i}.`:""}`}function ud(e){return/\[!\]|ERROR ITMS-\d+|ITMS-\d+|ENTITY_ERROR|previousBundleVersion|CFBundleVersion|Application Loader Error Output|Transporter Error|Transporter transfer failed|Asset validation failed|Validation failed|Error Domain=|The request could not be completed|No suitable application records|Could not|authentication|unauthori[sz]ed|invalid|failed|exception/i.test(e)}function zr(e){let t=new Set,n=[];for(let i of e){let r=i.trim();!r||t.has(r)||(t.add(r),n.push(i))}return n}function Wr(e,t,n){let i=[],r=0;for(let o=e.length-1;o>=0&&i.length<t;o--){let s=e[o],l=r+s.length+1;if(l>n&&i.length>0)break;i.unshift(s.length>n?`${s.slice(0,n-18)}... [truncated]`:s),r=l}return i}function Qr(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let i=String(n).split(/\r?\n/);for(let r of i){let o=eo(r);o&&t.push(o)}}return t.slice(-qr)}function eo(e){return fd(pd(e).trimEnd()).trim()}function pd(e){return e.replace(/[\u001b\u009b][[\]()#;?]*(?:(?:(?:[a-zA-Z\d]*(?:;[a-zA-Z\d]*)*)?\u0007)|(?:(?:\d{1,4}(?:;\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]))/g,"")}function fd(e){let t=e.replace(/-----BEGIN [^-]+-----[\s\S]*?-----END [^-]+-----/g,"[REDACTED_PRIVATE_KEY]").replace(/(authorization:\s*bearer\s+)[A-Za-z0-9._-]+/ig,"$1[REDACTED]").replace(/((?:password|token|secret|private[_-]?key)\s*[:=]\s*)("[^"]+"|'[^']+'|[^\s,]+)/ig,"$1[REDACTED]");for(let[n,i]of Object.entries(process.env))!i||i.length<8||/(TOKEN|SECRET|PASSWORD|PASS|PRIVATE|CREDENTIAL)/i.test(n)&&(t=t.replace(new RegExp(md(i),"g"),"[REDACTED]"));return t}function md(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function gd(e){return e?.code!=="ENOENT"?e:new Error(["fastlane was not found on PATH.","Mach submit uses Fastlane for iOS TestFlight/App Store uploads.","Run iOS submit on a macOS runner with Fastlane, or expose it via FASTLANE_BINARY / FASTLANE_BIN_DIR.","Example: gem install fastlane -NV"].join(`
|
|
1170
|
+
`))}function hd(e,t,n,i="production"){let r=e?.message||String(e);if(/changesNotSentForReview/i.test(r))return["Google Play rejected the commit because this change may need explicit review handling.",`Package: ${n||"unknown"} | Track: ${t}`,`Retry with: ${f.nameLower} submit --latest --platform android --profile ${i} --track ${t} --changes-not-sent-for-review`,"Then send the change for review from Google Play Console if required."].join(`
|
|
1171
1171
|
`);if(/caller does not have permission|permission denied|insufficient permissions|not authorized/i.test(r))return["Google Play rejected the service account permissions.",`Package: ${n||"unknown"} | Track: ${t}`,"Grant this service account access to the app in Play Console with release permissions, then retry."].join(`
|
|
1172
1172
|
`);if(/package.*not found|application.*not found|no application was found/i.test(r))return["Google Play could not find this package for the selected service account.",`Package: ${n||"unknown"} | Track: ${t}`,"Check android.package / submit.<profile>.android.package and make sure the app exists in this Play Console account."].join(`
|
|
1173
|
-
`);if(/only releases with status draft|draft app/i.test(r))return["Google Play requires a draft release for this app state.",`Package: ${n||"unknown"} | Track: ${t}`,`Retry with: ${
|
|
1174
|
-
`);if(r.includes("does not allow any existing users to upgrade"))return["Google Play rejected this release because the uploaded AAB is not an upgrade for existing users.",`Package: ${n||"unknown"} | Track: ${t}`,"Build a new Android artifact with a higher versionCode, then submit that build.",`Recommended: ${
|
|
1175
|
-
`);if(/version code \d+ has already been used/i.test(r))return[r.match(/version code \d+ has already been used[^\n]*/i)?.[0]||"Version code has already been used.",`Package: ${n||"unknown"} | Track: ${t}`,"Build a new Android artifact with a higher versionCode, then submit that build.",`Recommended: ${
|
|
1176
|
-
`);let o=r.match(/Google Api Error:[^\n]+/)||r.match(/Google Play API Error:[^\n]+/);return o?o[0]:r||"Google Play submission failed"}function sc(e){try{oe.existsSync(e)&&oe.rmSync(e,{recursive:!0,force:!0})}catch{}}function le(e){console.log(ee.red(`\u274C ${e}`))}function fe(e){console.log(ee.gray(`\u2022 ${e}`))}function hi(e){console.log(ee.green(`\u2713 ${e}`))}var bi=8,cc=6,Zr=Number(process.env.MACH_ARTIFACT_UPLOAD_MAX_ATTEMPTS||2),Ei=Number(process.env.MACH_ARTIFACT_UPLOAD_TIMEOUT_MS||12e4),lo=e=>new Promise(t=>setTimeout(t,e)),dc=e=>{if(!Number.isFinite(e)||e<=0)return"0 B";let t=["B","KB","MB","GB"],n=Math.min(Math.floor(Math.log(e)/Math.log(1024)),t.length-1);return`${(e/Math.pow(1024,n)).toFixed(n===0?0:1)} ${t[n]}`},uc=e=>{let t=e.response?.status,n=e.code||"",i=e.message||"";return t?t===408||t===409||t===425||t===429||t>=500||/ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|ECONNABORTED|socket hang up|network|timeout/i.test(`${n} ${i}`):!0},fn=async(e,t,n=cc)=>{let i;for(let r=1;r<=n;r++)try{return await t()}catch(o){if(i=o,!uc(o)||r>=n)break;let s=Math.min(6e4,2e3*Math.pow(2,r-1)),l=o.response?.status||o.code||o.message||"network error";D.warn(C.yellow(`${e} failed transiently (${l}). Retrying in ${Math.round(s/1e3)}s... (${r}/${n})`)),await lo(s)}throw i},pc=async(e,t,n)=>{let i=$e.basename(e),r=de.statSync(e).size,o=Math.round(Ei/1e3);try{await fn(`Upload artifact ${i}`,async()=>{let s=new AbortController,l=de.createReadStream(e),a=setTimeout(()=>{l.destroy(new Error(`Artifact upload timed out after ${o}s`)),s.abort()},Ei);try{await gn.put(t,l,{headers:{"Content-Type":n,"Content-Length":r,Connection:"close"},maxBodyLength:1/0,maxContentLength:1/0,timeout:Ei,timeoutErrorMessage:`Artifact upload timed out after ${o}s`,signal:s.signal})}finally{clearTimeout(a)}},Zr)}catch(s){throw new Error(`${i} (${dc(r)}) failed after ${Zr} upload attempt(s): ${s.message||s}`)}return r},fc=e=>{let t=e.response?.status;return t?t===408||t===429||t>=500:!0},Bt=e=>e.credentialId||e.id,mc=async(e,t)=>{let n=Bt(e);if(!n)return e.downloadUrl;let i=await v.get(`/credentials/${n}/download`,{params:{projectId:t,format:"raw"}});return i.data?.status==="success"&&i.data?.downloadUrl?i.data.downloadUrl:e.downloadUrl},co=async(e,t)=>{let n=e.downloadUrl;for(let i=1;i<=bi;i++)try{if((!n||i>1)&&(n=await mc(e,t)),!n)throw new Error(`Credential ${e.name||Bt(e)||"unknown"} has no download URL.`);let r=await gn.get(n,{responseType:"arraybuffer",timeout:6e4,maxContentLength:1/0,maxBodyLength:1/0,headers:{Connection:"close"}});return Buffer.from(r.data).toString("base64")}catch(r){if(i>=bi||!fc(r))throw r;let o=Math.min(1500*i*i,15e3);D.warn(C.dim(` - Temporary network error downloading ${e.name}. Retrying... (${i}/${bi})`)),await lo(o)}throw new Error(`Failed to download credential ${e.name||Bt(e)||"unknown"}.`)},Qr=async(e,t)=>{let n=await co(e,t);return Buffer.from(n,"base64").toString("utf8")},gc=(e,t)=>{try{return JSON.parse(e)}catch{throw new Error(`${t} is not valid JSON.`)}},hc=e=>/ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|ECONNABORTED|socket hang up|network|timeout/i.test(e),yc=(e,t)=>t?.ios?.buildNumber??t?.iosBuildNumber??e?.ios?.buildNumber??e?.expo?.ios?.buildNumber,Sc=(e,t,n)=>t?.ios?.ascAppId??t?.ascAppId??e?.ios?.ascAppId??e?.submit?.[n]?.ios?.ascAppId??e?.submit?.production?.ios?.ascAppId,eo=e=>e.bundleId||e.bundleIdentifier||e.meta?.bundleId||e.meta?.bundleIdentifier,to=(e,t)=>{let n=e.filter(i=>i.type==="asc_api_key");if(n.length!==0){if(t){let i=n.find(o=>eo(o)===t);if(i)return i;let r=n.find(o=>eo(o)==="*");if(r)return r}return n[0]}},bc=e=>typeof e=="string"&&e.trim().toLowerCase()==="auto",uo=(e,t,n=[])=>{if(!de.existsSync(e))return n;let i;try{i=de.readdirSync(e,{withFileTypes:!0})}catch{return n}for(let r of i){if(r.name==="Pods"||r.name==="build"||r.name==="DerivedData")continue;let o=$e.join(e,r.name);r.isDirectory()?uo(o,t,n):r.name===t&&n.push(o)}return n},Ec=(e,t,n)=>{let i=`${n} ${t.environment||""}`.toLowerCase(),r=e.toLowerCase(),o=0;return(i.includes("development")||i.includes("dev"))&&/(^|[.-])dev(elopment)?($|[.-])/.test(r)&&(o+=20),(i.includes("staging")||i.includes("stage"))&&/(^|[.-])stag(e|ing)?($|[.-])/.test(r)&&(o+=20),(i.includes("production")||i.includes("prod"))&&(/(^|[.-])(dev|development|stag|stage|staging)($|[.-])/.test(r)||(o+=20)),o},Ac=(e,t)=>{let n=$e.resolve(process.cwd(),de.existsSync("ios")?"ios":"."),i=uo(n,"project.pbxproj"),r=[];for(let o of i)try{let l=de.readFileSync(o,"utf8").matchAll(/PRODUCT_BUNDLE_IDENTIFIER\s*=\s*"?([^";\s]+)"?;/g);for(let a of l){let c=a[1]?.trim();c&&!c.includes("$")&&!c.startsWith("com.apple.")&&!r.includes(c)&&r.push(c)}}catch{}if(r.length!==0)return r.length===1?r[0]:r.map(o=>({bundleId:o,score:Ec(o,e,t)})).sort((o,s)=>s.score-o.score)[0]?.bundleId},mn=e=>String(e||"").trim().toLowerCase().replace(/_/g,"-"),hn=(e,t)=>{let n=mn(e);return t==="ios"&&(n==="internal"||n==="ad-hoc")?"adhoc":t==="android"&&["internal","adhoc","ad-hoc","development","dev","staging","stage"].includes(n)?"internal":n},no=(e,t,n)=>{let i=hn(e.distributionType||e.meta?.distributionType,n);return i?i===hn(t,n):!0},io=(e,t,n)=>{let i=hn(e.distributionType||e.meta?.distributionType,n),r=hn(t,n);return i?i===r?3:n==="android"&&r!=="store"&&i!=="store"?2:0:1},Ic=e=>{let t=e.toLowerCase();return t==="development"||t==="dev"||t.startsWith("development-")||t.startsWith("dev-")||t.endsWith("-development")||t.endsWith("-dev")},wc=e=>{let t=e.toLowerCase();return t.includes("staging")||t.includes("stage")||t.includes("preview")||t.includes("adhoc")||t.includes("ad-hoc")},_c=(e,t)=>{let n=mn(e.distribution),i=mn(e.iosExportMethod),r=mn(e.environment);return e.platform!=="ios"?n==="store"?"store":"internal":e.developmentClient||e.simulator?"development":i==="app-store"||n==="store"?"store":i==="development"||n==="development"?"development":i==="ad-hoc"||i==="adhoc"||n==="ad-hoc"||n==="adhoc"||n==="internal"?"adhoc":r==="production"||r==="store"?"store":r==="development"||r==="dev"?"development":r==="staging"||r==="stage"||r==="preview"?"adhoc":t.toLowerCase()==="production"||t.toLowerCase().includes("store")?"store":Ic(t)?"development":(wc(t),"adhoc")},po=e=>e.bundleId||e.bundleIdentifier||e.packageName||e.meta?.bundleId||e.meta?.bundleIdentifier||e.meta?.packageName,ro=(e,t)=>{if(!t)return!0;let n=po(e);return!n||n==="*"||n===t},oo=(e,t)=>{let n=po(e);return!t||!n?0:n===t?2:n==="*"?1:-1},fo=e=>{try{let t=Buffer.from(e,"base64").toString("utf8"),n=t.match(/<key>application-identifier<\/key>\s*<string>([^<]+)<\/string>/)?.[1]?.trim();if(!n)return;let i=t.match(/<key>TeamIdentifier<\/key>\s*<array>\s*<string>([^<]+)<\/string>/)?.[1]?.trim();if(i&&n.startsWith(`${i}.`))return n.slice(i.length+1);let r=n.indexOf(".");return r>=0?n.slice(r+1):n}catch{return}},$c=(e,t)=>{if(e===t||e==="*")return!0;if(e.endsWith(".*")){let n=e.slice(0,-2);return t.startsWith(`${n}.`)}return!1},Pc=(e,t)=>{if(!t)return!0;let n=fo(e);if(n)return $c(n,t);try{return Buffer.from(e,"base64").toString("latin1").includes(t)}catch{return!0}},yn=async e=>{if(e.failOnly){(!e.projectId||!e.buildId)&&(D.error(C.red("--project-id and --build-id are required with --fail-only.")),process.exit(1));let l=e.error||"Build runner failed before it could report a final status.";try{await v.patch(`/builds/${e.projectId}/${e.buildId}`,{status:"failed",error:l,endTime:Date.now()}),D.info(C.yellow(`Marked build ${e.buildId} as failed.`));return}catch(a){D.error(C.red(`Could not mark build failed: ${a.message}`)),process.exit(1)}}e.platform!=="android"&&e.platform!=="ios"&&(D.error(`Platform ${e.platform} is not supported. Use 'android' or 'ios'.`),process.exit(1)),e.autoSubmit&&e.platform==="ios"&&e.simulator&&(D.error(C.red("--auto-submit cannot be used with --simulator because simulator builds are not App Store artifacts.")),process.exit(1)),e.autoSubmit&&e.dryRun&&D.warn(C.yellow("--auto-submit is ignored during --dry-run."));let t=Ii(),n=e.buildId||ac(),i=e.projectId,r=Date.now(),o=!!i,s=async l=>{if(i)try{await v.patch(`/builds/${i}/${n}`,{status:"failed",error:l})}catch{}};if(e.local&&e.buildId){e.quiet||t.start(`Preparing isolated workspace for build: ${e.buildId}`);try{let l=await v.get(`/builds/${i}/${e.buildId}/source-url`);if(l.data.status!=="success")throw new Error("Failed to get source download URL from API");let a=await gn.get(l.data.downloadUrl,{responseType:"stream"}),c=(i||e.projectId||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),d=$e.join(lc.homedir(),m.workspacesDir,c);de.mkdirSync(d,{recursive:!0});let u=new Set(["node_modules",`.${m.nameLower}-cache-meta`]),p=new Set(["Pods"]);if(de.existsSync(d)){let x=de.readdirSync(d);for(let O of x){if(u.has(O))continue;if(O==="ios"){let h=$e.join(d,"ios");try{let H=de.readdirSync(h);for(let b of H)if(!p.has(b))try{de.rmSync($e.join(h,b),{recursive:!0,force:!0})}catch{}}catch{}continue}let G=$e.join(d,O);try{de.rmSync(G,{recursive:!0,force:!0})}catch{}}}let f=$e.join(d,"source.zip"),S=a.data,L=de.createWriteStream(f);await new Promise((x,O)=>{S.pipe(L),S.on("error",G=>O(G)),L.on("finish",()=>x())}),new Xr(f).extractAllTo(d,!0);try{de.unlinkSync(f)}catch{}process.chdir(d),D.info(C.green(`\u2713 Persistent workspace ready: ${d}`)),D.info(C.dim(` \u{1F4E6} Cached dirs preserved: node_modules=${de.existsSync($e.join(d,"node_modules"))?"\u2705":"\u274C"}, Pods=${de.existsSync($e.join(d,"ios","Pods"))?"\u2705":"\u274C"}`)),t.stop()}catch(l){t.stop(`Failed to prepare isolated workspace: ${l.message}`),i&&await s(`Setup Error: ${l.message}`),process.exit(1)}}try{let l=e.repo;if(!l)try{l=qr("git config --get remote.origin.url").toString().trim()}catch{D.warn("Could not detect git repository URL.")}!l&&e.dryRun,l||(l="https://github.com/placeholder/repo.git"),D.info(`Build ID: ${C.cyan(n)}`);let a={},c={},d=Te(`./${m.configFileName}`);if(d){i=d.projectId;let b=e.buildProfile||"production",I=Qe(d,b);!I&&e.buildProfile&&(D.error(`Build profile '${b}' not found in ${m.configFileName}`),process.exit(1));let N=I||{};process.env.MACH_DEBUG&&D.info(C.dim(`Build profile: ${b} | Platform: ${e.platform} | Distribution: ${N.distribution||"store"} | Environment: ${N.environment||b}`)),N.env&&(c=N.env,D.info(C.blue(`Use Build Profile: ${b}`)));let P=e.platform,T=N[P]||{},R=["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);let w=M=>M==="androidPackage"?T.androidPackage??T.package??N.androidPackage??N.android?.package:M==="iosBundleIdentifier"?T.iosBundleIdentifier??T.bundleIdentifier??N.iosBundleIdentifier??N.ios?.bundleIdentifier:T[M]!==void 0?T[M]:N[M];for(let M of R){let Y=w(M),E=M==="androidPackage"||M==="iosBundleIdentifier";Y!==void 0&&(e[M]===void 0||E)&&(e[M]=Y)}if(e.platform==="ios"&&!(T.iosBundleIdentifier??T.bundleIdentifier??N.iosBundleIdentifier??N.ios?.bundleIdentifier)){let Y=Ac(e,b);Y&&Y!==e.iosBundleIdentifier&&(D.warn(C.yellow(`Detected native iOS bundle identifier ${Y}; using it for credential lookup. Set build.${b}.ios.bundleIdentifier to make this explicit.`)),e.iosBundleIdentifier=Y)}e.branch=e.branch||"main",e.iosConfiguration=e.iosConfiguration||(e.developmentClient?"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 U=M=>{if(!M)return M;if(M.startsWith("scripts.")){let Y=M.split(".")[1],E=d.scripts?.[Y];if(E)return E;D.warn(`Script reference not found: ${M}`)}return M};e.buildCommand=U(e.buildCommand),e.preBuild=U(e.preBuild),e.postBuild=U(e.postBuild),!e.scheme&&d.scheme&&(e.scheme=d.scheme);let K={...St(d,m.envPrefix),...St(N,`${m.envPrefix}PROFILE_`)};a={...a,...c,...K},process.env.IOS_P12_PASSWORD&&!a.IOS_P12_PASSWORD&&(a.IOS_P12_PASSWORD=process.env.IOS_P12_PASSWORD),process.env.MATCH_PASSWORD&&!a.MATCH_PASSWORD&&(a.MATCH_PASSWORD=process.env.MATCH_PASSWORD),e.platform==="ios"&&(!e.iosTeamId&&N.ios?.appleTeamId&&(e.iosTeamId=N.ios.appleTeamId),!e.iosTeamId&&d.submit?.[b]?.ios?.appleTeamId&&(e.iosTeamId=d.submit[b].ios.appleTeamId),!e.iosTeamId&&d.submit?.production?.ios?.appleTeamId&&(D.warn(C.yellow(`Check: Using 'production' Team ID for '${b}' build.`)),e.iosTeamId=d.submit.production.ios.appleTeamId),e.iosTeamId?D.info(C.magenta(`\u2713 Injected iOS Team ID from config: ${e.iosTeamId}`)):D.warn(C.yellow("\u26A0\uFE0F No iOS Team ID found. Signing might fail if not managed automatically via Expo.")))}let u="unknown";try{u=qr("git rev-parse --abbrev-ref HEAD").toString().trim()}catch{D.warn("Failed to detect git branch.")}let p="1.0.0";try{de.existsSync("./package.json")&&(p=JSON.parse(de.readFileSync("./package.json","utf-8")).version||"1.0.0")}catch{}let f=e.buildProfile||"production",S="Internal";e.developmentClient?S="DevelopmentClient":f.toLowerCase().includes("store")||f.toLowerCase()==="production"?S="Store":f.toLowerCase().includes("preview")||f.toLowerCase().includes("staging")?S="Staging":(f.toLowerCase().includes("development")||f.toLowerCase().includes("dev"))&&(S="Development");let L=e.platform==="ios"?"iOS":"Android",k=e.platform==="ios"&&e.simulator?" (Simulator)":"",x=`${L}${k} v${p} (${S})`;if(Sn(e,{status:"created",projectId:i,buildId:n,platform:e.platform,profile:f,branch:u,version:p,buildType:S,developmentClient:!!e.developmentClient,summary:x}),i){try{let b=e.buildProfile||"production",I=e.environment||b;D.info(C.blue(`Fetching managed secrets for profile: ${b} (environment: ${I})...`));let P=(await v.get(`/projects/${i}/secrets/export?env=${I}`)).data;P.status==="success"&&P.secrets&&(a={...a,...P.secrets},Object.keys(P.secrets).length>0&&D.info(C.magenta(`\u2713 Injected ${Object.keys(P.secrets).length} secrets from Dashboard.`)))}catch(b){D.warn(`Failed to load managed secrets from Dashboard: ${b.message}`)}try{D.info(C.blue("Fetching managed credentials..."));let b=_c(e,f),I=e.platform==="ios"?e.iosBundleIdentifier:e.androidPackage,N=e.platform==="ios"?"bundle":"package";D.info(C.dim(` Credential target: ${N} ${I||"not set"} (${b})`));let P=await v.get("/credentials/resolve",{params:{projectId:i,platform:e.platform,bundleId:I,distributionType:b}});if(P.data.status==="success"&&P.data.credentials){let T=P.data.credentials;D.info(C.magenta(`\u2713 Found ${T.length} relevant credentials.`));let R=T.filter(E=>e.platform==="ios"&&E.type==="ios_profile"?no(E,b,e.platform)?ro(E,I):!1:e.platform==="android"&&E.type==="android_keystore"?ro(E,I):!!no(E,b,e.platform)).sort((E,re)=>oo(re,I)*10+io(re,b,e.platform)-(oo(E,I)*10+io(E,b,e.platform)));D.info(C.dim(` Filtered to ${R.length} credentials for distributionType: ${b}`));let w=!1,U=!1,K=!1,M=[];for(let E of R)if(!(E.type==="ios_cert"&&w||E.type==="ios_profile"&&U||E.type==="android_keystore"&&K)&&["ios_cert","ios_profile","android_keystore"].includes(E.type)&&(E.downloadUrl||Bt(E)))try{let q=await co(E,i);if(E.type==="ios_cert"&&!w)a.IOS_DIST_P12=q,E.password?(a.IOS_P12_PASSWORD=E.password,D.info(C.dim(` - Injected ${E.name} as IOS_DIST_P12 with password from credential record`))):D.info(C.dim(` - Injected ${E.name} as IOS_DIST_P12`)),w=!0;else if(E.type==="ios_profile"&&!U){if(!Pc(q,I)){let we=fo(q)||"unknown";throw new Error(`Provisioning profile ${E.name||Bt(E)||"unknown"} is for a different bundle ID. Expected ${I}, found ${we}. Upload a ${b} profile for ${I}.`)}a.IOS_PROVISIONING_PROFILE=q,D.info(C.dim(` - Injected ${E.name} as IOS_PROVISIONING_PROFILE`)),U=!0}else if(E.type==="android_keystore"&&!K){a.ANDROID_KEYSTORE_BASE64=q;let we=E.keystorePassword||E.password,ce=E.keyPassword||E.keystorePassword||E.password,j=E.alias||E.meta?.alias;if(we)a.ANDROID_STORE_PASSWORD=we,D.info(C.dim(" - Injected keystore password from credential record"));else{let _=["ANDROID_STORE_PASSWORD",...[b==="store"?"PRODUCTION":b==="internal"||b==="adhoc"?"STAGING":"DEVELOPMENT",b.toUpperCase(),"PRODUCTION","STORE","INTERNAL","STAGING","RELEASE","DEBUG"].map(z=>`KEYSTORE_PASSWORD_${z}`),"KEYSTORE_PASSWORD"].find(z=>!!a[z]);_&&a[_]&&(a.ANDROID_STORE_PASSWORD=a[_])}if(ce?(a.ANDROID_KEY_PASSWORD=ce,D.info(C.dim(" - Injected key password from credential record"))):a.ANDROID_KEY_PASSWORD=a.ANDROID_STORE_PASSWORD||"",j)a.ANDROID_KEY_ALIAS=j;else{let B=["ANDROID_KEY_ALIAS","KEYSTORE_ALIAS"].find(Z=>!!a[Z]);B&&(a.ANDROID_KEY_ALIAS=a[B])}D.info(C.dim(` - Injected ${E.name} as ANDROID_KEYSTORE_BASE64`)),K=!0}}catch(q){M.push(`${E.name||E.type}: ${q.message}`)}let Y=e.platform==="ios"?e.simulator||w&&U:K||!R.some(E=>E.type==="android_keystore");if(M.length>0&&!Y)throw new Error(`Credential setup failed:
|
|
1177
|
-
${
|
|
1178
|
-
`)}`);
|
|
1179
|
-
\u{1F517} Download Links:`));for(let
|
|
1180
|
-
\u2713 Build completed and reported to dashboard.`)),e.maestro&&!
|
|
1181
|
-
${
|
|
1182
|
-
\u{1F3BC} Queuing managed Maestro test...`)),await
|
|
1183
|
-
Auto-submit: submitting the successful build...`));try{await
|
|
1184
|
-
\u2717 Build failed: ${a.error||"Unknown error"}`)),process.exit(1);else if(r==="completed"||r==="success"){n.quiet||i.stop("Build successful!"),
|
|
1185
|
-
\u2713 Build completed successfully!`));try{n.quiet||(
|
|
1186
|
-
\u{1F4F1} Installation Hub:`)),
|
|
1187
|
-
`);if(u.length>o){for(let p=o;p<u.length;p++)u[p].trim()&&console.log(
|
|
1188
|
-
\u2717 Lost connection to Dashboard API.`)),process.exit(1))}await new Promise(l=>setTimeout(l,3e3))}}import*as
|
|
1173
|
+
`);if(/only releases with status draft|draft app/i.test(r))return["Google Play requires a draft release for this app state.",`Package: ${n||"unknown"} | Track: ${t}`,`Retry with: ${f.nameLower} submit --latest --platform android --profile ${i} --track ${t} --release-status draft`].join(`
|
|
1174
|
+
`);if(r.includes("does not allow any existing users to upgrade"))return["Google Play rejected this release because the uploaded AAB is not an upgrade for existing users.",`Package: ${n||"unknown"} | Track: ${t}`,"Build a new Android artifact with a higher versionCode, then submit that build.",`Recommended: ${f.nameLower} build --platform android --profile ${i} --auto-version`,`Then: ${f.nameLower} submit --latest --platform android --profile ${i} --track ${t}`].join(`
|
|
1175
|
+
`);if(/version code \d+ has already been used/i.test(r))return[r.match(/version code \d+ has already been used[^\n]*/i)?.[0]||"Version code has already been used.",`Package: ${n||"unknown"} | Track: ${t}`,"Build a new Android artifact with a higher versionCode, then submit that build.",`Recommended: ${f.nameLower} build --platform android --profile ${i} --auto-version`].join(`
|
|
1176
|
+
`);let o=r.match(/Google Api Error:[^\n]+/)||r.match(/Google Play API Error:[^\n]+/);return o?o[0]:r||"Google Play submission failed"}function yd(e){try{se.existsSync(e)&&se.rmSync(e,{recursive:!0,force:!0})}catch{}}function le(e){console.log(ne.red(`\u274C ${e}`))}function pe(e){console.log(ne.gray(`\u2022 ${e}`))}function Si(e){console.log(ne.green(`\u2713 ${e}`))}var Ai=8,Ed=6,oo=Number(process.env.MACH_ARTIFACT_UPLOAD_MAX_ATTEMPTS||2),Ii=Number(process.env.MACH_ARTIFACT_UPLOAD_TIMEOUT_MS||12e4),So=e=>new Promise(t=>setTimeout(t,e)),Ad=e=>{if(!Number.isFinite(e)||e<=0)return"0 B";let t=["B","KB","MB","GB"],n=Math.min(Math.floor(Math.log(e)/Math.log(1024)),t.length-1);return`${(e/Math.pow(1024,n)).toFixed(n===0?0:1)} ${t[n]}`},Id=e=>{let t=e.response?.status,n=e.code||"",i=e.message||"";return t?t===408||t===409||t===425||t===429||t>=500||/ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|ECONNABORTED|socket hang up|network|timeout/i.test(`${n} ${i}`):!0},gn=async(e,t,n=Ed)=>{let i;for(let r=1;r<=n;r++)try{return await t()}catch(o){if(i=o,!Id(o)||r>=n)break;let s=Math.min(6e4,2e3*Math.pow(2,r-1)),l=o.response?.status||o.code||o.message||"network error";_.warn($.yellow(`${e} failed transiently (${l}). Retrying in ${Math.round(s/1e3)}s... (${r}/${n})`)),await So(s)}throw i},wd=async(e,t,n)=>{let i=$e.basename(e),r=de.statSync(e).size,o=Math.round(Ii/1e3);try{await gn(`Upload artifact ${i}`,async()=>{let s=new AbortController,l=de.createReadStream(e),a=setTimeout(()=>{l.destroy(new Error(`Artifact upload timed out after ${o}s`)),s.abort()},Ii);try{await yn.put(t,l,{headers:{"Content-Type":n,"Content-Length":r,Connection:"close"},maxBodyLength:1/0,maxContentLength:1/0,timeout:Ii,timeoutErrorMessage:`Artifact upload timed out after ${o}s`,signal:s.signal})}finally{clearTimeout(a)}},oo)}catch(s){throw new Error(`${i} (${Ad(r)}) failed after ${oo} upload attempt(s): ${s.message||s}`)}return r},_d=e=>{let t=e.response?.status;return t?t===408||t===429||t>=500:!0},Ft=e=>e.credentialId||e.id,$d=async(e,t)=>{let n=Ft(e);if(!n)return e.downloadUrl;let i=await R.get(`/credentials/${n}/download`,{params:{projectId:t,format:"raw"}});return i.data?.status==="success"&&i.data?.downloadUrl?i.data.downloadUrl:e.downloadUrl},bo=async(e,t)=>{let n=e.downloadUrl;for(let i=1;i<=Ai;i++)try{if((!n||i>1)&&(n=await $d(e,t)),!n)throw new Error(`Credential ${e.name||Ft(e)||"unknown"} has no download URL.`);let r=await yn.get(n,{responseType:"arraybuffer",timeout:6e4,maxContentLength:1/0,maxBodyLength:1/0,headers:{Connection:"close"}});return Buffer.from(r.data).toString("base64")}catch(r){if(i>=Ai||!_d(r))throw r;let o=Math.min(1500*i*i,15e3);_.warn($.dim(` - Temporary network error downloading ${e.name}. Retrying... (${i}/${Ai})`)),await So(o)}throw new Error(`Failed to download credential ${e.name||Ft(e)||"unknown"}.`)},so=async(e,t)=>{let n=await bo(e,t);return Buffer.from(n,"base64").toString("utf8")},vd=(e,t)=>{try{return JSON.parse(e)}catch{throw new Error(`${t} is not valid JSON.`)}},Rd=e=>/ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|ECONNABORTED|socket hang up|network|timeout/i.test(e),Pd=(e,t)=>t?.ios?.buildNumber??t?.iosBuildNumber??e?.ios?.buildNumber??e?.expo?.ios?.buildNumber,Dd=(e,t,n)=>t?.ios?.ascAppId??t?.ascAppId??e?.ios?.ascAppId??e?.submit?.[n]?.ios?.ascAppId??e?.submit?.production?.ios?.ascAppId,ao=e=>e.bundleId||e.bundleIdentifier||e.meta?.bundleId||e.meta?.bundleIdentifier,lo=(e,t)=>{let n=e.filter(i=>i.type==="asc_api_key");if(n.length!==0){if(t){let i=n.find(o=>ao(o)===t);if(i)return i;let r=n.find(o=>ao(o)==="*");if(r)return r}return n[0]}},Od=e=>typeof e=="string"&&e.trim().toLowerCase()==="auto",Eo=(e,t,n=[])=>{if(!de.existsSync(e))return n;let i;try{i=de.readdirSync(e,{withFileTypes:!0})}catch{return n}for(let r of i){if(r.name==="Pods"||r.name==="build"||r.name==="DerivedData")continue;let o=$e.join(e,r.name);r.isDirectory()?Eo(o,t,n):r.name===t&&n.push(o)}return n},Cd=(e,t,n)=>{let i=`${n} ${t.environment||""}`.toLowerCase(),r=e.toLowerCase(),o=0;return(i.includes("development")||i.includes("dev"))&&/(^|[.-])dev(elopment)?($|[.-])/.test(r)&&(o+=20),(i.includes("staging")||i.includes("stage"))&&/(^|[.-])stag(e|ing)?($|[.-])/.test(r)&&(o+=20),(i.includes("production")||i.includes("prod"))&&(/(^|[.-])(dev|development|stag|stage|staging)($|[.-])/.test(r)||(o+=20)),o},Nd=(e,t)=>{let n=$e.resolve(process.cwd(),de.existsSync("ios")?"ios":"."),i=Eo(n,"project.pbxproj"),r=[];for(let o of i)try{let l=de.readFileSync(o,"utf8").matchAll(/PRODUCT_BUNDLE_IDENTIFIER\s*=\s*"?([^";\s]+)"?;/g);for(let a of l){let d=a[1]?.trim();d&&!d.includes("$")&&!d.startsWith("com.apple.")&&!r.includes(d)&&r.push(d)}}catch{}if(r.length!==0)return r.length===1?r[0]:r.map(o=>({bundleId:o,score:Cd(o,e,t)})).sort((o,s)=>s.score-o.score)[0]?.bundleId},hn=e=>String(e||"").trim().toLowerCase().replace(/_/g,"-"),Sn=(e,t)=>{let n=hn(e);return t==="ios"&&(n==="internal"||n==="ad-hoc")?"adhoc":t==="android"&&["internal","adhoc","ad-hoc","development","dev","staging","stage"].includes(n)?"internal":n},co=(e,t,n)=>{let i=Sn(e.distributionType||e.meta?.distributionType,n);return i?i===Sn(t,n):!0},uo=(e,t,n)=>{let i=Sn(e.distributionType||e.meta?.distributionType,n),r=Sn(t,n);return i?i===r?3:n==="android"&&r!=="store"&&i!=="store"?2:0:1},Td=e=>{let t=e.toLowerCase();return t==="development"||t==="dev"||t.startsWith("development-")||t.startsWith("dev-")||t.endsWith("-development")||t.endsWith("-dev")},kd=e=>{let t=e.toLowerCase();return t.includes("staging")||t.includes("stage")||t.includes("preview")||t.includes("adhoc")||t.includes("ad-hoc")},Ld=(e,t)=>{let n=hn(e.distribution),i=hn(e.iosExportMethod),r=hn(e.environment);return e.platform!=="ios"?n==="store"?"store":"internal":e.developmentClient||e.simulator?"development":i==="app-store"||n==="store"?"store":i==="development"||n==="development"?"development":i==="ad-hoc"||i==="adhoc"||n==="ad-hoc"||n==="adhoc"||n==="internal"?"adhoc":r==="production"||r==="store"?"store":r==="development"||r==="dev"?"development":r==="staging"||r==="stage"||r==="preview"?"adhoc":t.toLowerCase()==="production"||t.toLowerCase().includes("store")?"store":Td(t)?"development":(kd(t),"adhoc")},Ao=e=>e.bundleId||e.bundleIdentifier||e.packageName||e.meta?.bundleId||e.meta?.bundleIdentifier||e.meta?.packageName,po=(e,t)=>{if(!t)return!0;let n=Ao(e);return!n||n==="*"||n===t},fo=(e,t)=>{let n=Ao(e);return!t||!n?0:n===t?2:n==="*"?1:-1},Io=e=>{try{let t=Buffer.from(e,"base64").toString("utf8"),n=t.match(/<key>application-identifier<\/key>\s*<string>([^<]+)<\/string>/)?.[1]?.trim();if(!n)return;let i=t.match(/<key>TeamIdentifier<\/key>\s*<array>\s*<string>([^<]+)<\/string>/)?.[1]?.trim();if(i&&n.startsWith(`${i}.`))return n.slice(i.length+1);let r=n.indexOf(".");return r>=0?n.slice(r+1):n}catch{return}},xd=(e,t)=>{if(e===t||e==="*")return!0;if(e.endsWith(".*")){let n=e.slice(0,-2);return t.startsWith(`${n}.`)}return!1},Md=(e,t)=>{if(!t)return!0;let n=Io(e);if(n)return xd(n,t);try{return Buffer.from(e,"base64").toString("latin1").includes(t)}catch{return!0}},bn=async e=>{if(e.failOnly){(!e.projectId||!e.buildId)&&(_.error($.red("--project-id and --build-id are required with --fail-only.")),process.exit(1));let l=e.error||"Build runner failed before it could report a final status.";try{await R.patch(`/builds/${e.projectId}/${e.buildId}`,{status:"failed",error:l,endTime:Date.now()}),_.info($.yellow(`Marked build ${e.buildId} as failed.`));return}catch(a){_.error($.red(`Could not mark build failed: ${a.message}`)),process.exit(1)}}e.platform!=="android"&&e.platform!=="ios"&&(_.error(`Platform ${e.platform} is not supported. Use 'android' or 'ios'.`),process.exit(1)),e.autoSubmit&&e.platform==="ios"&&e.simulator&&(_.error($.red("--auto-submit cannot be used with --simulator because simulator builds are not App Store artifacts.")),process.exit(1)),e.autoSubmit&&e.dryRun&&_.warn($.yellow("--auto-submit is ignored during --dry-run."));let t=_i(),n=e.buildId||Sd(),i=e.projectId,r=Date.now(),o=!!i,s=async l=>{if(i)try{await R.patch(`/builds/${i}/${n}`,{status:"failed",error:l})}catch{}};if(e.local&&e.buildId){e.quiet||t.start(`Preparing isolated workspace for build: ${e.buildId}`);try{let l=await R.get(`/builds/${i}/${e.buildId}/source-url`);if(l.data.status!=="success")throw new Error("Failed to get source download URL from API");let a=await yn.get(l.data.downloadUrl,{responseType:"stream"}),d=(i||e.projectId||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),c=$e.join(bd.homedir(),f.workspacesDir,d);de.mkdirSync(c,{recursive:!0});let u=new Set(["node_modules",`.${f.nameLower}-cache-meta`]),p=new Set(["Pods"]);if(de.existsSync(c)){let M=de.readdirSync(c);for(let P of M){if(u.has(P))continue;if(P==="ios"){let S=$e.join(c,"ios");try{let G=de.readdirSync(S);for(let Q of G)if(!p.has(Q))try{de.rmSync($e.join(S,Q),{recursive:!0,force:!0})}catch{}}catch{}continue}let j=$e.join(c,P);try{de.rmSync(j,{recursive:!0,force:!0})}catch{}}}let m=$e.join(c,"source.zip"),y=a.data,C=de.createWriteStream(m);await new Promise((M,P)=>{y.pipe(C),y.on("error",j=>P(j)),C.on("finish",()=>M())}),new ro(m).extractAllTo(c,!0);try{de.unlinkSync(m)}catch{}process.chdir(c),_.info($.green(`\u2713 Persistent workspace ready: ${c}`)),_.info($.dim(` \u{1F4E6} Cached dirs preserved: node_modules=${de.existsSync($e.join(c,"node_modules"))?"\u2705":"\u274C"}, Pods=${de.existsSync($e.join(c,"ios","Pods"))?"\u2705":"\u274C"}`)),t.stop()}catch(l){t.stop(`Failed to prepare isolated workspace: ${l.message}`),i&&await s(`Setup Error: ${l.message}`),process.exit(1)}}try{let l=e.repo;if(!l)try{l=io("git config --get remote.origin.url").toString().trim()}catch{_.warn("Could not detect git repository URL.")}!l&&e.dryRun,l||(l="https://github.com/placeholder/repo.git"),_.info(`Build ID: ${$.cyan(n)}`);let a={},d={},c=null,u=Pe(`./${f.configFileName}`);if(u){c=u,i=u.projectId;let g=e.buildProfile||"production",T=Qe(u,g);!T&&e.buildProfile&&(_.error(`Build profile '${g}' not found in ${f.configFileName}`),process.exit(1));let I=T||{};process.env.MACH_DEBUG&&_.info($.dim(`Build profile: ${g} | Platform: ${e.platform} | Distribution: ${I.distribution||"store"} | Environment: ${I.environment||g}`)),I.env&&(d=I.env,_.info($.blue(`Use Build Profile: ${g}`)));let L=e.platform,v=I[L]||{},E=["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=u.name,e.appName=u.name,e.androidPackage=u.android?.package,e.iosBundleIdentifier=u.ios?.bundleIdentifier,e.iosScheme=u.ios?.iosScheme,!e.nodeVersion&&u.nodeVersion&&(e.nodeVersion=u.nodeVersion);let k=x=>x==="androidPackage"?v.androidPackage??v.package??I.androidPackage??I.android?.package:x==="iosBundleIdentifier"?v.iosBundleIdentifier??v.bundleIdentifier??I.iosBundleIdentifier??I.ios?.bundleIdentifier:v[x]!==void 0?v[x]:I[x];for(let x of E){let z=k(x),D=x==="androidPackage"||x==="iosBundleIdentifier";z!==void 0&&(e[x]===void 0||D)&&(e[x]=z)}if(e.platform==="ios"&&!(v.iosBundleIdentifier??v.bundleIdentifier??I.iosBundleIdentifier??I.ios?.bundleIdentifier)){let z=Nd(e,g);z&&z!==e.iosBundleIdentifier&&(_.warn($.yellow(`Detected native iOS bundle identifier ${z}; using it for credential lookup. Set build.${g}.ios.bundleIdentifier to make this explicit.`)),e.iosBundleIdentifier=z)}e.branch=e.branch||"main",e.iosConfiguration=e.iosConfiguration||(e.developmentClient?"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 K=x=>{if(!x)return x;if(x.startsWith("scripts.")){let z=x.split(".")[1],D=u.scripts?.[z];if(D)return D;_.warn(`Script reference not found: ${x}`)}return x};e.buildCommand=K(e.buildCommand),e.preBuild=K(e.preBuild),e.postBuild=K(e.postBuild),!e.scheme&&u.scheme&&(e.scheme=u.scheme);let W={...St(u,f.envPrefix),...St(I,`${f.envPrefix}PROFILE_`)};a={...a,...d,...W},process.env.IOS_P12_PASSWORD&&!a.IOS_P12_PASSWORD&&(a.IOS_P12_PASSWORD=process.env.IOS_P12_PASSWORD),process.env.MATCH_PASSWORD&&!a.MATCH_PASSWORD&&(a.MATCH_PASSWORD=process.env.MATCH_PASSWORD),e.platform==="ios"&&(!e.iosTeamId&&I.ios?.appleTeamId&&(e.iosTeamId=I.ios.appleTeamId),!e.iosTeamId&&u.submit?.[g]?.ios?.appleTeamId&&(e.iosTeamId=u.submit[g].ios.appleTeamId),!e.iosTeamId&&u.submit?.production?.ios?.appleTeamId&&(_.warn($.yellow(`Check: Using 'production' Team ID for '${g}' build.`)),e.iosTeamId=u.submit.production.ios.appleTeamId),e.iosTeamId?_.info($.magenta(`\u2713 Injected iOS Team ID from config: ${e.iosTeamId}`)):_.warn($.yellow("\u26A0\uFE0F No iOS Team ID found. Signing might fail if not managed automatically via Expo.")))}let p="unknown";try{p=io("git rev-parse --abbrev-ref HEAD").toString().trim()}catch{_.warn("Failed to detect git branch.")}let m="1.0.0";try{de.existsSync("./package.json")&&(m=JSON.parse(de.readFileSync("./package.json","utf-8")).version||"1.0.0")}catch{}let y=e.buildProfile||"production",C="Internal";e.developmentClient?C="DevelopmentClient":y.toLowerCase().includes("store")||y.toLowerCase()==="production"?C="Store":y.toLowerCase().includes("preview")||y.toLowerCase().includes("staging")?C="Staging":(y.toLowerCase().includes("development")||y.toLowerCase().includes("dev"))&&(C="Development");let N=e.platform==="ios"?"iOS":"Android",M=e.platform==="ios"&&e.simulator?" (Simulator)":"",P=`${N}${M} v${m} (${C})`;if(En(e,{status:"created",projectId:i,buildId:n,platform:e.platform,profile:y,branch:p,version:m,buildType:C,developmentClient:!!e.developmentClient,summary:P}),i){try{let g=e.buildProfile||"production",T=e.environment||g;_.info($.blue(`Fetching managed secrets for profile: ${g} (environment: ${T})...`));let L=(await R.get(`/projects/${i}/secrets/export?env=${T}`)).data;L.status==="success"&&L.secrets&&(a={...a,...L.secrets},Object.keys(L.secrets).length>0&&_.info($.magenta(`\u2713 Injected ${Object.keys(L.secrets).length} secrets from Dashboard.`)))}catch(g){_.warn(`Failed to load managed secrets from Dashboard: ${g.message}`)}try{_.info($.blue("Fetching managed credentials..."));let g=Ld(e,y),T=e.platform==="ios"?e.iosBundleIdentifier:e.androidPackage,I=e.platform==="ios"?"bundle":"package";_.info($.dim(` Credential target: ${I} ${T||"not set"} (${g})`));let L=await R.get("/credentials/resolve",{params:{projectId:i,platform:e.platform,bundleId:T,distributionType:g,teamId:e.platform==="ios"?e.iosTeamId:void 0}});if(L.data.status==="success"&&L.data.credentials){let v=L.data.credentials;_.info($.magenta(`\u2713 Found ${v.length} relevant credentials.`));let E=v.filter(D=>e.platform==="ios"&&D.type==="ios_profile"?co(D,g,e.platform)?po(D,T):!1:e.platform==="android"&&D.type==="android_keystore"?po(D,T):!!co(D,g,e.platform)).sort((D,J)=>fo(J,T)*10+uo(J,g,e.platform)-(fo(D,T)*10+uo(D,g,e.platform)));_.info($.dim(` Filtered to ${E.length} credentials for distributionType: ${g}`));let k=!1,K=!1,W=!1,x=[];for(let D of E)if(!(D.type==="ios_cert"&&k||D.type==="ios_profile"&&K||D.type==="android_keystore"&&W)&&["ios_cert","ios_profile","android_keystore"].includes(D.type)&&(D.downloadUrl||Ft(D)))try{let ye=await bo(D,i);if(D.type==="ios_cert"&&!k)a.IOS_DIST_P12=ye,D.password?(a.IOS_P12_PASSWORD=D.password,_.info($.dim(` - Injected ${D.name} as IOS_DIST_P12 with password from credential record`))):_.info($.dim(` - Injected ${D.name} as IOS_DIST_P12`)),k=!0;else if(D.type==="ios_profile"&&!K){if(!Md(ye,T)){let Ee=Io(ye)||"unknown";throw new Error(`Provisioning profile ${D.name||Ft(D)||"unknown"} is for a different bundle ID. Expected ${T}, found ${Ee}. Upload a ${g} profile for ${T}.`)}a.IOS_PROVISIONING_PROFILE=ye,_.info($.dim(` - Injected ${D.name} as IOS_PROVISIONING_PROFILE`)),K=!0}else if(D.type==="android_keystore"&&!W){a.ANDROID_KEYSTORE_BASE64=ye;let Ee=D.keystorePassword||D.password,B=D.keyPassword||D.keystorePassword||D.password,U=D.alias||D.meta?.alias;if(Ee)a.ANDROID_STORE_PASSWORD=Ee,_.info($.dim(" - Injected keystore password from credential record"));else{let F=["ANDROID_STORE_PASSWORD",...[g==="store"?"PRODUCTION":g==="internal"||g==="adhoc"?"STAGING":"DEVELOPMENT",g.toUpperCase(),"PRODUCTION","STORE","INTERNAL","STAGING","RELEASE","DEBUG"].map(X=>`KEYSTORE_PASSWORD_${X}`),"KEYSTORE_PASSWORD"].find(X=>!!a[X]);F&&a[F]&&(a.ANDROID_STORE_PASSWORD=a[F])}if(B?(a.ANDROID_KEY_PASSWORD=B,_.info($.dim(" - Injected key password from credential record"))):a.ANDROID_KEY_PASSWORD=a.ANDROID_STORE_PASSWORD||"",U)a.ANDROID_KEY_ALIAS=U;else{let q=["ANDROID_KEY_ALIAS","KEYSTORE_ALIAS"].find(O=>!!a[O]);q&&(a.ANDROID_KEY_ALIAS=a[q])}_.info($.dim(` - Injected ${D.name} as ANDROID_KEYSTORE_BASE64`)),W=!0}}catch(ye){x.push(`${D.name||D.type}: ${ye.message}`)}let z=e.platform==="ios"?e.simulator||k&&K:W||!E.some(D=>D.type==="android_keystore");if(x.length>0&&!z)throw new Error(`Credential setup failed:
|
|
1177
|
+
${x.map(D=>`- ${D}`).join(`
|
|
1178
|
+
`)}`);x.length>0&&_.warn($.dim(` Skipped ${x.length} stale or unusable credential(s).`))}if(e.platform==="ios"&&!e.simulator){let v=e.buildProfile||"production",E=Qe(u,v)||{},k=Pd(u,E),K=Od(k),W=e.distribution!==void 0?e.distribution==="store":C==="Store",x=k===void 0&&W,z=e.autoVersion||K&&W||x,D=e.autoVersion||K&&W;if(K&&!W&&_.info($.dim(` Skipping App Store Connect buildNumber lookup for ${e.distribution||"non-store"} build. Pass --auto-version to force it.`)),z){let J=e.iosBundleIdentifier||u.ios?.bundleIdentifier||u.expo?.ios?.bundleIdentifier,ye=Dd(u,E,v),Ee=L.data.credentials||[],B=lo(Ee,J);if(!B&&(D||x)){let U=await R.get(`/credentials/${i}`);B=lo(U.data.credentials||[],J)}if(B){t.start("Resolving latest iOS buildNumber from App Store Connect...");try{let U=B.keyId||B.meta?.keyId,q=B.issuerId||B.meta?.issuerId;if(!U||!q)throw new Error("App Store Connect credential is missing keyId or issuerId.");let O=await so(B,i),F=await Ir({keyId:U,issuerId:q,privateKey:O,ascAppId:ye,bundleId:J}),X=/^\d+$/.test(F.latestBuildNumber);X?(a.BUILD_NUMBER=F.nextBuildNumber,delete a.MACH_IOS_BUILD_NUMBER_LOCKED):(a.BUILD_NUMBER=F.nextBuildNumber,a.CURRENT_PROJECT_VERSION=F.nextBuildNumber,a.MACH_IOS_BUILD_NUMBER_LOCKED="1"),t.stop(X?`\u2713 Latest iOS buildNumber on App Store Connect: ${$.green(F.latestBuildNumber)} (Mach will assign >= ${F.nextBuildNumber})`:`\u2713 Resolved iOS buildNumber: ${$.green(F.nextBuildNumber)} (Latest on App Store Connect: ${F.latestBuildNumber})`)}catch(U){t.stop("iOS buildNumber lookup failed");let q=U.response?.data?.error?.message||U.message;if(D)throw new Error(`Auto-versioning failed: ${q}. Fix App Store Connect API key permissions or remove ios.buildNumber="auto".`);_.warn($.yellow(`Could not check App Store Connect buildNumber: ${q}. Falling back to Mach counter.`))}}else if(D)throw new Error(`Auto-versioning failed: App Store Connect API key not found. Upload it with '${f.nameLower} credentials:service --platform ios'.`)}}if(e.platform==="android"){let v=e.buildProfile||"production",E=Qe(u,v)||{},W=((E.android||{}).versionCode??E.androidVersionCode??u.android?.versionCode??u.expo?.android?.versionCode)==="auto",x=e.distribution!==void 0?e.distribution==="store":C==="Store",z=e.autoVersion||W&&x;if(W&&!z&&_.info($.dim(` Skipping Google Play versionCode lookup for ${e.distribution||"non-store"} build. Pass --auto-version to force it.`)),z){t.start("Resolving latest versionCode from Google Play...");try{let D=e.androidPackage||u.android?.package||u.expo?.android?.package||u.name,J=(L.data.credentials||[]).find(q=>q.type==="google_service_account"&&(!q.bundleId||q.bundleId===D));if(!J){let O=((await R.get(`/credentials/${i}`)).data.credentials||[]).filter(F=>F.type==="google_service_account");if(J=O.find(F=>F.type==="google_service_account"&&F.bundleId===D),!J&&O.length>0){let F=O.map(X=>X.bundleId).filter(Boolean).join(", ");throw new Error(`Google Service Account not found for package ${D}. Found service credential(s) for: ${F}.`)}}if(!J)throw new Error(`Google Service Account not found for package ${D}. Upload it under this package in Dashboard or run '${f.nameLower} credentials:service --platform android --package-name ${D}'.`);let ye=await so(J,i),Ee=vd(ye,"Google Play service account");if(!Ee.client_email||!Ee.private_key)throw new Error("Google Play service account JSON is missing client_email or private_key.");let B=await hr(D,Ee);if(B==null)throw new Error("Could not retrieve any version information from Google Play.");let U=B+1;a.ANDROID_VERSION_CODE=U.toString(),t.stop(`\u2713 Resolved versionCode: ${$.green(U)} (Latest on Play Store: ${B})`)}catch(D){t.stop("Version resolution failed");let J=D.response?.data?.error?.message||D.message,ye=Rd(J)?"This looks like a temporary network error while contacting Mach or Google Play. Retry the command, or build and submit as separate steps if it continues.":'Fix Google Play service account permissions or remove android.versionCode="auto".';throw new Error(`Auto-versioning failed: ${J}. ${ye}`)}}}if(e.platform==="ios"&&!e.simulator){let v=!!a.IOS_DIST_P12,E=!!a.IOS_PROVISIONING_PROFILE;if(!v||!E){let k=[...v?[]:["Distribution Certificate"],...E?[]:["Provisioning Profile"]].join(" and ");if(e.local&&e.buildId)throw new Error(`Missing iOS credentials: ${k}. Expected ${g} credentials for ${T||"the selected bundle ID"}. Run \`${f.nameLower} credentials --platform ios --profile ${y}\` and select ${T||"the correct bundle ID"}.`);_.error($.red(`Missing iOS credentials: ${k}`)),e.quiet&&process.exit(1);let K=e.yes||await to({message:"Would you like to generate these credentials now?",initialValue:!0});if(K&&!no(K))return await Ct({platform:"ios",profile:y}),e.quiet||_.info($.green("\u2713 Credentials setup complete! Restarting build phase...")),bn(e);e.quiet||_.info($.yellow(`Run \`${f.nameLower} credentials\` to set up signing credentials manually.`)),process.exit(1)}}if(e.platform==="android"&&!e.developmentClient&&(e.distribution==="internal"||e.distribution==="store")&&!(!!a.ANDROID_KEYSTORE_BASE64||!!a.ANDROID_KEYSTORE)){_.error($.red("Missing Android credentials: Signing Keystore")),e.quiet&&process.exit(1);let E=e.yes||await to({message:"Would you like to automatically create and upload an Android Keystore for this profile now?",initialValue:!0});if(E&&!no(E))return await Ct({platform:"android",profile:y}),e.quiet||_.info($.green("\u2713 Android Keystore setup complete! Restarting build phase...")),bn(e);e.quiet||_.info($.yellow(`Run \`${f.nameLower} credentials --platform android\` to set up a signing keystore manually.`)),process.exit(1)}}catch(g){(String(g.message||"").startsWith("Credential download failed")||String(g.message||"").startsWith("Credential setup failed")||String(g.message||"").startsWith("Missing iOS credentials")||String(g.message||"").startsWith("Auto-versioning failed"))&&(_.error($.red(g.message)),process.exit(1)),e.platform==="ios"&&e.local&&e.buildId&&(_.error($.red(`Failed to resolve iOS credentials: ${g.message}`)),process.exit(1)),_.warn(`Failed to resolve credentials: ${g.message}`)}}let j=!!(e.local&&e.buildId),S=!!(e.local||e.sshHost),G=!S&&!j;if(j){_.info($.magenta("\u{1F3D7}\uFE0F Runner Mode: Executing isolated build task..."));let g=await ti({...e,interactive:!1},n,a,i,{branch:p,version:m,summary:P,buildType:C});await Q(g),process.exit(0)}async function Q(g){let T=async I=>{if(i)try{await gn("Report failed build status",()=>R.patch(`/builds/${i}/${n}`,{status:"failed",error:I,endTime:Date.now()}),3)}catch(L){_.warn($.yellow(`Could not report failed build status: ${L.message}`))}};if(i&&g.length>0){let I=_i(),L=[];e.quiet||I.start("Uploading artifacts to Dashboard...");try{for(let v of g){let E=$e.basename(v),k=de.statSync(v).size,K=$e.extname(E).toLowerCase(),W="application/octet-stream",x=await gn(`Create artifact upload URL for ${E}`,()=>R.post(`/builds/${i}/${n}/artifact-upload-url`,{fileName:E,fileType:W}));if(x.data.status!=="success")throw new Error(`Failed to get upload URL for ${E}`);await wd(v,x.data.uploadUrl,W),L.push({name:E,url:x.data.downloadUrl,size:k,type:K.substring(1)})}e.quiet||I.stop("Artifacts uploaded.")}catch(v){e.quiet||I.stop("Failed to upload artifacts.");let E=`Artifact upload failed: ${v.message}`;throw _.error($.red(E)),await T(E),new Error(E)}if(i&&L.length>0)try{_.info($.cyan(`
|
|
1179
|
+
\u{1F517} Download Links:`));for(let v of L)_.info($.dim(` - ${v.name}: `)+$.blue.underline(v.url));await gn("Finalize build in dashboard",()=>R.patch(`/builds/${i}/${n}`,{status:"success",artifacts:L,endTime:Date.now()})),En(e,{status:"success",projectId:i,buildId:n,platform:e.platform,profile:y,branch:p,version:m,buildType:C,developmentClient:!!e.developmentClient,summary:P,artifacts:L}),_.success($.green(`
|
|
1180
|
+
\u2713 Build completed and reported to dashboard.`)),e.maestro&&!j&&await mo(i,n,e,y),e.autoSubmit&&!j&&await wi(i,n,e,y)}catch(v){let E=`Build artifact uploaded but dashboard finalization failed: ${v.message}`;throw _.error($.red(`
|
|
1181
|
+
${E}`)),await T(E),new Error(E)}}else if(i){let I="Build completed but produced no uploadable artifacts.";throw _.error($.red(I)),await T(I),new Error(I)}}if(S){if(_.info($.cyan(`\u{1F680} Direct Build Mode: Executing on ${e.sshHost||"local"}...`)),i&&!o){let g=process.argv.slice(3).join(" ");await R.post("/builds",{projectId:i,buildId:n,platform:e.platform,status:"building",branch:p,version:m,summary:P,startTime:r,buildType:C,buildProfile:y,buildArgs:g,simulator:!!e.simulator,developmentClient:!!e.developmentClient,...go(e,n,y,c)}),ho(e)}if(e.sshHost&&e.platform==="ios")await mr(e,n,a,i),e.autoSubmit&&await wi(i,n,e,y);else{let g=await ti({...e,interactive:!!e.local},n,a,i,{branch:p,version:m,summary:P,buildType:C});await Q(g)}return}if(G&&(_.info($.blue("\u{1F6F0}\uFE0F Cloud Initiator Mode: Preparing orchestration...")),!e.dryRun)){e.quiet||t.start("Zipping and uploading local source...");let g=await R.post("/builds/source-upload-url",{projectId:i,buildId:n});if(g.data.status!=="success")throw t.stop("Failed to get upload URL."),new Error("Failed to get source upload URL from API");let T=new ro,I=de.readdirSync("."),L=["node_modules",".git","dist","build","builds",".gradle",".idea","android/build","ios/build","ios/Pods",`.${f.nameLower}_cli`];for(let k of I){if(L.includes(k))continue;de.statSync(k).isDirectory()?T.addLocalFolder(k,k):T.addLocalFile(k)}let v=T.toBuffer();e.quiet||t.message(`Uploading source (${(v.length/1024/1024).toFixed(1)} MB)...`);let E=!1;for(let k=1;k<=3;k++)try{await yn.put(g.data.uploadUrl,v,{headers:{"Content-Type":"application/zip"},maxBodyLength:1/0,maxContentLength:1/0,timeout:12e4}),E=!0;break}catch(K){if(k<3)t.message(`Upload attempt ${k} failed (${K.code||K.message}), retrying...`),await new Promise(W=>setTimeout(W,2e3*k));else throw K}if(e.quiet||t.stop("Source uploaded"),i){let k=process.argv.slice(3).join(" ");await R.post("/builds",{projectId:i,buildId:n,platform:e.platform,status:"pending",branch:p,version:m,summary:P,startTime:r,buildType:C,buildProfile:y,buildArgs:k,simulator:!!e.simulator,developmentClient:!!e.developmentClient,...go(e,n,y,c)}),_.info($.green("\u2713 Cloud build registered.")),ho(e)}e.platform==="android"&&await ur(e,n,a,i,e.preBuild),e.quiet||_.info($.cyan("\u{1F4E1} Connecting to build stream...")),await Fd(i,n,e),e.maestro&&await mo(i,n,e,y),e.autoSubmit&&await wi(i,n,e,y);return}}catch(l){let a=l.message||"Build failed";l.response?.data?.message?a=l.response.data.message:l.message.includes("status code 402")?a="Insufficient wallet balance. Please add credits in the Dashboard.":l.message.includes("status code 403")&&(a="Monthly build quota exceeded. Upgrade your plan in the Dashboard."),i&&!e.local&&await s(a),_.error($.red(`\u2717 Build failed: ${a}`)),process.exit(1)}};async function mo(e,t,n,i){_.info($.cyan(`
|
|
1182
|
+
\u{1F3BC} Queuing managed Maestro test...`)),await ai({projectId:e,buildId:t,platform:n.platform,profile:i,maestroFlows:n.maestroFlows,maestroDevice:n.maestroDevice,maestroRetries:n.maestroRetries,maestroRecord:n.maestroRecord,maestroUseBuildSource:n.maestroUseBuildSource,quiet:n.quiet})}async function wi(e,t,n,i){if(!e){_.error($.red("Auto-submit requires a linked Mach project. Run `mach link` or pass --project-id.")),process.exitCode=1;return}_.info($.cyan(`
|
|
1183
|
+
Auto-submit: submitting the successful build...`));try{let r=await Ud(e,t);if(r?.autoSubmit){let o=r.submissionId?`${Ke}/submissions/${r.submissionId}?projectId=${encodeURIComponent(e)}`:void 0,s=String(r.status||"").toLowerCase(),l=String(r.autoSubmitStatus||"").toLowerCase(),a=r.submissionId||["success","completed","succeeded"].includes(s)||["starting","submitted","failed","skipped"].includes(l);if(r.submissionId?(_.info($.green(`Auto-submit is already queued by Mach backend: ${r.submissionId}`)),_.info($.dim(`Dashboard: ${o}`))):r.autoSubmitStatus==="failed"?_.warn($.yellow(`Backend auto-submit failed: ${r.autoSubmitError||"Unknown error"}`)):a&&_.info($.green("Auto-submit is registered with Mach backend; skipping local duplicate submit.")),a){writeSubmissionMetadata(n,{status:r.autoSubmitStatus||"pending",projectId:e,submitId:r.submissionId,platform:n.platform,profile:i,buildId:t,dashboardUrl:o});return}}await mn({platform:n.platform,profile:i,buildProfile:i,buildId:t,projectId:e,yes:n.yes,quiet:n.quiet,track:n.submitTrack,releaseStatus:n.submitReleaseStatus,rollout:n.submitRollout,changesNotSentForReview:n.submitChangesNotSentForReview,credentialId:n.submitCredentialId,packageName:n.androidPackage,jsonOutput:n.submitJsonOutput,submitArgs:wo(n,t,i)})}catch(r){_.error($.red(`Auto-submit failed: ${r.message||r}`)),process.exitCode=1}}function wo(e,t,n){let i=["--platform",e.platform,"--profile",n,"--build-id",t];return e.submitTrack&&i.push("--track",String(e.submitTrack)),e.submitReleaseStatus&&i.push("--release-status",String(e.submitReleaseStatus)),e.submitRollout!==void 0&&i.push("--rollout",String(e.submitRollout)),e.submitChangesNotSentForReview&&i.push("--changes-not-sent-for-review"),e.submitCredentialId&&i.push("--credential-id",e.submitCredentialId),e.platform==="android"&&e.androidPackage&&i.push("--package-name",e.androidPackage),e.platform==="ios"&&e.iosBundleIdentifier&&i.push("--bundle-id",e.iosBundleIdentifier),e.submitJsonOutput&&i.push("--json-output",e.submitJsonOutput),i.join(" ")}async function Ud(e,t){try{let i=(await R.get(`/builds/${e}/${t}`)).data?.build;if(i?.autoSubmit)return i}catch(n){_.warn($.dim(`Could not check backend auto-submit status: ${n.message}`))}return null}function _o(e){for(let t of Object.keys(e))e[t]===void 0&&delete e[t];return e}function Bd(e,t,n){let i=n?.submit?.[t]?.android||{},r=n?.submit?.production?.android||{},o=e.submitTrack||i.track||r.track,s=e.submitReleaseStatus||i.releaseStatus||r.releaseStatus,l=e.submitRollout??i.rollout??i.userFraction??i.rolloutFraction??r.rollout??r.userFraction??r.rolloutFraction,a=e.submitChangesNotSentForReview??i.changesNotSentForReview??i.changes_not_sent_for_review??r.changesNotSentForReview??r.changes_not_sent_for_review;return _o({track:o,releaseStatus:s,rollout:l,changesNotSentForReview:a===void 0?!1:a===!0||a==="true"||a==="1"})}function go(e,t,n,i){if(!e.autoSubmit||e.dryRun)return{};let r=e.platform==="android"?Bd(e,n,i):{};return{autoSubmit:!0,autoSubmitStatus:"pending",autoSubmitOptions:_o({platform:e.platform,profile:n,buildId:t,latest:!1,...r,credentialId:e.submitCredentialId,packageName:e.platform==="android"?e.androidPackage:void 0,bundleId:e.platform==="ios"?e.iosBundleIdentifier:void 0,submitArgs:wo(e,t,n)})}}function ho(e){!e.autoSubmit||e.dryRun||e.quiet||(_.info($.green("\u2713 Auto-submit has been registered with the build.")),_.info($.dim(" You can close this terminal; submission will start after build success.")))}function yo(e){return`${Ke}/build/${e}`}function En(e,t){if(!e.jsonOutput)return;let n=$e.resolve(e.jsonOutput),i={...t,url:t.url||yo(t.buildId),dashboardUrl:t.dashboardUrl||yo(t.buildId),updatedAt:new Date().toISOString()};try{let r=$e.dirname(n);r&&r!=="."&&de.mkdirSync(r,{recursive:!0}),de.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){_.warn($.yellow(`Could not write build metadata JSON: ${r.message}`))}}async function Fd(e,t,n){let i=_i(),r="pending",o=0,s=0;for(n.quiet||i.start("Connecting to build stream...");;){try{let a=(await R.get(`/builds/${e}/${t}`)).data.build;if(a){if(r=a.status,r==="building")n.quiet||i.message("Build in progress...");else if(r==="failed")n.quiet||i.stop("Build failed."),En(n,{status:"failed",projectId:e,buildId:t,platform:n.platform,profile:a.buildProfile,buildType:a.buildType,developmentClient:!!a.developmentClient,version:a.version,summary:a.summary,error:a.error||"Unknown error",artifacts:a.artifacts||[]}),_.error($.red(`
|
|
1184
|
+
\u2717 Build failed: ${a.error||"Unknown error"}`)),process.exit(1);else if(r==="completed"||r==="success"){n.quiet||i.stop("Build successful!"),En(n,{status:r,projectId:e,buildId:t,platform:n.platform,profile:a.buildProfile,buildType:a.buildType,developmentClient:!!a.developmentClient,version:a.version,summary:a.summary,artifacts:a.artifacts||[]}),_.success($.green(`
|
|
1185
|
+
\u2713 Build completed successfully!`));try{n.quiet||(_.info($.magenta(`
|
|
1186
|
+
\u{1F4F1} Installation Hub:`)),_.info($.dim(" - View & Install Build: ")+$.white.underline(`${Ke}/build/${t}`)))}catch{}return}else if(r!=="pending"){n.quiet||i.stop(`Build status: ${r}`);return}}try{let c=(await R.get(`/builds/${e}/${t}/logs`)).data;if(c&&typeof c=="string"&&!n.quiet){let u=c.split(`
|
|
1187
|
+
`);if(u.length>o){for(let p=o;p<u.length;p++)u[p].trim()&&console.log($.dim(` ${u[p]}`));o=u.length}}}catch{}s=0}catch{s++,s>10&&(i.stop("Connection lost."),_.error($.red(`
|
|
1188
|
+
\u2717 Lost connection to Dashboard API.`)),process.exit(1))}await new Promise(l=>setTimeout(l,3e3))}}import*as $n from"http";import*as Do from"net";import{execFile as Hd,execFileSync as vn,execSync as gt,spawn as $o}from"child_process";import ce from"chalk";import{log as Z}from"@clack/prompts";import jd from"axios";import fe from"fs";import Be from"os";import ie from"path";var Xe=7070,jt=`http://127.0.0.1:${Xe}`,_t="com.radhya.mach.agent",wt="Mach Agent",$t=`${_t}.service`,Gd=5e3,Kd=3e3,An=null,In=null,Fe=()=>ie.join(Be.homedir(),f.configDir),Oo=()=>ie.join(Be.homedir(),"Library","LaunchAgents"),wn=()=>ie.join(Oo(),`${_t}.plist`),Co=()=>ie.join(Be.homedir(),".config","systemd","user"),vi=()=>ie.join(Co(),$t),Ri=()=>ie.join(Fe(),"agent.cmd");function Pi(){return`gui/${process.getuid?.()||Number(gt("id -u").toString().trim())}`}function No(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Ht(e){return`<string>${No(e)}</string>`}function Di(){let e=process.argv[1]?fe.realpathSync(process.argv[1]):"";if(!e||!fe.existsSync(e))throw new Error("Could not resolve the current Mach CLI entrypoint.");return[process.execPath,e,"agent","run"]}function Oi(){let e=To(),t=process.platform==="win32"?[process.env.SystemRoot?ie.join(process.env.SystemRoot,"System32"):void 0,process.env.SystemRoot]:["/opt/homebrew/bin","/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"],n={HOME:Be.homedir(),PATH:[process.env.PATH,...e.flatMap(i=>[ie.join(i,"platform-tools"),ie.join(i,"emulator"),ie.join(i,"cmdline-tools","latest","bin"),ie.join(i,"tools","bin")]),...t].filter(Boolean).join(ie.delimiter)};for(let i of["ANDROID_HOME","ANDROID_SDK_ROOT","JAVA_HOME","SHELL"])process.env[i]&&(n[i]=process.env[i]);return n}function To(){let e=[process.env.ANDROID_HOME,process.env.ANDROID_SDK_ROOT];if(process.platform==="darwin")e.push(ie.join(Be.homedir(),"Library","Android","sdk"));else if(process.platform==="linux")e.push(ie.join(Be.homedir(),"Android","Sdk"),ie.join(Be.homedir(),"Android","sdk"),"/opt/android-sdk","/usr/lib/android-sdk");else if(process.platform==="win32"){let t=process.env.LOCALAPPDATA,n=process.env.USERPROFILE||Be.homedir();e.push(t?ie.join(t,"Android","Sdk"):void 0,ie.join(n,"AppData","Local","Android","Sdk"))}return Array.from(new Set(e.filter(t=>!!t)))}function Vd(e){return process.platform==="win32"&&!e.toLowerCase().endsWith(".exe")?`${e}.exe`:e}function ko(e,t){let n=Vd(e);for(let i of To()){let r=ie.join(i,t,n);if(fe.existsSync(r))return r}return n}function Lo(){return ko("adb","platform-tools")}function xo(){return ko("emulator","emulator")}function $i(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}"`}function zd(){if(process.platform!=="linux")throw new Error("Linux service install requires Linux.");fe.mkdirSync(Fe(),{recursive:!0}),fe.mkdirSync(Co(),{recursive:!0});let e=Di(),t=Oi(),n=Object.entries(t).map(([r,o])=>`Environment=${$i(`${r}=${o}`)}`).join(`
|
|
1189
1189
|
`),i=`[Unit]
|
|
1190
1190
|
Description=Mach local device agent
|
|
1191
1191
|
After=default.target
|
|
1192
1192
|
|
|
1193
1193
|
[Service]
|
|
1194
1194
|
Type=simple
|
|
1195
|
-
ExecStart=${e.map(
|
|
1196
|
-
WorkingDirectory=${
|
|
1195
|
+
ExecStart=${e.map($i).join(" ")}
|
|
1196
|
+
WorkingDirectory=${$i(Be.homedir())}
|
|
1197
1197
|
${n}
|
|
1198
1198
|
Restart=on-failure
|
|
1199
1199
|
RestartSec=5
|
|
1200
|
-
StandardOutput=append:%h/${
|
|
1201
|
-
StandardError=append:%h/${
|
|
1200
|
+
StandardOutput=append:%h/${f.configDir}/agent.log
|
|
1201
|
+
StandardError=append:%h/${f.configDir}/agent.error.log
|
|
1202
1202
|
|
|
1203
1203
|
[Install]
|
|
1204
1204
|
WantedBy=default.target
|
|
1205
|
-
`;return
|
|
1206
|
-
`),l=i.map(
|
|
1205
|
+
`;return fe.writeFileSync(vi(),i),vi()}function ot(e,t={}){try{return vn("systemctl",["--user",...e],{stdio:t.ignoreError?"ignore":"pipe"}),!0}catch(n){if(t.ignoreError)return!1;throw n}}function Wd(){if(process.platform!=="win32")throw new Error("Windows agent script requires Windows.");fe.mkdirSync(Fe(),{recursive:!0});let e=Oi(),[t,n,...i]=Di(),r=ie.join(Fe(),"agent.log"),o=ie.join(Fe(),"agent.error.log"),s=Object.entries(e).map(([d,c])=>`set "${d}=${c}"`).join(`\r
|
|
1206
|
+
`),l=i.map(d=>`"${d.replace(/"/g,'\\"')}"`).join(" "),a=`@echo off\r
|
|
1207
1207
|
${s}\r
|
|
1208
|
-
cd /d "${
|
|
1208
|
+
cd /d "${Be.homedir()}"\r
|
|
1209
1209
|
"${t}" "${n}" ${l} >> "${r}" 2>> "${o}"\r
|
|
1210
|
-
`;return
|
|
1211
|
-
${
|
|
1212
|
-
`),o=e.map(l=>` ${
|
|
1210
|
+
`;return fe.writeFileSync(Ri(),a),Ri()}function Gt(e,t={}){try{return vn("schtasks.exe",e,{stdio:t.ignoreError?"ignore":"pipe"}),!0}catch(n){if(t.ignoreError)return!1;throw n}}function Yd(){if(process.platform!=="darwin")throw new Error("Background agent install currently supports macOS only.");fe.mkdirSync(Fe(),{recursive:!0}),fe.mkdirSync(Oo(),{recursive:!0});let e=Di(),t=Oi(),n=ie.join(Fe(),"agent.log"),i=ie.join(Fe(),"agent.error.log"),r=Object.entries(t).map(([l,a])=>` <key>${No(l)}</key>
|
|
1211
|
+
${Ht(a)}`).join(`
|
|
1212
|
+
`),o=e.map(l=>` ${Ht(l)}`).join(`
|
|
1213
1213
|
`),s=`<?xml version="1.0" encoding="UTF-8"?>
|
|
1214
1214
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
1215
1215
|
<plist version="1.0">
|
|
1216
1216
|
<dict>
|
|
1217
1217
|
<key>Label</key>
|
|
1218
|
-
${
|
|
1218
|
+
${Ht(_t)}
|
|
1219
1219
|
<key>ProgramArguments</key>
|
|
1220
1220
|
<array>
|
|
1221
1221
|
${o}
|
|
@@ -1227,26 +1227,28 @@ ${r}
|
|
|
1227
1227
|
<key>RunAtLoad</key>
|
|
1228
1228
|
<true/>
|
|
1229
1229
|
<key>StandardOutPath</key>
|
|
1230
|
-
${
|
|
1230
|
+
${Ht(n)}
|
|
1231
1231
|
<key>StandardErrorPath</key>
|
|
1232
|
-
${
|
|
1232
|
+
${Ht(i)}
|
|
1233
1233
|
</dict>
|
|
1234
1234
|
</plist>
|
|
1235
|
-
`;return
|
|
1236
|
-
`).forEach(n=>{if(n.includes("List of devices")||!n.trim())return;let i=n.split(/\s+/);if(i.length<2||i[1]!=="device")return;let r=i[0],o=n.match(/model:([^\s]+)/);e.push({id:r,platform:"android",type:r.startsWith("emulator-")?"emulator":"physical",name:o?o[1].replace(/_/g," "):r,status:"online",details:n.trim()})})}catch{}try{let n=(await
|
|
1237
|
-
`).filter(r=>!!r.trim()),i=e.some(r=>r.platform==="android"&&r.id.startsWith("emulator-"));n.forEach(r=>{i||e.push({id:r,platform:"android",type:"emulator",name:r.replace(/_/g," "),status:"offline",details:`Android Virtual Device: ${r}`})})}catch{}return e}async function Jc(){if(process.platform!=="darwin")return[];try{let e=await In("/usr/bin/xcrun",["simctl","list","devices","--json"]),t=JSON.parse(e),n=[];return Object.entries(t.devices||{}).forEach(([i,r])=>{r.forEach(o=>{o.isAvailable&&n.push({id:o.udid,platform:"ios",type:"simulator",name:o.name,status:o.state?.toLowerCase()==="booted"?"online":"offline",runtime:i,details:`${o.name} (${i})`})})}),n}catch{return[]}}async function qc(){if(process.platform!=="darwin")return[];try{let e=await In("/usr/bin/xcrun",["devicectl","list","devices","--json-output","-"]);return(JSON.parse(e).result?.devices||[]).filter(n=>{let i=n.connectionProperties?.transportType;return i==="wired"||i==="localNetwork"}).map(n=>{let i=n.connectionProperties?.transportType,r=n.deviceProperties?.name||"iPhone";return{id:n.identifier,platform:"ios",type:"physical",name:r,status:"online",details:`${r} (${n.model?.name||n.hardwareModel||""}) - ${i}`}})}catch{return[]}}async function Xc(){let[e,t,n]=await Promise.all([Yc(),Jc(),qc()]);return[...e,...t,...n]}async function Zc(){let e=Date.now();return bn&&e-bn.updatedAt<Nc?bn.targets:(En||(En=Xc().then(t=>(bn={targets:t,updatedAt:Date.now()},t)).finally(()=>{En=null})),En)}async function yo(e){let t=[];for await(let n of e)t.push(Buffer.isBuffer(n)?n:Buffer.from(n));return t.length===0?{}:JSON.parse(Buffer.concat(t).toString("utf-8"))}async function Qc(e,t){let n=await Oc({method:"GET",url:e,responseType:"stream",timeout:12e4}),i=me.createWriteStream(t);n.data.pipe(i),await new Promise((r,o)=>{i.on("finish",r),i.on("error",o)})}async function ed(e,t,n){let i=n||(t.toLowerCase().includes(".apk")?"android":"ios"),r=t.toLowerCase().includes(".ipa"),o=me.mkdtempSync(ne.join(xe.tmpdir(),`${Xe}-install-`)),s=ne.join(o,i==="android"?"install.apk":r?"install.ipa":"install.zip");try{if(await Qc(t,s),i==="android"){_n(_o(),["-s",e,"install","-r",s],{stdio:"pipe"});return}if(process.platform!=="darwin")throw new Error("iOS local install requires macOS.");gt(`unzip -o ${JSON.stringify(s)} -d ${JSON.stringify(o)}`,{stdio:"pipe"});let l="";try{l=gt(`find ${JSON.stringify(ne.join(o,"Payload"))} -maxdepth 1 -name "*.app" 2>/dev/null | head -n 1`,{stdio:"pipe"}).toString().trim()}catch{}if(l||(l=gt(`find ${JSON.stringify(o)} -name "*.app" -type d | head -n 1`,{stdio:"pipe"}).toString().trim()),!l)throw new Error(`No .app bundle found inside the ${r?"IPA":"archive"}.`);try{gt(`/usr/bin/xcrun devicectl device install app --device ${JSON.stringify(e)} ${JSON.stringify(l)}`,{stdio:"pipe"})}catch(a){try{gt(`/usr/bin/xcrun simctl install ${JSON.stringify(e)} ${JSON.stringify(l)}`,{stdio:"pipe"})}catch{throw new Error(a.stderr?.toString().trim()||a.message||"iOS install failed.")}}}finally{me.rmSync(o,{recursive:!0,force:!0})}}function td(e,t){if(!e)throw new Error("Device id is required.");if(t==="ios"){if(process.platform!=="darwin")throw new Error("iOS Simulator launch requires macOS.");return gt(`/usr/bin/xcrun simctl boot ${JSON.stringify(e)}`,{stdio:"pipe"}),mo("open",["-a","Simulator"],{detached:!0,stdio:"ignore"}).unref(),"Simulator booting..."}if(t==="android")return mo($o(),["-avd",e],{detached:!0,stdio:"ignore",windowsHide:!0}).unref(),"Emulator booting in background...";throw new Error("Invalid platform.")}async function nd(){process.platform!=="darwin"&&J.warn("Running on non-macOS \u2014 iOS discovery unavailable, Android only.");let e=wn.createServer((i,r)=>{if(r.setHeader("Access-Control-Allow-Origin","*"),r.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),r.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),i.method==="OPTIONS"){r.writeHead(204),r.end();return}let o=new URL(i.url||"/",`http://localhost:${Xe}`);if(i.method==="GET"&&o.pathname==="/local/devices"){Zc().then(s=>{r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"success",targets:s}))}).catch(s=>{r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"error",message:s.message}))});return}if(i.method==="GET"&&o.pathname==="/health"){r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"success",service:"mach-agent",port:Xe,platform:process.platform}));return}if(i.method==="POST"&&o.pathname==="/install-local"){t(i,r);return}if(i.method==="POST"&&o.pathname==="/local/boot"){n(i,r);return}r.writeHead(404),r.end()}),t=async(i,r)=>{try{let{deviceId:o,artifactUrl:s,platform:l}=await yo(i);if(!o||!s){r.writeHead(400,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"error",message:"deviceId and artifactUrl are required"}));return}await ed(o,s,l),r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"success",message:`Installed on ${o}`}))}catch(o){r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"error",message:o.message||"Local install failed"}))}},n=async(i,r)=>{try{let{id:o,platform:s}=await yo(i),l=td(o,s);r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"success",message:l}))}catch(o){r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"error",message:o.message||"Local device launch failed"}))}};e.listen(Xe,"127.0.0.1",()=>{J.success(ue.green(`Local device agent running on http://localhost:${Xe}`)),J.info(ue.dim("Keep this running while using the Install Hub on the dashboard.")),J.info(ue.dim("Press Ctrl+C to stop."))}),e.on("error",i=>{i.code==="EADDRINUSE"?J.error(`Port ${Xe} is already in use \u2014 agent may already be running.`):J.error(`Agent error: ${i.message}`),process.exit(1)}),await new Promise(()=>{})}async function Oo(e="start"){let t=String(e||"start").toLowerCase();if(t==="start"||t==="run"){await nd();return}if(t==="install"){await go();return}if(t==="status"){await Wc();return}if(t==="stop"){await ho();return}if(t==="uninstall"){await zc();return}if(t==="restart"){await ho(),await go();return}J.error(`Unknown agent action: ${e}`),J.info(ue.dim(`Use: ${m.nameLower} agent start | install | status | restart | stop | uninstall`)),process.exit(1)}import{createRequire as Ou}from"module";import{text as rd,password as od,spinner as sd,isCancel as To}from"@clack/prompts";import Ti from"chalk";import Gt from"fs";import Co from"path";import id from"os";var Oi=Co.join(id.homedir(),m.configDir),Ci=Co.join(Oi,"config.json");function Ni(){if(!Gt.existsSync(Ci))return{};try{return JSON.parse(Gt.readFileSync(Ci,"utf-8"))}catch{return{}}}function No(e){Gt.existsSync(Oi)||Gt.mkdirSync(Oi,{recursive:!0});let n={...Ni(),...e};Gt.writeFileSync(Ci,JSON.stringify(n,null,2))}async function ko(){let e=Ni(),t=await rd({message:"Enter your email:",placeholder:"user@example.com",initialValue:e.lastLoginEmail,validate(r){if(r.length===0)return"Email is required!"}});if(To(t))return;let n=await od({message:"Enter your password:",validate(r){if(r.length===0)return"Password is required!"}});if(To(n))return;let i=sd();i.start("Authenticating...");try{let o=await(await fetch(`${yt}/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:t,password:n})})).json();o.status==="success"&&o.user.token?(Hi({id:o.user.id,email:t,token:o.user.token,refreshToken:o.user.refreshToken}),No({lastLoginEmail:t}),i.stop(Ti.green("Login successful!"))):i.stop(Ti.red("Login failed: "+(o.message||"Unknown error")))}catch(r){i.stop(Ti.red("Network error: "+r.message))}}import{log as $n,outro as ad}from"@clack/prompts";import Kt from"chalk";async function Lo(){let e=ji(),t=`${m.envPrefix}TOKEN`;e?$n.success(Kt.green(`Logged out. Removed saved credentials from ~/${m.configDir}/credentials.json.`)):$n.warn(Kt.yellow(`No saved ${m.name} credentials found.`)),process.env[t]&&($n.warn(Kt.yellow(`${t} is still set in this shell. Commands will continue to authenticate with that token until you unset it.`)),$n.info(Kt.dim(`Run: unset ${t}`))),ad(Kt.blue("---"))}import{outro as ld,select as cd,spinner as dd,isCancel as ud}from"@clack/prompts";import Pn from"chalk";import ki from"fs";import pd from"path";var xo=e=>e==="1234567890"||e==="ABC123DEFG"||e==="XXXXXXXXXX"?"":typeof e=="string"?e:"",fd=()=>process.versions.node.split(".")[0]||"24";async function Mo(){if(!Pe()){console.log(Pn.red(`You are not logged in. Run \`${m.nameLower} login\` first.`));return}let t=dd();t.start("Fetching projects...");try{let{data:n}=await v.get("/projects");if(t.stop("Projects loaded."),n.status!=="success"||!n.projects||n.projects.length===0){console.log(Pn.yellow(`No projects found. Run \`${m.nameLower} init\` to create one.`));return}let i=n.projects.map(S=>({value:S.projectId,label:`${S.name} (${S.slug})`})),r=await cd({message:"Select a project to link:",options:i});if(ud(r))return;let o=pd.join(process.cwd(),m.configFileName),s={};if(ki.existsSync(o))try{s=JSON.parse(ki.readFileSync(o,"utf-8"))}catch{}let l=n.projects.find(S=>S.projectId===r),a=s.android?.package||qe("android"),c=s.ios?.bundleIdentifier||qe("ios"),d=s.android||{},u=s.submit?.production?.android||{},p=s.submit?.production?.ios||{},f={projectId:r,name:l?.name,slug:l?.slug,nodeVersion:s.nodeVersion||fd(),scheme:l?.slug?.toLowerCase()||"app",android:{...d,package:a||"",versionCode:d.versionCode||"auto"},ios:{bundleIdentifier:c||"",buildNumber:s.ios?.buildNumber||"auto"},build:{development:{environment:"development",distribution:"development"},staging:{environment:"staging",distribution:"internal"},production:{environment:"production",distribution:"store"}},submit:{production:{android:{...u,track:u.track||"internal",releaseStatus:u.releaseStatus||"completed"},ios:{ascAppId:xo(p.ascAppId),appleTeamId:xo(p.appleTeamId)}}}};ki.writeFileSync(o,JSON.stringify(f,null,2)),ld(Pn.green(`Linked to project ${f.name} (${f.slug})`))}catch(n){t.stop(Pn.red("Error fetching projects: "+n.message))}}import{outro as md,text as Rn,select as gd,spinner as hd,isCancel as Vt}from"@clack/prompts";import zt from"chalk";import yd from"fs";import Sd from"path";import{randomUUID as bd}from"crypto";var Ed=()=>process.versions.node.split(".")[0]||"24";async function Uo(){if(!Pe()){console.log(zt.red(`You are not logged in. Run \`${m.nameLower} login\` first.`));return}let t=await Rn({message:"Project Name:",placeholder:"My Awesome App",validate(l){if(l.length===0)return"Name is required!"}});if(Vt(t))return;let n=await Rn({message:"Project Slug (URL friendly):",placeholder:"my-awesome-app",validate(l){if(l.length===0)return"Slug is required!";if(!/^[a-z0-9-]+$/.test(l))return"Slug must be lowercase alphanumeric with dashes."}});if(Vt(n))return;let i=await gd({message:"Platform:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"},{value:"web",label:"Web"},{value:"all",label:"All Platforms"}]});if(Vt(i))return;let r="";if(i==="android"||i==="all"){let l=qe("android");if(r=await Rn({message:"Android Package Name:",initialValue:l||"",placeholder:"com.example.app",validate(a){if(a.length===0)return"Package name is required for Android!"}}),Vt(r))return}let o="";if(i==="ios"||i==="all"){let l=qe("ios");if(o=await Rn({message:"iOS Bundle Identifier:",initialValue:l||"",placeholder:"com.example.app",validate(a){if(a.length===0)return"Bundle ID is required for iOS!"}}),Vt(o))return}let s=hd();s.start("Creating project...");try{let l=bd(),c={projectId:l,name:t,slug:n,storageType:"managed",platforms:i==="all"?["android","ios","web"]:[i]},{data:d}=await v.post("/projects",c);if(d.status==="success"){s.stop(zt.green("Project created successfully!"));let u=Sd.join(process.cwd(),m.configFileName);yd.writeFileSync(u,JSON.stringify({projectId:l,name:t,slug:n,nodeVersion:Ed(),...r?{android:{package:r,versionCode:"auto"}}:{},...o?{ios:{bundleIdentifier:o,buildNumber:"auto"}}:{},build:{development:{environment:"development",distribution:"development"},staging:{environment:"staging",distribution:"internal"},production:{environment:"production",distribution:"store"}},submit:{production:{android:{track:"internal",releaseStatus:"completed"},ios:{ascAppId:"",appleTeamId:""}}}},null,2)),md(zt.green(`Initialized project ${t} and linked locally!`))}else s.stop(zt.red("creation failed: "+d.message))}catch(l){s.stop(zt.red("Network error: "+l.message))}}import{spinner as Fo,log as De}from"@clack/prompts";import vn from"chalk";import Bo from"fs";import Ad from"path";function Ho(e,t,n,i){let r=e?.response?.status,o=e?.response?.data?.message||e?.response?.data?.error,s=i?` ${i}`:"";return r===401?`Not logged in or token expired while trying to ${n}${s}. Run \`${m.nameLower} login\` and try again.`:r===403?[`Permission denied while trying to ${n}${s}.`,o?`API says: ${o}.`:void 0,`Current Mach account/token does not have access to project ${t}.`,`Run \`${m.nameLower} login\` with the correct account, or ask a project owner to grant access.`].filter(Boolean).join(" "):r===404?[`Project or environment endpoint was not found while trying to ${n}${s}.`,`Project ID: ${t}.`,o?`API says: ${o}.`:void 0].filter(Boolean).join(" "):r?`Failed to ${n}${s}: ${o||`API returned HTTP ${r}`}`:`Network error while trying to ${n}${s}: ${e?.message||"Unknown error"}`}async function jo(e,t){let n=Pe();if(!n){De.error(`You are not logged in. Run \`${m.nameLower} login\` first.`);return}let i=Ad.join(process.cwd(),m.configFileName);if(!Bo.existsSync(i)){De.error(`No ${m.configFileName} found. Run \`${m.nameLower} init\` or \`${m.nameLower} link\` first.`);return}let r;try{r=JSON.parse(Bo.readFileSync(i,"utf-8"))}catch{De.error(`Failed to parse ${m.configFileName}`);return}let{projectId:o}=r;if(!o){De.error(`${m.configFileName} is missing projectId.`);return}e==="set"?await Id(o,t,n):e==="list"?await wd(o,n):De.error(`Unknown env action: ${e}. Use 'set' or 'list'.`)}async function Id(e,t,n){if(t.length===0){De.error(`Usage: ${m.nameLower} env set KEY=VALUE [KEY2=VALUE2 ...]`);return}let i=Fo();i.start("Setting environment variables...");let r=0,o=0;for(let s of t){let[l,...a]=s.split("="),c=a.join("=");if(!l||c===void 0){De.warn(`Invalid format for argument: ${s}. Expected KEY=VALUE.`),o++;continue}try{let d={key:l.trim(),value:c,type:"env",environment:"global",visibility:"secret"},{data:u}=await v.post(`/projects/${e}/secrets`,d);u.status==="success"?r++:(De.error(`Failed to set ${l}: ${u.message}`),o++)}catch(d){De.error(Ho(d,e,"set",l)),o++}}i.stop(`Set ${r} variable(s). ${o>0?`${o} failed.`:""}`)}async function wd(e,t){let n=Fo();n.start("Fetching environment variables...");try{let{data:i}=await v.get(`/projects/${e}/secrets`);if(i.status==="success"){n.stop("Fetched variables.");let r=i.secrets||[];r.length===0?De.info("No environment variables found for this project."):(De.info(vn.bold("Environment Variables (Global & Scoped):")),r.forEach(o=>{let s=o.visibility==="plain"?o.value:"********";console.log(` ${vn.cyan(o.key)} = ${s} ${vn.gray(`[${o.environment}]`)}`)}))}else n.stop(vn.red(`Failed to fetch variables: ${i.message}`))}catch(i){n.stop("Failed to fetch variables."),De.error(Ho(i,e,"list"))}}import{spinner as _d,log as ht,outro as $d}from"@clack/prompts";import Li from"chalk";import Go from"fs";import Pd from"path";import{execSync as Rd}from"child_process";import vd from"adm-zip";import Dd from"axios";import{randomUUID as Od}from"crypto";async function Ko(e){ht.info(Li.magenta("\u{1F680} Starting Over-The-Air (OTA) Update via Mach..."));let t=Te();(!t||!t.projectId)&&(ht.error(`No ${m.configFileName} found or missing projectId. Run \`mach link\` first.`),process.exit(1));let n=t.projectId,i=e.branch||"production",r="1.0.0";try{r=JSON.parse(Go.readFileSync("./package.json","utf-8")).version||"1.0.0"}catch{ht.warn("Could not read package.json version. Defaulting to 1.0.0")}let o=_d();o.start(`Compiling JavaScript bundles for OTA (Channel: ${i}, Runtime: ${r})...`);try{Rd("npx expo export --platform all",{stdio:"ignore"})}catch(c){o.stop("Compilation failed."),ht.error(`Failed to export JS bundles using Expo: ${c.message}`),process.exit(1)}o.message("Zipping artifact payload...");let s=Pd.join(process.cwd(),"dist");Go.existsSync(s)||(o.stop("Missing dist folder."),ht.error("The `dist` directory was not created. Export failed."),process.exit(1));let l=new vd;l.addLocalFolder(s,"dist");let a=l.toBuffer();o.message("Uploading payload to Mach Cloud...");try{let c=Od(),d=await v.post("/builds/source-upload-url",{projectId:n,buildId:c});if(d.data.status!=="success")throw new Error("Could not secure upload bucket URL");let{uploadUrl:u,key:p}=d.data;await Dd.put(u,a,{headers:{"Content-Type":"application/zip"},maxBodyLength:1/0,maxContentLength:1/0}),o.message(`Promoting Update to ${i}...`),await v.post("/updates/publish",{projectId:n,channelName:i,runtimeVersion:r,platform:"android",updateId:`${c}-android`,manifestKey:p}),await v.post("/updates/publish",{projectId:n,channelName:i,runtimeVersion:r,platform:"ios",updateId:`${c}-ios`,manifestKey:p}),o.stop("Update Live!"),$d(Li.green(`\u2713 OTA Update natively shipped to the '${i}' channel.`)),ht.info(Li.dim(`Any app running runtime '${r}' will download this bundle smoothly.`))}catch(c){o.stop("Update failed during Cloud Sync."),ht.error(`Upload error: ${c.message}`),process.exit(1)}}import{intro as Cd,outro as Vo,log as Pt}from"@clack/prompts";import Ve from"chalk";async function zo(){Cd(Ve.blue(`${m.name} CLI - User Profile`));let e=Pe();if(!e){Pt.warn(Ve.yellow("You are not logged in.")),Pt.info(`Run \`${m.nameLower} login\` to authenticate.`),Vo();return}Pt.info(`${Ve.bold("Logged in as:")} ${Ve.green(e.email)}`);try{await v.get("/projects");let n=Pe().token.split(".");if(n.length===3){let i=JSON.parse(Buffer.from(n[1],"base64").toString());if(i.exp){let r=new Date(i.exp*1e3),o=new Date,s=r.getTime()-o.getTime();if(s>0){let l=Math.round(s/6e4),a=(l/60).toFixed(1);Pt.info(`${Ve.bold("Token status:")} Valid (Expires in ~${a}h / ${l}m)`)}else Pt.warn(`${Ve.bold("Token status:")} ${Ve.red("Expired")} (Auto-refresh failed)`)}}}catch{Pt.warn(`${Ve.bold("Token status:")} ${Ve.red("Unreachable")} (Session might be truly expired)${yt}`)}Vo(Ve.blue("---"))}import{spawn as kd}from"child_process";import{log as st}from"@clack/prompts";import Oe from"chalk";import Ld from"fs";import Nd from"net";async function Td(e){return new Promise(t=>{let n=Nd.createServer();n.once("error",i=>{i.code==="EADDRINUSE"?t(!0):t(!1)}),n.once("listening",()=>{n.close(),t(!1)}),n.listen(e,"0.0.0.0")})}async function Wo(e,t=20){let n=e;for(;n<e+t;){if(!await Td(n))return n;n++}throw new Error(`Could not find an available port after ${t} attempts starting from ${e}.`)}var Yo=async e=>{st.info(Oe.blue(`Starting ${m.name} Dev Orchestrator...`));let t=Te(),n=e.buildProfile||"development",i=t?Qe(t,n):null,r={...process.env};if(t?.projectId)try{st.info(Oe.dim(`Fetching managed secrets for profile: ${n}...`));let u=await v.get(`/projects/${t.projectId}/secrets/export?env=${n}`);u.data?.status==="success"&&u.data.secrets&&(Object.assign(r,u.data.secrets),st.info(Oe.magenta(`\u2713 Injected secrets from ${m.name} Dashboard.`)))}catch{st.warn("Could not fetch managed secrets. Running with local env only.")}t&&Object.assign(r,St(t,m.envPrefix)),i&&(Object.assign(r,St(i,`${m.envPrefix}PROFILE_`)),i.env&&Object.assign(r,i.env));let o=!1;try{let u=JSON.parse(Ld.readFileSync("package.json","utf-8"));o=!!(u.dependencies?.expo||u.devDependencies?.expo)}catch{st.warn("Could not parse package.json. Defaulting to Bare React Native mode.")}let s=Number(e.port||i?.port||8081),l=await Wo(s);l!==s&&st.info(Oe.yellow(`Port ${s} is busy. ${m.name} is using ${l} instead.`));let a=process.platform==="win32"?"npx.cmd":"npx",c=[];if(o?(c=["expo","start","--port",String(l)],e.clear&&c.push("--clear"),e.tunnel&&c.push("--tunnel"),e.lan&&c.push("--lan"),e.localhost&&c.push("--localhost"),e.ios&&c.push("--ios"),e.android&&c.push("--android"),e.web&&c.push("--web")):(c=["react-native","start","--port",String(l)],e.clear&&c.push("--clear")),o){let u=[`${Oe.cyan("i")} open iOS simulator`,`${Oe.cyan("a")} open Android emulator/device`,`${Oe.cyan("w")} open web`,`${Oe.cyan("r")} reload app`];st.info([Oe.bold("Launch controls"),...u.map(p=>` ${p}`),"",Oe.dim("Direct launch: mach start --ios | --android | --web"),Oe.dim(`Metro URL: http://localhost:${l}`)].join(`
|
|
1238
|
-
`)
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
`),"
|
|
1243
|
-
|
|
1244
|
-
`),
|
|
1245
|
-
`),d=
|
|
1246
|
-
`),
|
|
1247
|
-
`)
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
`));for(let a of s)he.error(pe.red(`${pe.bold(a.name)} ${pe.dim(`(${a.arch})`)}`)),he.info(pe.dim(` PT_LOAD alignment: 2**${Math.log2(a.align)} (${a.align} bytes, needs 2**14 = ${Is})`))}return l.length>0&&(console.log(""),he.success(pe.green(`${l.length} librar${l.length===1?"y":"ies"} correctly aligned (2**14 or higher).`))),console.log(""),s.length===0?(he.success(pe.green.bold("ELF Verification Successful. APK is 16KB compatible.")),!0):(he.error(pe.red.bold(`Found ${s.length} unaligned lib${s.length===1?"":"s"} (arm64-v8a/x86_64 libs need to be aligned).`)),console.log(""),he.info(pe.yellow("To fix this:")),he.info(pe.dim(" 1. Rebuild with NDK r28+ which defaults to 16KB page alignment")),he.info(pe.dim(" 2. Or set -DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON in CMake")),he.info(pe.dim(" 3. Update third-party libraries that ship prebuilt .so files")),he.info(pe.dim(" 4. After rebuilding: zipalign -p -f -v 16 input.apk output.apk")),console.log(""),he.info(pe.dim("Reference: https://developer.android.com/guide/practices/page-sizes")),!1)}catch(r){return n.stop("Analysis failed."),he.error(pe.red(`Failed to analyze APK: ${r.message}`)),!1}finally{try{Ze.rmSync(i,{recursive:!0,force:!0})}catch{}}}function Eu(e){let t=Ze.openSync(e,"r");try{let n=Buffer.alloc(64);if(Ze.readSync(t,n,0,64,0),!n.subarray(0,4).equals(bu))return null;let i=n[4]===2,r=n[5]===1,o=(p,f)=>r?p.readUInt16LE(f):p.readUInt16BE(f),s=(p,f)=>r?p.readUInt32LE(f):p.readUInt32BE(f),l=(p,f)=>Number(r?p.readBigUInt64LE(f):p.readBigUInt64BE(f)),a,c,d;i?(a=l(n,32),c=o(n,54),d=o(n,56)):(a=s(n,28),c=o(n,42),d=o(n,44));let u=null;for(let p=0;p<d;p++){let f=Buffer.alloc(c);if(Ze.readSync(t,f,0,c,a+p*c),s(f,0)!==Su)continue;let L;i?L=l(f,48):L=s(f,28),L>0&&(u===null||L<u)&&(u=L)}return u??0}catch{return null}finally{Ze.closeSync(t)}}function _s(e){let t=[];if(!Ze.existsSync(e))return t;let n=Ze.readdirSync(e,{withFileTypes:!0});for(let i of n){let r=vt.join(e,i.name);i.isDirectory()?t.push(..._s(r)):i.name.endsWith(".so")&&t.push(r)}return t}function Au(e){return e.includes("arm64-v8a")?"arm64-v8a":e.includes("x86_64")?"x86_64":"unknown"}var Rs=async e=>{if(Pe()||(Ne.error(He.red(`You are not logged in. Run \`${m.nameLower} login\` first.`)),process.exit(1)),e.apk){await _u(e);return}let n=process.cwd(),i=Bn.join(n,"package.json");Qt.existsSync(i)||(Ne.error(He.red("No package.json found. Run this command from a project root.")),process.exit(1));let r=JSON.parse(Qt.readFileSync(i,"utf-8")),o=!!(r.dependencies?.expo||r.devDependencies?.expo);e.json||(Ne.info(He.dim(`Project: ${r.name||"unknown"} v${r.version||"0.0.0"}`)),Ne.info(He.dim(`Type: ${o?"Expo":"Bare React Native"}`)),Ne.info(""));let s={json:e.json,fix:e.fix,category:e.category,severity:e.severity,prebuild:e.prebuild},l=await bs(n,s);e.json?console.log(JSON.stringify(As(l,r),null,2)):Es(l,e.severity);let a=l.some(d=>d.findings.some(u=>u.severity==="critical")),c=l.some(d=>d.findings.some(u=>u.severity==="high"));(a||c)&&process.exit(1)},$s=["16kb"];async function _u(e){let t=e.category?.toLowerCase();t&&!$s.includes(t)&&(Ne.error(He.red(`Unknown APK check category: "${t}"`)),Ne.info(He.dim(`Available APK checks: ${$s.join(", ")}`)),process.exit(1));let n=await $u(e.apk);n||process.exit(1);let i=!t,r=!1;(i||t==="16kb")&&(await ws(n)||(r=!0)),r&&process.exit(1)}async function $u(e){if(e.startsWith("build:")){let n=e.slice(6);return await Pu(n)}if(e.startsWith("http://")||e.startsWith("https://"))return await vs(e);let t=Bn.resolve(e);return Qt.existsSync(t)?t:(Ne.error(He.red(`APK file not found: ${t}`)),null)}async function Pu(e){let t=Ps();t.start(`Fetching APK from build ${e}...`);try{let n=await v.get(`/build/${e}`);if(n.data.status!=="success")throw new Error(n.data.message);let i=n.data.build;if(!i)throw new Error("Build not found");let r=i.artifacts?.find(o=>o.type?o.type==="apk":o.name?.endsWith(".apk")||o.url?.includes(".apk"));return!r||!r.url?(t.stop("No APK artifact found"),Ne.error(He.red("This build does not have an APK artifact.")),Ne.info(He.dim("Make sure the build produced an APK (not just an AAB).")),null):(t.stop(`Found build: ${i.buildId||e}`),await vs(r.url))}catch(n){return t.stop("Failed to fetch build"),Ne.error(He.red(n.message)),null}}async function vs(e){let t=Ps();t.start("Downloading APK...");try{let n=Qt.mkdtempSync(Bn.join(Iu.tmpdir(),`${m.nameLower}-audit-`)),i=Bn.join(n,"app.apk"),r=await wu.get(e,{responseType:"arraybuffer"});Qt.writeFileSync(i,r.data);let o=(r.data.length/(1024*1024)).toFixed(1);return t.stop(`Downloaded APK (${o} MB)`),i}catch(n){return t.stop("Download failed"),Ne.error(He.red(`Failed to download APK: ${n.message}`)),null}}var Du=console.log;console.log=()=>{};vu();console.log=Du;Ie(be.bgCyan.black(m.cliTag("Production Build Orchestrator")));var Cu=Ou(import.meta.url),Nu=Cu("../package.json"),ie=new Ru;ie.name(m.nameLower).description(`${m.name} CLI: Powerful Cloud Infrastructure Tools`).version(Nu.version).option("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1);ie.command("agent").description("Manage local device discovery agent for the Install Hub (port 7070)").argument("[action]","start, run, install, status, restart, stop, or uninstall","start").action(async e=>{await Oo(e)});ie.command("host").description("Setup AWS S3 static hosting and CloudFront").action(async()=>{Ie(be.bgCyan.black(m.cliTag("Hosting"))),await Yi()});ie.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=>{Ie(be.bgCyan.black(m.cliTag("Sitemap Generator"))),await Zi(e)});ie.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 ze("--build-id <id>","Internal build ID").hideHelp()).addOption(new ze("--project-id <id>","Internal project ID").hideHelp()).addOption(new ze("--fail-only","Internal: mark an existing build failed").hideHelp()).addOption(new ze("--error <message>","Internal failure message").hideHelp()).option("--local","Run build on local machine").option("--auto-version","Automatically fetch and increment Android versionCode or iOS buildNumber from the store").option("--auto-submit","Submit this build after it completes successfully").option("--submit-track <track>","Google Play track to use with --auto-submit").option("--submit-release-status <status>","Google Play release status to use with --auto-submit").option("--submit-rollout <fraction>","Google Play staged rollout fraction to use with --auto-submit").option("--submit-changes-not-sent-for-review","Commit Google Play changes without automatically sending them for review when using --auto-submit").option("--submit-credential-id <id>","Service credential ID to use with --auto-submit").option("--submit-json-output <path>","Write auto-submit metadata JSON to a file for CI/CD").option("--verbose","Enable verbose logging").option("--json-output <path>","Write build metadata JSON to a file for CI/CD").option("--maestro","Queue a managed Maestro test run after a successful build").option("--maestro-flows <path>","Maestro flow file or directory (default: .maestro)").option("--maestro-device <device>","Managed Maestro device profile").option("--maestro-retries <n>","Retries for the Maestro run","1").option("--maestro-record","Enable screen recording where supported").option("--maestro-use-build-source","Use Maestro flows from the build source snapshot instead of uploading local flows").option("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1).action(async(e,t)=>{let n=ie.opts();t.yes=t.yes||n.yes,t.quiet=t.quiet||n.quiet,t.platform=e||t.platform,t.buildProfile=t.profile||t.buildProfile,t.quiet||Ie(be.bgCyan.black(m.cliTag("Cloud Build"))),await yn(t)});ie.command("maestro").description("Run Maestro tests locally or with the managed Mach runner").option("--platform <os>","Target platform (android/ios)").option("-p, --profile <name>","Build profile to resolve when using --latest","production").option("--latest","Use the latest successful build for the platform/profile").option("--build-id <id>","Use a specific Mach build ID").option("--build-url <url>","Use a Mach build URL").option("--artifact-url <url>","Use a direct APK or iOS simulator app artifact URL").option("--local","Run Maestro on a connected local emulator/device instead of the managed runner").option("--maestro-flows <path>","Maestro flow file or directory (default: .maestro)").option("--maestro-device <device>","Managed Maestro device profile").option("--maestro-retries <n>","Retries for the Maestro run","1").option("--maestro-record","Enable screen recording where supported").option("--maestro-use-build-source","Use Maestro flows from the build source snapshot instead of uploading local flows").option("--wait","Wait for managed Maestro completion and exit non-zero on failure").option("--wait-timeout <minutes>","Maximum minutes to wait for managed Maestro completion","60").option("--wait-interval <seconds>","Polling interval while waiting for managed Maestro completion","15").option("--json-output <path>","Write test run metadata JSON to a file for CI/CD").addOption(new ze("--local-runner","Internal: execute a managed Maestro run on this machine").hideHelp()).addOption(new ze("--test-run-id <id>","Internal test run ID").hideHelp()).addOption(new ze("--project-id <id>","Internal project ID").hideHelp()).addOption(new ze("--runner-token <token>","Internal runner token").hideHelp()).action(async e=>{Ie(be.bgCyan.black(m.cliTag("Maestro Testing"))),await Dr(e)});ie.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=>{Ie(be.bgCyan.black(m.cliTag("OTA Update"))),await Ko(e)});ie.command("submit").description("Automated Store Submission (App Store / Google Play)").option("--platform <os>","Target platform (ios/android)").option("-p, --profile <name>","Build/submission profile to submit from (e.g. production, preprod)").option("--track <track>","Google Play Track (internal, alpha, beta, production)").option("--release-status <status>","Google Play release status (completed, draft, halted, inProgress)").option("--rollout <fraction>","Google Play staged rollout fraction for inProgress releases (example: 0.1)").option("--changes-not-sent-for-review","Commit Google Play changes without automatically sending them for review").option("--ssh-host <host>","Remote macOS host for iOS submission").option("--ssh-user <user>","SSH username for remote iOS submission").option("--ssh-key <path>","Path to private SSH key for remote iOS submission").option("--credential-id <id>","Service credential ID to use when multiple submission credentials exist").option("--local","Run submission on this machine (internal runner mode for iOS)").addOption(new ze("--submit-id <id>","Internal submission ID").hideHelp()).addOption(new ze("--project-id <id>","Internal project ID").hideHelp()).option("--json-output <path>","Write submission metadata JSON to a file for CI/CD").option("--latest","Use the latest successful build for submission").option("--build-id <id>","Use a specific build ID for submission").action(async e=>{let t=ie.opts();e.quiet=e.quiet||t.quiet,e.yes=e.yes||t.yes,Ie(be.bgCyan.black(m.cliTag("Store Submission"))),await pn(e)});ie.command("login").description(`Login to ${m.name} Dashboard`).action(async()=>{Ie(be.bgCyan.black(m.cliTag("Login"))),await ko()});ie.command("logout").description(`Logout from ${m.name} on this machine`).action(async()=>{Ie(be.bgCyan.black(m.cliTag("Logout"))),await Lo()});ie.command("link").description(`Link local directory to a ${m.name} Project`).action(async()=>{Ie(be.bgCyan.black(m.cliTag("Link Project"))),await Mo()});ie.command("me").description("Display currently logged in user details").action(async()=>{await zo()});ie.command("init").description(`Create a new ${m.name} Project`).action(async()=>{Ie(be.bgCyan.black(m.cliTag("Init Project"))),await Uo()});ie.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,t)=>{Ie(be.bgCyan.black(m.cliTag("Env Manager"))),await jo(e,t)});ie.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=>{Ie(be.bgCyan.black(m.cliTag("Dev Server"))),await Yo(e)});ie.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 Jo(e)});ie.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:t}=await import("./credentials-G45XNNRU.js");await t(e)});ie.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=>{Ie(be.bgCyan.black(m.cliTag("Credentials Setup"))),await Ot(e),Ds(be.green("Done!"))});ie.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)").option("--bundle-id <id>","Bundle identifier / Android package name to attach this service credential to").option("--package-name <name>","Android package name to attach this service credential to").option("-p, --profile <name>","Build profile to resolve package/bundle identifier from config").action(async e=>{Ie(be.bgCyan.black(m.cliTag("Service Credentials"))),await zi(e),Ds(be.green("Done!"))});var Bi=ie.command("device").description("Manage registered iOS test devices");Bi.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 Dn("register",e)});Bi.command("list").description("List all registered devices").action(async()=>{await Dn("list",{})});Bi.command("remove").description("Remove a registered device").option("--udid <udid>","Device UDID to remove").action(async e=>{await Dn("remove",e)});ie.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=>{Ie(be.bgCyan.black(m.cliTag(e.apk?"APK Audit":"Security Audit"))),await Rs(e)});var Tu=new Set(["login","logout","agent"]);ie.hook("preAction",(e,t)=>{let n=t.name(),i=t.opts?.()||{};n==="maestro"&&(i.local||i.localRunner)||Tu.has(n)||Gi()});ie.on("command:*",()=>{console.error(`Invalid command: %s
|
|
1252
|
-
|
|
1235
|
+
`;return fe.writeFileSync(wn(),s),wn()}function rt(e,t={}){try{return vn("launchctl",e,{stdio:t.ignoreError?"ignore":"pipe"}),!0}catch(n){if(t.ignoreError)return!1;throw n}}function Jd(e){return new Promise(t=>setTimeout(t,e))}function _n(e,t,n=Gd){return new Promise((i,r)=>{Hd(e,t,{timeout:n,maxBuffer:10*1024*1024,windowsHide:!0},(o,s,l)=>{if(o){let a=l?.toString().trim();r(new Error(a||o.message));return}i(s?.toString()||"")})})}async function Mo(){if(typeof fetch=="function"){let e=new AbortController,t=setTimeout(()=>e.abort(),3e3);try{return(await fetch(`${jt}/health`,{signal:e.signal})).ok}catch{return!1}finally{clearTimeout(t)}}return new Promise(e=>{let t=!1,n=r=>{t||(t=!0,e(r))},i=$n.get(`${jt}/health`,r=>{r.resume(),n(r.statusCode===200)});i.setTimeout(3e3,()=>{i.destroy(),n(!1)}),i.on("error",()=>n(!1))})}async function qd(e=8e3){let t=Date.now()+e;for(;Date.now()<t;){if(await Mo())return!0;await Jd(250)}return!1}async function Uo(){return new Promise(e=>{let t=!1,n=Do.createConnection({host:"127.0.0.1",port:Xe}),i=r=>{t||(t=!0,n.destroy(),e(r))};n.setTimeout(1e3),n.once("connect",()=>i(!0)),n.once("timeout",()=>i(!1)),n.once("error",()=>i(!1))})}async function Ci(){if(await qd()){Z.success(ce.green("Mach agent installed and started."));return}if(await Uo()){Z.warn(`Mach agent service is installed, but port ${Xe} is held by a process that is not answering /health.`),Z.info(ce.dim(`Run \`${f.nameLower} agent stop\`, close any foreground \`${f.nameLower} agent\` terminal, then run \`${f.nameLower} agent install\` again.`));return}Z.warn(`Mach agent service is installed, but it did not start listening on ${jt}.`)}async function Xd(){let e=Yd(),t=Pi();rt(["bootout",t,e],{ignoreError:!0}),rt(["bootstrap",t,e],{ignoreError:!0})||rt(["load","-w",e]),rt(["enable",`${t}/${_t}`],{ignoreError:!0}),rt(["kickstart","-k",`${t}/${_t}`],{ignoreError:!0}),await Ci(),Z.info(ce.dim(`It will start automatically when you log in. Plist: ${e}`)),Z.info(ce.dim(`Logs: ${ie.join(Fe(),"agent.log")}`))}async function Bo(){let e=wn(),t=Pi();rt(["bootout",t,e],{ignoreError:!0})||rt(["unload","-w",e],{ignoreError:!0})?Z.success(ce.green("Mach agent service stopped.")):Z.warn("Mach agent service was not loaded.")}async function Zd(){await Bo();let e=wn();fe.existsSync(e)&&fe.unlinkSync(e),Z.success(ce.green("Mach agent service uninstalled."))}async function Qd(){let e=zd();ot(["daemon-reload"]),ot(["enable","--now",$t]),await Ci(),Z.info(ce.dim(`It will start automatically when you log in. Service: ${e}`)),Z.info(ce.dim(`Logs: ${ie.join(Fe(),"agent.log")}`))}async function ec(){ot(["stop",$t],{ignoreError:!0})?Z.success(ce.green("Mach agent service stopped.")):Z.warn("Mach agent service was not running.")}async function tc(){ot(["disable","--now",$t],{ignoreError:!0}),ot(["daemon-reload"],{ignoreError:!0});let e=vi();fe.existsSync(e)&&fe.unlinkSync(e),ot(["daemon-reload"],{ignoreError:!0}),Z.success(ce.green("Mach agent service uninstalled."))}async function nc(){let e=Wd();Gt(["/Create","/TN",wt,"/SC","ONLOGON","/TR",`"${e}"`,"/RL","LIMITED","/F"]),Gt(["/Run","/TN",wt],{ignoreError:!0}),await Ci(),Z.info(ce.dim(`It will start automatically when you log in. Task: ${wt}`)),Z.info(ce.dim(`Logs: ${ie.join(Fe(),"agent.log")}`))}async function Fo(){Gt(["/End","/TN",wt],{ignoreError:!0})?Z.success(ce.green("Mach agent task stopped.")):Z.warn("Mach agent task was not running.")}async function ic(){await Fo(),Gt(["/Delete","/TN",wt,"/F"],{ignoreError:!0});let e=Ri();fe.existsSync(e)&&fe.unlinkSync(e),Z.success(ce.green("Mach agent task uninstalled."))}async function vo(){if(process.platform==="darwin")return Xd();if(process.platform==="linux")return Qd();if(process.platform==="win32")return nc();throw new Error(`Background agent install is not supported on ${process.platform}.`)}async function Ro(){if(process.platform==="darwin")return Bo();if(process.platform==="linux")return ec();if(process.platform==="win32")return Fo();Z.warn(`Background agent service control is not supported on ${process.platform}.`)}async function rc(){if(process.platform==="darwin")return Zd();if(process.platform==="linux")return tc();if(process.platform==="win32")return ic();Z.warn(`Background agent uninstall is not supported on ${process.platform}.`)}async function oc(){let e=await Mo(),t=e?!0:await Uo();if(e?Z.success(ce.green(`Mach agent is online at ${jt}`)):t?Z.warn(`Mach agent port is open, but /health did not respond. Run \`${f.nameLower} agent restart\` if the dashboard still shows offline.`):Z.warn(`Mach agent is not responding at ${jt}`),process.platform==="darwin"){let n=rt(["print",`${Pi()}/${_t}`],{ignoreError:!0});Z.info(ce.dim(`Login service: ${n?"installed/loaded":"not loaded"}`))}else if(process.platform==="linux"){let n=ot(["is-enabled",$t],{ignoreError:!0}),i=ot(["is-active",$t],{ignoreError:!0});Z.info(ce.dim(`Login service: ${n?"enabled":"not enabled"} / ${i?"active":"inactive"}`))}else if(process.platform==="win32"){let n=Gt(["/Query","/TN",wt],{ignoreError:!0});Z.info(ce.dim(`Login task: ${n?"installed":"not installed"}`))}}async function sc(){let e=[];try{(await _n(Lo(),["devices","-l"])).split(`
|
|
1236
|
+
`).forEach(n=>{if(n.includes("List of devices")||!n.trim())return;let i=n.split(/\s+/);if(i.length<2||i[1]!=="device")return;let r=i[0],o=n.match(/model:([^\s]+)/);e.push({id:r,platform:"android",type:r.startsWith("emulator-")?"emulator":"physical",name:o?o[1].replace(/_/g," "):r,status:"online",details:n.trim()})})}catch{}try{let n=(await _n(xo(),["-list-avds"])).split(`
|
|
1237
|
+
`).filter(r=>!!r.trim()),i=e.some(r=>r.platform==="android"&&r.id.startsWith("emulator-"));n.forEach(r=>{i||e.push({id:r,platform:"android",type:"emulator",name:r.replace(/_/g," "),status:"offline",details:`Android Virtual Device: ${r}`})})}catch{}return e}async function ac(){if(process.platform!=="darwin")return[];try{let e=await _n("/usr/bin/xcrun",["simctl","list","devices","--json"]),t=JSON.parse(e),n=[];return Object.entries(t.devices||{}).forEach(([i,r])=>{r.forEach(o=>{o.isAvailable&&n.push({id:o.udid,platform:"ios",type:"simulator",name:o.name,status:o.state?.toLowerCase()==="booted"?"online":"offline",runtime:i,details:`${o.name} (${i})`})})}),n}catch{return[]}}async function lc(){if(process.platform!=="darwin")return[];try{let e=await _n("/usr/bin/xcrun",["devicectl","list","devices","--json-output","-"]);return(JSON.parse(e).result?.devices||[]).filter(n=>{let i=n.connectionProperties?.transportType;return i==="wired"||i==="localNetwork"}).map(n=>{let i=n.connectionProperties?.transportType,r=n.deviceProperties?.name||"iPhone";return{id:n.identifier,platform:"ios",type:"physical",name:r,status:"online",details:`${r} (${n.model?.name||n.hardwareModel||""}) - ${i}`}})}catch{return[]}}async function dc(){let[e,t,n]=await Promise.all([sc(),ac(),lc()]);return[...e,...t,...n]}async function cc(){let e=Date.now();return An&&e-An.updatedAt<Kd?An.targets:(In||(In=dc().then(t=>(An={targets:t,updatedAt:Date.now()},t)).finally(()=>{In=null})),In)}async function Po(e){let t=[];for await(let n of e)t.push(Buffer.isBuffer(n)?n:Buffer.from(n));return t.length===0?{}:JSON.parse(Buffer.concat(t).toString("utf-8"))}async function uc(e,t){let n=await jd({method:"GET",url:e,responseType:"stream",timeout:12e4}),i=fe.createWriteStream(t);n.data.pipe(i),await new Promise((r,o)=>{i.on("finish",r),i.on("error",o)})}async function pc(e,t,n){let i=n||(t.toLowerCase().includes(".apk")?"android":"ios"),r=t.toLowerCase().includes(".ipa"),o=fe.mkdtempSync(ie.join(Be.tmpdir(),`${Xe}-install-`)),s=ie.join(o,i==="android"?"install.apk":r?"install.ipa":"install.zip");try{if(await uc(t,s),i==="android"){vn(Lo(),["-s",e,"install","-r",s],{stdio:"pipe"});return}if(process.platform!=="darwin")throw new Error("iOS local install requires macOS.");gt(`unzip -o ${JSON.stringify(s)} -d ${JSON.stringify(o)}`,{stdio:"pipe"});let l="";try{l=gt(`find ${JSON.stringify(ie.join(o,"Payload"))} -maxdepth 1 -name "*.app" 2>/dev/null | head -n 1`,{stdio:"pipe"}).toString().trim()}catch{}if(l||(l=gt(`find ${JSON.stringify(o)} -name "*.app" -type d | head -n 1`,{stdio:"pipe"}).toString().trim()),!l)throw new Error(`No .app bundle found inside the ${r?"IPA":"archive"}.`);try{gt(`/usr/bin/xcrun devicectl device install app --device ${JSON.stringify(e)} ${JSON.stringify(l)}`,{stdio:"pipe"})}catch(a){try{gt(`/usr/bin/xcrun simctl install ${JSON.stringify(e)} ${JSON.stringify(l)}`,{stdio:"pipe"})}catch{throw new Error(a.stderr?.toString().trim()||a.message||"iOS install failed.")}}}finally{fe.rmSync(o,{recursive:!0,force:!0})}}function fc(e,t){if(!e)throw new Error("Device id is required.");if(t==="ios"){if(process.platform!=="darwin")throw new Error("iOS Simulator launch requires macOS.");return gt(`/usr/bin/xcrun simctl boot ${JSON.stringify(e)}`,{stdio:"pipe"}),$o("open",["-a","Simulator"],{detached:!0,stdio:"ignore"}).unref(),"Simulator booting..."}if(t==="android")return $o(xo(),["-avd",e],{detached:!0,stdio:"ignore",windowsHide:!0}).unref(),"Emulator booting in background...";throw new Error("Invalid platform.")}async function mc(){process.platform!=="darwin"&&Z.warn("Running on non-macOS \u2014 iOS discovery unavailable, Android only.");let e=$n.createServer((i,r)=>{if(r.setHeader("Access-Control-Allow-Origin","*"),r.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),r.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),i.method==="OPTIONS"){r.writeHead(204),r.end();return}let o=new URL(i.url||"/",`http://localhost:${Xe}`);if(i.method==="GET"&&o.pathname==="/local/devices"){cc().then(s=>{r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"success",targets:s}))}).catch(s=>{r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"error",message:s.message}))});return}if(i.method==="GET"&&o.pathname==="/health"){r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"success",service:"mach-agent",port:Xe,platform:process.platform}));return}if(i.method==="POST"&&o.pathname==="/install-local"){t(i,r);return}if(i.method==="POST"&&o.pathname==="/local/boot"){n(i,r);return}r.writeHead(404),r.end()}),t=async(i,r)=>{try{let{deviceId:o,artifactUrl:s,platform:l}=await Po(i);if(!o||!s){r.writeHead(400,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"error",message:"deviceId and artifactUrl are required"}));return}await pc(o,s,l),r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"success",message:`Installed on ${o}`}))}catch(o){r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"error",message:o.message||"Local install failed"}))}},n=async(i,r)=>{try{let{id:o,platform:s}=await Po(i),l=fc(o,s);r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"success",message:l}))}catch(o){r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"error",message:o.message||"Local device launch failed"}))}};e.listen(Xe,"127.0.0.1",()=>{Z.success(ce.green(`Local device agent running on http://localhost:${Xe}`)),Z.info(ce.dim("Keep this running while using the Install Hub on the dashboard.")),Z.info(ce.dim("Press Ctrl+C to stop."))}),e.on("error",i=>{i.code==="EADDRINUSE"?Z.error(`Port ${Xe} is already in use \u2014 agent may already be running.`):Z.error(`Agent error: ${i.message}`),process.exit(1)}),await new Promise(()=>{})}async function Ho(e="start"){let t=String(e||"start").toLowerCase();if(t==="start"||t==="run"){await mc();return}if(t==="install"){await vo();return}if(t==="status"){await oc();return}if(t==="stop"){await Ro();return}if(t==="uninstall"){await rc();return}if(t==="restart"){await Ro(),await vo();return}Z.error(`Unknown agent action: ${e}`),Z.info(ce.dim(`Use: ${f.nameLower} agent start | install | status | restart | stop | uninstall`)),process.exit(1)}import{createRequire as Ku}from"module";import{text as hc,password as yc,spinner as Sc,isCancel as Ko}from"@clack/prompts";import Li from"chalk";import Kt from"fs";import jo from"path";import gc from"os";var Ni=jo.join(gc.homedir(),f.configDir),Ti=jo.join(Ni,"config.json");function ki(){if(!Kt.existsSync(Ti))return{};try{return JSON.parse(Kt.readFileSync(Ti,"utf-8"))}catch{return{}}}function Go(e){Kt.existsSync(Ni)||Kt.mkdirSync(Ni,{recursive:!0});let n={...ki(),...e};Kt.writeFileSync(Ti,JSON.stringify(n,null,2))}async function Vo(){let e=ki(),t=await hc({message:"Enter your email:",placeholder:"user@example.com",initialValue:e.lastLoginEmail,validate(r){if(r.length===0)return"Email is required!"}});if(Ko(t))return;let n=await yc({message:"Enter your password:",validate(r){if(r.length===0)return"Password is required!"}});if(Ko(n))return;let i=Sc();i.start("Authenticating...");try{let o=await(await fetch(`${yt}/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:t,password:n})})).json();o.status==="success"&&o.user.token?(Wi({id:o.user.id,email:t,token:o.user.token,refreshToken:o.user.refreshToken}),Go({lastLoginEmail:t}),i.stop(Li.green("Login successful!"))):i.stop(Li.red("Login failed: "+(o.message||"Unknown error")))}catch(r){i.stop(Li.red("Network error: "+r.message))}}import{log as Rn,outro as bc}from"@clack/prompts";import Vt from"chalk";async function zo(){let e=Yi(),t=`${f.envPrefix}TOKEN`;e?Rn.success(Vt.green(`Logged out. Removed saved credentials from ~/${f.configDir}/credentials.json.`)):Rn.warn(Vt.yellow(`No saved ${f.name} credentials found.`)),process.env[t]&&(Rn.warn(Vt.yellow(`${t} is still set in this shell. Commands will continue to authenticate with that token until you unset it.`)),Rn.info(Vt.dim(`Run: unset ${t}`))),bc(Vt.blue("---"))}import{outro as Ec,select as Ac,spinner as Ic,isCancel as wc}from"@clack/prompts";import Pn from"chalk";import xi from"fs";import _c from"path";var Wo=e=>e==="1234567890"||e==="ABC123DEFG"||e==="XXXXXXXXXX"?"":typeof e=="string"?e:"",$c=()=>process.versions.node.split(".")[0]||"24";async function Yo(){if(!Re()){console.log(Pn.red(`You are not logged in. Run \`${f.nameLower} login\` first.`));return}let t=Ic();t.start("Fetching projects...");try{let{data:n}=await R.get("/projects");if(t.stop("Projects loaded."),n.status!=="success"||!n.projects||n.projects.length===0){console.log(Pn.yellow(`No projects found. Run \`${f.nameLower} init\` to create one.`));return}let i=n.projects.map(y=>({value:y.projectId,label:`${y.name} (${y.slug})`})),r=await Ac({message:"Select a project to link:",options:i});if(wc(r))return;let o=_c.join(process.cwd(),f.configFileName),s={};if(xi.existsSync(o))try{s=JSON.parse(xi.readFileSync(o,"utf-8"))}catch{}let l=n.projects.find(y=>y.projectId===r),a=s.android?.package||qe("android"),d=s.ios?.bundleIdentifier||qe("ios"),c=s.android||{},u=s.submit?.production?.android||{},p=s.submit?.production?.ios||{},m={projectId:r,name:l?.name,slug:l?.slug,nodeVersion:s.nodeVersion||$c(),scheme:l?.slug?.toLowerCase()||"app",android:{...c,package:a||"",versionCode:c.versionCode||"auto"},ios:{bundleIdentifier:d||"",buildNumber:s.ios?.buildNumber||"auto"},build:{development:{environment:"development",distribution:"development"},staging:{environment:"staging",distribution:"internal"},production:{environment:"production",distribution:"store"}},submit:{production:{android:{...u,track:u.track||"internal",releaseStatus:u.releaseStatus||"completed"},ios:{ascAppId:Wo(p.ascAppId),appleTeamId:Wo(p.appleTeamId)}}}};xi.writeFileSync(o,JSON.stringify(m,null,2)),Ec(Pn.green(`Linked to project ${m.name} (${m.slug})`))}catch(n){t.stop(Pn.red("Error fetching projects: "+n.message))}}import{outro as vc,text as Dn,select as Rc,spinner as Pc,isCancel as zt}from"@clack/prompts";import Wt from"chalk";import Dc from"fs";import Oc from"path";import{randomUUID as Cc}from"crypto";var Nc=()=>process.versions.node.split(".")[0]||"24";async function Jo(){if(!Re()){console.log(Wt.red(`You are not logged in. Run \`${f.nameLower} login\` first.`));return}let t=await Dn({message:"Project Name:",placeholder:"My Awesome App",validate(l){if(l.length===0)return"Name is required!"}});if(zt(t))return;let n=await Dn({message:"Project Slug (URL friendly):",placeholder:"my-awesome-app",validate(l){if(l.length===0)return"Slug is required!";if(!/^[a-z0-9-]+$/.test(l))return"Slug must be lowercase alphanumeric with dashes."}});if(zt(n))return;let i=await Rc({message:"Platform:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"},{value:"web",label:"Web"},{value:"all",label:"All Platforms"}]});if(zt(i))return;let r="";if(i==="android"||i==="all"){let l=qe("android");if(r=await Dn({message:"Android Package Name:",initialValue:l||"",placeholder:"com.example.app",validate(a){if(a.length===0)return"Package name is required for Android!"}}),zt(r))return}let o="";if(i==="ios"||i==="all"){let l=qe("ios");if(o=await Dn({message:"iOS Bundle Identifier:",initialValue:l||"",placeholder:"com.example.app",validate(a){if(a.length===0)return"Bundle ID is required for iOS!"}}),zt(o))return}let s=Pc();s.start("Creating project...");try{let l=Cc(),d={projectId:l,name:t,slug:n,storageType:"managed",platforms:i==="all"?["android","ios","web"]:[i]},{data:c}=await R.post("/projects",d);if(c.status==="success"){s.stop(Wt.green("Project created successfully!"));let u=Oc.join(process.cwd(),f.configFileName);Dc.writeFileSync(u,JSON.stringify({projectId:l,name:t,slug:n,nodeVersion:Nc(),...r?{android:{package:r,versionCode:"auto"}}:{},...o?{ios:{bundleIdentifier:o,buildNumber:"auto"}}:{},build:{development:{environment:"development",distribution:"development"},staging:{environment:"staging",distribution:"internal"},production:{environment:"production",distribution:"store"}},submit:{production:{android:{track:"internal",releaseStatus:"completed"},ios:{ascAppId:"",appleTeamId:""}}}},null,2)),vc(Wt.green(`Initialized project ${t} and linked locally!`))}else s.stop(Wt.red("creation failed: "+c.message))}catch(l){s.stop(Wt.red("Network error: "+l.message))}}import{spinner as Mi,log as ve}from"@clack/prompts";import Yt from"chalk";import On from"fs";import qo from"path";function Ui(e,t,n,i){let r=e?.response?.status,o=e?.response?.data?.message||e?.response?.data?.error,s=i?` ${i}`:"";return r===401?`Not logged in or token expired while trying to ${n}${s}. Run \`${f.nameLower} login\` and try again.`:r===403?[`Permission denied while trying to ${n}${s}.`,o?`API says: ${o}.`:void 0,`Current Mach account/token does not have access to project ${t}.`,`Run \`${f.nameLower} login\` with the correct account, or ask a project owner to grant access.`].filter(Boolean).join(" "):r===404?[`Project or environment endpoint was not found while trying to ${n}${s}.`,`Project ID: ${t}.`,o?`API says: ${o}.`:void 0].filter(Boolean).join(" "):r?`Failed to ${n}${s}: ${o||`API returned HTTP ${r}`}`:`Network error while trying to ${n}${s}: ${e?.message||"Unknown error"}`}function Tc(e){let t=String(e??"");return t===""?'""':/^[A-Za-z0-9_./:@%+-]+$/.test(t)?t:JSON.stringify(t)}function kc(e,t){return`${[`# Generated by ${f.nameLower} env pull --environment ${t}`,"# Do not commit this file.","",...Object.keys(e).sort((i,r)=>i.localeCompare(r)).map(i=>`${i}=${Tc(e[i])}`)].join(`
|
|
1238
|
+
`)}
|
|
1239
|
+
`}async function Xo(e,t,n={}){let i=Re();if(!i){ve.error(`You are not logged in. Run \`${f.nameLower} login\` first.`);return}let r=qo.join(process.cwd(),f.configFileName);if(!On.existsSync(r)){ve.error(`No ${f.configFileName} found. Run \`${f.nameLower} init\` or \`${f.nameLower} link\` first.`);return}let o;try{o=JSON.parse(On.readFileSync(r,"utf-8"))}catch{ve.error(`Failed to parse ${f.configFileName}`);return}let{projectId:s}=o;if(!s){ve.error(`${f.configFileName} is missing projectId.`);return}e==="set"?await Lc(s,t,i):e==="list"?await xc(s,i):e==="pull"||e==="download"||e==="export"?await Mc(s,n):ve.error(`Unknown env action: ${e}. Use 'set', 'list', or 'pull'.`)}async function Lc(e,t,n){if(t.length===0){ve.error(`Usage: ${f.nameLower} env set KEY=VALUE [KEY2=VALUE2 ...]`);return}let i=Mi();i.start("Setting environment variables...");let r=0,o=0;for(let s of t){let[l,...a]=s.split("="),d=a.join("=");if(!l||d===void 0){ve.warn(`Invalid format for argument: ${s}. Expected KEY=VALUE.`),o++;continue}try{let c={key:l.trim(),value:d,type:"env",environment:"global",visibility:"secret"},{data:u}=await R.post(`/projects/${e}/secrets`,c);u.status==="success"?r++:(ve.error(`Failed to set ${l}: ${u.message}`),o++)}catch(c){ve.error(Ui(c,e,"set",l)),o++}}i.stop(`Set ${r} variable(s). ${o>0?`${o} failed.`:""}`)}async function xc(e,t){let n=Mi();n.start("Fetching environment variables...");try{let{data:i}=await R.get(`/projects/${e}/secrets`);if(i.status==="success"){n.stop("Fetched variables.");let r=i.secrets||[];r.length===0?ve.info("No environment variables found for this project."):(ve.info(Yt.bold("Environment Variables (Global & Scoped):")),r.forEach(o=>{let s=o.visibility==="plain"?o.value:"********";console.log(` ${Yt.cyan(o.key)} = ${s} ${Yt.gray(`[${o.environment}]`)}`)}))}else n.stop(Yt.red(`Failed to fetch variables: ${i.message}`))}catch(i){n.stop("Failed to fetch variables."),ve.error(Ui(i,e,"list"))}}async function Mc(e,t){let n=(t.environment||"development").trim(),i=t.out||".env.local",r=qo.resolve(process.cwd(),i);if(On.existsSync(r)&&!t.overwrite){ve.error(`${i} already exists. Re-run with \`--overwrite\` to replace it.`);return}let o=Mi();o.start(`Downloading ${n} environment variables...`);try{let{data:s}=await R.get(`/projects/${e}/secrets/export?env=${encodeURIComponent(n)}`);if(s.status!=="success"){o.stop(Yt.red(`Failed to download variables: ${s.message||"Unknown API error"}`));return}let l=s.secrets||{},a=kc(l,n);On.writeFileSync(r,a,{encoding:"utf-8",mode:384}),o.stop(`Wrote ${Object.keys(l).length} variable(s) to ${i}.`)}catch(s){o.stop("Failed to download variables."),ve.error(Ui(s,e,"pull"))}}import{spinner as Uc,log as ht,outro as Bc}from"@clack/prompts";import Bi from"chalk";import Zo from"fs";import Fc from"path";import{execSync as Hc}from"child_process";import jc from"adm-zip";import Gc from"axios";import{randomUUID as Kc}from"crypto";async function Qo(e){ht.info(Bi.magenta("\u{1F680} Starting Over-The-Air (OTA) Update via Mach..."));let t=Pe();(!t||!t.projectId)&&(ht.error(`No ${f.configFileName} found or missing projectId. Run \`mach link\` first.`),process.exit(1));let n=t.projectId,i=e.branch||"production",r="1.0.0";try{r=JSON.parse(Zo.readFileSync("./package.json","utf-8")).version||"1.0.0"}catch{ht.warn("Could not read package.json version. Defaulting to 1.0.0")}let o=Uc();o.start(`Compiling JavaScript bundles for OTA (Channel: ${i}, Runtime: ${r})...`);try{Hc("npx expo export --platform all",{stdio:"ignore"})}catch(d){o.stop("Compilation failed."),ht.error(`Failed to export JS bundles using Expo: ${d.message}`),process.exit(1)}o.message("Zipping artifact payload...");let s=Fc.join(process.cwd(),"dist");Zo.existsSync(s)||(o.stop("Missing dist folder."),ht.error("The `dist` directory was not created. Export failed."),process.exit(1));let l=new jc;l.addLocalFolder(s,"dist");let a=l.toBuffer();o.message("Uploading payload to Mach Cloud...");try{let d=Kc(),c=await R.post("/builds/source-upload-url",{projectId:n,buildId:d});if(c.data.status!=="success")throw new Error("Could not secure upload bucket URL");let{uploadUrl:u,key:p}=c.data;await Gc.put(u,a,{headers:{"Content-Type":"application/zip"},maxBodyLength:1/0,maxContentLength:1/0}),o.message(`Promoting Update to ${i}...`),await R.post("/updates/publish",{projectId:n,channelName:i,runtimeVersion:r,platform:"android",updateId:`${d}-android`,manifestKey:p}),await R.post("/updates/publish",{projectId:n,channelName:i,runtimeVersion:r,platform:"ios",updateId:`${d}-ios`,manifestKey:p}),o.stop("Update Live!"),Bc(Bi.green(`\u2713 OTA Update natively shipped to the '${i}' channel.`)),ht.info(Bi.dim(`Any app running runtime '${r}' will download this bundle smoothly.`))}catch(d){o.stop("Update failed during Cloud Sync."),ht.error(`Upload error: ${d.message}`),process.exit(1)}}import{intro as Vc,outro as es,log as vt}from"@clack/prompts";import We from"chalk";async function ts(){Vc(We.blue(`${f.name} CLI - User Profile`));let e=Re();if(!e){vt.warn(We.yellow("You are not logged in.")),vt.info(`Run \`${f.nameLower} login\` to authenticate.`),es();return}vt.info(`${We.bold("Logged in as:")} ${We.green(e.email)}`);try{await R.get("/projects");let n=Re().token.split(".");if(n.length===3){let i=JSON.parse(Buffer.from(n[1],"base64").toString());if(i.exp){let r=new Date(i.exp*1e3),o=new Date,s=r.getTime()-o.getTime();if(s>0){let l=Math.round(s/6e4),a=(l/60).toFixed(1);vt.info(`${We.bold("Token status:")} Valid (Expires in ~${a}h / ${l}m)`)}else vt.warn(`${We.bold("Token status:")} ${We.red("Expired")} (Auto-refresh failed)`)}}}catch{vt.warn(`${We.bold("Token status:")} ${We.red("Unreachable")} (Session might be truly expired)${yt}`)}es(We.blue("---"))}import{spawn as Yc}from"child_process";import{log as st}from"@clack/prompts";import Ce from"chalk";import Jc from"fs";import zc from"net";async function Wc(e){return new Promise(t=>{let n=zc.createServer();n.once("error",i=>{i.code==="EADDRINUSE"?t(!0):t(!1)}),n.once("listening",()=>{n.close(),t(!1)}),n.listen(e,"0.0.0.0")})}async function ns(e,t=20){let n=e;for(;n<e+t;){if(!await Wc(n))return n;n++}throw new Error(`Could not find an available port after ${t} attempts starting from ${e}.`)}var is=async e=>{st.info(Ce.blue(`Starting ${f.name} Dev Orchestrator...`));let t=Pe(),n=e.buildProfile||"development",i=t?Qe(t,n):null,r={...process.env};if(t?.projectId)try{st.info(Ce.dim(`Fetching managed secrets for profile: ${n}...`));let u=await R.get(`/projects/${t.projectId}/secrets/export?env=${n}`);u.data?.status==="success"&&u.data.secrets&&(Object.assign(r,u.data.secrets),st.info(Ce.magenta(`\u2713 Injected secrets from ${f.name} Dashboard.`)))}catch{st.warn("Could not fetch managed secrets. Running with local env only.")}t&&Object.assign(r,St(t,f.envPrefix)),i&&(Object.assign(r,St(i,`${f.envPrefix}PROFILE_`)),i.env&&Object.assign(r,i.env));let o=!1;try{let u=JSON.parse(Jc.readFileSync("package.json","utf-8"));o=!!(u.dependencies?.expo||u.devDependencies?.expo)}catch{st.warn("Could not parse package.json. Defaulting to Bare React Native mode.")}let s=Number(e.port||i?.port||8081),l=await ns(s);l!==s&&st.info(Ce.yellow(`Port ${s} is busy. ${f.name} is using ${l} instead.`));let a=process.platform==="win32"?"npx.cmd":"npx",d=[];if(o?(d=["expo","start","--port",String(l)],e.clear&&d.push("--clear"),e.tunnel&&d.push("--tunnel"),e.lan&&d.push("--lan"),e.localhost&&d.push("--localhost"),e.ios&&d.push("--ios"),e.android&&d.push("--android"),e.web&&d.push("--web")):(d=["react-native","start","--port",String(l)],e.clear&&d.push("--clear")),o){let u=[`${Ce.cyan("i")} open iOS simulator`,`${Ce.cyan("a")} open Android emulator/device`,`${Ce.cyan("w")} open web`,`${Ce.cyan("r")} reload app`];st.info([Ce.bold("Launch controls"),...u.map(p=>` ${p}`),"",Ce.dim("Direct launch: mach start --ios | --android | --web"),Ce.dim(`Metro URL: http://localhost:${l}`)].join(`
|
|
1240
|
+
`))}else st.info(Ce.dim(`Metro URL: http://localhost:${l}`));let c=Yc(a,d,{stdio:"inherit",env:r});return new Promise((u,p)=>{c.on("exit",m=>{m===0?u():p(new Error(`Dev server exited with code ${m}`))}),c.on("error",m=>{p(m)})})};import{log as De}from"@clack/prompts";import He from"chalk";var rs=async e=>{let t=Pe();t||(De.error(He.red(`No ${f.configFileName} found in the current directory.`)),process.exit(1));let n=e.profile||"development",i=Qe(t,n);if(e.json){console.log(JSON.stringify({project:t,resolved:i},null,2));return}De.info(He.bgBlue.white(` Resolved ${f.name} Config [${n}] `)),De.info(He.dim("----------------------------------------")),De.info(`${He.blue("Project ID:")} ${t.projectId}`),De.info(`${He.blue("Name:")} ${t.name}`),De.info(`${He.blue("Scheme:")} ${t.scheme}`),i?(De.info(He.dim(`
|
|
1241
|
+
Profile Settings:`)),De.info(`${He.cyan("Distribution:")} ${i.distribution||"none"}`),De.info(`${He.cyan("Development Client:")} ${i.developmentClient||"false"}`),i.env&&Object.keys(i.env).length>0&&(De.info(He.dim(`
|
|
1242
|
+
Environment Variables:`)),Object.entries(i.env).forEach(([r,o])=>{De.info(` ${r}=${o}`)}))):De.warn(`Profile '${n}' not found.`),De.info(He.dim("----------------------------------------"))};import{log as Ne,spinner as Xt,text as os,select as ss,confirm as qc,isCancel as Jt,cancel as qt,outro as Zt,note as Xc}from"@clack/prompts";import re from"chalk";import{execSync as Zc}from"child_process";async function Qc(){try{let e=Zc("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[]}}var as=e=>e?.trim().toUpperCase()||void 0;function ls(e){let t=Pe(),n=t?qi(t):{},i=as(e.teamId),r=i||n.teamId;return{...n,teamId:r,developerTeamId:i||n.developerTeamId||r}}async function eu(e){let t=e.udid,n=e.name,i=ls(e),r=i.teamId;if(!t){let s=Xt();s.start("Scanning for connected iOS devices...");let l=await Qc();if(s.stop(l.length>0?`Found ${l.length} device(s)`:"No devices detected"),l.length===1)t=l[0].udid,n=n||l[0].name,Ne.info(`Detected: ${re.bold(n)} (${re.dim(t.substring(0,12)+"...")})`);else if(l.length>1){let a=await ss({message:"Select a device to register:",options:l.map(c=>({value:c.udid,label:`${c.name} (${c.model})`,hint:c.udid.substring(0,12)+"..."}))});if(Jt(a)){qt("Cancelled");return}t=a;let d=l.find(c=>c.udid===t);n=n||d.name}else{Ne.info(re.dim("No connected devices found. Enter UDID manually."));let a=await os({message:"Device UDID:",placeholder:"00008101-XXXXXXXXXXXX",validate(d){if(d.length<10)return"UDID seems too short"}});if(Jt(a)){qt("Cancelled");return}t=a}}if(!n){let s=await os({message:"Device name:",placeholder:"Nitesh's iPhone",validate(l){if(l.length===0)return"Name is required"}});if(Jt(s)){qt("Cancelled");return}n=s}let o=Xt();o.start("Registering device...");try{await R.post("/devices",{udid:t,name:n,platform:"ios",addedVia:"cli",teamId:r,teamName:i.teamName,developerTeamId:i.developerTeamId,appStoreConnectTeamId:i.appStoreConnectTeamId,providerId:i.providerId,providerName:i.providerName}),o.stop(re.green("Device registered!")),Ne.info(` ${re.bold("Name:")} ${n}`),Ne.info(` ${re.bold("UDID:")} ${re.dim(t)}`),r&&Ne.info(` ${re.bold("Team:")} ${re.dim(r)}`)}catch(s){o.stop(re.red("Failed to register device")),Ne.error(s.response?.data?.message||s.message)}Zt(re.blue("---"))}async function tu(e={}){let t=as(e.teamId),n=Xt();n.start("Fetching registered devices...");try{let r=(await R.get("/devices",t?{params:{teamId:t}}:void 0)).data.devices||[];if(n.stop(`${r.length} device(s) registered${t?` for team ${t}`:""}`),r.length===0){Ne.info(re.dim(`No devices registered yet. Run \`${f.nameLower} device register\` to add one.`)),Zt(re.blue("---"));return}let o=r.map(s=>{let l=new Date(s.createdAt).toLocaleDateString();return` ${re.bold(s.name.padEnd(24))} ${re.dim(s.udid.padEnd(28))} ${re.dim((s.teamId||"-").padEnd(12))} ${re.cyan((s.addedVia||"-").padEnd(10))} ${re.dim(l)}`});Xc(` ${re.bold("Name".padEnd(24))} ${"UDID".padEnd(28)} ${"Team".padEnd(12)} ${"Via".padEnd(10)} Date
|
|
1243
|
+
`+o.join(`
|
|
1244
|
+
`),"Registered Devices")}catch(i){n.stop(re.red("Failed to fetch devices")),Ne.error(i.response?.data?.message||i.message)}Zt(re.blue("---"))}async function nu(e){let t=e.udid,n=ls(e).teamId;if(!t){let o=Xt();o.start("Fetching registered devices...");try{let l=(await R.get("/devices",n?{params:{teamId:n}}:void 0)).data.devices||[];if(o.stop(`${l.length} device(s) found`),l.length===0){Ne.info(re.dim("No devices to remove.")),Zt(re.blue("---"));return}let a=await ss({message:"Select device to remove:",options:l.map(c=>({value:c.deviceKey||c.udid,label:c.name,hint:`${c.udid.substring(0,12)}...${c.teamId?` \xB7 ${c.teamId}`:""}`}))});if(Jt(a)){qt("Cancelled");return}let d=l.find(c=>(c.deviceKey||c.udid)===a);t=d?.udid||a,n=d?.teamId||n}catch(s){o.stop(re.red("Failed to fetch devices")),Ne.error(s.response?.data?.message||s.message);return}}let i=await qc({message:`Remove device ${re.dim(t.substring(0,12)+"...")}?`});if(Jt(i)||!i){qt("Cancelled");return}let r=Xt();r.start("Removing device...");try{await R.delete(`/devices/${encodeURIComponent(t)}`,n?{params:{teamId:n}}:void 0),r.stop(re.green("Device removed"))}catch(o){r.stop(re.red("Failed to remove device")),Ne.error(o.response?.data?.message||o.message)}Zt(re.blue("---"))}async function Cn(e,t){switch(e){case"register":await eu(t);break;case"list":await tu(t);break;case"remove":await nu(t);break;default:Ne.error(`Unknown action: ${e}`)}}import{log as ke,spinner as Ms}from"@clack/prompts";import Ge from"chalk";import Hn from"path";import tn from"fs";import xu from"os";import Mu from"axios";var Te=(o=>(o.CRITICAL="critical",o.HIGH="high",o.MEDIUM="medium",o.LOW="low",o.INFO="info",o))(Te||{}),je=(a=>(a.PERMISSIONS="permissions",a.SECRETS="secrets",a.DEPENDENCIES="dependencies",a.STORAGE="storage",a.NETWORK="network",a.DEBUG="debug",a.MANIFEST="manifest",a.ATS="ats",a))(je||{});import{spinner as Rs,log as en}from"@clack/prompts";import Oe from"chalk";import{execSync as vu}from"child_process";import Ps from"fs";import Ds from"path";import at from"fs";import Qt from"path";import{execSync as iu}from"child_process";var ds={"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"}},ru={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 ou(e){try{let n=iu("npx expo config --type introspect --json 2>/dev/null",{cwd:e,encoding:"utf-8",timeout:3e4});return JSON.parse(n)}catch{}let t=Qt.join(e,"app.json");if(at.existsSync(t))try{let n=JSON.parse(at.readFileSync(t,"utf-8"));return n.expo||n}catch{}return null}function su(e){let t=[],n=Qt.join(e,"node_modules");if(!at.existsSync(n))return t;let i=/<uses-permission\s+android:name="([^"]+)"/g;function r(o,s){let l=Qt.join(o,"android","src","main","AndroidManifest.xml");if(!at.existsSync(l))return;let a=at.readFileSync(l,"utf-8"),d;for(;(d=i.exec(a))!==null;)t.push({pkg:s,permission:d[1]});i.lastIndex=0}for(let o of at.readdirSync(n)){if(o.startsWith("."))continue;let s=Qt.join(n,o);if(o.startsWith("@")){if(!at.statSync(s).isDirectory())continue;for(let l of at.readdirSync(s))r(Qt.join(s,l),`${o}/${l}`)}else r(s,o)}return t}async function cs(e,t){let n=[],i=1,r=ou(e),o=r?.android?.permissions||[],s=r?.android?.blockedPermissions||[];for(let d of o){let c=ds[d];c&&n.push({id:`PERM-${String(i++).padStart(3,"0")}`,title:`${d.split(".").pop()} declared`,description:c.description,severity:c.severity,category:"permissions",file:"app.config.ts",recommendation:"Remove from permissions if not needed, or add justification."})}let l=su(e);for(let{pkg:d,permission:c}of l){let u=ds[c];u&&(s.includes(c)||o.includes(c)||n.push({id:`PERM-${String(i++).padStart(3,"0")}`,title:`${c.split(".").pop()} injected by ${d}`,description:`${u.description}. Auto-injected via ${d} AndroidManifest.xml`,severity:u.severity,category:"permissions",file:`node_modules/${d}/android/src/main/AndroidManifest.xml`,recommendation:`Add "${c}" to blockedPermissions if not needed.`,autoFixable:!0}))}let a=r?.ios?.infoPlist||{};for(let[d,c]of Object.entries(ru))d in a&&n.push({id:`PERM-${String(i++).padStart(3,"0")}`,title:`iOS: ${d} declared`,description:c.description,severity:c.severity,category:"permissions",file:"app.config.ts",recommendation:`Remove ${d} from infoPlist if the app does not use this capability.`});return{category:"permissions",label:"Permission Audit",findings:n,durationMs:0}}import Fi from"fs";import Nn from"path";var au=[{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"}],lu=new Set([".ts",".tsx",".js",".jsx"]),du=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function us(e){let t=[],n=Fi.readdirSync(e,{withFileTypes:!0});for(let i of n){if(du.has(i.name))continue;let r=Nn.join(e,i.name);i.isDirectory()?t.push(...us(r)):lu.has(Nn.extname(i.name))&&t.push(r)}return t}function cu(e){let t=e.trim();return t.startsWith("//")||t.startsWith("*")||t.startsWith("/*")}function uu(e){return/process\.env\./i.test(e)||/import\.meta\.env/i.test(e)}async function ps(e,t){let n=[],i=Nn.join(e,"src"),r=Fi.existsSync(i)?i:e,o=us(r);for(let s of o){let a=Fi.readFileSync(s,"utf-8").split(`
|
|
1245
|
+
`),d=Nn.relative(e,s);for(let c=0;c<a.length;c++){let u=a[c];if(!cu(u)&&!uu(u))for(let{id:p,pattern:m,severity:y,label:C}of au)m.lastIndex=0,m.test(u)&&n.push({id:p,title:C,description:`Potential ${C.toLowerCase()} found in source code`,severity:y,category:"secrets",file:d,line:c+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:n,durationMs:0}}import{execSync as pu}from"child_process";var fu={critical:"critical",high:"high",moderate:"medium",low:"low",info:"info"};async function fs(e,t){let n=[],i=1,r;try{r=pu("npm audit --json 2>/dev/null",{cwd:e,encoding:"utf-8",timeout:6e4})}catch(l){if(r=l.stdout||"",!r)return{category:"dependencies",label:"Dependency CVEs",findings:[],durationMs:0,error:"Failed to run npm audit. Ensure npm is available and dependencies are installed."}}let o;try{o=JSON.parse(r)}catch{return{category:"dependencies",label:"Dependency CVEs",findings:[],durationMs:0,error:"Failed to parse npm audit output."}}let s=o.vulnerabilities||{};for(let[l,a]of Object.entries(s)){let d=fu[a.severity]||"info",c=Array.isArray(a.via)?a.via.map(u=>typeof u=="string"?u:u.title||u.name).join(", "):String(a.via);n.push({id:`DEP-${String(i++).padStart(3,"0")}`,title:`${l} \u2014 ${a.severity}`,description:`Via: ${c}. Range: ${a.range||"unknown"}`,severity:d,category:"dependencies",recommendation:a.fixAvailable?`Run \`npm audit fix\` or update ${l} to a patched version.`:"No fix available yet. Monitor for updates or evaluate alternatives.",autoFixable:!!a.fixAvailable})}return{category:"dependencies",label:"Dependency CVEs",findings:n,durationMs:0}}import Tn from"fs";import kn from"path";var mu=/(?:token|password|credential|secret|apiKey|api_key|session|auth|jwt|refresh_token|access_token|private_key|pin|otp)/i,ms=/AsyncStorage\s*\.\s*(?:setItem|mergeItem)\s*\(\s*['"`]([^'"`]+)['"`]/g,gu=/from\s+['"]@react-native-async-storage\/async-storage['"]|from\s+['"]react-native['"].*AsyncStorage/,hu=new Set([".ts",".tsx",".js",".jsx"]),yu=new Set(["node_modules",".expo",".git","android","ios","dist","build"]);function gs(e){let t=[];if(!Tn.existsSync(e))return t;let n=Tn.readdirSync(e,{withFileTypes:!0});for(let i of n){if(yu.has(i.name))continue;let r=kn.join(e,i.name);i.isDirectory()?t.push(...gs(r)):hu.has(kn.extname(i.name))&&t.push(r)}return t}async function hs(e,t){let n=[],i=1,r=kn.join(e,"src"),o=Tn.existsSync(r)?r:e,s=gs(o);for(let l of s){let a=Tn.readFileSync(l,"utf-8");if(!gu.test(a))continue;let d=a.split(`
|
|
1246
|
+
`),c=kn.relative(e,l);for(let u=0;u<d.length;u++){let p=d[u];ms.lastIndex=0;let m;for(;(m=ms.exec(p))!==null;){let y=m[1];mu.test(y)&&n.push({id:`STOR-${String(i++).padStart(3,"0")}`,title:`AsyncStorage used for "${y}"`,description:`Sensitive data key "${y}" stored in AsyncStorage (unencrypted).`,severity:"high",category:"storage",file:c,line:u+1,recommendation:"Use expo-secure-store (SecureStore) for sensitive data instead of AsyncStorage."})}}}return{category:"storage",label:"Insecure Storage",findings:n,durationMs:0}}import Ln from"fs";import xn from"path";var ys=/['"`](http:\/\/(?!localhost|127\.0\.0\.1|10\.|192\.168\.|0\.0\.0\.0|172\.(?:1[6-9]|2\d|3[01])\.)[^'"`\s]+)['"`]/g,Su=/\/api\/|\/v[0-9]+\/|\/graphql|\/rest\//i,bu=new Set([".ts",".tsx",".js",".jsx"]),Eu=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function Ss(e){let t=[];if(!Ln.existsSync(e))return t;let n=Ln.readdirSync(e,{withFileTypes:!0});for(let i of n){if(Eu.has(i.name))continue;let r=xn.join(e,i.name);i.isDirectory()?t.push(...Ss(r)):bu.has(xn.extname(i.name))&&t.push(r)}return t}async function bs(e,t){let n=[],i=1,r=xn.join(e,"src"),o=Ln.existsSync(r)?r:e,s=Ss(o);for(let l of s){let d=Ln.readFileSync(l,"utf-8").split(`
|
|
1247
|
+
`),c=xn.relative(e,l);for(let u=0;u<d.length;u++){let p=d[u],m=p.trim();if(m.startsWith("//")||m.startsWith("*"))continue;ys.lastIndex=0;let y;for(;(y=ys.exec(p))!==null;){let C=y[1],N=Su.test(C);n.push({id:`NET-${String(i++).padStart(3,"0")}`,title:`Insecure HTTP URL${N?" (API endpoint)":""}`,description:`Plain HTTP URL found: ${C}`,severity:N?"high":"medium",category:"network",file:c,line:u+1,recommendation:"Use HTTPS instead of HTTP for all network requests."})}}}return{category:"network",label:"HTTP URLs",findings:n,durationMs:0}}import Mn from"fs";import Un from"path";var Es=/(?:debug|debugMode|devMode|enableDebug)\s*[:=]\s*true/gi,As=/console\.(?:log|warn|info|debug)\s*\([^)]*(?:token|password|secret|credential|key|auth)/gi,Au=new Set([".ts",".tsx",".js",".jsx"]),Iu=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function Is(e){let t=[];if(!Mn.existsSync(e))return t;let n=Mn.readdirSync(e,{withFileTypes:!0});for(let i of n){if(Iu.has(i.name))continue;let r=Un.join(e,i.name);i.isDirectory()?t.push(...Is(r)):Au.has(Un.extname(i.name))&&t.push(r)}return t}async function ws(e,t){let n=[],i=1,r=Un.join(e,"src"),o=Mn.existsSync(r)?r:e,s=Is(o);for(let l of s){let d=Mn.readFileSync(l,"utf-8").split(`
|
|
1248
|
+
`),c=Un.relative(e,l);for(let u=0;u<d.length;u++){let p=d[u],m=p.trim();if(!(m.startsWith("//")||m.startsWith("*"))&&(Es.lastIndex=0,Es.test(p)&&n.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:c,line:u+1,recommendation:"Use __DEV__ or environment variables instead of hardcoded debug flags."}),As.lastIndex=0,As.test(p))){let y=d.slice(Math.max(0,u-3),u).join(`
|
|
1249
|
+
`);/__DEV__/.test(y)||n.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:c,line:u+1,recommendation:"Wrap in __DEV__ check or remove sensitive data from console output."})}}}return{category:"debug",label:"Debug/Dev Flags",findings:n,durationMs:0}}import _s from"fs";import Hi from"path";var wu=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 _u(e){let t=[Hi.join(e,"android","app","src","main","AndroidManifest.xml"),Hi.join(e,"android","AndroidManifest.xml")];for(let n of t)if(_s.existsSync(n))return n;return null}async function $s(e,t){let n=[],i=1,r=_u(e);if(!r)return{category:"manifest",label:"Android Manifest",findings:[],durationMs:0,error:"No AndroidManifest.xml found. Run with --prebuild or run `expo prebuild` first."};let o=_s.readFileSync(r,"utf-8"),s=Hi.relative(e,r),l=/<(activity|service|receiver|provider)\s+([^>]*?)(?:\/>|>)/gs,a;for(;(a=l.exec(o))!==null;){let d=a[1],c=a[2],p=c.match(/android:name="([^"]+)"/)?.[1]||"unknown";if(wu.has(p))continue;let m=/android:exported="true"/.test(c),y=/android:permission="/.test(c);m&&!y&&n.push({id:`MAN-${String(i++).padStart(3,"0")}`,title:`Exported ${d}: ${p.split(".").pop()}`,description:`${p} is exported=true without android:permission protection`,severity:"medium",category:"manifest",file:s,recommendation:'Set android:exported="false" or add an android:permission attribute.'})}return/android:allowBackup="true"/.test(o)&&n.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:s,recommendation:'Set android:allowBackup="false" via expo-build-properties plugin.',autoFixable:!0}),/android:debuggable="true"/.test(o)&&n.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:s,recommendation:"Ensure debuggable is false for production builds. This is usually set automatically for release builds."}),{category:"manifest",label:"Android Manifest",findings:n,durationMs:0}}import Bn from"fs";import ji from"path";function $u(e){let t=ji.join(e,"ios");if(!Bn.existsSync(t))return null;let n=Bn.readdirSync(t,{withFileTypes:!0});for(let i of n){if(!i.isDirectory()||i.name==="Pods"||i.name.startsWith("."))continue;let r=ji.join(t,i.name,"Info.plist");if(Bn.existsSync(r))return r}return null}async function vs(e,t){let n=[],i=1,r=$u(e);if(!r)return{category:"ats",label:"iOS ATS Config",findings:[],durationMs:0,error:"No Info.plist found. Run with --prebuild or run `expo prebuild` first."};let o=Bn.readFileSync(r,"utf-8"),s=ji.relative(e,r),l=o.match(/<key>NSAppTransportSecurity<\/key>\s*<dict>([\s\S]*?)<\/dict>/);if(l){let a=l[1];/<key>NSAllowsArbitraryLoads<\/key>\s*<true\s*\/>/.test(a)&&n.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:s,recommendation:"Remove NSAllowsArbitraryLoads or set to false. Use domain-specific exceptions only if absolutely necessary."});let d=a.match(/<key>NSExceptionDomains<\/key>\s*<dict>([\s\S]*?)<\/dict>/);if(d){let c=d[1].match(/<key>([^<]+)<\/key>/g);if(c)for(let u of c){let p=u.replace(/<\/?key>/g,"");p!=="NSExceptionDomains"&&n.push({id:`ATS-${String(i++).padStart(3,"0")}`,title:`ATS exception: ${p}`,description:`ATS exception configured for ${p}`,severity:"low",category:"ats",file:s,recommendation:`Verify that the ATS exception for ${p} is necessary. Use HTTPS where possible.`})}}}return{category:"ats",label:"iOS ATS Config",findings:n,durationMs:0}}var Ru=[{category:"permissions",label:"Permission Audit",fn:cs,requiresPrebuild:!1},{category:"secrets",label:"Secrets Detection",fn:ps,requiresPrebuild:!1},{category:"dependencies",label:"Dependency CVEs",fn:fs,requiresPrebuild:!1},{category:"storage",label:"Insecure Storage",fn:hs,requiresPrebuild:!1},{category:"network",label:"HTTP URLs",fn:bs,requiresPrebuild:!1},{category:"debug",label:"Debug/Dev Flags",fn:ws,requiresPrebuild:!1},{category:"manifest",label:"Android Manifest",fn:$s,requiresPrebuild:!0},{category:"ats",label:"iOS ATS Config",fn:vs,requiresPrebuild:!0}];async function Os(e,t){let n=Ru;t.category&&(n=n.filter(s=>s.category===t.category),n.length===0&&(en.error(Oe.red(`Unknown category: ${t.category}`)),en.info(Oe.dim(`Available: ${Object.values(je).join(", ")}`)),process.exit(1)));let i=n.filter(s=>!s.requiresPrebuild),r=n.filter(s=>s.requiresPrebuild),o=[];for(let s of i){let l=Rs();l.start(Oe.dim(`Running ${s.label}...`));try{let a=Date.now(),d=await s.fn(e,t);d.durationMs=Date.now()-a,o.push(d);let c=d.findings.length;l.stop(c>0?Oe.yellow(`${s.label} \u2014 ${c} finding(s)`):Oe.green(`${s.label} \u2014 clean`))}catch(a){l.stop(Oe.red(`${s.label} \u2014 error`)),o.push({category:s.category,label:s.label,findings:[],durationMs:0,error:a.message})}}if(r.length>0){let s=Ds.join(e,"android"),l=Ds.join(e,"ios"),a=Ps.existsSync(s)||Ps.existsSync(l);if(!a&&t.prebuild){t.json||en.info(Oe.dim(`
|
|
1250
|
+
Running expo prebuild for deeper analysis...`));try{vu("npx expo prebuild --no-install",{cwd:e,stdio:"pipe"})}catch{return en.warn(Oe.yellow("Prebuild failed \u2014 skipping manifest/plist checks.")),o}}else if(!a)return t.json||en.info(Oe.dim(`
|
|
1251
|
+
Skipping manifest/plist checks \u2014 no android/ios dirs. Use --prebuild to generate them.`)),o;for(let d of r){let c=Rs();c.start(Oe.dim(`Running ${d.label}...`));try{let u=Date.now(),p=await d.fn(e,t);p.durationMs=Date.now()-u,o.push(p);let m=p.findings.length;c.stop(m>0?Oe.yellow(`${d.label} \u2014 ${m} finding(s)`):Oe.green(`${d.label} \u2014 clean`))}catch(u){c.stop(Oe.red(`${d.label} \u2014 error`)),o.push({category:d.category,label:d.label,findings:[],durationMs:0,error:u.message})}}}return o}import he from"chalk";import{log as me}from"@clack/prompts";var Rt={critical:he.bgRed.white.bold,high:he.red.bold,medium:he.yellow.bold,low:he.blue,info:he.dim},Fn={critical:0,high:1,medium:2,low:3,info:4};function Pu(e,t){if(!t)return!0;let n=Fn[t];return n===void 0?!0:Fn[e]<=n}function Cs(e,t){let n=0,i={critical:0,high:0,medium:0,low:0,info:0};for(let s of e){let l=s.findings.filter(d=>Pu(d.severity,t));if(l.length===0&&!s.error)continue;if(me.info(""),me.info(he.bold(` ${s.label}`)+he.dim(` ${l.length} finding(s)`)),me.info(he.dim(" "+"\u2500".repeat(60))),s.error){me.error(he.red(` Error: ${s.error}`));continue}let a=[...l].sort((d,c)=>Fn[d.severity]-Fn[c.severity]);for(let d of a){let c=Rt[d.severity](` ${d.severity.toUpperCase()} `);me.info(` ${c} ${he.bold(d.id)} ${d.title}`),me.info(he.dim(` ${d.description}`)),d.file&&me.info(he.dim(` File: ${d.file}${d.line?`:${d.line}`:""}`)),me.info(he.cyan(` Fix: ${d.recommendation}`)),me.info(""),i[d.severity]++,n++}}me.info(""),me.info(he.bold(" Summary")),me.info(he.dim(" "+"\u2500".repeat(60))),me.info(` Total: ${he.bold(String(n))} finding(s)`),me.info(` ${Rt.critical(` ${i.critical} Critical `)} ${Rt.high(` ${i.high} High `)} ${Rt.medium(` ${i.medium} Medium `)} ${Rt.low(` ${i.low} Low `)} ${Rt.info(` ${i.info} Info `)}`);let r=i.critical>0,o=i.high>0;r||o?(me.info(""),me.error(he.red.bold(` FAIL \u2014 ${i.critical} critical, ${i.high} high issue(s) found`))):n>0?(me.info(""),me.warn(he.yellow(" PASS (with warnings) \u2014 no critical or high issues"))):(me.info(""),me.success(he.green.bold(" PASS \u2014 no issues found")))}function Ns(e,t){let n=e.flatMap(r=>r.findings),i={};for(let r of Object.values(Te))i[r]=n.filter(o=>o.severity===r).length;return{version:"1.0.0",timestamp:new Date().toISOString(),project:t.name||"unknown",projectVersion:t.version||"0.0.0",summary:{total:n.length,...i},passed:i.critical===0&&i.high===0,checks:e.map(r=>({category:r.category,label:r.label,findingCount:r.findings.length,durationMs:r.durationMs,error:r.error||null})),findings:n}}import{log as ge,spinner as Du}from"@clack/prompts";import ue from"chalk";import Ze from"fs";import Ou from"os";import Pt from"path";import{execSync as Cu}from"child_process";var Ts=16384,Nu=1,Tu=Buffer.from([127,69,76,70]);async function ks(e){ge.info(ue.bold.underline("16KB Page Alignment Check")),console.log("");let t=Pt.resolve(e);if(!Ze.existsSync(t))return ge.error(ue.red(`APK file not found: ${t}`)),!1;if(!t.endsWith(".apk"))return ge.error(ue.red("The provided file is not an APK file.")),!1;let n=Du();n.start("Extracting and analyzing native libraries...");let i=Ze.mkdtempSync(Pt.join(Ou.tmpdir(),"mach-16kb-"));try{try{Cu(`unzip -o -q "${t}" "lib/arm64-v8a/*.so" "lib/x86_64/*.so" -d "${i}" 2>/dev/null`,{encoding:"utf-8",maxBuffer:50*1024*1024})}catch{}let r=Ls(Pt.join(i,"lib"));if(r.length===0)return n.stop("Analysis complete."),ge.info(ue.yellow("No arm64-v8a or x86_64 native libraries found in the APK.")),ge.info(ue.dim("16KB alignment check only applies to arm64-v8a and x86_64 architectures.")),!0;let o=[];for(let a of r){let d=Pt.relative(i,a),c=Lu(d),u=Pt.basename(a),p=ku(a);p!==null&&o.push({name:u,filePath:d,arch:c,align:p,compatible:p>=Ts})}if(n.stop("Analysis complete."),o.length===0)return ge.info(ue.yellow("No valid ELF shared libraries found.")),!0;let s=o.filter(a=>!a.compatible),l=o.filter(a=>a.compatible);if(ge.info(ue.dim(`Checked ${o.length} native librar${o.length===1?"y":"ies"}
|
|
1252
|
+
`)),s.length>0){ge.info(ue.red.bold(`Incompatible libraries:
|
|
1253
|
+
`));for(let a of s)ge.error(ue.red(`${ue.bold(a.name)} ${ue.dim(`(${a.arch})`)}`)),ge.info(ue.dim(` PT_LOAD alignment: 2**${Math.log2(a.align)} (${a.align} bytes, needs 2**14 = ${Ts})`))}return l.length>0&&(console.log(""),ge.success(ue.green(`${l.length} librar${l.length===1?"y":"ies"} correctly aligned (2**14 or higher).`))),console.log(""),s.length===0?(ge.success(ue.green.bold("ELF Verification Successful. APK is 16KB compatible.")),!0):(ge.error(ue.red.bold(`Found ${s.length} unaligned lib${s.length===1?"":"s"} (arm64-v8a/x86_64 libs need to be aligned).`)),console.log(""),ge.info(ue.yellow("To fix this:")),ge.info(ue.dim(" 1. Rebuild with NDK r28+ which defaults to 16KB page alignment")),ge.info(ue.dim(" 2. Or set -DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON in CMake")),ge.info(ue.dim(" 3. Update third-party libraries that ship prebuilt .so files")),ge.info(ue.dim(" 4. After rebuilding: zipalign -p -f -v 16 input.apk output.apk")),console.log(""),ge.info(ue.dim("Reference: https://developer.android.com/guide/practices/page-sizes")),!1)}catch(r){return n.stop("Analysis failed."),ge.error(ue.red(`Failed to analyze APK: ${r.message}`)),!1}finally{try{Ze.rmSync(i,{recursive:!0,force:!0})}catch{}}}function ku(e){let t=Ze.openSync(e,"r");try{let n=Buffer.alloc(64);if(Ze.readSync(t,n,0,64,0),!n.subarray(0,4).equals(Tu))return null;let i=n[4]===2,r=n[5]===1,o=(p,m)=>r?p.readUInt16LE(m):p.readUInt16BE(m),s=(p,m)=>r?p.readUInt32LE(m):p.readUInt32BE(m),l=(p,m)=>Number(r?p.readBigUInt64LE(m):p.readBigUInt64BE(m)),a,d,c;i?(a=l(n,32),d=o(n,54),c=o(n,56)):(a=s(n,28),d=o(n,42),c=o(n,44));let u=null;for(let p=0;p<c;p++){let m=Buffer.alloc(d);if(Ze.readSync(t,m,0,d,a+p*d),s(m,0)!==Nu)continue;let C;i?C=l(m,48):C=s(m,28),C>0&&(u===null||C<u)&&(u=C)}return u??0}catch{return null}finally{Ze.closeSync(t)}}function Ls(e){let t=[];if(!Ze.existsSync(e))return t;let n=Ze.readdirSync(e,{withFileTypes:!0});for(let i of n){let r=Pt.join(e,i.name);i.isDirectory()?t.push(...Ls(r)):i.name.endsWith(".so")&&t.push(r)}return t}function Lu(e){return e.includes("arm64-v8a")?"arm64-v8a":e.includes("x86_64")?"x86_64":"unknown"}var Us=async e=>{if(Re()||(ke.error(Ge.red(`You are not logged in. Run \`${f.nameLower} login\` first.`)),process.exit(1)),e.apk){await Uu(e);return}let n=process.cwd(),i=Hn.join(n,"package.json");tn.existsSync(i)||(ke.error(Ge.red("No package.json found. Run this command from a project root.")),process.exit(1));let r=JSON.parse(tn.readFileSync(i,"utf-8")),o=!!(r.dependencies?.expo||r.devDependencies?.expo);e.json||(ke.info(Ge.dim(`Project: ${r.name||"unknown"} v${r.version||"0.0.0"}`)),ke.info(Ge.dim(`Type: ${o?"Expo":"Bare React Native"}`)),ke.info(""));let s={json:e.json,fix:e.fix,category:e.category,severity:e.severity,prebuild:e.prebuild},l=await Os(n,s);e.json?console.log(JSON.stringify(Ns(l,r),null,2)):Cs(l,e.severity);let a=l.some(c=>c.findings.some(u=>u.severity==="critical")),d=l.some(c=>c.findings.some(u=>u.severity==="high"));(a||d)&&process.exit(1)},xs=["16kb"];async function Uu(e){let t=e.category?.toLowerCase();t&&!xs.includes(t)&&(ke.error(Ge.red(`Unknown APK check category: "${t}"`)),ke.info(Ge.dim(`Available APK checks: ${xs.join(", ")}`)),process.exit(1));let n=await Bu(e.apk);n||process.exit(1);let i=!t,r=!1;(i||t==="16kb")&&(await ks(n)||(r=!0)),r&&process.exit(1)}async function Bu(e){if(e.startsWith("build:")){let n=e.slice(6);return await Fu(n)}if(e.startsWith("http://")||e.startsWith("https://"))return await Bs(e);let t=Hn.resolve(e);return tn.existsSync(t)?t:(ke.error(Ge.red(`APK file not found: ${t}`)),null)}async function Fu(e){let t=Ms();t.start(`Fetching APK from build ${e}...`);try{let n=await R.get(`/build/${e}`);if(n.data.status!=="success")throw new Error(n.data.message);let i=n.data.build;if(!i)throw new Error("Build not found");let r=i.artifacts?.find(o=>o.type?o.type==="apk":o.name?.endsWith(".apk")||o.url?.includes(".apk"));return!r||!r.url?(t.stop("No APK artifact found"),ke.error(Ge.red("This build does not have an APK artifact.")),ke.info(Ge.dim("Make sure the build produced an APK (not just an AAB).")),null):(t.stop(`Found build: ${i.buildId||e}`),await Bs(r.url))}catch(n){return t.stop("Failed to fetch build"),ke.error(Ge.red(n.message)),null}}async function Bs(e){let t=Ms();t.start("Downloading APK...");try{let n=tn.mkdtempSync(Hn.join(xu.tmpdir(),`${f.nameLower}-audit-`)),i=Hn.join(n,"app.apk"),r=await Mu.get(e,{responseType:"arraybuffer"});tn.writeFileSync(i,r.data);let o=(r.data.length/(1024*1024)).toFixed(1);return t.stop(`Downloaded APK (${o} MB)`),i}catch(n){return t.stop("Download failed"),ke.error(Ge.red(`Failed to download APK: ${n.message}`)),null}}var Gu=console.log;console.log=()=>{};ju();console.log=Gu;we(be.bgCyan.black(f.cliTag("Production Build Orchestrator")));var Vu=Ku(import.meta.url),zu=Vu("../package.json"),oe=new Hu;oe.name(f.nameLower).description(`${f.name} CLI: Powerful Cloud Infrastructure Tools`).version(zu.version).option("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1);oe.command("agent").description("Manage local device discovery agent for the Install Hub (port 7070)").argument("[action]","start, run, install, status, restart, stop, or uninstall","start").action(async e=>{await Ho(e)});oe.command("host").description("Setup AWS S3 static hosting and CloudFront").action(async()=>{we(be.bgCyan.black(f.cliTag("Hosting"))),await tr()});oe.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=>{we(be.bgCyan.black(f.cliTag("Sitemap Generator"))),await or(e)});oe.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 Le("--build-id <id>","Internal build ID").hideHelp()).addOption(new Le("--project-id <id>","Internal project ID").hideHelp()).addOption(new Le("--fail-only","Internal: mark an existing build failed").hideHelp()).addOption(new Le("--error <message>","Internal failure message").hideHelp()).option("--local","Run build on local machine").option("--auto-version","Automatically fetch and increment Android versionCode or iOS buildNumber from the store").option("--auto-submit","Submit this build after it completes successfully").option("--submit-track <track>","Google Play track to use with --auto-submit").option("--submit-release-status <status>","Google Play release status to use with --auto-submit").option("--submit-rollout <fraction>","Google Play staged rollout fraction to use with --auto-submit").option("--submit-changes-not-sent-for-review","Commit Google Play changes without automatically sending them for review when using --auto-submit").option("--submit-credential-id <id>","Service credential ID to use with --auto-submit").option("--submit-json-output <path>","Write auto-submit metadata JSON to a file for CI/CD").option("--verbose","Enable verbose logging").option("--json-output <path>","Write build metadata JSON to a file for CI/CD").option("--maestro","Queue a managed Maestro test run after a successful build").option("--maestro-flows <path>","Maestro flow file or directory (default: .maestro)").option("--maestro-device <device>","Managed Maestro device profile").option("--maestro-retries <n>","Retries for the Maestro run","1").option("--maestro-record","Enable screen recording where supported").option("--maestro-use-build-source","Use Maestro flows from the build source snapshot instead of uploading local flows").option("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1).action(async(e,t)=>{let n=oe.opts();t.yes=t.yes||n.yes,t.quiet=t.quiet||n.quiet,t.platform=e||t.platform,t.buildProfile=t.profile||t.buildProfile,t.quiet||we(be.bgCyan.black(f.cliTag("Cloud Build"))),await bn(t)});oe.command("maestro").description("Run Maestro tests locally or with the managed Mach runner").option("--platform <os>","Target platform (android/ios)").option("-p, --profile <name>","Build profile to resolve when using --latest","production").option("--latest","Use the latest successful build for the platform/profile").option("--build-id <id>","Use a specific Mach build ID").option("--build-url <url>","Use a Mach build URL").option("--artifact-url <url>","Use a direct APK or iOS simulator app artifact URL").option("--local","Run Maestro on a connected local emulator/device instead of the managed runner").option("--maestro-flows <path>","Maestro flow file or directory (default: .maestro)").option("--maestro-device <device>","Managed Maestro device profile").option("--maestro-retries <n>","Retries for the Maestro run","1").option("--maestro-record","Enable screen recording where supported").option("--maestro-use-build-source","Use Maestro flows from the build source snapshot instead of uploading local flows").option("--wait","Wait for managed Maestro completion and exit non-zero on failure").option("--wait-timeout <minutes>","Maximum minutes to wait for managed Maestro completion","60").option("--wait-interval <seconds>","Polling interval while waiting for managed Maestro completion","15").option("--json-output <path>","Write test run metadata JSON to a file for CI/CD").addOption(new Le("--local-runner","Internal: execute a managed Maestro run on this machine").hideHelp()).addOption(new Le("--test-run-id <id>","Internal test run ID").hideHelp()).addOption(new Le("--project-id <id>","Internal project ID").hideHelp()).addOption(new Le("--runner-token <token>","Internal runner token").hideHelp()).action(async e=>{we(be.bgCyan.black(f.cliTag("Maestro Testing"))),await xr(e)});oe.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=>{we(be.bgCyan.black(f.cliTag("OTA Update"))),await Qo(e)});oe.command("submit").description("Automated Store Submission (App Store / Google Play)").option("--platform <os>","Target platform (ios/android)").option("-p, --profile <name>","Build/submission profile to submit from (e.g. production, preprod)").option("--track <track>","Google Play Track (internal, alpha, beta, production)").option("--release-status <status>","Google Play release status (completed, draft, halted, inProgress)").option("--rollout <fraction>","Google Play staged rollout fraction for inProgress releases (example: 0.1)").option("--changes-not-sent-for-review","Commit Google Play changes without automatically sending them for review").option("--ssh-host <host>","Remote macOS host for iOS submission").option("--ssh-user <user>","SSH username for remote iOS submission").option("--ssh-key <path>","Path to private SSH key for remote iOS submission").option("--credential-id <id>","Service credential ID to use when multiple submission credentials exist").option("--local","Run submission on this machine (internal runner mode for iOS)").addOption(new Le("--submit-id <id>","Internal submission ID").hideHelp()).addOption(new Le("--project-id <id>","Internal project ID").hideHelp()).addOption(new Le("--package-name <name>","Internal Android package name").hideHelp()).addOption(new Le("--bundle-id <id>","Internal iOS bundle identifier").hideHelp()).option("--json-output <path>","Write submission metadata JSON to a file for CI/CD").option("--latest","Use the latest successful build for submission").option("--build-id <id>","Use a specific build ID for submission").action(async e=>{let t=oe.opts();e.quiet=e.quiet||t.quiet,e.yes=e.yes||t.yes,we(be.bgCyan.black(f.cliTag("Store Submission"))),await mn(e)});oe.command("login").description(`Login to ${f.name} Dashboard`).action(async()=>{we(be.bgCyan.black(f.cliTag("Login"))),await Vo()});oe.command("logout").description(`Logout from ${f.name} on this machine`).action(async()=>{we(be.bgCyan.black(f.cliTag("Logout"))),await zo()});oe.command("link").description(`Link local directory to a ${f.name} Project`).action(async()=>{we(be.bgCyan.black(f.cliTag("Link Project"))),await Yo()});oe.command("me").description("Display currently logged in user details").action(async()=>{await ts()});oe.command("init").description(`Create a new ${f.name} Project`).action(async()=>{we(be.bgCyan.black(f.cliTag("Init Project"))),await Jo()});oe.command("env").description("Manage Environment Variables").argument("<action>","Action to perform: set, list, pull, download, or export").argument("[args...]","Key=Value pairs for set action").option("-e, --environment <name>","Environment to pull/download","development").option("-o, --out <file>","Output file for pull/download",".env.local").option("--overwrite","Overwrite output file if it already exists").action(async(e,t,n)=>{we(be.bgCyan.black(f.cliTag("Env Manager"))),await Xo(e,t,n)});oe.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=>{we(be.bgCyan.black(f.cliTag("Dev Server"))),await is(e)});oe.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 rs(e)});oe.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:t}=await import("./credentials-KDH6HGWP.js");await t(e)});oe.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=>{we(be.bgCyan.black(f.cliTag("Credentials Setup"))),await Ct(e),Fs(be.green("Done!"))});oe.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)").option("--bundle-id <id>","Bundle identifier / Android package name to attach this service credential to").option("--package-name <name>","Android package name to attach this service credential to").option("-p, --profile <name>","Build profile to resolve package/bundle identifier from config").action(async e=>{we(be.bgCyan.black(f.cliTag("Service Credentials"))),await Qi(e),Fs(be.green("Done!"))});var Gi=oe.command("device").description("Manage registered iOS test devices");Gi.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").option("--team-id <id>","Apple Developer Team ID for this device").action(async e=>{await Cn("register",e)});Gi.command("list").description("List all registered devices").option("--team-id <id>","Filter by Apple Developer Team ID").action(async e=>{await Cn("list",e)});Gi.command("remove").description("Remove a registered device").option("--udid <udid>","Device UDID to remove").option("--team-id <id>","Apple Developer Team ID for this device").action(async e=>{await Cn("remove",e)});oe.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=>{we(be.bgCyan.black(f.cliTag(e.apk?"APK Audit":"Security Audit"))),await Us(e)});var Wu=new Set(["login","logout","agent"]);oe.hook("preAction",(e,t)=>{let n=t.name(),i=t.opts?.()||{};n==="maestro"&&(i.local||i.localRunner)||Wu.has(n)||Ji()});oe.on("command:*",()=>{console.error(`Invalid command: %s
|
|
1254
|
+
See --help for a list of available commands.`,oe.args.join(" ")),process.exit(1)});process.argv.slice(2).length||oe.help();oe.parse(process.argv);
|