@radhya/mach 2.0.7 → 2.0.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +145 -133
- package/package.json +1 -1
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 tr,b as $e,c as nt,d as nr,e as ir,f as Et,g as rr,i as Tt}from"./chunk-UZNUPNFP.js";import{a as m,b as Zi,c as Pe,d as Qi,e as er,f as bt,g as We,h as P}from"./chunk-HIP5BA3H.js";import{Command as _f,Option as xe}from"commander";import{configDotenv as $f}from"dotenv";import{intro as we,outro as Qs}from"@clack/prompts";import be from"chalk";import{text as or,confirm as ta,spinner as na,isCancel as Yn,cancel as kt,note as ia,outro as ra}from"@clack/prompts";import xt from"chalk";async function sr(){try{let e=await or({message:"Enter Bucket Name:",placeholder:"e.g. my-app-dev",validate(r){if(r.length===0)return"Bucket name is required"}});Yn(e)&&(kt("Operation cancelled."),process.exit(0));let t=await or({message:"Enter Region:",initialValue:"ap-south-1"});Yn(t)&&(kt("Operation cancelled."),process.exit(0));let n=await ta({message:"Do you want to create a CloudFront Distribution for this bucket?",initialValue:!0});Yn(n)&&(kt("Operation cancelled."),process.exit(0));let i=na();i.start("Setting up hosting infrastructure...");try{let r=await P.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: ${xt.cyan(o.bucketName)}
|
|
3
|
+
`;s+=`Region: ${xt.cyan(o.region)}
|
|
4
|
+
`,s+=`S3 Website URL: ${xt.blue(o.s3WebsiteUrl)}`,o.cloudFrontId&&(s+=`
|
|
5
|
+
|
|
6
|
+
CloudFront ID: ${xt.cyan(o.cloudFrontId)}`,s+=`
|
|
7
|
+
CloudFront URL: ${xt.blue(o.cloudFrontUrl)}`),ia(s,"Setup Complete!"),ra("You are all set!")}catch(r){i.stop("Setup failed"),kt(`Error: ${r.response?.data?.message||r.message}`)}}catch(e){kt(`An unexpected error occurred: ${e.message}`)}}import{readdir as oa,writeFile as sa,access as aa,mkdir as la}from"fs/promises";import{join as ar}from"path";import{spinner as da,text as lr,isCancel as dr,cancel as Jn,note as ca,outro as ua}from"@clack/prompts";import fa from"chalk";async function pa(){let e=["./app","./src/app"];for(let t of e)try{return await aa(t),t}catch{}return null}async function cr(e){try{let n=await pa()||"./app",i=await lr({message:"Enter path to your app directory:",placeholder:n,initialValue:n,validate(u){if(u.length===0)return"Path is required"}});dr(i)&&(Jn("Operation cancelled."),process.exit(0));let r=await lr({message:"Enter your website base URL:",placeholder:"https://example.com",validate(u){if(u.length===0)return"Base URL is required";if(!u.startsWith("http"))return"URL must start with http:// or https://"}});dr(r)&&(Jn("Operation cancelled."),process.exit(0));let o=da();o.start("Scanning app directory for routes...");let s=await ur(i);o.stop(`Found ${s.length} routes`);let l=ma(s,r),a=e.output||"./public/sitemap.xml";o.start(`Writing sitemap to ${a}...`);let c=a.substring(0,a.lastIndexOf("/"));if(c)try{await la(c,{recursive:!0})}catch{}await sa(a,l,"utf-8"),o.stop("Sitemap generated successfully!"),ca(`Routes included:
|
|
8
|
+
${s.map(u=>` \u2022 ${u.path}`).join(`
|
|
9
|
+
`)}`,"Sitemap Summary"),ua(`Sitemap saved to ${fa.cyan(a)}`)}catch(t){Jn(`An error occurred: ${t.message}`)}}async function ur(e,t=""){let n=[];try{let i=await oa(e,{withFileTypes:!0});for(let r of i){let o=ar(e,r.name);if(!(r.name.startsWith("_")||r.name.startsWith("."))){if(r.isDirectory()){let s=await ur(o,ar(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 ma(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 zd}from"crypto";import ve from"path";import bn from"axios";import Wd from"os";import{spinner as Di,select as fo,confirm as po,isCancel as En,cancel as mo,log as $}from"@clack/prompts";import v from"chalk";import de from"fs";import{execSync as go}from"child_process";import ho from"adm-zip";import{spinner as Ea,log as ln}from"@clack/prompts";import pr from"chalk";import mr from"fs";import gr from"path";var fr=`#!/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
|
-
`):"",f;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 ga from"crypto";var ha="mach-env-v2-js-bundle-cache",ya=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"]),Sa=["PRESIGNED_","KEYSTORE_PASSWORD_"],ba=e=>!e||ya.has(e)?!1:!Sa.some(t=>e.startsWith(t)),ft=(e,t,n)=>({...e,EXPO_NO_DOTENV:"1",MACH_BUILD_PROFILE:t,MACH_APP_NAME:n.appName||n.name||"App"}),At=e=>{let t=Object.entries(e).filter(([n])=>ba(n)).sort(([n],[i])=>n.localeCompare(i));return ga.createHash("sha256").update(JSON.stringify({version:ha,entries:t})).digest("hex")};var qn=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`"),Xn=e=>["1","true","yes","on"].includes(String(e||"").trim().toLowerCase()),Aa=e=>/(^|[-_])(maestro|e2e|test|emulator)([-_]|$)/i.test(e),Ia=(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)||Xn(n.MACH_PROFILE_ANDROID_EMULATOR)||Xn(n.MACH_ANDROID_INCLUDE_EMULATOR_ABIS)||Xn(n.MACH_PROFILE_ANDROID_INCLUDE_EMULATOR_ABIS)?"armeabi-v7a,arm64-v8a,x86_64":"armeabi-v7a,arm64-v8a")},hr=async(e,t,n={},i,r)=>{let o=Ea(),s=e.buildProfile||"production",l=s==="production",a=e.apk===!0,c=e.developmentClient?"assembleDebug":l?"bundleRelease":"assembleRelease",u=e.buildCommand||(a?"assembleRelease":c),d=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
|
+
`):"",f;if(r){let U=gr.isAbsolute(r)?r:gr.resolve(process.cwd(),r);mr.existsSync(U)?(f=mr.readFileSync(U,"utf-8"),ln.info(pr.magenta(`\u2713 Loaded preBuild hook: ${r}`))):ln.warn(`preBuild script not found at ${U} \u2014 skipping`)}let p=Ia(e,s,n),h={...ft(n,s,e),MACH_ANDROID_RELEASE_ABIS:p},D=At(h),N=fr.replace(/\{\{BUILD_ID\}\}/g,t).replace(/\{\{BUILD_COMMAND\}\}/g,u).replace("{{NODE_VERSION_SETUP}}",d).replace("{{ENV_VARS}}",`
|
|
535
|
+
export MACH_APP_NAME="${qn(h.MACH_APP_NAME)}"
|
|
536
|
+
export MACH_BUILD_PROFILE="${qn(s)}"
|
|
537
|
+
export MACH_ANDROID_RELEASE_ABIS="${qn(p)}"
|
|
538
|
+
export MACH_ENV_FINGERPRINT="${D}"
|
|
539
539
|
export EXPO_NO_DOTENV=1
|
|
540
540
|
{{ENV_VARS}}
|
|
541
|
-
`);if(e.dryRun){
|
|
541
|
+
`);if(e.dryRun){ln.info("User Data Script (dry run):"),console.log(N);return}o.start("Requesting cloud build instance...");try{let U=await P.post("/builds/launch-android",{projectId:i,buildId:t,platform:e.platform,buildProfile:e.buildProfile,buildCommand:u,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:f});if(U.data.status!=="success")throw new Error(U.data.message||"Failed to launch build instance");let R=U.data.instanceId;return o.stop("Build Started"),ln.success(pr.green(`Build initiated on cloud instance (${R}).`)),{instanceId:R}}catch(U){o.stop("Android Build Failed");let R=U.response?.data?.message||U.message;throw new Error(`Failed to launch Android build: ${R}`)}};import{spinner as wa,log as It}from"@clack/prompts";import it from"chalk";import _a from"fs";import{execSync as Lt}from"child_process";var yr=`#!/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
|
|
|
@@ -1129,41 +1129,41 @@ touch done
|
|
|
1129
1129
|
if [ ! -z "$PRESIGNED_DONE_MARKER" ]; then
|
|
1130
1130
|
curl -X PUT -T done "$PRESIGNED_DONE_MARKER" --silent
|
|
1131
1131
|
fi
|
|
1132
|
-
`;var
|
|
1133
|
-
`:
|
|
1134
|
-
`);r.message("Generating macOS build script...");let
|
|
1135
|
-
`:"";if(n)for(let[
|
|
1136
|
-
`}let
|
|
1132
|
+
`;var Sr=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`"),br=async(e,t,n={},i)=>{let r=wa();e.sshHost||(e.sshHost="localhost",It.message(it.yellow("No SSH host provided, defaulting to localhost."))),r.start(`Connecting to remote Mac at ${it.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}`,c=`scp ${s?`-i ${s}`:""} -o StrictHostKeyChecking=no`;try{let u=o==="ubuntu"?"/home/ubuntu":`/Users/${o}`,d=(n.PROJECT_ID||"default_project").replace(/[^a-zA-Z0-9-_]/g,"_"),f=`${u}/${m.remoteWorkspacesDir}/${d}`;r.message(`Preparing stable workspace: ${f}...`),Lt(`${a} "mkdir -p ${f}"`,{stdio:"inherit"}),r.message("Transferring source code...");let p=`/tmp/${m.nameLower}-source-${t}.zip`;Lt(`${c} ${p} ${l}:${f}/source.zip`,{stdio:"inherit"});let h=e.iosApiKeyPath?`${f}/api_key.p8`:"",D="";e.iosApiKeyPath&&(r.message("Uploading App Store Connect API key..."),Lt(`${c} ${e.iosApiKeyPath} ${l}:${h}`),e.iosApiKeyId&&e.iosApiKeyIssuer&&(D=`-authenticationKeyID ${e.iosApiKeyId} -authenticationKeyIssuerID ${e.iosApiKeyIssuer} -authenticationKeyPath ${h}`));let N={};if(i)try{let A=await P.post(`/builds/${i}/${t}/build-urls`,{platform:"ios"});A.data.status==="success"&&(N=A.data.urls)}catch(A){It.warn(it.yellow(`Could not fetch build URLs: ${A.message}`))}let U="";if(N.credentials&&N.credentials.length>0)for(let A of N.credentials)A.type==="p12"?U+=`curl -sf -o "$CERT_DIR/${A.name}" "${A.downloadUrl}" || true
|
|
1133
|
+
`:A.type==="mobileprovision"&&(U+=`curl -sf -o "$PROV_TEMP/${A.name}" "${A.downloadUrl}" || true
|
|
1134
|
+
`);r.message("Generating macOS build script...");let R=process.env.CODEARTIFACT_AUTH_TOKEN?`export CODEARTIFACT_AUTH_TOKEN="${process.env.CODEARTIFACT_AUTH_TOKEN}"
|
|
1135
|
+
`:"";if(n)for(let[A,S]of Object.entries(n)){let x=S.replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");R+=`export ${A}="${x}"
|
|
1136
|
+
`}let K=e.buildProfile||"production",b=ft(n,K,e),W=At(b),ne=[R,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="${Sr(K)}"`,`export MACH_APP_NAME="${Sr(b.MACH_APP_NAME)}"`,`export MACH_ENV_FINGERPRINT="${W}"`,"export EXPO_NO_DOTENV=1",`export ${m.envPrefix}PROJECT_ID="${d}"`,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="${m.credentialsKeychain}"`,`export MATCH_KEYCHAIN_PASSWORD="${m.keychainPassword}"`].filter(Boolean).join(`
|
|
1137
1137
|
`),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(`
|
|
1138
|
-
`):"",T=
|
|
1139
|
-
${
|
|
1140
|
-
${
|
|
1141
|
-
${tt.dim("Note: Links are valid for 7 days.")}`)}else x&&It.warn("Simulator build completed. No artifacts uploaded.")}catch(v){r.stop("Could not fetch artifacts"),It.warn(tt.yellow(`Artifact listing failed: ${v.message}`))}}}catch(c){throw r.stop("iOS Build Failed"),c}};import Ia from"crypto";import Me from"axios";import br from"fs";var We=6e4,wa=12e4,Xn=4,qe=e=>encodeURIComponent(e),_a=e=>new Promise(t=>setTimeout(t,e));async function Ue(e,t){let n;for(let i=1;i<=Xn;i++)try{return await t()}catch(r){if(n=r,i>=Xn||!$a(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}/${Xn}); retrying in ${Math.round(s/1e3)}s...`),await _a(s)}throw n}function $a(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;try{let i=await ln(t),r=qe(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:We}))).data.id,!n)throw new Error("Google Play edit insert succeeded but did not return an edit id.");let s=qe(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:We}))).data.tracks||[];for(let c of d)if(c.releases){for(let u of c.releases)if(u.versionCodes)for(let f of u.versionCodes){let p=parseInt(f,10);p>l&&(l=p)}}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:We}))).data.bundles||[];for(let f of u)f.versionCode&&f.versionCode>l&&(l=f.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:We}))).data.apks||[];for(let f of u)f.versionCode&&f.versionCode>l&&(l=f.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 ln(t);await Ue("delete edit",()=>Me.delete(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${qe(e)}/edits/${qe(n)}`,{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:We}))}catch{}}}async function Ar(e){let{packageName:t,serviceAccount:n,aabPath:i,track:r,releaseStatus:o,userFraction:s,changesNotSentForReview:l}=e,a;try{let c={Authorization:`Bearer ${await ln(n)}`,Connection:"close"},u=qe(t);if(a=(await Ue("create edit",()=>Me.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${u}/edits`,{},{headers:c,timeout:We}))).data.id,!a)throw new Error("Google Play edit insert succeeded but did not return an edit id.");let p=qe(a),h=br.statSync(i),O=await Ue("upload AAB",()=>Me.post(`https://androidpublisher.googleapis.com/upload/androidpublisher/v3/applications/${u}/edits/${p}/bundles`,br.createReadStream(i),{headers:{...c,"Content-Type":"application/octet-stream","Content-Length":h.size},maxBodyLength:1/0,maxContentLength:1/0,params:{uploadType:"media"},timeout:wa})),N=Number(O.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/${p}/tracks/${qe(r)}`,{releases:[M]},{headers:c,timeout:We})),await Ue("commit edit",()=>Me.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${u}/edits/${p}:commit`,{},{headers:c,params:l?{changesNotSentForReview:!0}:void 0,timeout:We})),{editId:a,versionCode:N,track:r,releaseStatus:o,userFraction:s}}catch(d){if(a)try{let u=await ln(n);await Ue("delete edit",()=>Me.delete(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${qe(t)}/edits/${qe(a)}`,{headers:{Authorization:`Bearer ${u}`,Connection:"close"},timeout:We}))}catch{}let c=d.response?.data?.error?.message||d.message;throw new Error(`Google Play API Error: ${c}`)}}async function ln(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=Ia.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:We}))).data.access_token}import va from"crypto";import Ir from"axios";var Qn="https://api.appstoreconnect.apple.com/v1",wr=6e4,Zn=4,Ra=e=>new Promise(t=>setTimeout(t,e));function Pa(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=va.createSign("SHA256");l.update(s);let a=l.sign({key:n,dsaEncoding:"ieee-p1363"}).toString("base64url");return`${s}.${a}`}function Da(e){let t=e.response?.status;return t?t===408||t===409||t===425||t===429||t>=500:!0}async function _r(e,t){let n;for(let i=1;i<=Zn;i++)try{return await t()}catch(r){if(n=r,i>=Zn||!Da(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}/${Zn}); retrying in ${Math.round(s/1e3)}s...`),await Ra(s)}throw n}function $r(e){return{Authorization:`Bearer ${Pa(e.keyId,e.issuerId,e.privateKey)}`,"Content-Type":"application/json",Connection:"close"}}function Oa(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 dn(e){let t=String(e||"").trim();if(/^\d+(?:\.\d+){0,2}$/.test(t))return t.split(".").map(n=>Number(n))}function Ca(e,t){let n=dn(e),i=dn(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 Na(e){let t=dn(e);return!t||t.length===0?"1":(t[t.length-1]+=1,t.join("."))}async function Ta(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 _r("lookup app by bundle ID",()=>Ir.get(`${Qn}/apps`,{headers:$r(e),params:{"filter[bundleId]":n,limit:1},timeout:wr}))).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 vr(e){let t={keyId:e.keyId,issuerId:e.issuerId,privateKey:e.privateKey};try{let n=await Ta(t,e.ascAppId,e.bundleId),i=`${Qn}/builds`,r="0",o,s=0;for(;i&&s<10;){s+=1;let l=await _r("list builds",()=>Ir.get(i,{headers:$r(t),params:i===`${Qn}/builds`?{"filter[app]":n,"fields[builds]":"version,uploadedDate",sort:"-uploadedDate",limit:200}:void 0,timeout:wr})),a=l.data?.data||[];for(let d of a){let c=String(d.attributes?.version||"").trim();dn(c)&&Ca(c,r)>0&&(r=c,o=d.attributes?.uploadedDate)}i=l.data?.links?.next}return{appId:n,latestBuildNumber:r,nextBuildNumber:Na(r),latestUploadedDate:o}}catch(n){throw new Error(`App Store Connect API Error: ${Oa(n)}`)}}import{spinner as cn,log as I,isCancel as un,confirm as ka,select as ti}from"@clack/prompts";import b from"chalk";import y from"fs";import w from"path";import{execFileSync as xt,execSync as te,spawn as Or}from"child_process";import Ae from"os";import La from"crypto";var Cr=(e,t)=>t.filter(n=>y.existsSync(w.join(e,n))).reduce((n,i)=>n.update(y.readFileSync(w.join(e,i))),La.createHash("sha256")).digest("hex").slice(0,16),xa=e=>Cr(e,["package.json","yarn.lock","package-lock.json","bun.lockb"]),Ma=e=>Cr(e,["Podfile","Podfile.lock"]),Ua=e=>{let t=w.join(e,"fingerprint.json");try{return JSON.parse(y.readFileSync(t,"utf-8"))}catch{return{}}},Rr=(e,t)=>{y.mkdirSync(e,{recursive:!0}),y.writeFileSync(w.join(e,"fingerprint.json"),JSON.stringify(t,null,2))},Ba=7200*1e3,Fa=(e,t)=>{y.mkdirSync(e,{recursive:!0});let n=w.join(e,"build.lock");if(y.existsSync(n))try{let i=JSON.parse(y.readFileSync(n,"utf-8")),r=Date.now()-(i.timestamp||0);if(r<Ba)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}y.writeFileSync(n,JSON.stringify({buildId:t,pid:process.pid,timestamp:Date.now()}))},Ha=(e,t)=>{let n=w.join(e,"build.lock");try{y.existsSync(n)&&JSON.parse(y.readFileSync(n,"utf-8")).buildId===t&&y.unlinkSync(n)}catch{}},Pr=15e5,Dr=(e,t)=>{let n=e+t;return n.length>Pr?n.slice(-Pr):n},Nr=e=>e.replace(/\u001b\[[0-9;]*m/g,""),Tr=e=>/\berror:|fatal error:|xcodebuild: error|The following build commands failed|Command PhaseScriptExecution failed|PhaseScriptExecution|Command .* failed|CodeSign|Provisioning profile|No profiles|requires a provisioning profile|Undefined symbols|ld:|clang: error|SwiftCompile|CompileC|node: command not found|env: node|No such file or directory|Permission denied/i.test(e),ja=e=>{let t=new Set,n=[];e.forEach((r,o)=>{Tr(r)&&n.push(o)});for(let r of n){let o=/PhaseScriptExecution|Command PhaseScriptExecution failed|The following build commands failed/i.test(e[r])?18:8,s=/The following build commands failed/i.test(e[r])?18:10;for(let l=Math.max(0,r-o);l<=Math.min(e.length-1,r+s);l++)t.add(l)}if(t.size===0)return e.slice(-120);let i=Array.from(t).sort((r,o)=>r-o).map(r=>e[r]);return i.length>160?i.slice(-160):i},Ga=(e,t,n,i)=>{let r=Nr(i).replace(/\r/g,`
|
|
1138
|
+
`):"",T=yr,w={"{{REMOTE_DIR}}":f,"{{ENV_VARS}}":ne,"{{CREDENTIAL_DOWNLOADS}}":U,"{{IOS_SCHEME}}":e.iosScheme||"","{{IOS_CONFIG}}":e.iosConfiguration||"Release","{{TEAM_ID}}":e.iosTeamId||"","{{AUTH_PARAMS}}":D,"{{IS_SIMULATOR}}":e.simulator?"true":"false","{{BUILD_ID}}":t,"{{EXPORT_METHOD}}":e.iosExportMethod||"ad-hoc","{{NODE_VERSION_SETUP}}":g};Object.entries(w).forEach(([A,S])=>{T=T.split(A).join(S)});let k=`/tmp/${m.nameLower}-mac-build-${t}.sh`;if(_a.writeFileSync(k,T),Lt(`${c} ${k} ${l}:${f}/build.sh`),r.stop("Remote script uploaded."),It.info(it.cyan("Executing remote build. This might take a while...")),Lt(`${a} "bash ${f}/build.sh"`,{stdio:"inherit"}),r.stop("Remote build finished!"),i){r.start("Fetching artifact links...");try{let S=(await P.get(`/builds/${i}/${t}/artifacts`)).data.artifacts||[],x=e.simulator===!0;if(S.length===0&&!x)throw r.stop("Build Failed!"),new Error("Build completed but no artifacts were generated. Check build logs for errors.");if(r.stop("Build Successful!"),S.length>0){It.success("Build Artifacts Ready:");for(let B of S)console.log(`
|
|
1139
|
+
${it.yellow(B.name)}:
|
|
1140
|
+
${it.cyan(B.downloadUrl)}`);console.log(`
|
|
1141
|
+
${it.dim("Note: Links are valid for 7 days.")}`)}else x&&It.warn("Simulator build completed. No artifacts uploaded.")}catch(A){r.stop("Could not fetch artifacts"),It.warn(it.yellow(`Artifact listing failed: ${A.message}`))}}}catch(u){throw r.stop("iOS Build Failed"),u}};import $a from"crypto";import Me from"axios";import Er from"fs";var Ye=6e4,va=12e4,Zn=4,Xe=e=>encodeURIComponent(e),Ra=e=>new Promise(t=>setTimeout(t,e));async function Ue(e,t){let n;for(let i=1;i<=Zn;i++)try{return await t()}catch(r){if(n=r,i>=Zn||!Pa(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}/${Zn}); retrying in ${Math.round(s/1e3)}s...`),await Ra(s)}throw n}function Pa(e){let t=e.response?.status;return t?t===408||t===409||t===425||t===429||t>=500:!0}async function Ar(e,t){let n;try{let i=await dn(t),r=Xe(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:Ye}))).data.id,!n)throw new Error("Google Play edit insert succeeded but did not return an edit id.");let s=Xe(n),l=0,c=(await Ue("list tracks",()=>Me.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits/${s}/tracks`,{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Ye}))).data.tracks||[];for(let u of c)if(u.releases){for(let d of u.releases)if(d.versionCodes)for(let f of d.versionCodes){let p=parseInt(f,10);p>l&&(l=p)}}try{let d=(await Ue("list bundles",()=>Me.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits/${s}/bundles`,{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Ye}))).data.bundles||[];for(let f of d)f.versionCode&&f.versionCode>l&&(l=f.versionCode)}catch{}try{let d=(await Ue("list APKs",()=>Me.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits/${s}/apks`,{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Ye}))).data.apks||[];for(let f of d)f.versionCode&&f.versionCode>l&&(l=f.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 dn(t);await Ue("delete edit",()=>Me.delete(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${Xe(e)}/edits/${Xe(n)}`,{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Ye}))}catch{}}}async function Ir(e){let{packageName:t,serviceAccount:n,aabPath:i,track:r,releaseStatus:o,userFraction:s,changesNotSentForReview:l}=e,a;try{let u={Authorization:`Bearer ${await dn(n)}`,Connection:"close"},d=Xe(t);if(a=(await Ue("create edit",()=>Me.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${d}/edits`,{},{headers:u,timeout:Ye}))).data.id,!a)throw new Error("Google Play edit insert succeeded but did not return an edit id.");let p=Xe(a),h=Er.statSync(i),D=await Ue("upload AAB",()=>Me.post(`https://androidpublisher.googleapis.com/upload/androidpublisher/v3/applications/${d}/edits/${p}/bundles`,Er.createReadStream(i),{headers:{...u,"Content-Type":"application/octet-stream","Content-Length":h.size},maxBodyLength:1/0,maxContentLength:1/0,params:{uploadType:"media"},timeout:va})),N=Number(D.data.versionCode);if(!N)throw new Error("Google Play upload succeeded but did not return a versionCode.");let U={versionCodes:[String(N)],status:o};return(o==="inProgress"||o==="halted")&&typeof s=="number"&&(U.userFraction=s),await Ue("update track",()=>Me.put(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${d}/edits/${p}/tracks/${Xe(r)}`,{releases:[U]},{headers:u,timeout:Ye})),await Ue("commit edit",()=>Me.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${d}/edits/${p}:commit`,{},{headers:u,params:l?{changesNotSentForReview:!0}:void 0,timeout:Ye})),{editId:a,versionCode:N,track:r,releaseStatus:o,userFraction:s}}catch(c){if(a)try{let d=await dn(n);await Ue("delete edit",()=>Me.delete(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${Xe(t)}/edits/${Xe(a)}`,{headers:{Authorization:`Bearer ${d}`,Connection:"close"},timeout:Ye}))}catch{}let u=c.response?.data?.error?.message||c.message;throw new Error(`Google Play API Error: ${u}`)}}async function dn(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=$a.createSign("RSA-SHA256");a.update(l);let c=a.sign(e.private_key,"base64url"),u=`${l}.${c}`;return(await Ue("OAuth token exchange",()=>Me.post("https://oauth2.googleapis.com/token",{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:u},{headers:{Connection:"close"},timeout:Ye}))).data.access_token}import Da from"crypto";import wr from"axios";var ei="https://api.appstoreconnect.apple.com/v1",_r=6e4,Qn=4,Oa=e=>new Promise(t=>setTimeout(t,e));function Ca(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=Da.createSign("SHA256");l.update(s);let a=l.sign({key:n,dsaEncoding:"ieee-p1363"}).toString("base64url");return`${s}.${a}`}function Na(e){let t=e.response?.status;return t?t===408||t===409||t===425||t===429||t>=500:!0}async function $r(e,t){let n;for(let i=1;i<=Qn;i++)try{return await t()}catch(r){if(n=r,i>=Qn||!Na(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 Oa(s)}throw n}function vr(e){return{Authorization:`Bearer ${Ca(e.keyId,e.issuerId,e.privateKey)}`,"Content-Type":"application/json",Connection:"close"}}function Ta(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 cn(e){let t=String(e||"").trim();if(/^\d+(?:\.\d+){0,2}$/.test(t))return t.split(".").map(n=>Number(n))}function ka(e,t){let n=cn(e),i=cn(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 xa(e){let t=cn(e);return!t||t.length===0?"1":(t[t.length-1]+=1,t.join("."))}async function La(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 $r("lookup app by bundle ID",()=>wr.get(`${ei}/apps`,{headers:vr(e),params:{"filter[bundleId]":n,limit:1},timeout:_r}))).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 Rr(e){let t={keyId:e.keyId,issuerId:e.issuerId,privateKey:e.privateKey};try{let n=await La(t,e.ascAppId,e.bundleId),i=`${ei}/builds`,r="0",o,s=0;for(;i&&s<10;){s+=1;let l=await $r("list builds",()=>wr.get(i,{headers:vr(t),params:i===`${ei}/builds`?{"filter[app]":n,"fields[builds]":"version,uploadedDate",sort:"-uploadedDate",limit:200}:void 0,timeout:_r})),a=l.data?.data||[];for(let c of a){let u=String(c.attributes?.version||"").trim();cn(u)&&ka(u,r)>0&&(r=u,o=c.attributes?.uploadedDate)}i=l.data?.links?.next}return{appId:n,latestBuildNumber:r,nextBuildNumber:xa(r),latestUploadedDate:o}}catch(n){throw new Error(`App Store Connect API Error: ${Ta(n)}`)}}import{spinner as un,log as I,isCancel as fn,confirm as Ma,select as ni}from"@clack/prompts";import E from"chalk";import y from"fs";import _ from"path";import{execFileSync as Mt,execSync as ee,spawn as Cr}from"child_process";import Ae from"os";import Ua from"crypto";var Nr=(e,t)=>t.filter(n=>y.existsSync(_.join(e,n))).reduce((n,i)=>n.update(y.readFileSync(_.join(e,i))),Ua.createHash("sha256")).digest("hex").slice(0,16),Ba=e=>Nr(e,["package.json","yarn.lock","package-lock.json","bun.lockb"]),Fa=e=>Nr(e,["Podfile","Podfile.lock"]),Ha=e=>{let t=_.join(e,"fingerprint.json");try{return JSON.parse(y.readFileSync(t,"utf-8"))}catch{return{}}},Pr=(e,t)=>{y.mkdirSync(e,{recursive:!0}),y.writeFileSync(_.join(e,"fingerprint.json"),JSON.stringify(t,null,2))},ja=7200*1e3,Ga=(e,t)=>{y.mkdirSync(e,{recursive:!0});let n=_.join(e,"build.lock");if(y.existsSync(n))try{let i=JSON.parse(y.readFileSync(n,"utf-8")),r=Date.now()-(i.timestamp||0);if(r<ja)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}y.writeFileSync(n,JSON.stringify({buildId:t,pid:process.pid,timestamp:Date.now()}))},Ka=(e,t)=>{let n=_.join(e,"build.lock");try{y.existsSync(n)&&JSON.parse(y.readFileSync(n,"utf-8")).buildId===t&&y.unlinkSync(n)}catch{}},Dr=15e5,Or=(e,t)=>{let n=e+t;return n.length>Dr?n.slice(-Dr):n},Tr=e=>e.replace(/\u001b\[[0-9;]*m/g,""),kr=e=>/\berror:|fatal error:|xcodebuild: error|The following build commands failed|Command PhaseScriptExecution failed|PhaseScriptExecution|Command .* failed|CodeSign|Provisioning profile|No profiles|requires a provisioning profile|Undefined symbols|ld:|clang: error|SwiftCompile|CompileC|node: command not found|env: node|No such file or directory|Permission denied/i.test(e),Va=e=>{let t=new Set,n=[];e.forEach((r,o)=>{kr(r)&&n.push(o)});for(let r of n){let o=/PhaseScriptExecution|Command PhaseScriptExecution failed|The following build commands failed/i.test(e[r])?18:8,s=/The following build commands failed/i.test(e[r])?18:10;for(let l=Math.max(0,r-o);l<=Math.min(e.length-1,r+s);l++)t.add(l)}if(t.size===0)return e.slice(-120);let i=Array.from(t).sort((r,o)=>r-o).map(r=>e[r]);return i.length>160?i.slice(-160):i},za=(e,t,n,i)=>{let r=Tr(i).replace(/\r/g,`
|
|
1142
1142
|
`).split(`
|
|
1143
|
-
`).map(a=>a.trimEnd()).filter(Boolean),o=r.filter(
|
|
1143
|
+
`).map(a=>a.trimEnd()).filter(Boolean),o=r.filter(kr),s=o.length>0?Va(r):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?`
|
|
1144
1144
|
${l}:
|
|
1145
1145
|
${s.join(`
|
|
1146
|
-
`)}`:""].join("")},
|
|
1147
|
-
`)){if(/Ineligible destinations/i.test(
|
|
1148
|
-
`)),r(
|
|
1149
|
-
`)),r(
|
|
1150
|
-
`)));let
|
|
1151
|
-
`)))}let N=
|
|
1146
|
+
`)}`:""].join("")},Wa=e=>e==="xcodebuild"&&process.env.MACH_XCODE_FULL_LOGS!=="1",Ya=e=>{let t=Tr(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},Be=e=>{try{y.existsSync(e)&&y.rmSync(e,{recursive:!0,force:!0})}catch{}},Ja=(e,t)=>{try{if(!y.existsSync(e))return;for(let n of y.readdirSync(e))t(n)&&Be(_.join(e,n))}catch{}},ti=e=>{I.info(E.dim("Clearing Metro/Hermes JS transform caches..."));let t=Ae.tmpdir();Ja(t,n=>n==="metro-cache"||n.startsWith("metro-")||n.startsWith("haste-map-")||n.startsWith("react-native-packager-cache-")),Be(_.join(e,".expo")),Be(_.join(e,"node_modules/.cache/metro")),Be(_.join(Ae.homedir(),".cache/metro")),Be(_.join(Ae.homedir(),".cache/react-native-packager")),Be(_.join(Ae.homedir(),"Library/Caches/metro")),Be(_.join(Ae.homedir(),"Library/Caches/react-native-packager"))},qa=e=>/Internal inconsistency error|never received target ended message/i.test(String(e?.message||e)),Xa=e=>{I.warn(E.yellow("Xcode build system hit an internal inconsistency. Clearing simulator build state and retrying once...")),Be(_.join(e,"Build")),Be(_.join(e,"Index.noindex")),Be(_.join(e,"ModuleCache.noindex")),Be(_.join(e,"SourcePackages"))},Za=(e,t,n,i,r)=>{let o=a=>{let c=a.filter(d=>d?.id&&String(d?.platform||"").includes("iOS Simulator")&&!d?.error),u=c.find(d=>/iphone/i.test(d.name||""))||c[0];return u?.id?`id=${u.id}`:void 0},s=a=>{let c=[],u=!1;for(let d of a.split(`
|
|
1147
|
+
`)){if(/Ineligible destinations/i.test(d)&&(u=!0),u||!d.includes("platform:iOS Simulator")||d.includes("error:"))continue;let f=d.match(/\bid:([^,}]+)/)?.[1]?.trim(),p=d.match(/\bname:([^,}]+)/)?.[1]?.trim();f&&c.push({id:f,name:p,platform:"iOS Simulator"})}return o(c)},l=[t?"-workspace":"-project",t||n,"-scheme",i,"-configuration",r,"-sdk","iphonesimulator","-showdestinations"];try{let a=Mt("xcodebuild",[...l,"-json"],{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}),c=JSON.parse(a),u=Array.isArray(c.destinations)?c.destinations:Array.isArray(c.availableDestinations)?c.availableDestinations:[],d=o(u);if(d)return d}catch{}try{let a=Mt("xcodebuild",l,{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]});return s(a)}catch{}},Fe=(e,t,n=process.cwd(),i={},r,o)=>new Promise((s,l)=>{let a="",c=Wa(e),u=Date.now(),d=["/opt/homebrew/bin","/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin",_.join(Ae.homedir(),".npm-global/bin")],p=[...(process.env.PATH||"").split(":"),...d].filter((R,K,b)=>R&&b.indexOf(R)===K).join(":");process.env[`${m.envPrefix}DEBUG`]&&console.log(E.magenta(`[${m.nameUpper}_DEBUG] Execution PATH: ${p}`));let h={...process.env,...i,PATH:p,LANG:"en_US.UTF-8",LC_ALL:"en_US.UTF-8"};r&&process.env[`${m.envPrefix}DEBUG`]&&(r(E.magenta(`[ENVIRONMENT] node: ${process.execPath}
|
|
1148
|
+
`)),r(E.magenta(`[ENVIRONMENT] PATH: ${p}
|
|
1149
|
+
`)),r(E.magenta(`[ENVIRONMENT] command: ${e} ${t.join(" ")}
|
|
1150
|
+
`)));let D=e;if(["node","npm","npx","pod"].includes(e)){let R=_.dirname(process.execPath),K=_.join(R,e);y.existsSync(K)&&(D=K,r&&r(E.dim(`[EXEC] Using absolute path: ${D}
|
|
1151
|
+
`)))}let N=Cr(D,t,{stdio:"pipe",cwd:n,shell:!0,env:h,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 U=(R,K)=>{if(!c){K.write(R);return}let b=R.replace(/\r/g,`
|
|
1152
1152
|
`).split(`
|
|
1153
|
-
`).filter(
|
|
1153
|
+
`).filter(Ya);if(b.length>0){K.write(`${b.join(`
|
|
1154
1154
|
`)}
|
|
1155
|
-
`),
|
|
1156
|
-
`),
|
|
1157
|
-
`).find(r=>/^Payload\/[^/]+\.app\/Info\.plist$/.test(r.trim()));if(!n)throw new Error(`Could not validate iOS build number: ${
|
|
1158
|
-
\u{1F6D1} Build cancelled from dashboard. Terminating...`)),
|
|
1159
|
-
`)},
|
|
1160
|
-
`);else if(i&&l==="ios"&&!e.simulator)try{let g=parseInt(n.BUILD_NUMBER||"0",10),T=Number.isFinite(g)?g:0,
|
|
1161
|
-
`)),n.BUILD_NUMBER=
|
|
1162
|
-
`)}}catch(g){I.warn(
|
|
1163
|
-
`)}if(await
|
|
1164
|
-
`),I.info(
|
|
1165
|
-
`),I.warn(
|
|
1166
|
-
`),y.rmSync(
|
|
1155
|
+
`),u=Date.now();return}let W=Date.now();W-u>3e4&&(K.write(`[xcodebuild] still running; detailed output is streamed to Mach logs.
|
|
1156
|
+
`),u=W)};N.stdout.on("data",R=>{let K=R.toString();a=Or(a,K),U(K,process.stdout),r&&r(K)}),N.stderr.on("data",R=>{let K=R.toString();a=Or(a,K),U(K,process.stderr),r&&r(K)}),N.on("close",R=>{R===0?s(R):l(new Error(za(e,t,R,a)))}),N.on("error",R=>l(R))}),Qa=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(" ")},pt=(e,t)=>{let n=[];try{if(!y.existsSync(e))return n;let i=y.readdirSync(e);for(let r of i){let o=_.join(e,r);try{let s=y.statSync(o);if(t.some(a=>r.endsWith(a))){n.push(_.resolve(o));continue}s.isDirectory()&&(n=n.concat(pt(o,t)))}catch{}}}catch{}return n},el=/^\d+(?:\.\d+){0,2}$/,ii=e=>{let t=String(e||"").trim();return!t||t==="undefined"||t==="null"?null:el.test(t)?t:null},xr=(e,t)=>{let n=ii(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},Lr=(e,t)=>Mt("/usr/libexec/PlistBuddy",["-c",`Print :${t}`,e],{encoding:"utf-8"}).trim(),tl=e=>{let t=_.join(e,"Info.plist");if(!y.existsSync(t))throw new Error(`Could not validate iOS build number: ${t} not found.`);return xr(Lr(t,"CFBundleVersion"),t)},nl=e=>{let n=Mt("unzip",["-Z1",e],{encoding:"utf-8"}).split(`
|
|
1157
|
+
`).find(r=>/^Payload\/[^/]+\.app\/Info\.plist$/.test(r.trim()));if(!n)throw new Error(`Could not validate iOS build number: ${_.basename(e)} has no Payload/*.app/Info.plist.`);let i=y.mkdtempSync(_.join(Ae.tmpdir(),`${m.nameLower}-ipa-plist-`));try{let r=_.join(i,"Info.plist"),o=Mt("unzip",["-p",e,n.trim()]);return y.writeFileSync(r,o),xr(Lr(r,"CFBundleVersion"),`${_.basename(e)}:${n.trim()}`)}finally{y.rmSync(i,{recursive:!0,force:!0})}},ri=async(e,t,n={},i,r={})=>{let o=un(),s=Date.now(),l=e.platform,a=e.buildProfile||"production",c=()=>ft(n,a,e),u=async(g,T={})=>{if(i)for(let w=1;w<=3;w++)try{await P.patch(`/builds/${i}/${t}`,{status:g,...T});return}catch(k){let A=k?.response?.data?.message||k?.message||String(k);console.error(`[reportStatus] attempt ${w}/3 failed (status=${g}): ${A}`),w<3&&await new Promise(S=>setTimeout(S,2e3))}},d=new AbortController,{signal:f}=d,p=null;i&&(p=setInterval(async()=>{try{(await P.get(`/builds/${i}/${t}`)).data.status==="cancelled"&&(I.warn(E.yellow(`
|
|
1158
|
+
\u{1F6D1} Build cancelled from dashboard. Terminating...`)),d.abort(),p&&clearInterval(p))}catch{}},5e3));let h=_.join(process.cwd(),".mach-cache"),D="setup",N="",U=null,R=async()=>{if(!N||!i)return;let g=N;N="";try{let T=g;Object.values(n).forEach(w=>{if(w&&w.length>5){let k=w.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");T=T.replace(new RegExp(k,"g"),"[SECRET]")}}),await P.post(`/builds/${i}/${t}/logs`,{log:T,step:D})}catch{}},K=async()=>{U&&(clearTimeout(U),U=null),await R(),Ka(h,t),p&&(clearInterval(p),p=null);try{let g=_.join(Ae.tmpdir(),`${m.buildPrefix}-${t}.keychain-db`);y.existsSync(g)&&(ee(`security delete-keychain "${g}"`,{stdio:"ignore"}),I.info(E.dim("\u{1F511} Build keychain deleted.")))}catch{}try{let g=_.join(Ae.homedir(),"Library/MobileDevice/Provisioning Profiles");if(y.existsSync(g)){let T=y.readdirSync(g).filter(w=>w.includes(t)||w.startsWith(`${m.nameLower}-temp-${t}`));for(let w of T)y.unlinkSync(_.join(g,w))}}catch{}},b=async g=>{i&&(N+=g,N.length>=8192?(U&&(clearTimeout(U),U=null),await R()):U||(U=setTimeout(()=>{U=null,R()},2e3)))},W=async g=>{D=g,await b(`[STEP_START:${g}] ${Math.floor(Date.now()/1e3)}
|
|
1159
|
+
`)},ne=async(g,T,w,k)=>await Fe(g,T,w,k,A=>{b(A)},f);I.info(E.blue(`\u{1F680} Starting local build for ${l} (${a})...`));try{Ga(h,t)}catch(g){throw await u("failed",{error:g.message}),g}if(await u("building"),await W("setup"),l==="ios"&&!e.simulator&&n.MACH_IOS_BUILD_NUMBER_LOCKED==="1"&&n.BUILD_NUMBER)I.info(E.dim(`Auto build number: ${n.BUILD_NUMBER}`)),await b(`[BUILD_NUMBER] ${n.BUILD_NUMBER}
|
|
1160
|
+
`);else if(i&&l==="ios"&&!e.simulator)try{let g=parseInt(n.BUILD_NUMBER||"0",10),T=Number.isFinite(g)?g:0,w=await P.post(`/projects/${i}/next-build-number`,{platform:"ios",startFrom:T});if(w.data.status==="success"){let k=ii(String(w.data.buildNumber||""));if(!k)throw new Error(`Dashboard returned invalid iOS build number: "${w.data.buildNumber||""}"`);let A=parseInt(k,10),S=T>0&&Number.isFinite(A)&&A<T?String(T):k;S!==k&&(I.warn(E.yellow(`Dashboard build counter returned ${k}; using minimum ${S}.`)),await b(`[BUILD_NUMBER] Dashboard returned ${k}; using minimum ${S}
|
|
1161
|
+
`)),n.BUILD_NUMBER=S,I.info(E.dim(`Auto build number: ${n.BUILD_NUMBER}`)),await b(`[BUILD_NUMBER] ${n.BUILD_NUMBER}
|
|
1162
|
+
`)}}catch(g){I.warn(E.yellow(`Could not fetch auto build number: ${g.message}`))}await W("lock"),e.developmentClient?(I.info(E.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):(I.info(E.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 W("clone"),I.info(E.dim("Preparing source...")),await W("read_config");let g=_.join(process.cwd(),m.configFileName);if(y.existsSync(g)){let F=JSON.parse(y.readFileSync(g,"utf-8"))?.build?.[a]||{};await b(`[CONFIG] Profile: ${a}, distribution: ${F.distribution||"not set"}, simulator: ${F.simulator||!1}
|
|
1163
|
+
`)}if(await W("read_package"),e.nodeVersion){let H=process.env.NVM_DIR||_.join(Ae.homedir(),".nvm"),F=_.join(H,"versions","node"),X;if(y.existsSync(F)){let C=y.readdirSync(F).sort().reverse(),j=e.nodeVersion.startsWith("v")?e.nodeVersion:`v${e.nodeVersion}`,Z=C.find(ae=>ae===j||ae.startsWith(j+".")||ae.startsWith(`v${e.nodeVersion}.`));Z&&(X=_.join(F,Z,"bin"))}if(X&&y.existsSync(X)){let C=process.env.PATH||"";process.env.PATH=`${X}:${C}`,await b(`[NODE] Switched to Node ${e.nodeVersion} \u2014 using ${X}
|
|
1164
|
+
`),I.info(E.green(`\u2713 Node switched to ${e.nodeVersion} (${X})`))}else await b(`[NODE] Warning: Node ${e.nodeVersion} not found in nvm. Run: nvm install ${e.nodeVersion} on the build machine.
|
|
1165
|
+
`),I.warn(E.yellow(`Node ${e.nodeVersion} not found in nvm \u2014 using system default`))}await W("deps"),o.start("Checking dependencies...");let T=Ha(h),w=Ba(process.cwd()),k=y.existsSync("node_modules"),A=y.existsSync("yarn.lock"),S=y.existsSync("bun.lockb");k&&T.node&&T.node!==w&&(o.stop("Dependency fingerprint changed \u2014 clearing node_modules for clean install..."),await b(`[CACHE] package.json/lockfile changed \u2014 wiping node_modules
|
|
1166
|
+
`),y.rmSync(_.join(process.cwd(),"node_modules"),{recursive:!0,force:!0}),k=!1);let x="npm",B=["install","--prefer-offline"];A?(x="yarn",B=["install","--prefer-offline"]):S&&(x="bun",B=["install"]),k?o.stop("Cached node_modules found. Syncing dependencies..."):o.stop("No cached dependencies. Running fresh install..."),e.preBuild&&(I.info(E.blue("Running pre-install hook...")),I.info(E.dim(`> ${e.preBuild}`)),await W("prebuild"),await ne("bash",[e.preBuild],process.cwd(),c())),I.info(E.dim(`Running ${x} ${B.join(" ")}...`)),await ne(x,B,process.cwd(),c()),T.node=w,Pr(h,T);let Y=JSON.parse(y.readFileSync("package.json","utf-8")),L=Y.dependencies?.expo||Y.devDependencies?.expo,J=e.iosBundleIdentifier||"",O=e.name||"";if(L){o.start(`Enforcing ${m.name} configuration...`);let H=_.join(process.cwd(),"app.json"),F=null;if(y.existsSync(H)){F=y.readFileSync(H,"utf-8");let C=JSON.parse(F);C.expo=C.expo||{},O||(O=C.expo.name||""),l==="ios"&&!J&&(J=C.expo?.ios?.bundleIdentifier||""),e.name&&(C.expo.name=e.name),e.scheme&&(C.expo.scheme=e.scheme),l==="ios"&&e.iosBundleIdentifier?(C.expo.ios=C.expo.ios||{},C.expo.ios.bundleIdentifier=e.iosBundleIdentifier):l==="android"&&e.androidPackage&&(C.expo.android=C.expo.android||{},C.expo.android.package=e.androidPackage),y.writeFileSync(H,JSON.stringify(C,null,2))}let X=["exec","--","expo","prebuild","--platform",l,"--no-install"];try{if(await W("prebuild"),await ne("npm",X,process.cwd(),c()),l==="ios"&&y.existsSync("ios")){await W("pods"),I.info(E.blue("Running pod install..."));try{let C=_.resolve("ios"),j=_.join(C,"Podfile");if(!y.existsSync(j))throw new Error("ios/Podfile not found. Skipping pod install.");let Z=y.readFileSync(j,"utf-8"),ae=e.iosDeploymentTarget||"13.4";if(!e.developmentClient&&(I.info(E.blue("\u2139\uFE0F Patching Podfile to EXCLUDE expo-dev-client...")),Z.includes("use_expo_modules!")&&!Z.includes("exclude:"))){let ut=/use_expo_modules!(\s*)$/m;ut.test(Z)?Z=Z.replace(ut,'use_expo_modules!(exclude: ["expo-dev-client"])$1'):Z=Z.replace("use_expo_modules!",'use_expo_modules!(exclude: ["expo-dev-client"])')}let Se=`
|
|
1167
1167
|
installer.generated_projects.each do |project|
|
|
1168
1168
|
project.targets.each do |target|
|
|
1169
1169
|
target.build_configurations.each do |config|
|
|
@@ -1176,19 +1176,19 @@ ${s.join(`
|
|
|
1176
1176
|
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '${ae}'
|
|
1177
1177
|
end
|
|
1178
1178
|
end
|
|
1179
|
-
`,
|
|
1180
|
-
${Se}`),y.writeFileSync(j,
|
|
1179
|
+
`,qe=/post_install\s+do\s+\|installer\|/;if(qe.test(Z))I.info(E.dim(`Injecting deployment target (${ae}) into existing post_install hook...`)),Z=Z.replace(qe,`post_install do |installer|
|
|
1180
|
+
${Se}`),y.writeFileSync(j,Z);else{I.info(E.dim(`Appending new post_install hook for deployment target (${ae})...`));let ut=`
|
|
1181
1181
|
post_install do |installer|
|
|
1182
1182
|
${Se}
|
|
1183
1183
|
end
|
|
1184
|
-
`;y.appendFileSync(j,
|
|
1185
|
-
`),I.info(
|
|
1186
|
-
\u2713 Local build completed successfully in ${ye}`)),await
|
|
1187
|
-
\u{1F4E6} Generated Artifacts:`)),
|
|
1188
|
-
\u274C Build aborted.`)),await
|
|
1189
|
-
\u2717 Local build failed: ${g.message}`)),await
|
|
1190
|
-
`)[0]||"unknown"}`))}if(!
|
|
1191
|
-
`).map(_e=>_e.trim().replace(/^"|"$/g,"")).filter(_e=>_e.length>0),
|
|
1184
|
+
`;y.appendFileSync(j,ut)}let Ct="/opt/homebrew/bin/pod",on=y.existsSync(Ct)?Ct:"pod",sn=Fa(C);y.existsSync(_.join(C,"Pods"))&&T.pods&&T.pods!==sn&&(await b(`[CACHE] Podfile/Podfile.lock changed \u2014 wiping ios/Pods
|
|
1185
|
+
`),I.info(E.dim("Podfile fingerprint changed \u2014 clearing Pods for clean install...")),y.rmSync(_.join(C,"Pods"),{recursive:!0,force:!0})),I.info(E.dim(`Using pod command: ${on} in ${C}`)),await ne(on,["install"],C,c()),T.pods=sn,Pr(h,T)}catch(C){let j=C.message||"Unknown error";I.warn(E.yellow(`Native "pod" command failed: ${j}`)),I.info(E.dim("Falling back to npm exec pod-install...")),I.info(E.magenta(`${m.nameUpper}_DEBUG: Executing pod-install override via npx --yes pod-install@latest`)),await ne("npx",["--yes","pod-install@latest","ios"],process.cwd(),c())}if(y.existsSync("ios/Pods")){I.info(E.dim("Disabling signing for Pod targets to prevent conflicts..."));try{ee(`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{F&&y.writeFileSync(H,F)}o.stop(`Expo prebuild complete (${m.name} config enforced).`)}let q=[];if(l==="android")await W("build"),q=await il(e,a,n,H=>b(H),f);else if(l==="ios"){await W("signing"),I.info(E.dim("Preparing credentials..."));let H=r?.distributionType;q=await rl(e,t,a,n,i,F=>b(F),f,H,F=>W(F))}e.postBuild&&(I.info(E.blue("Running post-build hook...")),I.info(E.dim(`> ${e.postBuild}`)),await ne(e.postBuild,[],process.cwd(),c()));let ye=Qa(Date.now()-s);if(I.success(E.green(`
|
|
1186
|
+
\u2713 Local build completed successfully in ${ye}`)),await u("building",{...J&&{bundleId:J},...O&&{appName:O}}),q.length>0&&(I.info(E.cyan(`
|
|
1187
|
+
\u{1F4E6} Generated Artifacts:`)),q.forEach(H=>{let F=_.resolve(H);I.info(E.dim(` - ${H}`)),I.info(E.gray(` Path: ${F}`))}),e.interactive)){let H=await Ma({message:"Install on connected device?"});if(!fn(H)&&H){if(l==="android"){let F=q.find(X=>X.endsWith(".apk"))||q[0];await sl(F,X=>b(X))}else if(l==="ios"){let F=q.find(C=>C.endsWith(".ipa"))||q.find(C=>C.endsWith(".app"))||q[0],X=Ze("ios");e.simulator?await al(F,X||"",C=>b(C)):await ll(F,X||"",C=>b(C))}}}await W("upload");let Ee=[];for(let H of q)try{let F=_.join(Ae.tmpdir(),`${t}-${_.basename(H)}`);y.copyFileSync(H,F),Ee.push(F),I.info(E.dim(` \u{1F4CB} Preserved artifact: ${_.basename(H)}`))}catch{I.warn(E.yellow(` Failed to preserve artifact: ${_.basename(H)}`))}q=Ee,I.info(E.dim("\u{1F9F9} Cleaning workspace (preserving dependency cache)..."));try{let H=process.cwd(),F=new Set(["node_modules"]),X=y.readdirSync(H),C=0;for(let j of X)if(!F.has(j)){if(j==="ios"){let Z=_.join(H,"ios"),ae=y.readdirSync(Z);for(let Se of ae)if(Se!=="Pods")try{y.rmSync(_.join(Z,Se),{recursive:!0,force:!0}),C++}catch{}continue}try{y.rmSync(_.join(H,j),{recursive:!0,force:!0}),C++}catch{}}I.info(E.dim(` Cleaned ${C} items. Cached: node_modules${y.existsSync(_.join(H,"ios","Pods"))?", ios/Pods":""}`)),I.info(E.green("\u{1F512} Security: No source code retained on build server. Only public dependencies cached."))}catch{I.warn(E.yellow("Post-build cleanup encountered errors (non-fatal)."))}try{let F=_.join(Ae.homedir(),m.workspacesDir),X=ee(`df -k "${F}" | tail -1 | awk '{print $4}'`,{encoding:"utf8"}).trim(),C=parseInt(X,10)*1024;if(C<53687091200&&y.existsSync(F)){I.info(E.dim(` \u26A0\uFE0F Low disk space (${(C/1024/1024/1024).toFixed(0)} GB free). Running cache eviction...`));let j=_.basename(process.cwd()),Z=y.readdirSync(F).filter(ae=>ae!==j).map(ae=>{let Se=_.join(F,ae);try{let qe=y.statSync(Se);return qe.isDirectory()?{name:ae,dir:Se,mtime:qe.mtimeMs}:null}catch{return null}}).filter(Boolean);Z.sort((ae,Se)=>ae.mtime-Se.mtime);for(let ae of Z){if(C>=53687091200)break;try{y.rmSync(ae.dir,{recursive:!0,force:!0}),I.info(E.dim(` \u{1F5D1}\uFE0F Evicted stale workspace: ${ae.name}`));let Se=ee(`df -k "${F}" | tail -1 | awk '{print $4}'`,{encoding:"utf8"}).trim();if(parseInt(Se,10)*1024>=53687091200)break}catch{}}}}catch{}return await K(),q}catch(g){throw await K(),g.message==="Command aborted"?(I.warn(E.yellow(`
|
|
1188
|
+
\u274C Build aborted.`)),await u("failed",{error:"Aborted by user"}),g):(I.error(E.red(`
|
|
1189
|
+
\u2717 Local build failed: ${g.message}`)),await u("failed",{error:g.message}),g)}},il=async(e,t,n={},i,r)=>{let o=y.existsSync("android/gradlew")?"android/gradlew":y.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;I.info(E.blue(`Running Android build: ${l}...`));let a=o.includes("android/")?"android":".",c=(o.includes("android/"),"./gradlew"),u=[l],d={...n,EXPO_NO_DOTENV:"1",MACH_BUILD_PROFILE:t,MACH_APP_NAME:e.appName||e.name||"App"};if(n.ANDROID_VERSION_CODE){let p=_.join(a,"app/build.gradle");if(y.existsSync(p)){let h=n.ANDROID_VERSION_CODE,D=y.readFileSync(p,"utf-8");D=D.replace(/versionCode\s+\d+/,`versionCode ${h}`),y.writeFileSync(p,D),I.info(E.green(`\u2713 Applied Android versionCode ${h}`))}u.push(`-Pandroid.injected.version.code=${n.ANDROID_VERSION_CODE}`)}for(let p of["app/build","build",".cxx"]){let h=_.join(a,p);y.existsSync(h)&&y.rmSync(h,{recursive:!0,force:!0})}ti(process.cwd()),await Fe(c,u,a,d,i,r);let f=_.join(a,"app/build/outputs");return pt(f,[".apk",".aab"])},rl=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 c=_.resolve(process.cwd(),y.existsSync("ios")?"ios":"."),u=y.readdirSync(c),d=u.find(w=>w.endsWith(".xcworkspace")),f=u.find(w=>w.endsWith(".xcodeproj")),p=ft(i,n,e),h=ii(p.BUILD_NUMBER||p.CURRENT_PROJECT_VERSION);if((p.BUILD_NUMBER||p.CURRENT_PROJECT_VERSION)&&!h)throw new Error(`Invalid iOS BUILD_NUMBER/CURRENT_PROJECT_VERSION: "${p.BUILD_NUMBER||p.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 D=h?[`BUILD_NUMBER=${h}`,`CURRENT_PROJECT_VERSION=${h}`]:[];if(h&&(p.BUILD_NUMBER=h,p.CURRENT_PROJECT_VERSION=h,I.info(E.dim(`Using iOS build number: ${h}`))),!d&&!f)throw new Error("Could not find Xcode workspace or project in ios/ directory.");try{let w=ee("xcode-select -p").toString().trim();I.info(E.dim(`Using Xcode at: ${w}`))}catch{I.warn(E.dim("Could not detect Xcode path."))}I.info(E.blue("Running iOS build via xcodebuild..."));let N=d?d.replace(".xcworkspace",""):f?.replace(".xcodeproj",""),U=e.iosScheme||N||e.scheme,R=e.developmentClient?"Debug":e.iosConfiguration||"Release",K=(r||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),b=_.join(Ae.homedir(),`Library/Developer/Xcode/DerivedData/${m.nameLower}`,K);y.mkdirSync(b,{recursive:!0});let W=At(p),ne=_.join(b,".mach-env-hash"),g=_.join(b,"Build"),T=y.existsSync(ne)?y.readFileSync(ne,"utf-8").trim():"";if(y.existsSync(g)){let w=T&&T!==W?"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.";I.info(E.dim(w)),y.rmSync(g,{recursive:!0,force:!0})}if(y.writeFileSync(ne,W),ti(process.cwd()),e.simulator){let w=Za(c,d,f,U,R),k=w?["-destination",w]:[];I.info(E.dim(w?`Building for simulator (Scheme: ${U}, Config: ${R}, Destination: ${w})...`:`Building for simulator (Scheme: ${U}, Config: ${R}; xcodebuild will choose destination)...`));let A=[d?"-workspace":"-project",d||f,"-scheme",U,"-configuration",R,"-sdk","iphonesimulator",...k,"-derivedDataPath",b,...D,"COMPILER_INDEX_STORE_ENABLE=NO","CODE_SIGNING_ALLOWED=NO","CODE_SIGNING_REQUIRED=NO"];try{await Fe("xcodebuild",A,c,p,o,s)}catch(B){if(!qa(B))throw B;Xa(b),ti(process.cwd()),await Fe("xcodebuild",A,c,p,o,s)}let S=_.join(b,"Build/Products",`${R}-iphonesimulator`),x=pt(S,[".app"]);if(x.length>0){let B=x[0],Y=_.basename(B,".app"),L=_.join(S,`${Y}_simulator.zip`);return I.info(E.dim(`Creating simulator artifact: ${L}...`)),ee(`cd "${S}" && zip -r "${L}" "${_.basename(B)}"`),[L]}return[]}else{I.info(E.dim(`Archiving (Scheme: ${U}, Config: ${R})...`));let w=_.join(c,"build.xcarchive"),k=_.join(c,"export");y.rmSync(w,{recursive:!0,force:!0}),y.rmSync(k,{recursive:!0,force:!0});let A=i.IOS_DIST_P12,S=i.IOS_PROVISIONING_PROFILE,x=i.IOS_P12_PASSWORD||"",B=[],Y,L,J={isAppStore:!1,isDevelopment:!1};if(A&&S){I.info(E.blue("\u{1F510} CI/CD Signing: Importing certificates..."));try{let C=`${m.buildPrefix}-${t}.keychain-db`,j=_.join(Ae.tmpdir(),C),Z=m.keychainPassword;ee(`security create-keychain -p "${Z}" "${j}" 2>/dev/null || true`),ee(`security set-keychain-settings -t 3600 -l "${j}"`),ee(`security unlock-keychain -p "${Z}" "${j}"`);let ae=_.join(Ae.tmpdir(),`cert-${t}.p12`),Se=Buffer.from(A,"base64");y.writeFileSync(ae,Se),I.info(E.dim(`P12 data size: ${Se.length} bytes, first bytes: ${Se.slice(0,4).toString("hex")}`)),(Se.length<100||Se[0]!==48)&&(I.warn(E.yellow("\u26A0\uFE0F P12 data looks corrupted or was not decrypted correctly.")),I.warn(E.yellow(" This usually means MACH_ENCRYPTION_KEY on the Remote API differs from when credentials were uploaded.")));let qe=[x,"",m.keychainPassword],Ct=!1;for(let _e of qe)try{ee(`security import "${ae}" -k "${j}" -P "${_e}" -A -T /usr/bin/codesign -T /usr/bin/security`,{stdio:"pipe"}),Ct=!0,I.info(E.dim(`\u2713 P12 imported successfully with password: ${_e?"[set]":"[empty]"}`));break}catch(Le){I.info(E.dim(` P12 import attempt with password ${_e?`"${_e.substring(0,3)}..."`:"[empty]"} failed: ${Le.message?.split(`
|
|
1190
|
+
`)[0]||"unknown"}`))}if(!Ct)throw new Error("Failed to import P12.");y.unlinkSync(ae),ee(`security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "${Z}" "${j}"`);let on=ee("security list-keychains -d user",{encoding:"utf-8"}).split(`
|
|
1191
|
+
`).map(_e=>_e.trim().replace(/^"|"$/g,"")).filter(_e=>_e.length>0),sn=[j,...on].map(_e=>`"${_e}"`).join(" ");ee(`security list-keychains -d user -s ${sn}`),ee(`security default-keychain -s "${j}"`);let an=_.join(Ae.homedir(),"Library/MobileDevice/Provisioning Profiles");y.mkdirSync(an,{recursive:!0});let ut=Buffer.from(S,"base64"),Vn=_.join(an,`${m.nameLower}-temp-${t}.mobileprovision`);y.writeFileSync(Vn,ut);let zn=ut.toString("utf-8"),Ji=/<key>get-task-allow<\/key>\s*<true\/>/.test(zn);J={isAppStore:!zn.includes("<key>ProvisionedDevices</key>")&&!Ji,isDevelopment:Ji};try{let Le=ee(`security cms -D -i "${Vn}"`,{encoding:"utf-8"}).match(/<key>UUID<\/key>\s*<string>([^<]+)<\/string>/);L=Le?Le[1]:void 0}catch{let Le=zn.match(/<key>UUID<\/key>\s*<string>([^<]+)<\/string>/);L=Le?Le[1]:void 0}L||(I.warn("Could not extract UUID from provisioning profile. Using fallback."),L=`${m.nameLower}-${t}`);let Wn=_.join(an,`${L}.mobileprovision`);y.existsSync(Wn)&&y.unlinkSync(Wn),y.renameSync(Vn,Wn);try{let _e=ee(`security find-identity -v -p codesigning "${j}"`,{encoding:"utf-8"}),Le=Array.from(_e.matchAll(/"((?:Apple|iPhone) (?:Distribution|Developer|Development)[^"]*)"/g),Nt=>Nt[1]),qi=J.isDevelopment?Le.find(Nt=>/\b(Development|Developer)\b/.test(Nt)):Le.find(Nt=>/\bDistribution\b/.test(Nt)),Xi=Le[0];(qi||Xi)&&(Y=qi||Xi,I.info(E.blue(`Identity auto-detected from keychain: "${Y}"`)))}catch{}Y||(Y=J.isDevelopment?"Apple Development":"Apple Distribution",I.info(E.blue(`Identity fallback (profile heuristic): "${Y}"`))),I.info(E.dim(`Profile type: ${J.isDevelopment?"Development":J.isAppStore?"App Store":"Ad-Hoc"}`)),I.info(E.dim(`Identity Detection: get-task-allow=${J.isDevelopment}, Selected Identity="${Y}"`)),B.push("CODE_SIGN_STYLE=Manual"),B.push(`CODE_SIGN_IDENTITY="${Y}"`),B.push(`PROVISIONING_PROFILE_SPECIFIER=${L}`),e.iosTeamId&&B.push(`DEVELOPMENT_TEAM=${e.iosTeamId}`)}catch(C){throw I.error(`Signing setup failed: ${C.message}`),C}}else B.push("-allowProvisioningUpdates"),e.iosTeamId&&B.push(`DEVELOPMENT_TEAM=${e.iosTeamId}`);a&&await a("archive"),I.info(E.blue(`Archive detected Identity: "${Y}"`)),I.info(E.blue(`Archive detected UUID: "${L}"`)),await Fe("xcodebuild",["archive",d?"-workspace":"-project",d||f,"-scheme",U,"-configuration",R,"-archivePath",w,"-derivedDataPath",b,...D,...B],c,p,o,s);let O=pt(_.join(w,"Products","Applications"),[".app"]);for(let C of O){let j=tl(C);I.info(E.dim(`Validated iOS CFBundleVersion ${j} in ${_.basename(C)}`))}let q;L?(J.isAppStore?q="app-store":J.isDevelopment?q="development":q="ad-hoc",I.info(E.blue(`Export method from profile: "${q}"`))):(q=e.distribution==="store"?"app-store":e.distribution==="internal"?"ad-hoc":"development",I.warn(E.yellow(`No profile UUID detected. Export method from distribution flag: "${q}"`)));let ye=e.iosExportMethod||q,Ee=e.iosBundleIdentifier||Ze("ios"),H=_.join(c,"ExportOptions.plist"),F=`<?xml version="1.0" encoding="UTF-8"?>
|
|
1192
1192
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
1193
1193
|
<plist version="1.0">
|
|
1194
1194
|
<dict>
|
|
@@ -1208,45 +1208,57 @@ end
|
|
|
1208
1208
|
<string>${L}</string>
|
|
1209
1209
|
</dict>`:""}
|
|
1210
1210
|
</dict>
|
|
1211
|
-
</plist>`;if(y.writeFileSync(H,
|
|
1212
|
-
${
|
|
1211
|
+
</plist>`;if(y.writeFileSync(H,F),process.env[`${m.envPrefix}DEBUG`]&&I.info(E.magenta(`[${m.nameUpper}_DEBUG] ExportOptions.plist:
|
|
1212
|
+
${F}`)),a&&await a("export"),I.info(E.blue(`Exporting with Bundle ID: "${Ee}"`)),I.info(E.blue(`Exporting with Method: "${ye}"`)),o){o(E.magenta(`
|
|
1213
1213
|
[DIAGNOSTIC] Checking available signing identities...
|
|
1214
|
-
`));try{let C=
|
|
1215
|
-
`))}catch(C){o(
|
|
1216
|
-
`))}}await Fe("xcodebuild",["-exportArchive","-archivePath",
|
|
1214
|
+
`));try{let C=ee("security find-identity -v -p codesigning",{encoding:"utf-8"});o(E.magenta(`${C}
|
|
1215
|
+
`))}catch(C){o(E.red(`[DIAGNOSTIC] Failed to list identities: ${C.message}
|
|
1216
|
+
`))}}await Fe("xcodebuild",["-exportArchive","-archivePath",w,"-exportPath",k,"-exportOptionsPlist",H],c,p,o,s),a&&await a("validate");let X=pt(k,[".ipa"]);for(let C of X)try{ee(`unzip -t "${C}"`,{stdio:"pipe"});let j=nl(C);o&&o(`[IPA VALID] ${_.basename(C)} \u2014 archive integrity OK
|
|
1217
1217
|
`),o&&o(`[IPA VALID] CFBundleVersion ${j}
|
|
1218
|
-
`)}catch(j){let
|
|
1219
|
-
`),new Error(
|
|
1220
|
-
`).slice(1).map(s=>s.trim()).filter(s=>s.length>0&&!s.startsWith("*")).map(s=>s.split(" ")[0]).length===0){I.warn(
|
|
1221
|
-
`).filter(a=>a.trim().length>0)}catch{}if(l.length>0){let a=await
|
|
1222
|
-
`).find(a=>a.includes("android.intent.action.MAIN")&&a.includes("android.intent.category.LAUNCHER"))?
|
|
1218
|
+
`)}catch(j){let Z=`IPA validation failed for ${_.basename(C)}: ${j.message||"archive may be corrupt"}`;throw o&&o(`[IPA CORRUPT] ${Z}
|
|
1219
|
+
`),new Error(Z)}return X}},Ze=e=>{try{let t=_.join(process.cwd(),m.configFileName);if(y.existsSync(t)){let n=JSON.parse(y.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(y.existsSync(i)){let o=y.readFileSync(i,"utf-8").match(/applicationId\s+['"]([^'"]+)['"]/);if(o)return o[1]}}else{let n=_.resolve(process.cwd(),y.existsSync("ios")?"ios":"."),i=pt(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=y.readFileSync(s,"utf-8").match(/<key>CFBundleIdentifier<\/key>\s*<string>([^<]+)<\/string>/);if(a&&!a[1].includes("$"))return a[1]}let r=pt(n,[".xcodeproj"]);if(r.length>0){let s=_.join(r[0],"project.pbxproj");if(y.existsSync(s)){let a=y.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(y.existsSync(s)){let a=y.readFileSync(s,"utf-8").match(/"bundleIdentifier":\s*"([^"]+)"/);if(a)return a[1]}}}catch{return null}return null},ol=()=>{try{return ee("emulator -version",{stdio:"ignore"}),"emulator"}catch{let t=Ae.homedir(),n=[_.join(t,"Library/Android/sdk/emulator/emulator"),_.join(t,"Android/Sdk/emulator/emulator"),"/usr/local/lib/android/sdk/emulator/emulator"];for(let i of n)if(y.existsSync(i))return i}return"emulator"},sl=async(e,t)=>{let n=un();try{if(ee("adb devices").toString().split(`
|
|
1220
|
+
`).slice(1).map(s=>s.trim()).filter(s=>s.length>0&&!s.startsWith("*")).map(s=>s.split(" ")[0]).length===0){I.warn(E.yellow("No Android devices or emulators found."));let s=ol(),l=[];try{l=ee(`${s} -list-avds`).toString().split(`
|
|
1221
|
+
`).filter(a=>a.trim().length>0)}catch{}if(l.length>0){let a=await ni({message:"Select an emulator to launch:",options:l.map(d=>({value:d,label:d}))});if(fn(a))return;n.start(`Launching emulator ${a}...`),Cr(s,["-avd",a],{detached:!0,stdio:"ignore"}).unref();let c=0,u=!1;for(;c<60;){try{if(ee("adb shell getprop sys.boot_completed",{stdio:"pipe"}).toString().trim()==="1"){u=!0;break}}catch{}await new Promise(d=>setTimeout(d,2e3)),c++}if(!u)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 Fe("adb",["install","-r",e],process.cwd(),{},t),n.stop("Installation complete.");let o=Ze("android");if(o){I.info(E.blue(`\u{1F680} Launching ${o}...`));try{ee(`adb shell dumpsys package ${o}`).toString().split(`
|
|
1222
|
+
`).find(a=>a.includes("android.intent.action.MAIN")&&a.includes("android.intent.category.LAUNCHER"))?ee(`adb shell monkey -p ${o} -c android.intent.category.LAUNCHER 1`,{stdio:"ignore"}):ee(`adb shell monkey -p ${o} -c android.intent.category.LAUNCHER 1`,{stdio:"ignore"})}catch{I.warn("Could not auto-launch app. You may need to open it manually.")}}}catch(i){n.stop("Installation failed."),I.error(E.red(`Failed to install APK: ${i.message}`))}},al=async(e,t,n)=>{let i=un();try{if(!ee("xcrun simctl list devices booted").toString().includes("(Booted)")){I.warn(E.yellow("No iOS Simulator is currently booted."));let o=ee("xcrun simctl list devices --json").toString(),s=JSON.parse(o).devices,l=[];Object.keys(s).forEach(d=>{s[d].forEach(f=>{f.isAvailable&&l.push({...f,runtime:d})})});let a=await ni({message:"Select a simulator to launch:",options:l.map(d=>({value:d.udid,label:`${d.name} (${d.runtime.split(".").pop()})`}))});if(fn(a))return;i.start(`Booting ${a}...`),ee(`xcrun simctl boot ${a}`),ee(`open -a Simulator --args -CurrentDeviceUDID ${a}`);let c=0,u=!1;for(;c<30;){try{if(ee("xcrun simctl list devices booted").toString().includes(a)){u=!0;break}}catch{}await new Promise(d=>setTimeout(d,2e3)),c++}if(!u)throw i.stop("Simulator boot timed out."),new Error("Simulator boot timed out.");i.stop("Simulator booted.")}i.start("Installing on iOS Simulator..."),await Fe("xcrun",["simctl","install","booted",e],process.cwd(),{},n),i.stop("Installation complete."),I.info(E.blue(`\u{1F680} Launching ${t}...`)),await Fe("xcrun",["simctl","launch","booted",t],process.cwd(),{},n)}catch(r){i.stop("Installation failed."),I.error(E.red(`Failed to install on Simulator: ${r.message}`))}},ll=async(e,t,n)=>{let i=un();i.start("Scanning for connected iOS devices...");try{let r=ee("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 ni({message:"Select a device to install on:",options:s.map(c=>({value:c.identifier,label:`${c.deviceProperties?.name||c.name||c.model?.name} (${c.model?.name||"iPhone"}) - ${c.identifier}`}))});if(fn(a))return;l=a,i.start(`Installing on ${l}...`)}else i.message(`Installing on ${s[0].model.name}...`);await Fe("xcrun",["devicectl","device","install","app","--device",l,e],process.cwd(),{},n),i.stop("Installation complete."),I.info(E.blue(`\u{1F680} Launching ${t}...`)),await Fe("xcrun",["devicectl","device","launch","app","--device",l,t],process.cwd(),{},n)}catch(r){i.stop("Installation failed."),I.error(E.red(`Failed to install on device: ${r.message}`)),I.info(E.dim('Make sure your device is unlocked and "Developer Mode" is enabled in Settings -> Privacy & Security.'))}};import M from"fs";import _t from"os";import V from"path";import{spawn as dl,spawnSync as He}from"child_process";import{randomUUID as cl}from"crypto";import{pipeline as ul}from"stream/promises";import{isCancel as li,log as G,select as Kr,spinner as Bt,text as fl}from"@clack/prompts";import Ut from"axios";import z from"chalk";import pn from"adm-zip";async function Vr(e){if(e.localRunner){let n=await yl(e);process.exitCode=n?n.exitCode:1;return}if(e.local){let n=await Sl(e);n&&(process.exitCode=n.exitCode);return}let t=await fi(e);if(t&&(G.success(z.green(`Maestro run ${t.status||"queued"}: ${t.testRunId}`)),t.launchDeferredReason&&G.warn(z.yellow(t.launchDeferredReason)),t.dashboardUrl&&G.info(z.dim("View test run: ")+z.white.underline(t.dashboardUrl)),e.wait)){let n=await bl(e,t);n&&(process.exitCode=n.status==="passed"?0:1)}}var pl=new Set(["passed","failed","cancelled","interrupted"]),Mr=Number(process.env.MACH_FLOW_UPLOAD_MAX_ATTEMPTS||4),ml=Number(process.env.MACH_FLOW_UPLOAD_TIMEOUT_MS||12e4);function ui(e){let t=Array.isArray(e)?e:e?[e]:[];return[...new Set(t.flatMap(n=>String(n||"").split(",")).map(n=>n.trim()).filter(Boolean))]}function gl(e){let t=ui(e);if(t.length===0)return;let n={};for(let i of t){let r=process.env[i];r!==void 0&&(n[i]=r)}return Object.keys(n).length>0?n:void 0}function hl(e){let t={};for(let[i,r]of Object.entries(process.env))i.startsWith("MAESTRO_TEST_")&&r!==void 0&&(t[i]=r);let n=ui(e);for(let i of n){let r=process.env[i];r!==void 0&&(t[i]=r)}return t}async function yl(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||bt).replace(/\/$/,""),o=M.mkdtempSync(V.join(_t.tmpdir(),"mach-maestro-runner-")),s=V.join(o,"mach-maestro-output"),l=V.join(o,"runner.log");if(M.mkdirSync(s,{recursive:!0}),!t||!n||!i)return G.error(z.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,c=null,u=null,d=p=>{M.appendFileSync(l,`${p}${p.endsWith(`
|
|
1223
1223
|
`)?"":`
|
|
1224
|
-
`}`)},u=async(f,p)=>{try{await Mt.post(`${r}/internal/tests/${encodeURIComponent(n)}/runner`,{projectId:t,runnerToken:i,status:f,error:p,logPreview:_l(l),junitUrl:a?.urls?.junitDownloadUrl,logsUrl:a?.urls?.logsDownloadUrl,artifactsUrl:a?.urls?.artifactsDownloadUrl})}catch(h){c(`[WARN] Could not post runner update: ${h.message||h}`)}};try{c(`Mach Maestro local runner starting for ${n}`);let f=await Mt.post(`${r}/internal/tests/${encodeURIComponent(n)}/runner-payload`,{projectId:t,runnerToken:i});if(f.data?.status!=="success"||!f.data?.payload)throw new Error(f.data?.message||"Runner payload was not returned.");a=f.data.payload;let p=Object.keys(a.env||{});c(`Using Maestro env vars: ${p.length>0?p.join(", "):"none"}`);let h={...process.env,...a.env||{}},O=$l(a.env);O.length>0&&c(`Passing Maestro env vars to test command: ${p.sort().join(", ")}`),await u("running");let N=a.platform==="android"?"app.apk":"app.zip",M=Z.join(o,N),P=Z.join(o,"source.zip"),F=Z.join(o,"source");K.mkdirSync(F,{recursive:!0}),c("Downloading app artifact..."),await ai(a.artifactUrl,M),c(`Downloaded app artifact: ${N} (${Ur(K.statSync(M).size)})`),c("Downloading Maestro source..."),await ai(a.urls.sourceUrl,P),c(`Downloaded Maestro source: source.zip (${Ur(K.statSync(P).size)})`),new fn(P).extractAllTo(F,!0);let S=vl(F,a.flowPath||".maestro");if(!K.existsSync(S))throw new Error(`Maestro flow path not found: ${a.flowPath||".maestro"}`);if(c(`Resolved Maestro flow path: ${Z.relative(F,S)||"."}`),a.platform==="ios"){await Cl(a.device||"iphone_15",l);let k=Nl(M,o),v=zr(k,l);c(`Resolved iOS app bundle: ${k}`),c(`Resolved iOS bundle id: ${v||"unknown"}`),kl(k,l),li("xcrun",["simctl","install","booted",k],l),v&&pt("xcrun",["simctl","get_app_container","booted",v,"app"],l),ri(s,l,"ios-before-maestro.png"),a.record&&(d=Tl(s,l))}else li("adb",["install","-r",M],l);let ee=Math.max(0,Math.min(10,Number(a.retries??1)))+1,g=Z.join(s,"report.xml"),T=Dl(l);if(!T)throw new Error("Maestro CLI not found on this runner. Install Maestro or set MAESTRO_BIN to the full maestro path.");let E=1;for(let k=1;k<=ee&&(c(`Running Maestro attempt ${k}/${ee}...`),E=pt(T,["test","--platform",a.platform,...O,S,"--format","junit","--output",g,"--test-output-dir",s],l,void 0,h),E!==0);k+=1);return a.platform==="ios"&&ri(s,l,"ios-after-maestro.png"),await Br(d,l),d=null,await Fr(a.urls,o,s,l),E===0?(await u("passed"),G.success(V.green(`Managed Maestro run passed: ${n}`)),{status:"passed",exitCode:0,attempts:ee,flows:a.flowPath,platform:a.platform}):(await u("failed",`Maestro exited with code ${E}`),G.error(V.red(`Managed Maestro run failed with exit code ${E}`)),{status:"failed",exitCode:E,attempts:ee,flows:a.flowPath,platform:a.platform})}catch(f){let p=f.message||String(f);return c(`MACH_MAESTRO_RUN_FAILED: ${p}`),a?.platform==="ios"&&ri(s,l,"ios-after-failure.png"),await Br(d,l),a?.urls&&await Fr(a.urls,o,s,l),await u("failed",p),G.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 gl(e){let t=e.maestroFlows||".maestro",n=Kr(e.maestroRetries);if(n===null)return null;let i=Z.resolve(t);if(!K.existsSync(i))return G.error(V.red(`Maestro flows not found: ${t}`)),{status:"failed",exitCode:1,attempts:0,flows:t,platform:e.platform};let r=await Al(e);if(r?.url){if(!await wl(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&&G.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));let l=pl(e.maestroEnv),a=Object.keys(l);if(a.length>0){G.info(V.dim(`Passing Maestro env vars to local run: ${a.join(", ")}`));for(let[p,h]of Object.entries(l))s.push("-e",`${p}=${h}`)}s.push(t);let d=n+1,c=1;for(let p=1;p<=d;p+=1){G.info(V.dim(`Running local Maestro attempt ${p}/${d}...`));let h=nt("maestro",s,{cwd:process.cwd(),stdio:"inherit",env:process.env});if(h.error){let O=h.error.message||"Failed to run Maestro";G.error(V.red(`Local Maestro failed to start: ${O}`)),G.info(V.dim("Install Maestro locally, then retry: https://maestro.mobile.dev/getting-started/installing-maestro")),c=1;break}if(c=typeof h.status=="number"?h.status:1,c===0)break}let u=c===0?"passed":"failed",f={status:u,exitCode:c,attempts:d,flows:t,platform:o};return Bl(e,f),u==="passed"?G.success(V.green("Local Maestro run passed")):G.error(V.red(`Local Maestro run failed with exit code ${c}`)),f}async function ui(e){let t=$e(`./${m.configFileName}`),n=e.projectId||t?.projectId,i=String(e.profile||e.buildProfile||"production").toLowerCase();if(!n)return G.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 u=await Hr({message:"Select platform for the latest build:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"}]});if(si(u))return null;r=u}let o=await El(e);if(!o)return null;if(o.kind==="latest"&&!r)return G.error("Pass --platform when using --latest."),null;if(o.kind==="artifact-url"&&!r)return G.error("Pass --platform when using --artifact-url."),null;let s=Kr(e.maestroRetries);if(s===null)return null;let l=ci(e.maestroEnv),a=fl(e.maestroEnv);!e.quiet&&l.length>0&&G.info(V.dim(`Forwarding Maestro env vars by name: ${l.join(", ")}`));let d=await yl(e,n);if(d===null)return null;let c=Ut();e.quiet||c.start("Queuing Maestro run...");try{let u=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:d,flows:e.maestroFlows||".maestro",device:e.maestroDevice||(r==="ios"?"iphone_15":"pixel_6"),retries:s,record:!!e.maestroRecord,...l.length>0?{envNames:l}:{},...a?{env:a}:{}});if(u.data.status!=="success")throw new Error(u.data.message||"Failed to queue Maestro run");let f=u.data.testRun,p={testRunId:f.testRunId,status:f.status,projectId:n,buildId:f.buildId,platform:f.platform,dashboardUrl:f.dashboardUrl||`${ze}/tests/${f.testRunId}`,launchDeferredReason:f.launchDeferredReason};return Yr(e,p),e.quiet||c.stop("Maestro run queued"),p}catch(u){e.quiet||c.stop("Could not queue Maestro run");let f=u.response?.data?.message||u.message||"Unknown error";return G.error(V.red(`Maestro queue failed: ${f}`)),null}}async function hl(e,t){let n=Mr(e.waitTimeout,60,"--wait-timeout"),i=Mr(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(G.info(V.dim(`Waiting for Maestro run ${t.testRunId} to finish...`));Date.now()-s<=r;){let a=await bl(t.projectId,t.testRunId);if(!a)return null;if(a.status&&a.status!==l&&(l=a.status,G.info(V.dim(`Maestro status: ${l}`))),cl.has(String(a.status)))return Yr(e,a),a.status==="passed"?G.success(V.green(`Maestro run passed: ${a.testRunId}`)):(G.error(V.red(`Maestro run ${a.status}: ${a.testRunId}`)),a.error&&G.error(V.red(String(a.error)))),a;await fi(o)}return G.error(V.red(`Timed out waiting for Maestro run ${t.testRunId} after ${n} minute(s).`)),{...t,status:"timeout"}}async function yl(e,t){if(e.maestroUseBuildSource)return;let n=e.maestroFlows||".maestro",i=Z.resolve(n);if(!K.existsSync(i))return e.maestroFlows?(G.error(V.red(`Maestro flows not found: ${n}`)),null):void 0;let r=Z.relative(process.cwd(),i);if(!r||r.startsWith("..")||Z.isAbsolute(r))return G.error(V.red("Managed Maestro flow uploads must be inside the current project directory.")),null;let o=Ut();e.quiet||o.start(`Uploading Maestro flows from ${r}...`);try{let s=await R.post("/tests/maestro/source-upload-url",{projectId:t,uploadId:al()});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 fn;if(K.statSync(i).isDirectory())l.addLocalFolder(i,r);else{let c=Z.dirname(r);l.addLocalFile(i,c==="."?void 0:c,Z.basename(r))}let d=l.toBuffer();return await Sl(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 G.error(V.red(`Maestro flow upload failed: ${l}`)),null}}function Gr(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 Sl(e,t,n,i,r){let o;for(let s=1;s<=xr;s+=1)try{await Mt.put(e,t,{headers:{"Content-Type":n},maxBodyLength:1/0,maxContentLength:1/0,timeout:ul});return}catch(l){if(o=l,!Gr(l)||s>=xr)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 fi(a)}throw o}async function bl(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||`${ze}/tests/${i.testRunId}`,launchDeferredReason:i.launchDeferredReason,...i.error?{error:i.error}:{}}}catch(n){let i=n.response?.data?.message||n.message||"Unknown error";return G.error(V.red(`Could not fetch Maestro run status: ${i}`)),null}}async function El(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 Hr({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(si(t))return null;if(t==="latest")return{kind:"latest"};let n=await dl({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 si(n)?null:{kind:t,value:String(n).trim()}}function Mr(e,t,n){if(e==null||e==="")return t;let i=Number(e);return!Number.isFinite(i)||i<=0?(G.error(`${n} must be a positive number.`),null):i}function fi(e){return new Promise(t=>setTimeout(t,e))}function Kr(e){if(e==null||e==="")return 1;let t=Number(e);return!Number.isInteger(t)||t<0||t>10?(G.error("--maestro-retries must be an integer between 0 and 10."),null):t}async function Al(e){if(e.artifactUrl)return{url:e.artifactUrl,platform:e.platform||mi(e.artifactUrl),name:Wr(e.artifactUrl)};let t=e.buildId||Ul(e.buildUrl);return t?Vr(t,e.platform):e.latest?Il(e):null}async function Vr(e,t){let n=Ut();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=Ml(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||mi(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 G.error(V.red(`Local Maestro artifact lookup failed: ${r}`)),null}}async function Il(e){let t=$e(`./${m.configFileName}`),n=e.projectId||t?.projectId,i=String(e.profile||e.buildProfile||"production").toLowerCase();if(!n)return G.error(`No projectId found. Run \`${m.nameLower} link\` first or pass --build-id/--artifact-url.`),null;if(!e.platform)return G.error("Pass --platform when using --latest with --local."),null;let r=Ut();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}`),Vr(l.buildId,e.platform)}catch(o){r.stop("Could not resolve latest build");let s=o.response?.data?.message||o.message||"Unknown error";return G.error(V.red(`Latest build lookup failed: ${s}`)),null}}async function wl(e){let t=e.platform||mi(e.url);if(!t)return G.error(V.red("Could not infer platform for local install. Pass --platform android or --platform ios.")),!1;let n=K.mkdtempSync(Z.join(di.tmpdir(),"mach-maestro-")),i=e.name||Wr(e.url)||(t==="android"?"app.apk":"app.zip"),r=Z.join(n,i),o=Ut();o.start(`Downloading ${i}...`);try{await ai(e.url,r),o.stop("Artifact downloaded")}catch(s){return o.stop("Artifact download failed"),G.error(V.red(s.message||"Failed to download artifact")),!1}return t==="android"?Ll(r):xl(r,n)}async function ai(e,t){let n=await Mt.get(e,{responseType:"stream"});await ll(n.data,K.createWriteStream(t))}function _l(e,t=12e3){try{return K.readFileSync(e,"utf-8").slice(-t)}catch{return""}}function Ur(e){if(!Number.isFinite(e)||e<0)return"unknown size";if(e<1024)return`${e} B`;let t=["KB","MB","GB"],n=e/1024,i=t[0];for(let r=1;n>=1024&&r<t.length;r+=1)n/=1024,i=t[r];return`${n.toFixed(n>=10?1:2)} ${i}`}function $l(e){return Object.entries(e||{}).filter(([t,n])=>!!t&&n!==void 0).sort(([t],[n])=>t.localeCompare(n)).flatMap(([t,n])=>["-e",`${t}=${n}`])}function vl(e,t){let n=Z.resolve(e,t||".maestro"),i=Z.relative(e,n);if(i.startsWith("..")||Z.isAbsolute(i))throw new Error("Maestro flow path must stay inside the build source.");return n}function Rl(e,t){let n=[e];for(let i=0;i<t.length;i+=1){let r=t[i],o=t[i-1];(o==="-e"||o==="--env")&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(r)?n.push(`${r.slice(0,r.indexOf("="))}=<redacted>`):n.push(r)}return n.join(" ")}function pt(e,t,n,i,r=process.env){K.appendFileSync(n,`
|
|
1225
|
-
$ ${
|
|
1226
|
-
`);let o=
|
|
1227
|
-
`),1):typeof o.status=="number"?o.status:1}function
|
|
1228
|
-
`)[0]?.trim():"";i&&t.unshift(i);for(let r of t)if(r&&
|
|
1229
|
-
`),r;return e&&
|
|
1230
|
-
`),null}function
|
|
1231
|
-
`);return}let i=
|
|
1232
|
-
`),
|
|
1233
|
-
`),
|
|
1234
|
-
`),null;let i=
|
|
1235
|
-
`),null):r}function
|
|
1236
|
-
`)}function
|
|
1237
|
-
`);let i=
|
|
1238
|
-
`)}),i}async function
|
|
1239
|
-
`),e.kill("SIGINT")),setTimeout(()=>{!i&&!e.killed&&(
|
|
1240
|
-
`),e.kill("SIGKILL")),r()},5e3).unref?.()})}function
|
|
1241
|
-
`),
|
|
1242
|
-
`)}
|
|
1243
|
-
`)
|
|
1244
|
-
`)
|
|
1245
|
-
`)}}function Ll(e){if(!e.endsWith(".apk"))return G.error(V.red("Local Android Maestro runs need an APK artifact.")),!1;G.info(V.dim("Installing APK on local Android device/emulator..."));let t=nt("adb",["install","-r",e],{stdio:"inherit",env:process.env});return t.error?(G.error(V.red(`adb failed to start: ${t.error.message}`)),!1):t.status!==0?(G.error(V.red(`adb install failed with exit code ${t.status??1}`)),!1):!0}function xl(e,t){if(e.endsWith(".ipa"))return G.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=Z.join(t,"ios-app");K.mkdirSync(r,{recursive:!0}),new fn(e).extractAllTo(r,!0);let o=pi(r);if(!o)return G.error(V.red("Could not find a .app bundle inside the downloaded zip.")),!1;n=o}if(!n.endsWith(".app"))return G.error(V.red("Local iOS Maestro runs need an iOS Simulator .app bundle or .app.zip artifact.")),!1;G.info(V.dim("Installing app on booted iOS Simulator..."));let i=nt("xcrun",["simctl","install","booted",n],{stdio:"inherit",env:process.env});return i.error?(G.error(V.red(`xcrun failed to start: ${i.error.message}`)),!1):i.status!==0?(G.error(V.red(`iOS Simulator install failed with exit code ${i.status??1}`)),!1):!0}function pi(e){let t=K.readdirSync(e,{withFileTypes:!0});for(let n of t){let i=Z.join(e,n.name);if(n.isDirectory()&&n.name.endsWith(".app"))return i;if(n.isDirectory()){let r=pi(i);if(r)return r}}return null}function Ml(e,t){let n=String(t||"").toLowerCase();return n==="android"?e.find(i=>wt(i,".apk")):n==="ios"?e.find(i=>wt(i,".app.zip"))||e.find(i=>wt(i,".zip")):e.find(i=>wt(i,".apk"))||e.find(i=>wt(i,".app.zip"))||e.find(i=>wt(i,".zip"))}function wt(e,t){return String(e?.name||e?.downloadUrl||e?.url||"").toLowerCase().endsWith(t)}function mi(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 Wr(e){if(e)try{return Z.basename(new URL(e).pathname)||void 0}catch{return Z.basename(e)||void 0}}function Ul(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 Yr(e,t){if(!e.jsonOutput)return;let n=Z.resolve(e.jsonOutput),i={...t,updatedAt:new Date().toISOString()};try{let r=Z.dirname(n);r&&r!=="."&&K.mkdirSync(r,{recursive:!0}),K.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){G.warn(V.yellow(`Could not write Maestro metadata JSON: ${r.message}`))}}function Bl(e,t){if(!e.jsonOutput)return;let n=Z.resolve(e.jsonOutput),i={mode:"local",...t,updatedAt:new Date().toISOString()};try{let r=Z.dirname(n);r&&r!=="."&&K.mkdirSync(r,{recursive:!0}),K.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){G.warn(V.yellow(`Could not write Maestro metadata JSON: ${r.message}`))}}import{spinner as ot,text as Bt,select as bi,isCancel as it,cancel as Ei,log as to}from"@clack/prompts";import ne from"chalk";import se from"fs";import Ie from"path";import{spawn as Fl,spawnSync as mt}from"child_process";import no from"axios";import ht from"os";import wi from"crypto";var Hl=5e3,jl=12,io=100,gi=24,Jr=8e3,Gl={completed:"completed",draft:"draft",halted:"halted",inprogress:"inProgress","in-progress":"inProgress"},Kl=e=>e?.type==="google_service_account",mn=e=>e?.bundleId||e?.packageName||e?.meta?.packageName||e?.meta?.bundleId,ro=e=>e.submitArgs||process.argv.slice(3).join(" ");async function gn(e){let t=ot(),n=Pe(),i=Vl(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(ne.dim(`Submit for project: ${i.name||r} | Profile: ${o}`));let s=e.platform;if(!s){let A=await bi({message:"Select platform to submit:",options:[{value:"ios",label:"iOS (App Store Connect / TestFlight)"},{value:"android",label:"Android (Google Play Console)"}]});if(it(A)){Ei("Operation cancelled");return}s=A}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?ad(i,o,e):null;if(s==="ios"&&!e.local&&!l){await zl(i,o,e);return}let a=e.submitId,d=!!(e.local&&a),c=a||null,u=async(A,x={})=>{c&&await ql(r,c,{status:A,...x})},f=s==="android"?e.packageName||e.androidPackage||rd(i,o):void 0,p=s==="ios"?e.bundleId||e.iosBundleIdentifier||sd(i,o):void 0,h,O,N,M=!1;try{s==="android"&&(h=e.track||i.submit?.[o]?.android?.track||i.submit?.production?.android?.track||"internal",O=ld(i,o,e.releaseStatus),N=cd(i,o,e.rollout),M=ud(i,o,e.changesNotSentForReview),fd(O,N))}catch(A){le(A.message),process.exitCode=1;return}if(s==="android"&&!d&&(c=await Wl(i,r,s,o,e,{packageName:f,track:h,releaseStatus:O,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:f,track:h,releaseStatus:O,rollout:N,startTime:Date.now(),...d?Zl():{}});let P=null,F=null;try{F=await pd(r,s,e,n?.token),P=F?.filePath||null}catch(A){await u("failed",{error:`Failed to resolve submission artifact: ${A.message}`,endTime:Date.now()}),le(`Failed to resolve submission artifact: ${A.message}`),process.exitCode=1;return}if(!P){let A=gd(s,e);await u("failed",{error:A,endTime:Date.now()}),le(A),process.exitCode=1;return}await u("running",{buildId:F?.buildId,artifactName:F?.artifactName,artifactSource:F?.source}),fe(`Using artifact: ${ne.green(Ie.basename(P))} `),t.start("Fetching submission credentials from Dashboard...");let S;try{let x=(await R.get(`/credentials/${r}`)).data.credentials||[];if(s==="android"&&!f){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 U=x.filter(Kl),z=s==="ios"?x.filter(L=>L.type==="asc_api_key"):od(U,f);if(z.length===0){if(t.stop("Credentials missing"),le(s==="android"?`No Google Play service credential found for package ${f}.`:`No Service Credentials found for ${s}.`),s==="android"){let L=U.map(mn).filter(Boolean).join(", ");L&&fe(`Found Google Play service credential(s) for: ${L}`),fe(`Use '${m.nameLower} credentials:service --platform android --package-name ${f}' 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(S=ed(z,e.credentialId),!S&&s==="ios"&&p&&(S=td(z,p)),S||z.length===1)S=S||z[0],t.stop(`Using: ${S.name}`),s==="android"&&mn(S)==="*"&&fe(ne.yellow(`Using legacy wildcard Google Play credential for ${f}. Upload a package-scoped credential when possible.`));else{if(t.stop("Multiple credentials found"),nd()){let W=z.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: ${W}`),await u("failed",{error:"Multiple submission credentials found; --credential-id is required in CI.",endTime:Date.now()}),process.exitCode=1;return}let L=await bi({message:`Choose a ${s==="ios"?"App Store Connect":"Google Play"} credential:`,options:z.map(W=>({value:W.credentialId,label:W.name,hint:`${W.keyId?`ID: ${W.keyId}`:""} ${W.issuerId?`(Issuer: ${W.issuerId.substring(0,8)}...)`:""}`}))});if(it(L)){Ei("Submission cancelled"),await u("failed",{error:"Submission cancelled while selecting credential.",endTime:Date.now()}),process.exitCode=1;return}S=z.find(W=>W.credentialId===L),fe(`Using selected: ${ne.green(S.name)}`)}}catch(A){t.stop("Failed to fetch credentials"),le(`API Error: ${A.message} `),await u("failed",{error:`Failed to fetch credentials: ${A.message}`,endTime:Date.now()}),process.exitCode=1;return}let Y=se.mkdtempSync(Ie.join(ht.tmpdir(),`${m.nameLower}-submit-`)),ee=S.keyId||S.meta?.keyId,g=S.issuerId||S.meta?.issuerId,T=S.type==="asc_api_key"?`AuthKey_${ee}.p8`:"service-account.json",E=Ie.join(Y,T);t.start("Downloading secure key...");try{let A=await R.get(`/credentials/${S.credentialId}/download`,{params:{projectId:r,format:"raw"}});if(A.data.status!=="success"||!A.data.downloadUrl)throw new Error("Failed to get secure download URL");let x=await no.get(A.data.downloadUrl,{responseType:"arraybuffer"});se.writeFileSync(E,Buffer.from(x.data)),t.stop("Key downloaded to secure temp storage")}catch(A){t.stop("Download failed"),le(`Failed to download key: ${A.message}`);try{se.rmSync(Y,{recursive:!0,force:!0})}catch{}await u("failed",{error:`Failed to download credential key: ${A.message}`,endTime:Date.now()}),process.exitCode=1;return}fe(ne.blue(`Initiating ${s==="ios"?"TestFlight":"Google Play"} submission...`));let k=!1,v;try{if(s==="ios"){if(!ee){let x=await Bt({message:"Enter App Store Connect Key ID (e.g. 2X948D...):",validate:U=>U.length>0?void 0:"Key ID is required"});if(it(x)){await u("failed",{error:"Submission cancelled while entering ASC Key ID.",endTime:Date.now()}),process.exitCode=1;return}ee=x}if(!g||g==="undefined"){let x=await Bt({message:"Enter App Store Connect Issuer ID (Found on ASC Keys page):",validate:U=>U.length>0?void 0:"Issuer ID is required"});if(it(x)){await u("failed",{error:"Submission cancelled while entering ASC Issuer ID.",endTime:Date.now()}),process.exitCode=1;return}g=x}fe(`Using ASC Key ID: ${ee}`),fe(`Using ASC Issuer ID: ${g}`);let A=l?await yd(P,E,g,ee,p,l):await hd(P,E,g,ee,p);Ii(`${s==="ios"?"App Store":"Google Play"} submission successful!`),k=!0}else v=await Id(P,E,h||"internal",f,O||"completed",N,M,o),Ii("Google Play submission successful!"),k=!0}catch(A){le(`Submission failed: ${A.message}`),await u("failed",{error:A.message,endTime:Date.now()}),rt(e,{status:"failed",projectId:r,submitId:c,platform:s,profile:o,buildId:F?.buildId||e.buildId,artifactName:F?.artifactName,error:A.message,dashboardUrl:c?gt(c,r):void 0}),process.exitCode=1}finally{k&&(await u("success",{endTime:Date.now(),versionCode:v?.versionCode,track:h,releaseStatus:O}),rt(e,{status:"success",projectId:r,submitId:c,platform:s,profile:o,buildId:F?.buildId||e.buildId,artifactName:F?.artifactName,versionCode:v?.versionCode,track:h,releaseStatus:O,dashboardUrl:c?gt(c,r):void 0})),Md(Y),P&&P.includes(`${m.nameLower}-artifact-`)}}function Vl(e){let t=`./${m.configFileName}`;if(se.existsSync(t))try{return JSON.parse(se.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 zl(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||wi.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:ro(n),runnerArgs:s,runnerCommand:[m.nameLower,"submit",...s].map(id).join(" "),appName:e.name,startTime:Date.now()},a=ot();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||gt(r,i);a.stop("iOS submit queued"),fe(`Submission ID: ${ne.cyan(r)}`),fe(`Dashboard: ${ne.blue.underline(u)}`),rt(n,{status:"pending",projectId:i,submitId:r,platform:"ios",profile:t,latest:o,buildId:n.buildId,dashboardUrl:u}),await Jl(i,r,n)}catch(d){a.stop("Could not queue iOS submit"),le(Ql(d)),process.exitCode=1}}async function Wl(e,t,n,i,r,o={}){let s=r.submitId||wi.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:ro(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||gt(s,t);return fe(`Submission ID: ${ne.cyan(s)}`),fe(`Dashboard: ${ne.blue.underline(u)}`),rt(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 fe(ne.yellow(`Could not create submission tracking record: ${c}`)),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.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 Jl(e,t,n){let i=ot(),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"),Ii("App Store submission successful!"),rt(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||gt(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),rt(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||gt(t,e)}),process.exitCode=1;return}n.quiet||i.message(`iOS submit ${a}...`),await Ai(Hl)}catch(s){if(r++,r>=jl){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 Ai(Math.min(2e3*r,15e3))}}async function ql(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||!Xl(o))break;await Ai(1e3*r)}to.warn(ne.dim(`Could not report submission status: ${i?.message||i}`))}function Xl(e){let t=e.response?.status;return!t||t===408||t===409||t===425||t===429||t>=500}function Zl(){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 Ql(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(`
|
|
1246
|
-
`):n||e.message||String(e)}function gt(e,t){if(!e)return ze;let n=t?`?projectId=${encodeURIComponent(t)}`:"";return`${ze}/submissions/${e}${n}`}function rt(e,t){if(!e.jsonOutput)return;let n=Ie.resolve(e.jsonOutput),i={...t,url:t.url||t.dashboardUrl||gt(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){to.warn(ne.yellow(`Could not write submission metadata JSON: ${r.message}`))}}function ed(e,t){return t&&e.find(n=>n.credentialId===t||n.id===t||n.keyId===t||n.meta?.keyId===t)||null}function td(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 nd(){return process.env.CI==="true"||process.env.CI==="1"||!process.stdin.isTTY}function Ai(e){return new Promise(t=>setTimeout(t,e))}function id(e){return/^[a-zA-Z0-9_./:=@-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function rd(e,t){if(e.submit?.[t]?.android?.package)return e.submit[t].android.package;let n=tr(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 od(e,t){let n=e.filter(o=>mn(o)===t);if(n.length>0)return n;let i=e.filter(o=>{let s=mn(o);return!s||s==="*"});return e.length>0&&e.length===i.length?i:[]}function sd(e,t){return e.submit?.[t]?.ios?.bundleIdentifier?e.submit[t].ios.bundleIdentifier:e.submit?.[t]?.ios?.bundleId?e.submit[t].ios.bundleId:nr(e,t)}function ad(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 ld(e,t,n){let i=n||e.submit?.[t]?.android?.releaseStatus||e.submit?.production?.android?.releaseStatus||"completed";return dd(i)}function dd(e){let t=Gl[String(e).trim().toLowerCase()];if(!t)throw new Error(`Invalid Android release status "${e}". Use completed, draft, halted, or inProgress.`);return t}function cd(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 ud(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 fd(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 pd(e,t,n,i){let r=n.buildId?"id":n.latest?"latest":null;if(!r){let s=await bi({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(it(s))return Ei("Operation cancelled"),null;r=s}if(r==="local"){let s=await Bt({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 it(s)?null:{filePath:s,source:"local"}}let o=ot();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(Y=>String(Y).toLowerCase()===d):!0,f=a.filter(S=>c(S)&&u(S)),p=f.find(S=>S.buildType?.toLowerCase()==="store"||S.distribution?.toLowerCase()==="store")||f[0],h=a.some(S=>S.platform?.toLowerCase()===t.toLowerCase()&&S.status?.toLowerCase()==="success");if(!p)return o.stop("No suitable build found"),le(s&&h?`No successful ${t} builds found for profile "${s}".`:"No successful builds found for this platform."),null;o.stop(`Found build: ${p.buildId}`);let O=p.artifacts||[];if(O.length===0||O.every(S=>!(S.url||S.downloadUrl)))try{let S=await R.get(`/builds/${e}/${p.buildId}/artifacts`);S.data.status==="success"&&S.data.artifacts?.length>0?(O=S.data.artifacts.map(Y=>({...Y,url:Y.url||Y.downloadUrl})),console.log(ne.cyan(` [RECOVERY] Fetched ${O.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=O.find(S=>{let Y=(S.type||"").toLowerCase(),ee=(S.name||"").toLowerCase();if(console.log(ne.dim(` - Checking: ${S.name} (Type: ${S.type}, HasLink: ${!!(S.url||S.downloadUrl)})`)),Y)return Y===(M?"ipa":"aab");let g=M?".ipa":".aab",T=(S.url||S.downloadUrl||"").toLowerCase();return ee.endsWith(g)||T.includes(g)});if(!P||!(P.url||P.downloadUrl))return le("Build found but artifact URL is missing."),null;let F=P.url||P.downloadUrl;return{filePath:await hi(F,M?"ios":"android"),buildId:p.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 Bt({message:"Enter Build ID:",validate:a=>a.length<5?"Invalid ID":void 0});if(it(s))return null;let l=String(s);o.start("Fetching build...");try{let a=null;try{let p=await R.get(`/builds/${e}/${l}`);p.data.status==="success"&&(a=p.data.build)}catch(p){p.response?.status!==404&&console.log(ne.dim(` [RECOVERY] Project build lookup skipped: ${p.message}`))}if(!a){let p=await R.get(`/build/${l}`);if(p.data.status!=="success")throw new Error(p.data.message);a=p.data.build}if(!a)throw new Error(`Build ${l} was not found.`);let d=t==="ios",c=pn(a.artifacts);md(c)||(c=await Xr(e,l,c));let u=qr(c,t);if(u||(c=await Xr(e,l,c),u=qr(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 f=u.url||u.downloadUrl;if(!f)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 hi(f,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 Bt({message:"Enter Artifact URL:",validate:l=>l.startsWith("http")?void 0:"Must be a valid URL"});return it(s)?null:{filePath:await hi(s,t),source:"url"}}return null}function pn(e){return(e||[]).map(t=>({...t,url:t.url||t.downloadUrl}))}function md(e){return e.some(t=>!!(t.url||t.downloadUrl))}function qr(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 gd(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 Xr(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 hi(e,t,n=3){let i=ot();i.start("Downloading artifact...");let r=se.mkdtempSync(Ie.join(ht.tmpdir(),`${m.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 no({url:e,method:"GET",responseType:"stream",timeout:6e4});return await new Promise((c,u)=>{d.data.pipe(a);let f=!1;d.data.on("error",p=>{f||(f=!0,a.close(),u(p))}),a.on("finish",()=>{f||c()}),a.on("error",p=>{f||(f=!0,u(p))})}),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 hd(e,t,n,i,r){let o=ot();if(r&&fe(`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=oo(t,n,i),l=_d();return o.start("Uploading to TestFlight (pilot)..."),new Promise((a,d)=>{let c=vd(),u=Fl(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",f=>c.append(f,process.stdout)),u.stderr?.on("data",f=>c.append(f,process.stderr)),u.on("close",f=>{if(c.flush(),f!==0){o.stop("Pilot failed");try{se.unlinkSync(s)}catch{}d(Rd(f,c.lines()))}else{o.stop("IPA uploaded to TestFlight");try{se.unlinkSync(s)}catch{}a({})}}),u.on("error",f=>{c.flush();try{se.unlinkSync(s)}catch{}o.stop("Pilot execution error");let p=Ld(f);p.logs=c.lines(),d(p)})})}async function yd(e,t,n,i,r,o){let s=ot();if(r&&fe(`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=oo(t,n,i),a=`${o.sshUser}@${o.sshHost}`,d=Sd(o),c=bd(o),u="",f="";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..."),yi("scp",[...c,e,`${a}:${u}/app.ipa`],"IPA upload to remote runner"),yi("scp",[...c,l,`${a}:${u}/api_key.json`],"ASC key upload to remote runner"),f=Ie.join(ht.tmpdir(),`${m.nameLower}-ios-submit-${Date.now()}.sh`),se.writeFileSync(f,Ad(u)),yi("scp",[...c,f,`${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 p=`chmod +x ${Ft(`${u}/submit.sh`)} && bash ${Ft(`${u}/submit.sh`)}`,h=mt("ssh",[...d,p],{stdio:"inherit"});if(h.error)throw _i("ssh",h.error);if(h.status!==0)throw new Error(`Remote iOS submit failed with exit code ${h.status}.`);return s.stop("IPA uploaded to TestFlight"),{apiKeyJsonPath:null}}catch(p){throw s.stop("Remote iOS submit failed"),p}finally{try{se.unlinkSync(l)}catch{}if(f)try{se.unlinkSync(f)}catch{}if(u)try{mt("ssh",[...d,`rm -rf ${Ft(u)}`],{stdio:"ignore"})}catch{}}}function oo(e,t,n){let i=se.readFileSync(e,"utf8"),r;try{r=wi.createPrivateKey(i).export({type:"pkcs8",format:"pem"})}catch{fe("Key normalization failed, falling back to manual re-wrapping..."),r=`-----BEGIN PRIVATE KEY-----
|
|
1224
|
+
`}`)},f=async(p,h)=>{try{await Ut.post(`${r}/internal/tests/${encodeURIComponent(n)}/runner`,{projectId:t,runnerToken:i,status:p,error:h,logPreview:Rl(l),junitUrl:a?.urls?.junitDownloadUrl,logsUrl:a?.urls?.logsDownloadUrl,artifactsUrl:a?.urls?.artifactsDownloadUrl})}catch(D){d(`[WARN] Could not post runner update: ${D.message||D}`)}};try{d(`Mach Maestro local runner starting for ${n}`);let p=await Ut.post(`${r}/internal/tests/${encodeURIComponent(n)}/runner-payload`,{projectId:t,runnerToken:i});if(p.data?.status!=="success"||!p.data?.payload)throw new Error(p.data?.message||"Runner payload was not returned.");a=p.data.payload;let h=Object.keys(a.env||{});d(`Using Maestro env vars: ${h.length>0?h.join(", "):"none"}`);let D={...process.env,...a.env||{}},N=Pl(a.env);N.length>0&&d(`Passing Maestro env vars to test command: ${h.sort().join(", ")}`),await f("running");let U=a.platform==="android"?"app.apk":"app.zip",R=V.join(o,U),K=V.join(o,"source.zip"),b=V.join(o,"source");M.mkdirSync(b,{recursive:!0}),d("Downloading app artifact..."),await di(a.artifactUrl,R),d(`Downloaded app artifact: ${U} (${Br(M.statSync(R).size)})`),d("Downloading Maestro source..."),await di(a.urls.sourceUrl,K),d(`Downloaded Maestro source: source.zip (${Br(M.statSync(K).size)})`),new pn(K).extractAllTo(b,!0);let W=Dl(b,a.flowPath||".maestro");if(!M.existsSync(W))throw new Error(`Maestro flow path not found: ${a.flowPath||".maestro"}`);if(d(`Resolved Maestro flow path: ${V.relative(b,W)||"."}`),a.platform==="ios"){await kl(a.device||"iphone_15",l);let A=xl(R,o),S=Jr(A,l);d(`Resolved iOS app bundle: ${A}`),d(`Resolved iOS bundle id: ${S||"unknown"}`),Ml(A,l),ci("xcrun",["simctl","install","booted",A],l),S&&(u={platform:a.platform,appId:S}),S&&Qe("xcrun",["simctl","get_app_container","booted",S,"app"],l),oi(s,l,"ios-before-maestro.png"),a.record&&(c=Ll(s,l))}else{let A=Fl(R,l),S=Bl(a.device,l),x=S?["-s",S]:[];d(`Resolved Android application id: ${A||"unknown"}`),ci("adb",[...x,"install","-r",R],l),A&&(u={platform:a.platform,appId:A,deviceId:S||void 0})}let g=Math.max(0,Math.min(10,Number(a.retries??1)))+1,T=V.join(s,"report.xml"),w=Nl(l);if(!w)throw new Error("Maestro CLI not found on this runner. Install Maestro or set MAESTRO_BIN to the full maestro path.");let k=1;for(let A=1;A<=g&&(d(`Running Maestro attempt ${A}/${g}...`),k=Qe(w,["test","--platform",a.platform,...N,W,"--format","junit","--output",T,"--test-output-dir",s],l,void 0,D),k!==0);A+=1);return a.platform==="ios"&&oi(s,l,"ios-after-maestro.png"),await Fr(c,l),c=null,await Gr(a.urls,o,s,l),k===0?(await f("passed"),G.success(z.green(`Managed Maestro run passed: ${n}`)),{status:"passed",exitCode:0,attempts:g,flows:a.flowPath,platform:a.platform}):(await f("failed",`Maestro exited with code ${k}`),G.error(z.red(`Managed Maestro run failed with exit code ${k}`)),{status:"failed",exitCode:k,attempts:g,flows:a.flowPath,platform:a.platform})}catch(p){let h=p.message||String(p);return d(`MACH_MAESTRO_RUN_FAILED: ${h}`),a?.platform==="ios"&&oi(s,l,"ios-after-failure.png"),await Fr(c,l),a?.urls&&await Gr(a.urls,o,s,l),await f("failed",h),G.error(z.red(`Managed Maestro runner failed: ${h}`)),{status:"failed",exitCode:1,attempts:0,flows:a?.flowPath||".maestro",platform:a?.platform||e.platform}}finally{Ul(u,l)}}async function Sl(e){let t=e.maestroFlows||".maestro",n=Wr(e.maestroRetries);if(n===null)return null;let i=V.resolve(t);if(!M.existsSync(i))return G.error(z.red(`Maestro flows not found: ${t}`)),{status:"failed",exitCode:1,attempts:0,flows:t,platform:e.platform};let r=await _l(e);if(r?.url){if(!await vl(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&&G.warn(z.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));let l=hl(e.maestroEnv),a=Object.keys(l);if(a.length>0){G.info(z.dim(`Passing Maestro env vars to local run: ${a.join(", ")}`));for(let[p,h]of Object.entries(l))s.push("-e",`${p}=${h}`)}s.push(t);let c=n+1,u=1;for(let p=1;p<=c;p+=1){G.info(z.dim(`Running local Maestro attempt ${p}/${c}...`));let h=He("maestro",s,{cwd:process.cwd(),stdio:"inherit",env:process.env});if(h.error){let D=h.error.message||"Failed to run Maestro";G.error(z.red(`Local Maestro failed to start: ${D}`)),G.info(z.dim("Install Maestro locally, then retry: https://maestro.mobile.dev/getting-started/installing-maestro")),u=1;break}if(u=typeof h.status=="number"?h.status:1,u===0)break}let d=u===0?"passed":"failed",f={status:d,exitCode:u,attempts:c,flows:t,platform:o};return Wl(e,f),d==="passed"?G.success(z.green("Local Maestro run passed")):G.error(z.red(`Local Maestro run failed with exit code ${u}`)),f}async function fi(e){let t=$e(`./${m.configFileName}`),n=e.projectId||t?.projectId,i=String(e.profile||e.buildProfile||"production").toLowerCase();if(!n)return G.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 d=await Kr({message:"Select platform for the latest build:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"}]});if(li(d))return null;r=d}let o=await wl(e);if(!o)return null;if(o.kind==="latest"&&!r)return G.error("Pass --platform when using --latest."),null;if(o.kind==="artifact-url"&&!r)return G.error("Pass --platform when using --artifact-url."),null;let s=Wr(e.maestroRetries);if(s===null)return null;let l=ui(e.maestroEnv),a=gl(e.maestroEnv);!e.quiet&&l.length>0&&G.info(z.dim(`Forwarding Maestro env vars by name: ${l.join(", ")}`));let c=await El(e,n);if(c===null)return null;let u=Bt();e.quiet||u.start("Queuing Maestro run...");try{let d=await P.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:c,flows:e.maestroFlows||".maestro",device:e.maestroDevice||(r==="ios"?"iphone_15":"pixel_6"),retries:s,record:!!e.maestroRecord,...l.length>0?{envNames:l}:{},...a?{env:a}:{}});if(d.data.status!=="success")throw new Error(d.data.message||"Failed to queue Maestro run");let f=d.data.testRun,p={testRunId:f.testRunId,status:f.status,projectId:n,buildId:f.buildId,platform:f.platform,dashboardUrl:f.dashboardUrl||`${We}/tests/${f.testRunId}`,launchDeferredReason:f.launchDeferredReason};return Xr(e,p),e.quiet||u.stop("Maestro run queued"),p}catch(d){e.quiet||u.stop("Could not queue Maestro run");let f=d.response?.data?.message||d.message||"Unknown error";return G.error(z.red(`Maestro queue failed: ${f}`)),null}}async function bl(e,t){let n=Ur(e.waitTimeout,60,"--wait-timeout"),i=Ur(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(G.info(z.dim(`Waiting for Maestro run ${t.testRunId} to finish...`));Date.now()-s<=r;){let a=await Il(t.projectId,t.testRunId);if(!a)return null;if(a.status&&a.status!==l&&(l=a.status,G.info(z.dim(`Maestro status: ${l}`))),pl.has(String(a.status)))return Xr(e,a),a.status==="passed"?G.success(z.green(`Maestro run passed: ${a.testRunId}`)):(G.error(z.red(`Maestro run ${a.status}: ${a.testRunId}`)),a.error&&G.error(z.red(String(a.error)))),a;await pi(o)}return G.error(z.red(`Timed out waiting for Maestro run ${t.testRunId} after ${n} minute(s).`)),{...t,status:"timeout"}}async function El(e,t){if(e.maestroUseBuildSource)return;let n=e.maestroFlows||".maestro",i=V.resolve(n);if(!M.existsSync(i))return e.maestroFlows?(G.error(z.red(`Maestro flows not found: ${n}`)),null):void 0;let r=V.relative(process.cwd(),i);if(!r||r.startsWith("..")||V.isAbsolute(r))return G.error(z.red("Managed Maestro flow uploads must be inside the current project directory.")),null;let o=Bt();e.quiet||o.start(`Uploading Maestro flows from ${r}...`);try{let s=await P.post("/tests/maestro/source-upload-url",{projectId:t,uploadId:cl()});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 pn;if(M.statSync(i).isDirectory())l.addLocalFolder(i,r);else{let u=V.dirname(r);l.addLocalFile(i,u==="."?void 0:u,V.basename(r))}let c=l.toBuffer();return await Al(s.data.uploadUrl,c,"application/zip","Maestro flow upload",u=>{e.quiet||o.message(u)}),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 G.error(z.red(`Maestro flow upload failed: ${l}`)),null}}function zr(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 Al(e,t,n,i,r){let o;for(let s=1;s<=Mr;s+=1)try{await Ut.put(e,t,{headers:{"Content-Type":n},maxBodyLength:1/0,maxContentLength:1/0,timeout:ml});return}catch(l){if(o=l,!zr(l)||s>=Mr)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 pi(a)}throw o}async function Il(e,t){try{let n=await P.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||`${We}/tests/${i.testRunId}`,launchDeferredReason:i.launchDeferredReason,...i.error?{error:i.error}:{}}}catch(n){let i=n.response?.data?.message||n.message||"Unknown error";return G.error(z.red(`Could not fetch Maestro run status: ${i}`)),null}}async function wl(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 Kr({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(li(t))return null;if(t==="latest")return{kind:"latest"};let n=await fl({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 li(n)?null:{kind:t,value:String(n).trim()}}function Ur(e,t,n){if(e==null||e==="")return t;let i=Number(e);return!Number.isFinite(i)||i<=0?(G.error(`${n} must be a positive number.`),null):i}function pi(e){return new Promise(t=>setTimeout(t,e))}function Wr(e){if(e==null||e==="")return 1;let t=Number(e);return!Number.isInteger(t)||t<0||t>10?(G.error("--maestro-retries must be an integer between 0 and 10."),null):t}async function _l(e){if(e.artifactUrl)return{url:e.artifactUrl,platform:e.platform||gi(e.artifactUrl),name:qr(e.artifactUrl)};let t=e.buildId||zl(e.buildUrl);return t?Yr(t,e.platform):e.latest?$l(e):null}async function Yr(e,t){let n=Bt();n.start(`Resolving build ${e}...`);try{let i=await P.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=Vl(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||gi(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 G.error(z.red(`Local Maestro artifact lookup failed: ${r}`)),null}}async function $l(e){let t=$e(`./${m.configFileName}`),n=e.projectId||t?.projectId,i=String(e.profile||e.buildProfile||"production").toLowerCase();if(!n)return G.error(`No projectId found. Run \`${m.nameLower} link\` first or pass --build-id/--artifact-url.`),null;if(!e.platform)return G.error("Pass --platform when using --latest with --local."),null;let r=Bt();r.start("Resolving latest build...");try{let o=await P.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}`),Yr(l.buildId,e.platform)}catch(o){r.stop("Could not resolve latest build");let s=o.response?.data?.message||o.message||"Unknown error";return G.error(z.red(`Latest build lookup failed: ${s}`)),null}}async function vl(e){let t=e.platform||gi(e.url);if(!t)return G.error(z.red("Could not infer platform for local install. Pass --platform android or --platform ios.")),!1;let n=M.mkdtempSync(V.join(_t.tmpdir(),"mach-maestro-")),i=e.name||qr(e.url)||(t==="android"?"app.apk":"app.zip"),r=V.join(n,i),o=Bt();o.start(`Downloading ${i}...`);try{await di(e.url,r),o.stop("Artifact downloaded")}catch(s){return o.stop("Artifact download failed"),G.error(z.red(s.message||"Failed to download artifact")),!1}return t==="android"?Gl(r):Kl(r,n)}async function di(e,t){let n=await Ut.get(e,{responseType:"stream"});await ul(n.data,M.createWriteStream(t))}function Rl(e,t=12e3){try{return M.readFileSync(e,"utf-8").slice(-t)}catch{return""}}function Br(e){if(!Number.isFinite(e)||e<0)return"unknown size";if(e<1024)return`${e} B`;let t=["KB","MB","GB"],n=e/1024,i=t[0];for(let r=1;n>=1024&&r<t.length;r+=1)n/=1024,i=t[r];return`${n.toFixed(n>=10?1:2)} ${i}`}function Pl(e){return Object.entries(e||{}).filter(([t,n])=>!!t&&n!==void 0).sort(([t],[n])=>t.localeCompare(n)).flatMap(([t,n])=>["-e",`${t}=${n}`])}function Dl(e,t){let n=V.resolve(e,t||".maestro"),i=V.relative(e,n);if(i.startsWith("..")||V.isAbsolute(i))throw new Error("Maestro flow path must stay inside the build source.");return n}function Ol(e,t){let n=[e];for(let i=0;i<t.length;i+=1){let r=t[i],o=t[i-1];(o==="-e"||o==="--env")&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(r)?n.push(`${r.slice(0,r.indexOf("="))}=<redacted>`):n.push(r)}return n.join(" ")}function Qe(e,t,n,i,r=process.env){M.appendFileSync(n,`
|
|
1225
|
+
$ ${Ol(e,t)}
|
|
1226
|
+
`);let o=He(e,t,{cwd:i,encoding:"utf-8",env:r});return o.stdout&&M.appendFileSync(n,o.stdout),o.stderr&&M.appendFileSync(n,o.stderr),o.error?(M.appendFileSync(n,`${o.error.message}
|
|
1227
|
+
`),1):typeof o.status=="number"?o.status:1}function ci(e,t,n,i){let r=Qe(e,t,n,i);if(r!==0)throw new Error(`${e} ${t.join(" ")} failed with exit code ${r}`)}function Cl(e){try{return M.accessSync(e,M.constants.X_OK),!0}catch{return!1}}function Nl(e){let t=[process.env.MAESTRO_BIN,V.join(_t.homedir(),".maestro","bin","maestro"),"/opt/homebrew/bin/maestro","/usr/local/bin/maestro"].filter(Boolean),n=He("/usr/bin/env",["which","maestro"],{encoding:"utf-8",env:process.env}),i=n.status===0?String(n.stdout||"").split(`
|
|
1228
|
+
`)[0]?.trim():"";i&&t.unshift(i);for(let r of t)if(r&&Cl(r))return e&&M.appendFileSync(e,`Using Maestro CLI at ${r}
|
|
1229
|
+
`),r;return e&&M.appendFileSync(e,`Maestro CLI not found. Checked: ${t.join(", ")}
|
|
1230
|
+
`),null}function Tl(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 kl(e,t){if((He("xcrun",["simctl","list","devices","booted"],{encoding:"utf-8"}).stdout||"").includes("(Booted)")){M.appendFileSync(t,`Using already booted iOS Simulator.
|
|
1231
|
+
`);return}let i=Tl(e),r=He("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(c=>Array.isArray(c)?c:[]).filter(c=>c?.isAvailable),l=s.find(c=>c.name===i)||s.find(c=>String(c.name||"").toLowerCase().includes(i.toLowerCase()))||s.find(c=>String(c.name||"").startsWith("iPhone"));if(!l?.udid)throw new Error(`No available iOS Simulator found for ${i}.`);M.appendFileSync(t,`Booting iOS Simulator ${l.name} (${l.udid})...
|
|
1232
|
+
`),Qe("xcrun",["simctl","boot",l.udid],t)!==0&&M.appendFileSync(t,`simctl boot returned non-zero; continuing to bootstatus in case it was already booting.
|
|
1233
|
+
`),ci("xcrun",["simctl","bootstatus",l.udid,"-b"],t)}function xl(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=V.join(t,"ios-app");M.mkdirSync(n,{recursive:!0}),new pn(e).extractAllTo(n,!0);let i=mi(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 Jr(e,t){let n=V.join(e,"Info.plist");if(!M.existsSync(n))return M.appendFileSync(t,`Could not find Info.plist in ${e}; skipping uninstall.
|
|
1234
|
+
`),null;let i=He("/usr/bin/plutil",["-extract","CFBundleIdentifier","raw","-o","-",n],{encoding:"utf-8",env:process.env}),r=String(i.stdout||"").trim();return i.status!==0||!r?(M.appendFileSync(t,`Could not read CFBundleIdentifier from Info.plist; skipping uninstall.
|
|
1235
|
+
`),null):r}function oi(e,t,n){let i=V.join(e,n);Qe("xcrun",["simctl","io","booted","screenshot",i],t)!==0&&M.appendFileSync(t,`[WARN] Could not capture iOS simulator screenshot: ${n}
|
|
1236
|
+
`)}function Ll(e,t){let n=V.join(e,"ios-simulator-recording.mp4");M.appendFileSync(t,`Starting iOS simulator recording: ${n}
|
|
1237
|
+
`);let i=dl("xcrun",["simctl","io","booted","recordVideo",n],{stdio:["ignore","pipe","pipe"],env:process.env});return i.stdout?.on("data",r=>{M.appendFileSync(t,r)}),i.stderr?.on("data",r=>{M.appendFileSync(t,r)}),i.on("error",r=>{M.appendFileSync(t,`[WARN] Could not start iOS simulator recording: ${r.message}
|
|
1238
|
+
`)}),i}async function Fr(e,t){e&&await new Promise(n=>{let i=!1,r=()=>{i||(i=!0,n())};e.once("exit",r),e.once("close",r),e.killed||(M.appendFileSync(t,`Stopping iOS simulator recording...
|
|
1239
|
+
`),e.kill("SIGINT")),setTimeout(()=>{!i&&!e.killed&&(M.appendFileSync(t,`[WARN] iOS simulator recording did not stop after SIGINT; sending SIGKILL.
|
|
1240
|
+
`),e.kill("SIGKILL")),r()},5e3).unref?.()})}function Ml(e,t){let n=Jr(e,t);if(!n)return;M.appendFileSync(t,`Uninstalling existing iOS app data for ${n} if present...
|
|
1241
|
+
`),Qe("xcrun",["simctl","uninstall","booted",n],t)!==0&&M.appendFileSync(t,`No existing app install removed for ${n}; continuing.
|
|
1242
|
+
`)}function Ul(e,t){if(!e?.appId)return;if(M.appendFileSync(t,`Cleaning up installed app after Maestro run...
|
|
1243
|
+
`),e.platform==="ios"){let r=Qe("xcrun",["simctl","uninstall","booted",e.appId],t);r===0?M.appendFileSync(t,`Uninstalled iOS app ${e.appId} after Maestro run.
|
|
1244
|
+
`):M.appendFileSync(t,`Warning: failed to uninstall iOS app ${e.appId} after Maestro run: xcrun simctl uninstall exited with code ${r}
|
|
1245
|
+
`);return}let n=e.deviceId?["-s",e.deviceId]:[],i=Qe("adb",[...n,"uninstall",e.appId],t);i===0?M.appendFileSync(t,`Uninstalled Android app ${e.appId} after Maestro run.
|
|
1246
|
+
`):M.appendFileSync(t,`Warning: failed to uninstall Android app ${e.appId} after Maestro run: adb uninstall exited with code ${i}
|
|
1247
|
+
`)}function Bl(e,t){let n=He("adb",["devices"],{encoding:"utf-8",env:process.env});if(n.status!==0||n.error)return M.appendFileSync(t,`[WARN] Could not list Android devices before install; using adb default target.
|
|
1248
|
+
`),null;let i=String(n.stdout||"").split(`
|
|
1249
|
+
`).map(r=>r.trim().split(/\s+/)).filter(r=>r.length>=2&&r[1]==="device").map(r=>r[0]).filter(Boolean);return e&&i.includes(e)?(M.appendFileSync(t,`Using Android device ${e} for install and cleanup.
|
|
1250
|
+
`),e):i.length===1?(M.appendFileSync(t,`Using Android device ${i[0]} for install and cleanup.
|
|
1251
|
+
`),i[0]):(i.length>1&&M.appendFileSync(t,`[WARN] Multiple Android devices are connected; using adb default target for install and cleanup.
|
|
1252
|
+
`),null)}function Fl(e,t){let i=(si("aapt",["dump","badging",e])||si("aapt2",["dump","badging",e]))?.match(/package:\s+name='([^']+)'/);if(i?.[1])return i[1];let o=si("apkanalyzer",["manifest","application-id",e])?.split(/\s+/).find(Boolean);return o||(M.appendFileSync(t,`[WARN] Could not determine Android application id from APK; post-run uninstall will be skipped.
|
|
1253
|
+
`),null)}function si(e,t){for(let n of Hl(e)){let i=He(n,t,{encoding:"utf-8",env:process.env,maxBuffer:10485760});if(i.status===0&&i.stdout)return String(i.stdout).trim()}return null}function Hl(e){let t=process.platform==="win32"&&!e.endsWith(".exe")?`${e}.exe`:e,n=[];if(e==="aapt"||e==="aapt2")for(let r of Hr()){let o=V.join(r,"build-tools");for(let s of jr(o))n.push(V.join(o,s,t))}if(e==="apkanalyzer")for(let r of Hr()){n.push(V.join(r,"cmdline-tools","latest","bin",t));let o=V.join(r,"cmdline-tools");for(let s of jr(o))n.push(V.join(o,s,"bin",t));n.push(V.join(r,"tools","bin",t))}let i=jl(e);return i&&n.unshift(i),n.push(t),[...new Set(n)]}function Hr(){let e=[process.env.ANDROID_HOME,process.env.ANDROID_SDK_ROOT];return process.platform==="darwin"?e.push(V.join(_t.homedir(),"Library","Android","sdk")):process.platform==="linux"&&e.push(V.join(_t.homedir(),"Android","Sdk"),V.join(_t.homedir(),"Android","sdk"),"/opt/android-sdk","/usr/lib/android-sdk"),[...new Set(e.filter(t=>!!t))]}function jr(e){try{return M.readdirSync(e,{withFileTypes:!0}).filter(t=>t.isDirectory()).map(t=>t.name).sort((t,n)=>n.localeCompare(t,void 0,{numeric:!0}))}catch{return[]}}function jl(e){let t=process.platform==="win32"?"where":"/usr/bin/env",n=process.platform==="win32"?[e]:["which",e],i=He(t,n,{encoding:"utf-8",env:process.env});return i.status!==0||!i.stdout?null:String(i.stdout).split(`
|
|
1254
|
+
`)[0]?.trim()||null}async function ai(e,t,n){if(!M.existsSync(e))return;let i=M.readFileSync(e),r;for(let o=1;o<=3;o+=1)try{await Ut.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,!zr(s)||o>=3)break;await pi(2e3*o)}throw r}async function Gr(e,t,n,i){let r=V.join(n,"report.xml"),o=V.join(t,"artifacts.tar.gz");try{await ai(r,e.junitUploadUrl,"application/xml")}catch(s){M.appendFileSync(i,`[WARN] Failed to upload JUnit report: ${s.message||s}
|
|
1255
|
+
`)}try{await ai(i,e.logUploadUrl,"text/plain")}catch(s){M.appendFileSync(i,`[WARN] Failed to upload runner log: ${s.message||s}
|
|
1256
|
+
`)}try{Qe("tar",["-czf",o,"-C",t,V.basename(n)],i),await ai(o,e.artifactsUploadUrl,"application/gzip")}catch(s){M.appendFileSync(i,`[WARN] Failed to upload Maestro artifacts: ${s.message||s}
|
|
1257
|
+
`)}}function Gl(e){if(!e.endsWith(".apk"))return G.error(z.red("Local Android Maestro runs need an APK artifact.")),!1;G.info(z.dim("Installing APK on local Android device/emulator..."));let t=He("adb",["install","-r",e],{stdio:"inherit",env:process.env});return t.error?(G.error(z.red(`adb failed to start: ${t.error.message}`)),!1):t.status!==0?(G.error(z.red(`adb install failed with exit code ${t.status??1}`)),!1):!0}function Kl(e,t){if(e.endsWith(".ipa"))return G.error(z.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=V.join(t,"ios-app");M.mkdirSync(r,{recursive:!0}),new pn(e).extractAllTo(r,!0);let o=mi(r);if(!o)return G.error(z.red("Could not find a .app bundle inside the downloaded zip.")),!1;n=o}if(!n.endsWith(".app"))return G.error(z.red("Local iOS Maestro runs need an iOS Simulator .app bundle or .app.zip artifact.")),!1;G.info(z.dim("Installing app on booted iOS Simulator..."));let i=He("xcrun",["simctl","install","booted",n],{stdio:"inherit",env:process.env});return i.error?(G.error(z.red(`xcrun failed to start: ${i.error.message}`)),!1):i.status!==0?(G.error(z.red(`iOS Simulator install failed with exit code ${i.status??1}`)),!1):!0}function mi(e){let t=M.readdirSync(e,{withFileTypes:!0});for(let n of t){let i=V.join(e,n.name);if(n.isDirectory()&&n.name.endsWith(".app"))return i;if(n.isDirectory()){let r=mi(i);if(r)return r}}return null}function Vl(e,t){let n=String(t||"").toLowerCase();return n==="android"?e.find(i=>wt(i,".apk")):n==="ios"?e.find(i=>wt(i,".app.zip"))||e.find(i=>wt(i,".zip")):e.find(i=>wt(i,".apk"))||e.find(i=>wt(i,".app.zip"))||e.find(i=>wt(i,".zip"))}function wt(e,t){return String(e?.name||e?.downloadUrl||e?.url||"").toLowerCase().endsWith(t)}function gi(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 qr(e){if(e)try{return V.basename(new URL(e).pathname)||void 0}catch{return V.basename(e)||void 0}}function zl(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 Xr(e,t){if(!e.jsonOutput)return;let n=V.resolve(e.jsonOutput),i={...t,updatedAt:new Date().toISOString()};try{let r=V.dirname(n);r&&r!=="."&&M.mkdirSync(r,{recursive:!0}),M.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){G.warn(z.yellow(`Could not write Maestro metadata JSON: ${r.message}`))}}function Wl(e,t){if(!e.jsonOutput)return;let n=V.resolve(e.jsonOutput),i={mode:"local",...t,updatedAt:new Date().toISOString()};try{let r=V.dirname(n);r&&r!=="."&&M.mkdirSync(r,{recursive:!0}),M.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){G.warn(z.yellow(`Could not write Maestro metadata JSON: ${r.message}`))}}import{spinner as st,text as Ft,select as Ei,isCancel as rt,cancel as Ai,log as ro}from"@clack/prompts";import te from"chalk";import se from"fs";import Ie from"path";import{spawn as Yl,spawnSync as mt}from"child_process";import oo from"axios";import ht from"os";import _i from"crypto";var Jl=5e3,ql=12,so=100,hi=24,Zr=8e3,Xl={completed:"completed",draft:"draft",halted:"halted",inprogress:"inProgress","in-progress":"inProgress"},Zl=e=>e?.type==="google_service_account",gn=e=>e?.bundleId||e?.packageName||e?.meta?.packageName||e?.meta?.bundleId,ao=e=>e.submitArgs||process.argv.slice(3).join(" ");async function hn(e){let t=st(),n=Pe(),i=Ql(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(te.dim(`Submit for project: ${i.name||r} | Profile: ${o}`));let s=e.platform;if(!s){let S=await Ei({message:"Select platform to submit:",options:[{value:"ios",label:"iOS (App Store Connect / TestFlight)"},{value:"android",label:"Android (Google Play Console)"}]});if(rt(S)){Ai("Operation cancelled");return}s=S}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?gd(i,o,e):null;if(s==="ios"&&!e.local&&!l){await ed(i,o,e);return}let a=e.submitId,c=!!(e.local&&a),u=a||null,d=async(S,x={})=>{u&&await rd(r,u,{status:S,...x})},f=s==="android"?e.packageName||e.androidPackage||fd(i,o):void 0,p=s==="ios"?e.bundleId||e.iosBundleIdentifier||md(i,o):void 0,h,D,N,U=!1;try{s==="android"&&(h=e.track||i.submit?.[o]?.android?.track||i.submit?.production?.android?.track||"internal",D=hd(i,o,e.releaseStatus),N=Sd(i,o,e.rollout),U=bd(i,o,e.changesNotSentForReview),Ed(D,N))}catch(S){le(S.message),process.exitCode=1;return}if(s==="android"&&!c&&(u=await td(i,r,s,o,e,{packageName:f,track:h,releaseStatus:D,rollout:N,changesNotSentForReview:U}),!u)){le("Could not create submission tracking record. Submission was not started."),process.exitCode=1;return}await d("running",{platform:s,profile:o,packageName:f,track:h,releaseStatus:D,rollout:N,startTime:Date.now(),...c?sd():{}});let R=null,K=null;try{K=await Ad(r,s,e,n?.token),R=K?.filePath||null}catch(S){await d("failed",{error:`Failed to resolve submission artifact: ${S.message}`,endTime:Date.now()}),le(`Failed to resolve submission artifact: ${S.message}`),process.exitCode=1;return}if(!R){let S=wd(s,e);await d("failed",{error:S,endTime:Date.now()}),le(S),process.exitCode=1;return}await d("running",{buildId:K?.buildId,artifactName:K?.artifactName,artifactSource:K?.source}),fe(`Using artifact: ${te.green(Ie.basename(R))} `),t.start("Fetching submission credentials from Dashboard...");let b;try{let x=(await P.get(`/credentials/${r}`)).data.credentials||[];if(s==="android"&&!f){t.stop("Package name missing"),le("Could not resolve Android package name. Set android.package in mach.config.json/app.json."),await d("failed",{error:"Could not resolve Android package name.",endTime:Date.now()}),process.exitCode=1;return}let B=x.filter(Zl),Y=s==="ios"?x.filter(L=>L.type==="asc_api_key"):pd(B,f);if(Y.length===0){if(t.stop("Credentials missing"),le(s==="android"?`No Google Play service credential found for package ${f}.`:`No Service Credentials found for ${s}.`),s==="android"){let L=B.map(gn).filter(Boolean).join(", ");L&&fe(`Found Google Play service credential(s) for: ${L}`),fe(`Use '${m.nameLower} credentials:service --platform android --package-name ${f}' 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 d("failed",{error:`No submission credentials found for ${s}.`,endTime:Date.now()}),process.exitCode=1;return}if(b=ld(Y,e.credentialId),!b&&s==="ios"&&p&&(b=dd(Y,p)),b||Y.length===1)b=b||Y[0],t.stop(`Using: ${b.name}`),s==="android"&&gn(b)==="*"&&fe(te.yellow(`Using legacy wildcard Google Play credential for ${f}. Upload a package-scoped credential when possible.`));else{if(t.stop("Multiple credentials found"),cd()){let J=Y.map(O=>`${O.name||"credential"} (${O.credentialId||O.id||"no-id"})`).join(", ");le(`Multiple ${s==="ios"?"App Store Connect":"Google Play"} credentials found. Use --credential-id in CI. Available: ${J}`),await d("failed",{error:"Multiple submission credentials found; --credential-id is required in CI.",endTime:Date.now()}),process.exitCode=1;return}let L=await Ei({message:`Choose a ${s==="ios"?"App Store Connect":"Google Play"} credential:`,options:Y.map(J=>({value:J.credentialId,label:J.name,hint:`${J.keyId?`ID: ${J.keyId}`:""} ${J.issuerId?`(Issuer: ${J.issuerId.substring(0,8)}...)`:""}`}))});if(rt(L)){Ai("Submission cancelled"),await d("failed",{error:"Submission cancelled while selecting credential.",endTime:Date.now()}),process.exitCode=1;return}b=Y.find(J=>J.credentialId===L),fe(`Using selected: ${te.green(b.name)}`)}}catch(S){t.stop("Failed to fetch credentials"),le(`API Error: ${S.message} `),await d("failed",{error:`Failed to fetch credentials: ${S.message}`,endTime:Date.now()}),process.exitCode=1;return}let W=se.mkdtempSync(Ie.join(ht.tmpdir(),`${m.nameLower}-submit-`)),ne=b.keyId||b.meta?.keyId,g=b.issuerId||b.meta?.issuerId,T=b.type==="asc_api_key"?`AuthKey_${ne}.p8`:"service-account.json",w=Ie.join(W,T);t.start("Downloading secure key...");try{let S=await P.get(`/credentials/${b.credentialId}/download`,{params:{projectId:r,format:"raw"}});if(S.data.status!=="success"||!S.data.downloadUrl)throw new Error("Failed to get secure download URL");let x=await oo.get(S.data.downloadUrl,{responseType:"arraybuffer"});se.writeFileSync(w,Buffer.from(x.data)),t.stop("Key downloaded to secure temp storage")}catch(S){t.stop("Download failed"),le(`Failed to download key: ${S.message}`);try{se.rmSync(W,{recursive:!0,force:!0})}catch{}await d("failed",{error:`Failed to download credential key: ${S.message}`,endTime:Date.now()}),process.exitCode=1;return}fe(te.blue(`Initiating ${s==="ios"?"TestFlight":"Google Play"} submission...`));let k=!1,A;try{if(s==="ios"){if(!ne){let x=await Ft({message:"Enter App Store Connect Key ID (e.g. 2X948D...):",validate:B=>B.length>0?void 0:"Key ID is required"});if(rt(x)){await d("failed",{error:"Submission cancelled while entering ASC Key ID.",endTime:Date.now()}),process.exitCode=1;return}ne=x}if(!g||g==="undefined"){let x=await Ft({message:"Enter App Store Connect Issuer ID (Found on ASC Keys page):",validate:B=>B.length>0?void 0:"Issuer ID is required"});if(rt(x)){await d("failed",{error:"Submission cancelled while entering ASC Issuer ID.",endTime:Date.now()}),process.exitCode=1;return}g=x}fe(`Using ASC Key ID: ${ne}`),fe(`Using ASC Issuer ID: ${g}`);let S=l?await $d(R,w,g,ne,p,l):await _d(R,w,g,ne,p);wi(`${s==="ios"?"App Store":"Google Play"} submission successful!`),k=!0}else A=await Od(R,w,h||"internal",f,D||"completed",N,U,o),wi("Google Play submission successful!"),k=!0}catch(S){le(`Submission failed: ${S.message}`),await d("failed",{error:S.message,endTime:Date.now()}),ot(e,{status:"failed",projectId:r,submitId:u,platform:s,profile:o,buildId:K?.buildId||e.buildId,artifactName:K?.artifactName,error:S.message,dashboardUrl:u?gt(u,r):void 0}),process.exitCode=1}finally{k&&(await d("success",{endTime:Date.now(),versionCode:A?.versionCode,track:h,releaseStatus:D}),ot(e,{status:"success",projectId:r,submitId:u,platform:s,profile:o,buildId:K?.buildId||e.buildId,artifactName:K?.artifactName,versionCode:A?.versionCode,track:h,releaseStatus:D,dashboardUrl:u?gt(u,r):void 0})),Vd(W),R&&R.includes(`${m.nameLower}-artifact-`)}}function Ql(e){let t=`./${m.configFileName}`;if(se.existsSync(t))try{return JSON.parse(se.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 ed(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||_i.randomUUID(),o=!!n.latest||!n.buildId,s=nd({...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:ao(n),runnerArgs:s,runnerCommand:[m.nameLower,"submit",...s].map(ud).join(" "),appName:e.name,startTime:Date.now()},a=st();a.start("Queuing iOS submit on macOS runner...");try{let c=await P.post("/submissions",l),u=c.data?.submission||c.data?.submit||{},d=c.data?.dashboardUrl||gt(r,i);a.stop("iOS submit queued"),fe(`Submission ID: ${te.cyan(r)}`),fe(`Dashboard: ${te.blue.underline(d)}`),ot(n,{status:"pending",projectId:i,submitId:r,platform:"ios",profile:t,latest:o,buildId:n.buildId,dashboardUrl:d}),await id(i,r,n)}catch(c){a.stop("Could not queue iOS submit"),le(ad(c)),process.exitCode=1}}async function td(e,t,n,i,r,o={}){let s=r.submitId||_i.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:ao(r),appName:e.name,startTime:Date.now(),...o};try{let c=await P.post("/submissions",a),u=c.data?.submission||c.data?.submit||{},d=c.data?.dashboardUrl||u.dashboardUrl||gt(s,t);return fe(`Submission ID: ${te.cyan(s)}`),fe(`Dashboard: ${te.blue.underline(d)}`),ot(r,{status:"running",projectId:t,submitId:s,platform:n,profile:i,latest:l,buildId:r.buildId,dashboardUrl:d}),s}catch(c){let u=c.response?.data?.message||c.response?.data?.error||c.message;return fe(te.yellow(`Could not create submission tracking record: ${u}`)),null}}function nd(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 id(e,t,n){let i=st(),r=0,o=0;for(n.quiet||i.start("Waiting for iOS submit runner...");;)try{let s=await P.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 u=o;u<c.length;u++){let d=c[u];d&&console.log(te.dim(String(d)))}if(o=c.length,["success","completed","succeeded"].includes(a)){n.quiet||i.stop("iOS submit completed"),wi("App Store submission successful!"),ot(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||gt(t,e)});return}if(["failed","error","cancelled","canceled"].includes(a)){n.quiet||i.stop("iOS submit failed");let u=l?.error||l?.message||"Unknown iOS submit failure.";le(u),ot(n,{status:"failed",projectId:e,submitId:t,platform:"ios",profile:l?.profile||n.profile||"production",buildId:l?.buildId||n.buildId,artifactName:l?.artifactName,error:u,dashboardUrl:l?.dashboardUrl||gt(t,e)}),process.exitCode=1;return}n.quiet||i.message(`iOS submit ${a}...`),await Ii(Jl)}catch(s){if(r++,r>=ql){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 Ii(Math.min(2e3*r,15e3))}}async function rd(e,t,n){let i;for(let r=1;r<=3;r++)try{await P.patch(`/submissions/${e}/${t}`,n);return}catch(o){if(i=o,r>=3||!od(o))break;await Ii(1e3*r)}ro.warn(te.dim(`Could not report submission status: ${i?.message||i}`))}function od(e){let t=e.response?.status;return!t||t===408||t===409||t===425||t===429||t>=500}function sd(){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 ad(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(`
|
|
1258
|
+
`):n||e.message||String(e)}function gt(e,t){if(!e)return We;let n=t?`?projectId=${encodeURIComponent(t)}`:"";return`${We}/submissions/${e}${n}`}function ot(e,t){if(!e.jsonOutput)return;let n=Ie.resolve(e.jsonOutput),i={...t,url:t.url||t.dashboardUrl||gt(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){ro.warn(te.yellow(`Could not write submission metadata JSON: ${r.message}`))}}function ld(e,t){return t&&e.find(n=>n.credentialId===t||n.id===t||n.keyId===t||n.meta?.keyId===t)||null}function dd(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 cd(){return process.env.CI==="true"||process.env.CI==="1"||!process.stdin.isTTY}function Ii(e){return new Promise(t=>setTimeout(t,e))}function ud(e){return/^[a-zA-Z0-9_./:=@-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function fd(e,t){if(e.submit?.[t]?.android?.package)return e.submit[t].android.package;let n=nr(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 pd(e,t){let n=e.filter(o=>gn(o)===t);if(n.length>0)return n;let i=e.filter(o=>{let s=gn(o);return!s||s==="*"});return e.length>0&&e.length===i.length?i:[]}function md(e,t){return e.submit?.[t]?.ios?.bundleIdentifier?e.submit[t].ios.bundleIdentifier:e.submit?.[t]?.ios?.bundleId?e.submit[t].ios.bundleId:ir(e,t)}function gd(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 hd(e,t,n){let i=n||e.submit?.[t]?.android?.releaseStatus||e.submit?.production?.android?.releaseStatus||"completed";return yd(i)}function yd(e){let t=Xl[String(e).trim().toLowerCase()];if(!t)throw new Error(`Invalid Android release status "${e}". Use completed, draft, halted, or inProgress.`);return t}function Sd(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 bd(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 Ed(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 Ad(e,t,n,i){let r=n.buildId?"id":n.latest?"latest":null;if(!r){let s=await Ei({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(rt(s))return Ai("Operation cancelled"),null;r=s}if(r==="local"){let s=await Ft({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 rt(s)?null:{filePath:s,source:"local"}}let o=st();if(r==="latest"){let s=n.profile||n.buildProfile;o.start(`Fetching latest${s?` ${s}`:""} build...`);try{let l=await P.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(),u=b=>b.platform?.toLowerCase()===t.toLowerCase()&&b.status?.toLowerCase()==="success",d=b=>c?[b.buildProfile,b.profile,b.profileName,b.buildType].filter(Boolean).some(W=>String(W).toLowerCase()===c):!0,f=a.filter(b=>u(b)&&d(b)),p=f.find(b=>b.buildType?.toLowerCase()==="store"||b.distribution?.toLowerCase()==="store")||f[0],h=a.some(b=>b.platform?.toLowerCase()===t.toLowerCase()&&b.status?.toLowerCase()==="success");if(!p)return o.stop("No suitable build found"),le(s&&h?`No successful ${t} builds found for profile "${s}".`:"No successful builds found for this platform."),null;o.stop(`Found build: ${p.buildId}`);let D=p.artifacts||[];if(D.length===0||D.every(b=>!(b.url||b.downloadUrl)))try{let b=await P.get(`/builds/${e}/${p.buildId}/artifacts`);b.data.status==="success"&&b.data.artifacts?.length>0?(D=b.data.artifacts.map(W=>({...W,url:W.url||W.downloadUrl})),console.log(te.cyan(` [RECOVERY] Fetched ${D.length} artifact(s) with download URLs.`))):console.log(te.yellow(" [RECOVERY] /artifacts endpoint returned 0 artifacts."))}catch(b){console.log(te.red(` [RECOVERY] /artifacts fetch failed: ${b.message}`))}let U=t==="ios",R=D.find(b=>{let W=(b.type||"").toLowerCase(),ne=(b.name||"").toLowerCase();if(console.log(te.dim(` - Checking: ${b.name} (Type: ${b.type}, HasLink: ${!!(b.url||b.downloadUrl)})`)),W)return W===(U?"ipa":"aab");let g=U?".ipa":".aab",T=(b.url||b.downloadUrl||"").toLowerCase();return ne.endsWith(g)||T.includes(g)});if(!R||!(R.url||R.downloadUrl))return le("Build found but artifact URL is missing."),null;let K=R.url||R.downloadUrl;return{filePath:await yi(K,U?"ios":"android"),buildId:p.buildId,artifactName:R.name,source:"latest"}}catch(l){return o.stop("Fetch failed"),le(`API Error: ${l.message}`),null}}if(r==="id"){let s=n.buildId||await Ft({message:"Enter Build ID:",validate:a=>a.length<5?"Invalid ID":void 0});if(rt(s))return null;let l=String(s);o.start("Fetching build...");try{let a=null;try{let p=await P.get(`/builds/${e}/${l}`);p.data.status==="success"&&(a=p.data.build)}catch(p){p.response?.status!==404&&console.log(te.dim(` [RECOVERY] Project build lookup skipped: ${p.message}`))}if(!a){let p=await P.get(`/build/${l}`);if(p.data.status!=="success")throw new Error(p.data.message);a=p.data.build}if(!a)throw new Error(`Build ${l} was not found.`);let c=t==="ios",u=mn(a.artifacts);Id(u)||(u=await eo(e,l,u));let d=Qr(u,t);if(d||(u=await eo(e,l,u),d=Qr(u,t)),!d)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 f=d.url||d.downloadUrl;if(!f)throw new Error(`Artifact ${d.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 yi(f,c?"ios":"android"),buildId:a.buildId||l,artifactName:d.name,source:"id"}}catch(a){throw o.stop("Fetch failed"),a}}if(r==="url"){let s=await Ft({message:"Enter Artifact URL:",validate:l=>l.startsWith("http")?void 0:"Must be a valid URL"});return rt(s)?null:{filePath:await yi(s,t),source:"url"}}return null}function mn(e){return(e||[]).map(t=>({...t,url:t.url||t.downloadUrl}))}function Id(e){return e.some(t=>!!(t.url||t.downloadUrl))}function Qr(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 wd(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 eo(e,t,n){try{let i=await P.get(`/builds/${e}/${t}/artifacts`);if(i.data.status==="success"&&i.data.artifacts?.length>0){let r=mn(i.data.artifacts);return console.log(te.cyan(` [RECOVERY] Fetched ${r.length} artifact(s) with download URLs.`)),r}}catch(i){console.log(te.dim(` [RECOVERY] Project artifact lookup skipped: ${i.message}`))}try{let i=await P.get(`/public/builds/${t}`);if(i.data.status==="success"&&i.data.artifacts?.length>0){let r=mn(i.data.artifacts);return console.log(te.cyan(` [RECOVERY] Fetched ${r.length} public artifact(s) with download URLs.`)),r}}catch(i){console.log(te.dim(` [RECOVERY] Public artifact lookup skipped: ${i.message}`))}return mn(n)}async function yi(e,t,n=3){let i=st();i.start("Downloading artifact...");let r=se.mkdtempSync(Ie.join(ht.tmpdir(),`${m.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(u=>setTimeout(u,2e3*l)));let a=se.createWriteStream(s),c=await oo({url:e,method:"GET",responseType:"stream",timeout:6e4});return await new Promise((u,d)=>{c.data.pipe(a);let f=!1;c.data.on("error",p=>{f||(f=!0,a.close(),d(p))}),a.on("finish",()=>{f||u()}),a.on("error",p=>{f||(f=!0,d(p))})}),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 _d(e,t,n,i,r){let o=st();if(r&&fe(`Bundle ID: ${te.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=lo(t,n,i),l=Nd();return o.start("Uploading to TestFlight (pilot)..."),new Promise((a,c)=>{let u=kd(),d=Yl(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});d.stdout?.on("data",f=>u.append(f,process.stdout)),d.stderr?.on("data",f=>u.append(f,process.stderr)),d.on("close",f=>{if(u.flush(),f!==0){o.stop("Pilot failed");try{se.unlinkSync(s)}catch{}c(xd(f,u.lines()))}else{o.stop("IPA uploaded to TestFlight");try{se.unlinkSync(s)}catch{}a({})}}),d.on("error",f=>{u.flush();try{se.unlinkSync(s)}catch{}o.stop("Pilot execution error");let p=Gd(f);p.logs=u.lines(),c(p)})})}async function $d(e,t,n,i,r,o){let s=st();if(r&&fe(`Bundle ID: ${te.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=lo(t,n,i),a=`${o.sshUser}@${o.sshHost}`,c=vd(o),u=Rd(o),d="",f="";try{if(s.start(`Preparing remote iOS submit runner (${a})...`),d=Pd("ssh",[...c,"mktemp -d /tmp/mach-submit.XXXXXX"]).trim(),!d)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..."),Si("scp",[...u,e,`${a}:${d}/app.ipa`],"IPA upload to remote runner"),Si("scp",[...u,l,`${a}:${d}/api_key.json`],"ASC key upload to remote runner"),f=Ie.join(ht.tmpdir(),`${m.nameLower}-ios-submit-${Date.now()}.sh`),se.writeFileSync(f,Dd(d)),Si("scp",[...u,f,`${a}:${d}/submit.sh`],"submit script upload to remote runner"),s.stop("Remote submit inputs uploaded"),s.start("Uploading to TestFlight on remote runner...");let p=`chmod +x ${Ht(`${d}/submit.sh`)} && bash ${Ht(`${d}/submit.sh`)}`,h=mt("ssh",[...c,p],{stdio:"inherit"});if(h.error)throw $i("ssh",h.error);if(h.status!==0)throw new Error(`Remote iOS submit failed with exit code ${h.status}.`);return s.stop("IPA uploaded to TestFlight"),{apiKeyJsonPath:null}}catch(p){throw s.stop("Remote iOS submit failed"),p}finally{try{se.unlinkSync(l)}catch{}if(f)try{se.unlinkSync(f)}catch{}if(d)try{mt("ssh",[...c,`rm -rf ${Ht(d)}`],{stdio:"ignore"})}catch{}}}function lo(e,t,n){let i=se.readFileSync(e,"utf8"),r;try{r=_i.createPrivateKey(i).export({type:"pkcs8",format:"pem"})}catch{fe("Key normalization failed, falling back to manual re-wrapping..."),r=`-----BEGIN PRIVATE KEY-----
|
|
1247
1259
|
${(i.replace(/-----BEGIN[^-]*-----/g,"").replace(/-----END[^-]*-----/g,"").replace(/\s+/g,"").match(/.{1,64}/g)||[]).join(`
|
|
1248
1260
|
`)}
|
|
1249
|
-
-----END PRIVATE KEY-----`}let o=Ie.join(ht.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
|
|
1261
|
+
-----END PRIVATE KEY-----`}let o=Ie.join(ht.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 vd(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 Rd(e){let t=["-o","StrictHostKeyChecking=no","-o","ServerAliveInterval=30"];return e.sshKey&&t.push("-i",e.sshKey),t}function Pd(e,t){let n=mt(e,t,{encoding:"utf-8",stdio:["ignore","pipe","inherit"]});if(n.error)throw $i(e,n.error);if(n.status!==0)throw new Error(`${e} failed with exit code ${n.status}.`);return n.stdout||""}function Si(e,t,n){let i=mt(e,t,{stdio:"inherit"});if(i.error)throw $i(e,i.error);if(i.status!==0)throw new Error(`${n} failed with exit code ${i.status}.`)}function $i(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 Ht(e){return`'${e.replace(/'/g,"'\\''")}'`}function Dd(e){let t=Ht(`${e}/app.ipa`),n=Ht(`${e}/api_key.json`);return`#!/bin/bash
|
|
1250
1262
|
set -euo pipefail
|
|
1251
1263
|
|
|
1252
1264
|
export PATH="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:$HOME/.local/share/fastlane/3.4.0/bin:$PATH"
|
|
@@ -1274,39 +1286,39 @@ fastlane pilot upload \\
|
|
|
1274
1286
|
--api_key_path ${n} \\
|
|
1275
1287
|
--skip_submission true \\
|
|
1276
1288
|
--skip_waiting_for_build_processing true
|
|
1277
|
-
`}async function
|
|
1289
|
+
`}async function Od(e,t,n="internal",i,r="completed",o,s=!1,l="production"){let a=st();if(!i||i==="*")throw new Error("Android package name is required for Google Play submission.");let c=o!==void 0?` (${o} rollout)`:"";a.start(`Uploading to Google Play ${n} track with ${r} release status${c}...`);try{let u=JSON.parse(se.readFileSync(t,"utf-8"));Cd(u);let d=await Ir({packageName:i,serviceAccount:u,aabPath:e,track:n,releaseStatus:r,userFraction:o,changesNotSentForReview:s});return a.stop(`AAB uploaded to ${n} track (versionCode ${d.versionCode})`),d}catch(u){throw a.stop("Google Play upload failed"),new Error(Kd(u,n,i,l))}}function Cd(e){if(!e?.client_email||!e?.private_key)throw new Error("Invalid Google service account JSON: missing client_email or private_key.")}function bi(){let e=process.env.HOME||ht.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 Nd(){let e=bi(),t=to(e);if(t)return t;if(process.env.MACH_SKIP_FASTLANE_INSTALL!=="1"){Td(e);let n=to(bi());if(n)return n}return{command:"fastlane",env:bi()}}function to(e){let t=process.env.HOME||ht.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(!mt(i,["--version"],{env:e,stdio:"ignore"}).error)return{command:i,env:e}}return null}function Td(e){let t=mt("gem",["--version"],{env:e,stdio:"ignore"});if(t.error||t.status!==0)return;let n=process.env.HOME||ht.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}),fe(te.dim("fastlane not found. Installing fastlane into the local Mach runner cache..."));let o=mt("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)&&fe(te.yellow("Automatic fastlane install failed; Mach will try PATH resolution once more."))}function kd(e=so){let t=[],n="",i=r=>{let o=uo(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 xd(e,t){let n=new Error(Ld(e,t));return n.logs=co(t),n.exitCode=e,n}function Ld(e,t){let n=`fastlane pilot failed with exit code ${e??"unknown"}.`,i=Md(t);return i.length===0?n:`${n}
|
|
1278
1290
|
|
|
1279
1291
|
Fastlane output:
|
|
1280
1292
|
${i.join(`
|
|
1281
|
-
`)}`}function
|
|
1282
|
-
`),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
|
|
1283
|
-
`))}function
|
|
1293
|
+
`)}`}function Md(e){let t=co(e);if(t.length===0)return[];let n=no(t.filter(Bd)),i=Ud(t);if(i)return[i,...io(n,hi-1,Zr)];let r=n.length>0?n:t.slice(-hi);return io(no(r),hi,Zr)}function Ud(e){let t=e.join(`
|
|
1294
|
+
`),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 Bd(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 no(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 io(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 co(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=uo(r);o&&t.push(o)}}return t.slice(-so)}function uo(e){return Hd(Fd(e).trimEnd()).trim()}function Fd(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 Hd(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(jd(i),"g"),"[REDACTED]"));return t}function jd(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(`
|
|
1295
|
+
`))}function Kd(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: ${m.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(`
|
|
1284
1296
|
`);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(`
|
|
1285
1297
|
`);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(`
|
|
1286
1298
|
`);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: ${m.nameLower} submit --latest --platform android --profile ${i} --track ${t} --release-status draft`].join(`
|
|
1287
1299
|
`);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: ${m.nameLower} build --platform android --profile ${i} --auto-version`,`Then: ${m.nameLower} submit --latest --platform android --profile ${i} --track ${t}`].join(`
|
|
1288
1300
|
`);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: ${m.nameLower} build --platform android --profile ${i} --auto-version`].join(`
|
|
1289
|
-
`);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 Md(e){try{se.existsSync(e)&&se.rmSync(e,{recursive:!0,force:!0})}catch{}}function le(e){console.log(ne.red(`\u274C ${e}`))}function fe(e){console.log(ne.gray(`\u2022 ${e}`))}function Ii(e){console.log(ne.green(`\u2713 ${e}`))}var $i=8,Fd=6,mo=Number(process.env.MACH_ARTIFACT_UPLOAD_MAX_ATTEMPTS||2),vi=Number(process.env.MACH_ARTIFACT_UPLOAD_TIMEOUT_MS||12e4),Hd=[{value:"production",label:"production",hint:"Store / release build"},{value:"staging",label:"staging",hint:"Internal testing build"},{value:"development",label:"development",hint:"Development build"}],Ro=e=>new Promise(t=>setTimeout(t,e)),jd=e=>!e.yes&&!e.failOnly&&!e.buildId&&process.stdin.isTTY&&process.stdout.isTTY,Gd=e=>{if(!e||typeof e!="object")return;let t=[e.distribution?`distribution: ${e.distribution}`:void 0,e.environment?`env: ${e.environment}`:void 0,e.developmentClient?"development client":void 0,e.simulator?"simulator":void 0].filter(Boolean);return t.length>0?t.join(", "):void 0},Kd=()=>{let e=$e(`./${m.configFileName}`),t=e?.build&&typeof e.build=="object"?e.build:{},n=Object.keys(t);return n.length===0?Hd:n.map(i=>({value:i,label:i,hint:Gd(t[i])}))},Vd=async e=>{let t=jd(e);if(!e.platform&&t){let n=await lo({message:"Select platform",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"}]});bn(n)&&(uo("Build cancelled."),process.exit(0)),e.platform=n}if(!e.buildProfile&&t){let n=Kd(),i=await lo({message:"Select build profile",options:n,initialValue:n.find(r=>r.value==="production")?.value||n[0]?.value});bn(i)&&(uo("Build cancelled."),process.exit(0)),e.buildProfile=i}e.buildProfile||(e.buildProfile="production")},go=e=>{if(e===!0||e===!1)return e;if(e===1||e==="1")return!0;if(e===0||e==="0")return!1;if(typeof e!="string")return;let t=e.trim().toLowerCase();if(["true","yes","on"].includes(t))return!0;if(["false","no","off"].includes(t))return!1},Po=(e,t)=>{if(e)for(let n of t){let i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=e.match(new RegExp(`(?:^|\\s)${i}(?:=|\\s+)([^\\s]+)`));if(r?.[1])return r[1].replace(/^["']|["']$/g,"")}},zd=(e,t)=>!!e&&t.some(n=>new RegExp(`(?:^|\\s)${n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:\\s|$)`).test(e)),Wd=e=>{let n=Po(e,["--platform"])||e?.split(/\s+/).find(i=>i==="ios"||i==="android");return n==="ios"||n==="android"?n:void 0},Yd=async e=>{if(!(!e.projectId||!e.buildId))try{let t=await R.get(`/builds/${e.projectId}/${e.buildId}`),n=t.data?.build||t.data;if(!n||typeof n!="object")return;let i=typeof n.buildArgs=="string"?n.buildArgs:void 0;if(!e.platform){let r=n.platform||Wd(i);(r==="ios"||r==="android")&&(e.platform=r)}if(e.buildProfile||(e.buildProfile=n.buildProfile||n.profile||n.profileName||Po(i,["--profile","--build-profile","-p"])),e.simulator===void 0){let r=go(n.simulator??n.isSimulator);r!==void 0?e.simulator=r:zd(i,["--simulator"])&&(e.simulator=!0)}if(e.developmentClient===void 0){let r=go(n.developmentClient??n.devClient);r!==void 0&&(e.developmentClient=r)}}catch(t){_.warn($.yellow(`Could not load saved build options for runner: ${t.message}`))}},Jd=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]}`},qd=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},hn=async(e,t,n=Fd)=>{let i;for(let r=1;r<=n;r++)try{return await t()}catch(o){if(i=o,!qd(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 Ro(s)}throw i},Xd=async(e,t,n)=>{let i=ve.basename(e),r=de.statSync(e).size,o=Math.round(vi/1e3);try{await hn(`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()},vi);try{await Sn.put(t,l,{headers:{"Content-Type":n,"Content-Length":r,Connection:"close"},maxBodyLength:1/0,maxContentLength:1/0,timeout:vi,timeoutErrorMessage:`Artifact upload timed out after ${o}s`,signal:s.signal})}finally{clearTimeout(a)}},mo)}catch(s){throw new Error(`${i} (${Jd(r)}) failed after ${mo} upload attempt(s): ${s.message||s}`)}return r},Zd=e=>{let t=e.response?.status;return t?t===408||t===429||t>=500:!0},Ht=e=>e.credentialId||e.id,Qd=async(e,t)=>{let n=Ht(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},Do=async(e,t)=>{let n=e.downloadUrl;for(let i=1;i<=$i;i++)try{if((!n||i>1)&&(n=await Qd(e,t)),!n)throw new Error(`Credential ${e.name||Ht(e)||"unknown"} has no download URL.`);let r=await Sn.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>=$i||!Zd(r))throw r;let o=Math.min(1500*i*i,15e3);_.warn($.dim(` - Temporary network error downloading ${e.name}. Retrying... (${i}/${$i})`)),await Ro(o)}throw new Error(`Failed to download credential ${e.name||Ht(e)||"unknown"}.`)},ho=async(e,t)=>{let n=await Do(e,t);return Buffer.from(n,"base64").toString("utf8")},ec=(e,t)=>{try{return JSON.parse(e)}catch{throw new Error(`${t} is not valid JSON.`)}},tc=e=>/ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|ECONNABORTED|socket hang up|network|timeout/i.test(e),nc=(e,t)=>t?.ios?.buildNumber??t?.iosBuildNumber??e?.ios?.buildNumber??e?.expo?.ios?.buildNumber,ic=(e,t,n)=>t?.ios?.ascAppId??t?.ascAppId??e?.ios?.ascAppId??e?.submit?.[n]?.ios?.ascAppId??e?.submit?.production?.ios?.ascAppId,yo=e=>e.bundleId||e.bundleIdentifier||e.meta?.bundleId||e.meta?.bundleIdentifier,So=(e,t)=>{let n=e.filter(i=>i.type==="asc_api_key");if(n.length!==0){if(t){let i=n.find(o=>yo(o)===t);if(i)return i;let r=n.find(o=>yo(o)==="*");if(r)return r}return n[0]}},rc=e=>typeof e=="string"&&e.trim().toLowerCase()==="auto",Oo=(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=ve.join(e,r.name);r.isDirectory()?Oo(o,t,n):r.name===t&&n.push(o)}return n},oc=(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},sc=(e,t)=>{let n=ve.resolve(process.cwd(),de.existsSync("ios")?"ios":"."),i=Oo(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:oc(o,e,t)})).sort((o,s)=>s.score-o.score)[0]?.bundleId},yn=e=>String(e||"").trim().toLowerCase().replace(/_/g,"-"),En=(e,t)=>{let n=yn(e);return t==="ios"&&(n==="internal"||n==="ad-hoc")?"adhoc":t==="android"&&["internal","adhoc","ad-hoc","development","dev","staging","stage"].includes(n)?"internal":n},bo=(e,t,n)=>{let i=En(e.distributionType||e.meta?.distributionType,n);return i?i===En(t,n):!0},Eo=(e,t,n)=>{let i=En(e.distributionType||e.meta?.distributionType,n),r=En(t,n);return i?i===r?3:n==="android"&&r!=="store"&&i!=="store"?2:0:1},ac=e=>{let t=e.toLowerCase();return t==="development"||t==="dev"||t.startsWith("development-")||t.startsWith("dev-")||t.endsWith("-development")||t.endsWith("-dev")},lc=e=>{let t=e.toLowerCase();return t.includes("staging")||t.includes("stage")||t.includes("preview")||t.includes("adhoc")||t.includes("ad-hoc")},dc=(e,t)=>{let n=yn(e.distribution),i=yn(e.iosExportMethod),r=yn(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":ac(t)?"development":(lc(t),"adhoc")},Co=e=>e.bundleId||e.bundleIdentifier||e.packageName||e.meta?.bundleId||e.meta?.bundleIdentifier||e.meta?.packageName,Ao=(e,t)=>{if(!t)return!0;let n=Co(e);return!n||n==="*"||n===t},Io=(e,t)=>{let n=Co(e);return!t||!n?0:n===t?2:n==="*"?1:-1},No=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}},cc=(e,t)=>{if(e===t||e==="*")return!0;if(e.endsWith(".*")){let n=e.slice(0,-2);return t.startsWith(`${n}.`)}return!1},uc=(e,t)=>{if(!t)return!0;let n=No(e);if(n)return cc(n,t);try{return Buffer.from(e,"base64").toString("latin1").includes(t)}catch{return!0}},An=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)}}await Yd(e),await Vd(e),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=Pi(),n=e.buildId||Ud(),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 Sn.get(l.data.downloadUrl,{responseType:"stream"}),d=(i||e.projectId||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),c=ve.join(Bd.homedir(),m.workspacesDir,d);de.mkdirSync(c,{recursive:!0});let u=new Set(["node_modules",`.${m.nameLower}-cache-meta`]),f=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=ve.join(c,"ios");try{let Y=de.readdirSync(S);for(let ee of Y)if(!f.has(ee))try{de.rmSync(ve.join(S,ee),{recursive:!0,force:!0})}catch{}}catch{}continue}let F=ve.join(c,P);try{de.rmSync(F,{recursive:!0,force:!0})}catch{}}}let p=ve.join(c,"source.zip"),h=a.data,O=de.createWriteStream(p);await new Promise((M,P)=>{h.pipe(O),h.on("error",F=>P(F)),O.on("finish",()=>M())}),new po(p).extractAllTo(c,!0);try{de.unlinkSync(p)}catch{}process.chdir(c),_.info($.green(`\u2713 Persistent workspace ready: ${c}`)),_.info($.dim(` \u{1F4E6} Cached dirs preserved: node_modules=${de.existsSync(ve.join(c,"node_modules"))?"\u2705":"\u274C"}, Pods=${de.existsSync(ve.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=fo("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=$e(`./${m.configFileName}`);if(u){c=u,i=u.projectId;let g=e.buildProfile||"production",T=et(u,g);!T&&e.buildProfile&&(_.error(`Build profile '${g}' not found in ${m.configFileName}`),process.exit(1));let E=T||{};process.env.MACH_DEBUG&&_.info($.dim(`Build profile: ${g} | Platform: ${e.platform} | Distribution: ${E.distribution||"store"} | Environment: ${E.environment||g}`)),E.env&&(d=E.env,_.info($.blue(`Use Build Profile: ${g}`)));let k=e.platform,v=E[k]||{},A=["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 x=L=>L==="androidPackage"?v.androidPackage??v.package??E.androidPackage??E.android?.package:L==="iosBundleIdentifier"?v.iosBundleIdentifier??v.bundleIdentifier??E.iosBundleIdentifier??E.ios?.bundleIdentifier:v[L]!==void 0?v[L]:E[L];for(let L of A){let W=x(L),D=L==="androidPackage"||L==="iosBundleIdentifier";W!==void 0&&(e[L]===void 0||D)&&(e[L]=W)}if(e.platform==="ios"&&!(v.iosBundleIdentifier??v.bundleIdentifier??E.iosBundleIdentifier??E.ios?.bundleIdentifier)){let W=sc(e,g);W&&W!==e.iosBundleIdentifier&&(_.warn($.yellow(`Detected native iOS bundle identifier ${W}; using it for credential lookup. Set build.${g}.ios.bundleIdentifier to make this explicit.`)),e.iosBundleIdentifier=W)}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=L=>{if(!L)return L;if(L.startsWith("scripts.")){let W=L.split(".")[1],D=u.scripts?.[W];if(D)return D;_.warn(`Script reference not found: ${L}`)}return L};e.buildCommand=U(e.buildCommand),e.preBuild=U(e.preBuild),e.postBuild=U(e.postBuild),!e.scheme&&u.scheme&&(e.scheme=u.scheme);let z={...Et(u,m.envPrefix),...Et(E,`${m.envPrefix}PROFILE_`)};a={...a,...d,...z},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&&E.ios?.appleTeamId&&(e.iosTeamId=E.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}`)):e.simulator||_.warn($.yellow("\u26A0\uFE0F No iOS Team ID found. Device or archive signing may fail unless managed iOS credentials provide the team automatically.")))}let f="unknown";try{f=fo("git rev-parse --abbrev-ref HEAD").toString().trim()}catch{_.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 h=e.buildProfile||"production",O="Internal";e.developmentClient?O="DevelopmentClient":h.toLowerCase().includes("store")||h.toLowerCase()==="production"?O="Store":h.toLowerCase().includes("preview")||h.toLowerCase().includes("staging")?O="Staging":(h.toLowerCase().includes("development")||h.toLowerCase().includes("dev"))&&(O="Development");let N=e.platform==="ios"?"iOS":"Android",M=e.platform==="ios"&&e.simulator?" (Simulator)":"",P=`${N}${M} v${p} (${O})`;if(In(e,{status:"created",projectId:i,buildId:n,platform:e.platform,profile:h,branch:f,version:p,buildType:O,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 k=(await R.get(`/projects/${i}/secrets/export?env=${T}`)).data;k.status==="success"&&k.secrets&&(a={...a,...k.secrets},Object.keys(k.secrets).length>0&&_.info($.magenta(`\u2713 Injected ${Object.keys(k.secrets).length} secrets from Dashboard.`)))}catch(g){_.warn(`Failed to load managed secrets from Dashboard: ${g.message}`)}if(e.platform==="ios"&&e.simulator)_.info($.dim("Skipping managed iOS signing credentials for simulator build."));else try{_.info($.blue("Fetching managed credentials..."));let g=dc(e,h),T=e.platform==="ios"?e.iosBundleIdentifier:e.androidPackage,E=e.platform==="ios"?"bundle":"package";_.info($.dim(` Credential target: ${E} ${T||"not set"} (${g})`));let k=await R.get("/credentials/resolve",{params:{projectId:i,platform:e.platform,bundleId:T,distributionType:g,teamId:e.platform==="ios"?e.iosTeamId:void 0}});if(k.data.status==="success"&&k.data.credentials){let v=k.data.credentials;_.info($.magenta(`\u2713 Found ${v.length} relevant credentials.`));let A=v.filter(D=>e.platform==="ios"&&D.type==="ios_profile"?bo(D,g,e.platform)?Ao(D,T):!1:e.platform==="android"&&D.type==="android_keystore"?Ao(D,T):!!bo(D,g,e.platform)).sort((D,J)=>Io(J,T)*10+Eo(J,g,e.platform)-(Io(D,T)*10+Eo(D,g,e.platform)));_.info($.dim(` Filtered to ${A.length} credentials for distributionType: ${g}`));let x=!1,U=!1,z=!1,L=[];for(let D of A)if(!(D.type==="ios_cert"&&x||D.type==="ios_profile"&&U||D.type==="android_keystore"&&z)&&["ios_cert","ios_profile","android_keystore"].includes(D.type)&&(D.downloadUrl||Ht(D)))try{let ye=await Do(D,i);if(D.type==="ios_cert"&&!x)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`)),x=!0;else if(D.type==="ios_profile"&&!U){if(!uc(ye,T)){let Ee=No(ye)||"unknown";throw new Error(`Provisioning profile ${D.name||Ht(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`)),U=!0}else if(D.type==="android_keystore"&&!z){a.ANDROID_KEYSTORE_BASE64=ye;let Ee=D.keystorePassword||D.password,H=D.keyPassword||D.keystorePassword||D.password,B=D.alias||D.meta?.alias;if(Ee)a.ANDROID_STORE_PASSWORD=Ee,_.info($.dim(" - Injected keystore password from credential record"));else{let j=["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]);j&&a[j]&&(a.ANDROID_STORE_PASSWORD=a[j])}if(H?(a.ANDROID_KEY_PASSWORD=H,_.info($.dim(" - Injected key password from credential record"))):a.ANDROID_KEY_PASSWORD=a.ANDROID_STORE_PASSWORD||"",B)a.ANDROID_KEY_ALIAS=B;else{let q=["ANDROID_KEY_ALIAS","KEYSTORE_ALIAS"].find(C=>!!a[C]);q&&(a.ANDROID_KEY_ALIAS=a[q])}_.info($.dim(` - Injected ${D.name} as ANDROID_KEYSTORE_BASE64`)),z=!0}}catch(ye){L.push(`${D.name||D.type}: ${ye.message}`)}let W=e.platform==="ios"?e.simulator||x&&U:z||!A.some(D=>D.type==="android_keystore");if(L.length>0&&!W)throw new Error(`Credential setup failed:
|
|
1290
|
-
${L.map(
|
|
1291
|
-
`)}`);L.length>0
|
|
1292
|
-
\u{1F517} Download Links:`));for(let
|
|
1293
|
-
\u2713 Build completed and reported to dashboard.`)),e.maestro&&!
|
|
1294
|
-
${
|
|
1295
|
-
\u{1F3BC} Queuing managed Maestro test...`)),await
|
|
1296
|
-
Auto-submit: submitting the successful build...`));try{let r=await
|
|
1297
|
-
\u2717 Build failed: ${a.error||"Unknown error"}`)),process.exit(1);else if(r==="completed"||r==="success"){n.quiet||i.stop("Build successful!"),
|
|
1298
|
-
\u2713 Build completed successfully!`));try{n.quiet||(
|
|
1299
|
-
\u{1F4F1} Installation Hub:`))
|
|
1300
|
-
`);if(
|
|
1301
|
-
\u2717 Lost connection to Dashboard API.`)),process.exit(1))}await new Promise(l=>setTimeout(l,3e3))}}import*as
|
|
1301
|
+
`);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 Vd(e){try{se.existsSync(e)&&se.rmSync(e,{recursive:!0,force:!0})}catch{}}function le(e){console.log(te.red(`\u274C ${e}`))}function fe(e){console.log(te.gray(`\u2022 ${e}`))}function wi(e){console.log(te.green(`\u2713 ${e}`))}var vi=8,Yd=6,yo=Number(process.env.MACH_ARTIFACT_UPLOAD_MAX_ATTEMPTS||2),Ri=Number(process.env.MACH_ARTIFACT_UPLOAD_TIMEOUT_MS||12e4),Jd=[{value:"production",label:"production",hint:"Store / release build"},{value:"staging",label:"staging",hint:"Internal testing build"},{value:"development",label:"development",hint:"Development build"}],Oo=e=>new Promise(t=>setTimeout(t,e)),qd=e=>!e.yes&&!e.failOnly&&!e.buildId&&process.stdin.isTTY&&process.stdout.isTTY,Xd=e=>{if(!e||typeof e!="object")return;let t=[e.distribution?`distribution: ${e.distribution}`:void 0,e.environment?`env: ${e.environment}`:void 0,e.developmentClient?"development client":void 0,e.simulator?"simulator":void 0].filter(Boolean);return t.length>0?t.join(", "):void 0},Zd=()=>{let e=$e(`./${m.configFileName}`),t=e?.build&&typeof e.build=="object"?e.build:{},n=Object.keys(t);return n.length===0?Jd:n.map(i=>({value:i,label:i,hint:Xd(t[i])}))},Qd=async e=>{let t=qd(e);if(!e.platform&&t){let n=await fo({message:"Select platform",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"}]});En(n)&&(mo("Build cancelled."),process.exit(0)),e.platform=n}if(!e.buildProfile&&t){let n=Zd(),i=await fo({message:"Select build profile",options:n,initialValue:n.find(r=>r.value==="production")?.value||n[0]?.value});En(i)&&(mo("Build cancelled."),process.exit(0)),e.buildProfile=i}e.buildProfile||(e.buildProfile="production")},So=e=>{if(e===!0||e===!1)return e;if(e===1||e==="1")return!0;if(e===0||e==="0")return!1;if(typeof e!="string")return;let t=e.trim().toLowerCase();if(["true","yes","on"].includes(t))return!0;if(["false","no","off"].includes(t))return!1},Co=(e,t)=>{if(e)for(let n of t){let i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=e.match(new RegExp(`(?:^|\\s)${i}(?:=|\\s+)([^\\s]+)`));if(r?.[1])return r[1].replace(/^["']|["']$/g,"")}},ec=(e,t)=>!!e&&t.some(n=>new RegExp(`(?:^|\\s)${n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:\\s|$)`).test(e)),tc=e=>{let n=Co(e,["--platform"])||e?.split(/\s+/).find(i=>i==="ios"||i==="android");return n==="ios"||n==="android"?n:void 0},nc=async e=>{if(!(!e.projectId||!e.buildId))try{let t=await P.get(`/builds/${e.projectId}/${e.buildId}`),n=t.data?.build||t.data;if(!n||typeof n!="object")return;let i=typeof n.buildArgs=="string"?n.buildArgs:void 0;if(!e.platform){let r=n.platform||tc(i);(r==="ios"||r==="android")&&(e.platform=r)}if(e.buildProfile||(e.buildProfile=n.buildProfile||n.profile||n.profileName||Co(i,["--profile","--build-profile","-p"])),e.simulator===void 0){let r=So(n.simulator??n.isSimulator);r!==void 0?e.simulator=r:ec(i,["--simulator"])&&(e.simulator=!0)}if(e.developmentClient===void 0){let r=So(n.developmentClient??n.devClient);r!==void 0&&(e.developmentClient=r)}}catch(t){$.warn(v.yellow(`Could not load saved build options for runner: ${t.message}`))}},ic=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]}`},rc=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},yn=async(e,t,n=Yd)=>{let i;for(let r=1;r<=n;r++)try{return await t()}catch(o){if(i=o,!rc(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(v.yellow(`${e} failed transiently (${l}). Retrying in ${Math.round(s/1e3)}s... (${r}/${n})`)),await Oo(s)}throw i},oc=async(e,t,n)=>{let i=ve.basename(e),r=de.statSync(e).size,o=Math.round(Ri/1e3);try{await yn(`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()},Ri);try{await bn.put(t,l,{headers:{"Content-Type":n,"Content-Length":r,Connection:"close"},maxBodyLength:1/0,maxContentLength:1/0,timeout:Ri,timeoutErrorMessage:`Artifact upload timed out after ${o}s`,signal:s.signal})}finally{clearTimeout(a)}},yo)}catch(s){throw new Error(`${i} (${ic(r)}) failed after ${yo} upload attempt(s): ${s.message||s}`)}return r},sc=e=>{let t=e.response?.status;return t?t===408||t===429||t>=500:!0},jt=e=>e.credentialId||e.id,ac=async(e,t)=>{let n=jt(e);if(!n)return e.downloadUrl;let i=await P.get(`/credentials/${n}/download`,{params:{projectId:t,format:"raw"}});return i.data?.status==="success"&&i.data?.downloadUrl?i.data.downloadUrl:e.downloadUrl},No=async(e,t)=>{let n=e.downloadUrl;for(let i=1;i<=vi;i++)try{if((!n||i>1)&&(n=await ac(e,t)),!n)throw new Error(`Credential ${e.name||jt(e)||"unknown"} has no download URL.`);let r=await bn.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>=vi||!sc(r))throw r;let o=Math.min(1500*i*i,15e3);$.warn(v.dim(` - Temporary network error downloading ${e.name}. Retrying... (${i}/${vi})`)),await Oo(o)}throw new Error(`Failed to download credential ${e.name||jt(e)||"unknown"}.`)},bo=async(e,t)=>{let n=await No(e,t);return Buffer.from(n,"base64").toString("utf8")},lc=(e,t)=>{try{return JSON.parse(e)}catch{throw new Error(`${t} is not valid JSON.`)}},dc=e=>/ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|ECONNABORTED|socket hang up|network|timeout/i.test(e),cc=(e,t)=>t?.ios?.buildNumber??t?.iosBuildNumber??e?.ios?.buildNumber??e?.expo?.ios?.buildNumber,uc=(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,Ao=(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]}},fc=e=>typeof e=="string"&&e.trim().toLowerCase()==="auto",To=(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=ve.join(e,r.name);r.isDirectory()?To(o,t,n):r.name===t&&n.push(o)}return n},pc=(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},mc=(e,t)=>{let n=ve.resolve(process.cwd(),de.existsSync("ios")?"ios":"."),i=To(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:pc(o,e,t)})).sort((o,s)=>s.score-o.score)[0]?.bundleId},Sn=e=>String(e||"").trim().toLowerCase().replace(/_/g,"-"),An=(e,t)=>{let n=Sn(e);return t==="ios"&&(n==="internal"||n==="ad-hoc")?"adhoc":t==="android"&&["internal","adhoc","ad-hoc","development","dev","staging","stage"].includes(n)?"internal":n},Io=(e,t,n)=>{let i=An(e.distributionType||e.meta?.distributionType,n);return i?i===An(t,n):!0},wo=(e,t,n)=>{let i=An(e.distributionType||e.meta?.distributionType,n),r=An(t,n);return i?i===r?3:n==="android"&&r!=="store"&&i!=="store"?2:0:1},gc=e=>{let t=e.toLowerCase();return t==="development"||t==="dev"||t.startsWith("development-")||t.startsWith("dev-")||t.endsWith("-development")||t.endsWith("-dev")},hc=e=>{let t=e.toLowerCase();return t.includes("staging")||t.includes("stage")||t.includes("preview")||t.includes("adhoc")||t.includes("ad-hoc")},yc=(e,t)=>{let n=Sn(e.distribution),i=Sn(e.iosExportMethod),r=Sn(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":gc(t)?"development":(hc(t),"adhoc")},ko=e=>e.bundleId||e.bundleIdentifier||e.packageName||e.meta?.bundleId||e.meta?.bundleIdentifier||e.meta?.packageName,_o=(e,t)=>{if(!t)return!0;let n=ko(e);return!n||n==="*"||n===t},$o=(e,t)=>{let n=ko(e);return!t||!n?0:n===t?2:n==="*"?1:-1},xo=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}},Sc=(e,t)=>{if(e===t||e==="*")return!0;if(e.endsWith(".*")){let n=e.slice(0,-2);return t.startsWith(`${n}.`)}return!1},bc=(e,t)=>{if(!t)return!0;let n=xo(e);if(n)return Sc(n,t);try{return Buffer.from(e,"base64").toString("latin1").includes(t)}catch{return!0}},In=async e=>{if(e.failOnly){(!e.projectId||!e.buildId)&&($.error(v.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 P.patch(`/builds/${e.projectId}/${e.buildId}`,{status:"failed",error:l,endTime:Date.now()}),$.info(v.yellow(`Marked build ${e.buildId} as failed.`));return}catch(a){$.error(v.red(`Could not mark build failed: ${a.message}`)),process.exit(1)}}await nc(e),await Qd(e),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(v.red("--auto-submit cannot be used with --simulator because simulator builds are not App Store artifacts.")),process.exit(1)),e.autoSubmit&&e.dryRun&&$.warn(v.yellow("--auto-submit is ignored during --dry-run."));let t=Di(),n=e.buildId||zd(),i=e.projectId,r=Date.now(),o=!!i,s=async l=>{if(i)try{await P.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 P.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 bn.get(l.data.downloadUrl,{responseType:"stream"}),c=(i||e.projectId||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),u=ve.join(Wd.homedir(),m.workspacesDir,c);de.mkdirSync(u,{recursive:!0});let d=new Set(["node_modules",`.${m.nameLower}-cache-meta`]),f=new Set(["Pods"]);if(de.existsSync(u)){let U=de.readdirSync(u);for(let R of U){if(d.has(R))continue;if(R==="ios"){let b=ve.join(u,"ios");try{let W=de.readdirSync(b);for(let ne of W)if(!f.has(ne))try{de.rmSync(ve.join(b,ne),{recursive:!0,force:!0})}catch{}}catch{}continue}let K=ve.join(u,R);try{de.rmSync(K,{recursive:!0,force:!0})}catch{}}}let p=ve.join(u,"source.zip"),h=a.data,D=de.createWriteStream(p);await new Promise((U,R)=>{h.pipe(D),h.on("error",K=>R(K)),D.on("finish",()=>U())}),new ho(p).extractAllTo(u,!0);try{de.unlinkSync(p)}catch{}process.chdir(u),$.info(v.green(`\u2713 Persistent workspace ready: ${u}`)),$.info(v.dim(` \u{1F4E6} Cached dirs preserved: node_modules=${de.existsSync(ve.join(u,"node_modules"))?"\u2705":"\u274C"}, Pods=${de.existsSync(ve.join(u,"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=go("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: ${v.cyan(n)}`);let a={},c={},u=null,d=$e(`./${m.configFileName}`);if(d){u=d,i=d.projectId;let g=e.buildProfile||"production",T=nt(d,g);!T&&e.buildProfile&&($.error(`Build profile '${g}' not found in ${m.configFileName}`),process.exit(1));let w=T||{};process.env.MACH_DEBUG&&$.info(v.dim(`Build profile: ${g} | Platform: ${e.platform} | Distribution: ${w.distribution||"store"} | Environment: ${w.environment||g}`)),w.env&&(c=w.env,$.info(v.blue(`Use Build Profile: ${g}`)));let k=e.platform,A=w[k]||{},S=["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 x=L=>L==="androidPackage"?A.androidPackage??A.package??w.androidPackage??w.android?.package:L==="iosBundleIdentifier"?A.iosBundleIdentifier??A.bundleIdentifier??w.iosBundleIdentifier??w.ios?.bundleIdentifier:A[L]!==void 0?A[L]:w[L];for(let L of S){let J=x(L),O=L==="androidPackage"||L==="iosBundleIdentifier";J!==void 0&&(e[L]===void 0||O)&&(e[L]=J)}if(e.platform==="ios"&&!(A.iosBundleIdentifier??A.bundleIdentifier??w.iosBundleIdentifier??w.ios?.bundleIdentifier)){let J=mc(e,g);J&&J!==e.iosBundleIdentifier&&($.warn(v.yellow(`Detected native iOS bundle identifier ${J}; using it for credential lookup. Set build.${g}.ios.bundleIdentifier to make this explicit.`)),e.iosBundleIdentifier=J)}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 B=L=>{if(!L)return L;if(L.startsWith("scripts.")){let J=L.split(".")[1],O=d.scripts?.[J];if(O)return O;$.warn(`Script reference not found: ${L}`)}return L};e.buildCommand=B(e.buildCommand),e.preBuild=B(e.preBuild),e.postBuild=B(e.postBuild),!e.scheme&&d.scheme&&(e.scheme=d.scheme);let Y={...Et(d,m.envPrefix),...Et(w,`${m.envPrefix}PROFILE_`)};a={...a,...c,...Y},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&&w.ios?.appleTeamId&&(e.iosTeamId=w.ios.appleTeamId),!e.iosTeamId&&d.submit?.[g]?.ios?.appleTeamId&&(e.iosTeamId=d.submit[g].ios.appleTeamId),!e.iosTeamId&&d.submit?.production?.ios?.appleTeamId&&($.warn(v.yellow(`Check: Using 'production' Team ID for '${g}' build.`)),e.iosTeamId=d.submit.production.ios.appleTeamId),e.iosTeamId?$.info(v.magenta(`\u2713 Injected iOS Team ID from config: ${e.iosTeamId}`)):e.simulator||$.warn(v.yellow("\u26A0\uFE0F No iOS Team ID found. Device or archive signing may fail unless managed iOS credentials provide the team automatically.")))}let f="unknown";try{f=go("git rev-parse --abbrev-ref HEAD").toString().trim()}catch{$.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 h=e.buildProfile||"production",D="Internal";e.developmentClient?D="DevelopmentClient":h.toLowerCase().includes("store")||h.toLowerCase()==="production"?D="Store":h.toLowerCase().includes("preview")||h.toLowerCase().includes("staging")?D="Staging":(h.toLowerCase().includes("development")||h.toLowerCase().includes("dev"))&&(D="Development");let N=e.platform==="ios"?"iOS":"Android",U=e.platform==="ios"&&e.simulator?" (Simulator)":"",R=`${N}${U} v${p} (${D})`;if(wn(e,{status:"created",projectId:i,buildId:n,platform:e.platform,profile:h,branch:f,version:p,buildType:D,developmentClient:!!e.developmentClient,summary:R}),i){try{let g=e.buildProfile||"production",T=e.environment||g;$.info(v.blue(`Fetching managed secrets for profile: ${g} (environment: ${T})...`));let k=(await P.get(`/projects/${i}/secrets/export?env=${T}`)).data;k.status==="success"&&k.secrets&&(a={...a,...k.secrets},Object.keys(k.secrets).length>0&&$.info(v.magenta(`\u2713 Injected ${Object.keys(k.secrets).length} secrets from Dashboard.`)))}catch(g){$.warn(`Failed to load managed secrets from Dashboard: ${g.message}`)}if(e.platform==="ios"&&e.simulator)$.info(v.dim("Skipping managed iOS signing credentials for simulator build."));else try{$.info(v.blue("Fetching managed credentials..."));let g=yc(e,h),T=e.platform==="ios"?e.iosBundleIdentifier:e.androidPackage,w=e.platform==="ios"?"bundle":"package";$.info(v.dim(` Credential target: ${w} ${T||"not set"} (${g})`));let k=await P.get("/credentials/resolve",{params:{projectId:i,platform:e.platform,bundleId:T,distributionType:g,teamId:e.platform==="ios"?e.iosTeamId:void 0}});if(k.data.status==="success"&&k.data.credentials){let A=k.data.credentials;$.info(v.magenta(`\u2713 Found ${A.length} relevant credentials.`));let S=A.filter(O=>e.platform==="ios"&&O.type==="ios_profile"?Io(O,g,e.platform)?_o(O,T):!1:e.platform==="android"&&O.type==="android_keystore"?_o(O,T):!!Io(O,g,e.platform)).sort((O,q)=>$o(q,T)*10+wo(q,g,e.platform)-($o(O,T)*10+wo(O,g,e.platform)));$.info(v.dim(` Filtered to ${S.length} credentials for distributionType: ${g}`));let x=!1,B=!1,Y=!1,L=[];for(let O of S)if(!(O.type==="ios_cert"&&x||O.type==="ios_profile"&&B||O.type==="android_keystore"&&Y)&&["ios_cert","ios_profile","android_keystore"].includes(O.type)&&(O.downloadUrl||jt(O)))try{let ye=await No(O,i);if(O.type==="ios_cert"&&!x)a.IOS_DIST_P12=ye,O.password?(a.IOS_P12_PASSWORD=O.password,$.info(v.dim(` - Injected ${O.name} as IOS_DIST_P12 with password from credential record`))):$.info(v.dim(` - Injected ${O.name} as IOS_DIST_P12`)),x=!0;else if(O.type==="ios_profile"&&!B){if(!bc(ye,T)){let Ee=xo(ye)||"unknown";throw new Error(`Provisioning profile ${O.name||jt(O)||"unknown"} is for a different bundle ID. Expected ${T}, found ${Ee}. Upload a ${g} profile for ${T}.`)}a.IOS_PROVISIONING_PROFILE=ye,$.info(v.dim(` - Injected ${O.name} as IOS_PROVISIONING_PROFILE`)),B=!0}else if(O.type==="android_keystore"&&!Y){a.ANDROID_KEYSTORE_BASE64=ye;let Ee=O.keystorePassword||O.password,H=O.keyPassword||O.keystorePassword||O.password,F=O.alias||O.meta?.alias;if(Ee)a.ANDROID_STORE_PASSWORD=Ee,$.info(v.dim(" - Injected keystore password from credential record"));else{let j=["ANDROID_STORE_PASSWORD",...[g==="store"?"PRODUCTION":g==="internal"||g==="adhoc"?"STAGING":"DEVELOPMENT",g.toUpperCase(),"PRODUCTION","STORE","INTERNAL","STAGING","RELEASE","DEBUG"].map(Z=>`KEYSTORE_PASSWORD_${Z}`),"KEYSTORE_PASSWORD"].find(Z=>!!a[Z]);j&&a[j]&&(a.ANDROID_STORE_PASSWORD=a[j])}if(H?(a.ANDROID_KEY_PASSWORD=H,$.info(v.dim(" - Injected key password from credential record"))):a.ANDROID_KEY_PASSWORD=a.ANDROID_STORE_PASSWORD||"",F)a.ANDROID_KEY_ALIAS=F;else{let X=["ANDROID_KEY_ALIAS","KEYSTORE_ALIAS"].find(C=>!!a[C]);X&&(a.ANDROID_KEY_ALIAS=a[X])}$.info(v.dim(` - Injected ${O.name} as ANDROID_KEYSTORE_BASE64`)),Y=!0}}catch(ye){L.push(`${O.name||O.type}: ${ye.message}`)}let J=e.platform==="ios"?e.simulator||x&&B:Y||!S.some(O=>O.type==="android_keystore");if(L.length>0&&!J)throw new Error(`Credential setup failed:
|
|
1302
|
+
${L.map(O=>`- ${O}`).join(`
|
|
1303
|
+
`)}`);L.length>0&&$.warn(v.dim(` Skipped ${L.length} stale or unusable credential(s).`))}if(e.platform==="ios"&&!e.simulator){let A=e.buildProfile||"production",S=nt(d,A)||{},x=cc(d,S),B=fc(x),Y=e.distribution!==void 0?e.distribution==="store":D==="Store",L=x===void 0&&Y,J=e.autoVersion||B&&Y||L,O=e.autoVersion||B&&Y;if(B&&!Y&&$.info(v.dim(` Skipping App Store Connect buildNumber lookup for ${e.distribution||"non-store"} build. Pass --auto-version to force it.`)),J){let q=e.iosBundleIdentifier||d.ios?.bundleIdentifier||d.expo?.ios?.bundleIdentifier,ye=uc(d,S,A),Ee=k.data.credentials||[],H=Ao(Ee,q);if(!H&&(O||L)){let F=await P.get(`/credentials/${i}`);H=Ao(F.data.credentials||[],q)}if(H){t.start("Resolving latest iOS buildNumber from App Store Connect...");try{let F=H.keyId||H.meta?.keyId,X=H.issuerId||H.meta?.issuerId;if(!F||!X)throw new Error("App Store Connect credential is missing keyId or issuerId.");let C=await bo(H,i),j=await Rr({keyId:F,issuerId:X,privateKey:C,ascAppId:ye,bundleId:q}),Z=/^\d+$/.test(j.latestBuildNumber);Z?(a.BUILD_NUMBER=j.nextBuildNumber,delete a.MACH_IOS_BUILD_NUMBER_LOCKED):(a.BUILD_NUMBER=j.nextBuildNumber,a.CURRENT_PROJECT_VERSION=j.nextBuildNumber,a.MACH_IOS_BUILD_NUMBER_LOCKED="1"),t.stop(Z?`\u2713 Latest iOS buildNumber on App Store Connect: ${v.green(j.latestBuildNumber)} (Mach will assign >= ${j.nextBuildNumber})`:`\u2713 Resolved iOS buildNumber: ${v.green(j.nextBuildNumber)} (Latest on App Store Connect: ${j.latestBuildNumber})`)}catch(F){t.stop("iOS buildNumber lookup failed");let X=F.response?.data?.error?.message||F.message;if(O)throw new Error(`Auto-versioning failed: ${X}. Fix App Store Connect API key permissions or remove ios.buildNumber="auto".`);$.warn(v.yellow(`Could not check App Store Connect buildNumber: ${X}. Falling back to Mach counter.`))}}else if(O)throw new Error(`Auto-versioning failed: App Store Connect API key not found. Upload it with '${m.nameLower} credentials:service --platform ios'.`)}}if(e.platform==="android"){let A=e.buildProfile||"production",S=nt(d,A)||{},Y=((S.android||{}).versionCode??S.androidVersionCode??d.android?.versionCode??d.expo?.android?.versionCode)==="auto",L=e.distribution!==void 0?e.distribution==="store":D==="Store",J=e.autoVersion||Y&&L;if(Y&&!J&&$.info(v.dim(` Skipping Google Play versionCode lookup for ${e.distribution||"non-store"} build. Pass --auto-version to force it.`)),J){t.start("Resolving latest versionCode from Google Play...");try{let O=e.androidPackage||d.android?.package||d.expo?.android?.package||d.name,q=(k.data.credentials||[]).find(X=>X.type==="google_service_account"&&(!X.bundleId||X.bundleId===O));if(!q){let C=((await P.get(`/credentials/${i}`)).data.credentials||[]).filter(j=>j.type==="google_service_account");if(q=C.find(j=>j.type==="google_service_account"&&j.bundleId===O),!q&&C.length>0){let j=C.map(Z=>Z.bundleId).filter(Boolean).join(", ");throw new Error(`Google Service Account not found for package ${O}. Found service credential(s) for: ${j}.`)}}if(!q)throw new Error(`Google Service Account not found for package ${O}. Upload it under this package in Dashboard or run '${m.nameLower} credentials:service --platform android --package-name ${O}'.`);let ye=await bo(q,i),Ee=lc(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 H=await Ar(O,Ee);if(H==null)throw new Error("Could not retrieve any version information from Google Play.");let F=H+1;a.ANDROID_VERSION_CODE=F.toString(),t.stop(`\u2713 Resolved versionCode: ${v.green(F)} (Latest on Play Store: ${H})`)}catch(O){t.stop("Version resolution failed");let q=O.response?.data?.error?.message||O.message,ye=dc(q)?"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: ${q}. ${ye}`)}}}if(e.platform==="ios"&&!e.simulator){let A=!!a.IOS_DIST_P12,S=!!a.IOS_PROVISIONING_PROFILE;if(!A||!S){let x=[...A?[]:["Distribution Certificate"],...S?[]:["Provisioning Profile"]].join(" and ");if(e.local&&e.buildId)throw new Error(`Missing iOS credentials: ${x}. Expected ${g} credentials for ${T||"the selected bundle ID"}. Run \`${m.nameLower} credentials --platform ios --profile ${h}\` and select ${T||"the correct bundle ID"}.`);$.error(v.red(`Missing iOS credentials: ${x}`)),e.quiet&&process.exit(1);let B=e.yes||await po({message:"Would you like to generate these credentials now?",initialValue:!0});if(B&&!En(B))return await Tt({platform:"ios",profile:h}),e.quiet||$.info(v.green("\u2713 Credentials setup complete! Restarting build phase...")),In(e);e.quiet||$.info(v.yellow(`Run \`${m.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(v.red("Missing Android credentials: Signing Keystore")),e.quiet&&process.exit(1);let S=e.yes||await po({message:"Would you like to automatically create and upload an Android Keystore for this profile now?",initialValue:!0});if(S&&!En(S))return await Tt({platform:"android",profile:h}),e.quiet||$.info(v.green("\u2713 Android Keystore setup complete! Restarting build phase...")),In(e);e.quiet||$.info(v.yellow(`Run \`${m.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(v.red(g.message)),process.exit(1)),e.platform==="ios"&&e.local&&e.buildId&&($.error(v.red(`Failed to resolve iOS credentials: ${g.message}`)),process.exit(1)),$.warn(`Failed to resolve credentials: ${g.message}`)}}let K=!!(e.local&&e.buildId),b=!!(e.local||e.sshHost),W=!b&&!K;if(K){$.info(v.magenta("\u{1F3D7}\uFE0F Runner Mode: Executing isolated build task..."));let g=await ri({...e,interactive:!1},n,a,i,{branch:f,version:p,summary:R,buildType:D});await ne(g),process.exit(0)}async function ne(g){let T=async w=>{if(i)try{await yn("Report failed build status",()=>P.patch(`/builds/${i}/${n}`,{status:"failed",error:w,endTime:Date.now()}),3)}catch(k){$.warn(v.yellow(`Could not report failed build status: ${k.message}`))}};if(i&&g.length>0){let w=Di(),k=[];e.quiet||w.start("Uploading artifacts to Dashboard...");try{for(let A of g){let S=ve.basename(A),x=de.statSync(A).size,B=ve.extname(S).toLowerCase(),Y="application/octet-stream",L=await yn(`Create artifact upload URL for ${S}`,()=>P.post(`/builds/${i}/${n}/artifact-upload-url`,{fileName:S,fileType:Y}));if(L.data.status!=="success")throw new Error(`Failed to get upload URL for ${S}`);await oc(A,L.data.uploadUrl,Y),k.push({name:S,url:L.data.downloadUrl,size:x,type:B.substring(1)})}e.quiet||w.stop("Artifacts uploaded.")}catch(A){e.quiet||w.stop("Failed to upload artifacts.");let S=`Artifact upload failed: ${A.message}`;throw $.error(v.red(S)),await T(S),new Error(S)}if(i&&k.length>0)try{$.info(v.cyan(`
|
|
1304
|
+
\u{1F517} Download Links:`));for(let A of k)$.info(v.dim(` - ${A.name}: `)+v.blue.underline(A.url));await yn("Finalize build in dashboard",()=>P.patch(`/builds/${i}/${n}`,{status:"success",artifacts:k,endTime:Date.now()})),wn(e,{status:"success",projectId:i,buildId:n,platform:e.platform,profile:h,branch:f,version:p,buildType:D,developmentClient:!!e.developmentClient,summary:R,artifacts:k}),$.success(v.green(`
|
|
1305
|
+
\u2713 Build completed and reported to dashboard.`)),e.maestro&&!K&&await vo(i,n,e,h),e.autoSubmit&&!K&&await Pi(i,n,e,h)}catch(A){let S=`Build artifact uploaded but dashboard finalization failed: ${A.message}`;throw $.error(v.red(`
|
|
1306
|
+
${S}`)),await T(S),new Error(S)}}else if(i){let w="Build completed but produced no uploadable artifacts.";throw $.error(v.red(w)),await T(w),new Error(w)}}if(b){if($.info(v.cyan(`\u{1F680} Direct Build Mode: Executing on ${e.sshHost||"local"}...`)),i&&!o){let g=process.argv.slice(3).join(" ");await P.post("/builds",{projectId:i,buildId:n,platform:e.platform,status:"building",branch:f,version:p,summary:R,startTime:r,buildType:D,buildProfile:h,buildArgs:g,simulator:!!e.simulator,developmentClient:!!e.developmentClient,...Ro(e,n,h,u)}),Po(e)}if(e.sshHost&&e.platform==="ios")await br(e,n,a,i),e.autoSubmit&&await Pi(i,n,e,h);else{let g=await ri({...e,interactive:!!e.local},n,a,i,{branch:f,version:p,summary:R,buildType:D});await ne(g)}return}if(W&&($.info(v.blue("\u{1F6F0}\uFE0F Cloud Initiator Mode: Preparing orchestration...")),!e.dryRun)){e.quiet||t.start("Zipping and uploading local source...");let g=await P.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 ho,w=de.readdirSync("."),k=["node_modules",".git","dist","build","builds",".gradle",".idea","android/build","ios/build","ios/Pods",`.${m.nameLower}_cli`];for(let x of w){if(k.includes(x))continue;de.statSync(x).isDirectory()?T.addLocalFolder(x,x):T.addLocalFile(x)}let A=T.toBuffer();e.quiet||t.message(`Uploading source (${(A.length/1024/1024).toFixed(1)} MB)...`);let S=!1;for(let x=1;x<=3;x++)try{await bn.put(g.data.uploadUrl,A,{headers:{"Content-Type":"application/zip"},maxBodyLength:1/0,maxContentLength:1/0,timeout:12e4}),S=!0;break}catch(B){if(x<3)t.message(`Upload attempt ${x} failed (${B.code||B.message}), retrying...`),await new Promise(Y=>setTimeout(Y,2e3*x));else throw B}if(e.quiet||t.stop("Source uploaded"),i){let x=process.argv.slice(3).join(" ");await P.post("/builds",{projectId:i,buildId:n,platform:e.platform,status:"pending",branch:f,version:p,summary:R,startTime:r,buildType:D,buildProfile:h,buildArgs:x,simulator:!!e.simulator,developmentClient:!!e.developmentClient,...Ro(e,n,h,u)}),$.info(v.green("\u2713 Cloud build registered.")),Po(e)}e.platform==="android"&&await hr(e,n,a,i,e.preBuild),e.quiet||$.info(v.cyan("\u{1F4E1} Connecting to build stream...")),await Ic(i,n,e),e.maestro&&await vo(i,n,e,h),e.autoSubmit&&await Pi(i,n,e,h);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(v.red(`\u2717 Build failed: ${a}`)),process.exit(1)}};async function vo(e,t,n,i){$.info(v.cyan(`
|
|
1307
|
+
\u{1F3BC} Queuing managed Maestro test...`)),await fi({projectId:e,buildId:t,platform:n.platform,profile:i,maestroFlows:n.maestroFlows,maestroDevice:n.maestroDevice,maestroRetries:n.maestroRetries,maestroRecord:n.maestroRecord,maestroUseBuildSource:n.maestroUseBuildSource,maestroEnv:n.maestroEnv,quiet:n.quiet})}async function Pi(e,t,n,i){if(!e){$.error(v.red("Auto-submit requires a linked Mach project. Run `mach link` or pass --project-id.")),process.exitCode=1;return}$.info(v.cyan(`
|
|
1308
|
+
Auto-submit: submitting the successful build...`));try{let r=await Ec(e,t);if(r?.autoSubmit){let o=r.submissionId?`${We}/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(v.green(`Auto-submit is already queued by Mach backend: ${r.submissionId}`)),$.info(v.dim(`Dashboard: ${o}`))):r.autoSubmitStatus==="failed"?$.warn(v.yellow(`Backend auto-submit failed: ${r.autoSubmitError||"Unknown error"}`)):a&&$.info(v.green("Auto-submit is registered with Mach backend; skipping local duplicate submit.")),a){ot(n,{status:r.autoSubmitStatus||"pending",projectId:e,submitId:r.submissionId,platform:n.platform,profile:i,buildId:t,dashboardUrl:o});return}}await hn({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:Lo(n,t,i)})}catch(r){$.error(v.red(`Auto-submit failed: ${r.message||r}`)),process.exitCode=1}}function Lo(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 Ec(e,t){try{let i=(await P.get(`/builds/${e}/${t}`)).data?.build;if(i?.autoSubmit)return i}catch(n){$.warn(v.dim(`Could not check backend auto-submit status: ${n.message}`))}return null}function Mo(e){for(let t of Object.keys(e))e[t]===void 0&&delete e[t];return e}function Ac(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 Mo({track:o,releaseStatus:s,rollout:l,changesNotSentForReview:a===void 0?!1:a===!0||a==="true"||a==="1"})}function Ro(e,t,n,i){if(!e.autoSubmit||e.dryRun)return{};let r=e.platform==="android"?Ac(e,n,i):{};return{autoSubmit:!0,autoSubmitStatus:"pending",autoSubmitOptions:Mo({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:Lo(e,t,n)})}}function Po(e){!e.autoSubmit||e.dryRun||e.quiet||($.info(v.green("\u2713 Auto-submit has been registered with the build.")),$.info(v.dim(" You can close this terminal; submission will start after build success.")))}function Do(e){return`${We}/build/${e}`}function wn(e,t){if(!e.jsonOutput)return;let n=ve.resolve(e.jsonOutput),i={...t,url:t.url||Do(t.buildId),dashboardUrl:t.dashboardUrl||Do(t.buildId),updatedAt:new Date().toISOString()};try{let r=ve.dirname(n);r&&r!=="."&&de.mkdirSync(r,{recursive:!0}),de.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){$.warn(v.yellow(`Could not write build metadata JSON: ${r.message}`))}}async function Ic(e,t,n){let i=Di(),r="pending",o=0,s=0;for(n.quiet||i.start("Connecting to build stream...");;){try{let a=(await P.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."),wn(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(v.red(`
|
|
1309
|
+
\u2717 Build failed: ${a.error||"Unknown error"}`)),process.exit(1);else if(r==="completed"||r==="success"){n.quiet||i.stop("Build successful!"),wn(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(v.green(`
|
|
1310
|
+
\u2713 Build completed successfully!`));try{n.quiet||($.info(v.magenta(`
|
|
1311
|
+
\u{1F4F1} Installation Hub:`)),$.info(v.dim(" - View & Install Build: ")+v.white.underline(`${We}/build/${t}`)))}catch{}return}else if(r!=="pending"){n.quiet||i.stop(`Build status: ${r}`);return}}try{let u=(await P.get(`/builds/${e}/${t}/logs`)).data;if(u&&typeof u=="string"&&!n.quiet){let d=u.split(`
|
|
1312
|
+
`);if(d.length>o){for(let f=o;f<d.length;f++)d[f].trim()&&console.log(v.dim(` ${d[f]}`));o=d.length}}}catch{}s=0}catch{s++,s>10&&(i.stop("Connection lost."),$.error(v.red(`
|
|
1313
|
+
\u2717 Lost connection to Dashboard API.`)),process.exit(1))}await new Promise(l=>setTimeout(l,3e3))}}import*as Pn from"http";import*as jo from"net";import{execFile as wc,execFileSync as Dn,execSync as yt,spawn as Uo}from"child_process";import ce from"chalk";import{log as Q}from"@clack/prompts";import _c from"axios";import pe from"fs";import je from"os";import ie from"path";var et=7070,Kt=`http://127.0.0.1:${et}`,vt="com.radhya.mach.agent",$t="Mach Agent",Rt=`${vt}.service`,$c=5e3,vc=3e3,_n=null,$n=null,Ge=()=>ie.join(je.homedir(),m.configDir),Go=()=>ie.join(je.homedir(),"Library","LaunchAgents"),vn=()=>ie.join(Go(),`${vt}.plist`),Ko=()=>ie.join(je.homedir(),".config","systemd","user"),Ci=()=>ie.join(Ko(),Rt),Ni=()=>ie.join(Ge(),"agent.cmd");function Ti(){return`gui/${process.getuid?.()||Number(yt("id -u").toString().trim())}`}function Vo(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Gt(e){return`<string>${Vo(e)}</string>`}function ki(){let e=process.argv[1]?pe.realpathSync(process.argv[1]):"";if(!e||!pe.existsSync(e))throw new Error("Could not resolve the current Mach CLI entrypoint.");return[process.execPath,e,"agent","run"]}function xi(){let e=zo(),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:je.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 zo(){let e=[process.env.ANDROID_HOME,process.env.ANDROID_SDK_ROOT];if(process.platform==="darwin")e.push(ie.join(je.homedir(),"Library","Android","sdk"));else if(process.platform==="linux")e.push(ie.join(je.homedir(),"Android","Sdk"),ie.join(je.homedir(),"Android","sdk"),"/opt/android-sdk","/usr/lib/android-sdk");else if(process.platform==="win32"){let t=process.env.LOCALAPPDATA,n=process.env.USERPROFILE||je.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 Rc(e){return process.platform==="win32"&&!e.toLowerCase().endsWith(".exe")?`${e}.exe`:e}function Wo(e,t){let n=Rc(e);for(let i of zo()){let r=ie.join(i,t,n);if(pe.existsSync(r))return r}return n}function Yo(){return Wo("adb","platform-tools")}function Jo(){return Wo("emulator","emulator")}function Oi(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}"`}function Pc(){if(process.platform!=="linux")throw new Error("Linux service install requires Linux.");pe.mkdirSync(Ge(),{recursive:!0}),pe.mkdirSync(Ko(),{recursive:!0});let e=ki(),t=xi(),n=Object.entries(t).map(([r,o])=>`Environment=${Oi(`${r}=${o}`)}`).join(`
|
|
1302
1314
|
`),i=`[Unit]
|
|
1303
1315
|
Description=Mach local device agent
|
|
1304
1316
|
After=default.target
|
|
1305
1317
|
|
|
1306
1318
|
[Service]
|
|
1307
1319
|
Type=simple
|
|
1308
|
-
ExecStart=${e.map(
|
|
1309
|
-
WorkingDirectory=${
|
|
1320
|
+
ExecStart=${e.map(Oi).join(" ")}
|
|
1321
|
+
WorkingDirectory=${Oi(je.homedir())}
|
|
1310
1322
|
${n}
|
|
1311
1323
|
Restart=on-failure
|
|
1312
1324
|
RestartSec=5
|
|
@@ -1315,20 +1327,20 @@ StandardError=append:%h/${m.configDir}/agent.error.log
|
|
|
1315
1327
|
|
|
1316
1328
|
[Install]
|
|
1317
1329
|
WantedBy=default.target
|
|
1318
|
-
`;return pe.writeFileSync(
|
|
1319
|
-
`),l=i.map(
|
|
1330
|
+
`;return pe.writeFileSync(Ci(),i),Ci()}function lt(e,t={}){try{return Dn("systemctl",["--user",...e],{stdio:t.ignoreError?"ignore":"pipe"}),!0}catch(n){if(t.ignoreError)return!1;throw n}}function Dc(){if(process.platform!=="win32")throw new Error("Windows agent script requires Windows.");pe.mkdirSync(Ge(),{recursive:!0});let e=xi(),[t,n,...i]=ki(),r=ie.join(Ge(),"agent.log"),o=ie.join(Ge(),"agent.error.log"),s=Object.entries(e).map(([c,u])=>`set "${c}=${u}"`).join(`\r
|
|
1331
|
+
`),l=i.map(c=>`"${c.replace(/"/g,'\\"')}"`).join(" "),a=`@echo off\r
|
|
1320
1332
|
${s}\r
|
|
1321
|
-
cd /d "${
|
|
1333
|
+
cd /d "${je.homedir()}"\r
|
|
1322
1334
|
"${t}" "${n}" ${l} >> "${r}" 2>> "${o}"\r
|
|
1323
|
-
`;return pe.writeFileSync(
|
|
1324
|
-
${
|
|
1325
|
-
`),o=e.map(l=>` ${
|
|
1335
|
+
`;return pe.writeFileSync(Ni(),a),Ni()}function Vt(e,t={}){try{return Dn("schtasks.exe",e,{stdio:t.ignoreError?"ignore":"pipe"}),!0}catch(n){if(t.ignoreError)return!1;throw n}}function Oc(){if(process.platform!=="darwin")throw new Error("Background agent install currently supports macOS only.");pe.mkdirSync(Ge(),{recursive:!0}),pe.mkdirSync(Go(),{recursive:!0});let e=ki(),t=xi(),n=ie.join(Ge(),"agent.log"),i=ie.join(Ge(),"agent.error.log"),r=Object.entries(t).map(([l,a])=>` <key>${Vo(l)}</key>
|
|
1336
|
+
${Gt(a)}`).join(`
|
|
1337
|
+
`),o=e.map(l=>` ${Gt(l)}`).join(`
|
|
1326
1338
|
`),s=`<?xml version="1.0" encoding="UTF-8"?>
|
|
1327
1339
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
1328
1340
|
<plist version="1.0">
|
|
1329
1341
|
<dict>
|
|
1330
1342
|
<key>Label</key>
|
|
1331
|
-
${
|
|
1343
|
+
${Gt(vt)}
|
|
1332
1344
|
<key>ProgramArguments</key>
|
|
1333
1345
|
<array>
|
|
1334
1346
|
${o}
|
|
@@ -1340,28 +1352,28 @@ ${r}
|
|
|
1340
1352
|
<key>RunAtLoad</key>
|
|
1341
1353
|
<true/>
|
|
1342
1354
|
<key>StandardOutPath</key>
|
|
1343
|
-
${
|
|
1355
|
+
${Gt(n)}
|
|
1344
1356
|
<key>StandardErrorPath</key>
|
|
1345
|
-
${
|
|
1357
|
+
${Gt(i)}
|
|
1346
1358
|
</dict>
|
|
1347
1359
|
</plist>
|
|
1348
|
-
`;return pe.writeFileSync(
|
|
1349
|
-
`).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
|
|
1350
|
-
`).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 Lc(){if(process.platform!=="darwin")return[];try{let e=await vn("/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 xc(){if(process.platform!=="darwin")return[];try{let e=await vn("/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 Mc(){let[e,t,n]=await Promise.all([kc(),Lc(),xc()]);return[...e,...t,...n]}async function Uc(){let e=Date.now();return wn&&e-wn.updatedAt<Sc?wn.targets:(_n||(_n=Mc().then(t=>(wn={targets:t,updatedAt:Date.now()},t)).finally(()=>{_n=null})),_n)}async function Uo(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 Bc(e,t){let n=await hc({method:"GET",url:e,responseType:"stream",timeout:12e4}),i=pe.createWriteStream(t);n.data.pipe(i),await new Promise((r,o)=>{i.on("finish",r),i.on("error",o)})}async function Fc(e,t,n){let i=n||(t.toLowerCase().includes(".apk")?"android":"ios"),r=t.toLowerCase().includes(".ipa"),o=pe.mkdtempSync(ie.join(He.tmpdir(),`${Ze}-install-`)),s=ie.join(o,i==="android"?"install.apk":r?"install.ipa":"install.zip");try{if(await Bc(t,s),i==="android"){Pn(Vo(),["-s",e,"install","-r",s],{stdio:"pipe"});return}if(process.platform!=="darwin")throw new Error("iOS local install requires macOS.");yt(`unzip -o ${JSON.stringify(s)} -d ${JSON.stringify(o)}`,{stdio:"pipe"});let l="";try{l=yt(`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=yt(`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{yt(`/usr/bin/xcrun devicectl device install app --device ${JSON.stringify(e)} ${JSON.stringify(l)}`,{stdio:"pipe"})}catch(a){try{yt(`/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{pe.rmSync(o,{recursive:!0,force:!0})}}function Hc(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 yt(`/usr/bin/xcrun simctl boot ${JSON.stringify(e)}`,{stdio:"pipe"}),Lo("open",["-a","Simulator"],{detached:!0,stdio:"ignore"}).unref(),"Simulator booting..."}if(t==="android")return Lo(zo(),["-avd",e],{detached:!0,stdio:"ignore",windowsHide:!0}).unref(),"Emulator booting in background...";throw new Error("Invalid platform.")}async function jc(){process.platform!=="darwin"&&Q.warn("Running on non-macOS \u2014 iOS discovery unavailable, Android only.");let e=Rn.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:${Ze}`);if(i.method==="GET"&&o.pathname==="/local/devices"){Uc().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:Ze,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 Uo(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 Fc(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 Uo(i),l=Hc(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(Ze,"127.0.0.1",()=>{Q.success(ce.green(`Local device agent running on http://localhost:${Ze}`)),Q.info(ce.dim("Keep this running while using the Install Hub on the dashboard.")),Q.info(ce.dim("Press Ctrl+C to stop."))}),e.on("error",i=>{i.code==="EADDRINUSE"?Q.error(`Port ${Ze} is already in use \u2014 agent may already be running.`):Q.error(`Agent error: ${i.message}`),process.exit(1)}),await new Promise(()=>{})}async function Xo(e="start"){let t=String(e||"start").toLowerCase();if(t==="start"||t==="run"){await jc();return}if(t==="install"){await xo();return}if(t==="status"){await Tc();return}if(t==="stop"){await Mo();return}if(t==="uninstall"){await Nc();return}if(t==="restart"){await Mo(),await xo();return}Q.error(`Unknown agent action: ${e}`),Q.info(ce.dim(`Use: ${m.nameLower} agent start | install | status | restart | stop | uninstall`)),process.exit(1)}import{createRequire as bf}from"module";import{text as Kc,password as Vc,spinner as zc,isCancel as es}from"@clack/prompts";import Bi from"chalk";import Vt from"fs";import Zo from"path";import Gc from"os";var xi=Zo.join(Gc.homedir(),m.configDir),Mi=Zo.join(xi,"config.json");function Ui(){if(!Vt.existsSync(Mi))return{};try{return JSON.parse(Vt.readFileSync(Mi,"utf-8"))}catch{return{}}}function Qo(e){Vt.existsSync(xi)||Vt.mkdirSync(xi,{recursive:!0});let n={...Ui(),...e};Vt.writeFileSync(Mi,JSON.stringify(n,null,2))}async function ts(){let e=Ui(),t=await Kc({message:"Enter your email:",placeholder:"user@example.com",initialValue:e.lastLoginEmail,validate(r){if(r.length===0)return"Email is required!"}});if(es(t))return;let n=await Vc({message:"Enter your password:",validate(r){if(r.length===0)return"Password is required!"}});if(es(n))return;let i=zc();i.start("Authenticating...");try{let o=await(await fetch(`${bt}/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:t,password:n})})).json();o.status==="success"&&o.user.token?(Xi({id:o.user.id,email:t,token:o.user.token,refreshToken:o.user.refreshToken}),Qo({lastLoginEmail:t}),i.stop(Bi.green("Login successful!"))):i.stop(Bi.red("Login failed: "+(o.message||"Unknown error")))}catch(r){i.stop(Bi.red("Network error: "+r.message))}}import{log as Dn,outro as Wc}from"@clack/prompts";import zt from"chalk";async function ns(){let e=Zi(),t=`${m.envPrefix}TOKEN`;e?Dn.success(zt.green(`Logged out. Removed saved credentials from ~/${m.configDir}/credentials.json.`)):Dn.warn(zt.yellow(`No saved ${m.name} credentials found.`)),process.env[t]&&(Dn.warn(zt.yellow(`${t} is still set in this shell. Commands will continue to authenticate with that token until you unset it.`)),Dn.info(zt.dim(`Run: unset ${t}`))),Wc(zt.blue("---"))}import{outro as Yc,select as Jc,spinner as qc,isCancel as Xc}from"@clack/prompts";import On from"chalk";import Fi from"fs";import Zc from"path";var is=e=>e==="1234567890"||e==="ABC123DEFG"||e==="XXXXXXXXXX"?"":typeof e=="string"?e:"",Qc=()=>process.versions.node.split(".")[0]||"24";async function rs(){if(!Pe()){console.log(On.red(`You are not logged in. Run \`${m.nameLower} login\` first.`));return}let t=qc();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(On.yellow(`No projects found. Run \`${m.nameLower} init\` to create one.`));return}let i=n.projects.map(h=>({value:h.projectId,label:`${h.name} (${h.slug})`})),r=await Jc({message:"Select a project to link:",options:i});if(Xc(r))return;let o=Zc.join(process.cwd(),m.configFileName),s={};if(Fi.existsSync(o))try{s=JSON.parse(Fi.readFileSync(o,"utf-8"))}catch{}let l=n.projects.find(h=>h.projectId===r),a=s.android?.package||Xe("android"),d=s.ios?.bundleIdentifier||Xe("ios"),c=s.android||{},u=s.submit?.production?.android||{},f=s.submit?.production?.ios||{},p={projectId:r,name:l?.name,slug:l?.slug,nodeVersion:s.nodeVersion||Qc(),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:is(f.ascAppId),appleTeamId:is(f.appleTeamId)}}}};Fi.writeFileSync(o,JSON.stringify(p,null,2)),Yc(On.green(`Linked to project ${p.name} (${p.slug})`))}catch(n){t.stop(On.red("Error fetching projects: "+n.message))}}import{outro as eu,text as Cn,select as tu,spinner as nu,isCancel as Wt}from"@clack/prompts";import Yt from"chalk";import iu from"fs";import ru from"path";import{randomUUID as ou}from"crypto";var su=()=>process.versions.node.split(".")[0]||"24";async function os(){if(!Pe()){console.log(Yt.red(`You are not logged in. Run \`${m.nameLower} login\` first.`));return}let t=await Cn({message:"Project Name:",placeholder:"My Awesome App",validate(l){if(l.length===0)return"Name is required!"}});if(Wt(t))return;let n=await Cn({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(Wt(n))return;let i=await tu({message:"Platform:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"},{value:"web",label:"Web"},{value:"all",label:"All Platforms"}]});if(Wt(i))return;let r="";if(i==="android"||i==="all"){let l=Xe("android");if(r=await Cn({message:"Android Package Name:",initialValue:l||"",placeholder:"com.example.app",validate(a){if(a.length===0)return"Package name is required for Android!"}}),Wt(r))return}let o="";if(i==="ios"||i==="all"){let l=Xe("ios");if(o=await Cn({message:"iOS Bundle Identifier:",initialValue:l||"",placeholder:"com.example.app",validate(a){if(a.length===0)return"Bundle ID is required for iOS!"}}),Wt(o))return}let s=nu();s.start("Creating project...");try{let l=ou(),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(Yt.green("Project created successfully!"));let u=ru.join(process.cwd(),m.configFileName);iu.writeFileSync(u,JSON.stringify({projectId:l,name:t,slug:n,nodeVersion:su(),...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)),eu(Yt.green(`Initialized project ${t} and linked locally!`))}else s.stop(Yt.red("creation failed: "+c.message))}catch(l){s.stop(Yt.red("Network error: "+l.message))}}import{spinner as Hi,log as Re}from"@clack/prompts";import Jt from"chalk";import Nn from"fs";import ss from"path";function ji(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"}`}function au(e){let t=String(e??"");return t===""?'""':/^[A-Za-z0-9_./:@%+-]+$/.test(t)?t:JSON.stringify(t)}function lu(e,t){return`${[`# Generated by ${m.nameLower} env pull --environment ${t}`,"# Do not commit this file.","",...Object.keys(e).sort((i,r)=>i.localeCompare(r)).map(i=>`${i}=${au(e[i])}`)].join(`
|
|
1360
|
+
`;return pe.writeFileSync(vn(),s),vn()}function at(e,t={}){try{return Dn("launchctl",e,{stdio:t.ignoreError?"ignore":"pipe"}),!0}catch(n){if(t.ignoreError)return!1;throw n}}function Cc(e){return new Promise(t=>setTimeout(t,e))}function Rn(e,t,n=$c){return new Promise((i,r)=>{wc(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 qo(){if(typeof fetch=="function"){let e=new AbortController,t=setTimeout(()=>e.abort(),3e3);try{return(await fetch(`${Kt}/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=Pn.get(`${Kt}/health`,r=>{r.resume(),n(r.statusCode===200)});i.setTimeout(3e3,()=>{i.destroy(),n(!1)}),i.on("error",()=>n(!1))})}async function Nc(e=8e3){let t=Date.now()+e;for(;Date.now()<t;){if(await qo())return!0;await Cc(250)}return!1}async function Xo(){return new Promise(e=>{let t=!1,n=jo.createConnection({host:"127.0.0.1",port:et}),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 Li(){if(await Nc()){Q.success(ce.green("Mach agent installed and started."));return}if(await Xo()){Q.warn(`Mach agent service is installed, but port ${et} is held by a process that is not answering /health.`),Q.info(ce.dim(`Run \`${m.nameLower} agent stop\`, close any foreground \`${m.nameLower} agent\` terminal, then run \`${m.nameLower} agent install\` again.`));return}Q.warn(`Mach agent service is installed, but it did not start listening on ${Kt}.`)}async function Tc(){let e=Oc(),t=Ti();at(["bootout",t,e],{ignoreError:!0}),at(["bootstrap",t,e],{ignoreError:!0})||at(["load","-w",e]),at(["enable",`${t}/${vt}`],{ignoreError:!0}),at(["kickstart","-k",`${t}/${vt}`],{ignoreError:!0}),await Li(),Q.info(ce.dim(`It will start automatically when you log in. Plist: ${e}`)),Q.info(ce.dim(`Logs: ${ie.join(Ge(),"agent.log")}`))}async function Zo(){let e=vn(),t=Ti();at(["bootout",t,e],{ignoreError:!0})||at(["unload","-w",e],{ignoreError:!0})?Q.success(ce.green("Mach agent service stopped.")):Q.warn("Mach agent service was not loaded.")}async function kc(){await Zo();let e=vn();pe.existsSync(e)&&pe.unlinkSync(e),Q.success(ce.green("Mach agent service uninstalled."))}async function xc(){let e=Pc();lt(["daemon-reload"]),lt(["enable","--now",Rt]),await Li(),Q.info(ce.dim(`It will start automatically when you log in. Service: ${e}`)),Q.info(ce.dim(`Logs: ${ie.join(Ge(),"agent.log")}`))}async function Lc(){lt(["stop",Rt],{ignoreError:!0})?Q.success(ce.green("Mach agent service stopped.")):Q.warn("Mach agent service was not running.")}async function Mc(){lt(["disable","--now",Rt],{ignoreError:!0}),lt(["daemon-reload"],{ignoreError:!0});let e=Ci();pe.existsSync(e)&&pe.unlinkSync(e),lt(["daemon-reload"],{ignoreError:!0}),Q.success(ce.green("Mach agent service uninstalled."))}async function Uc(){let e=Dc();Vt(["/Create","/TN",$t,"/SC","ONLOGON","/TR",`"${e}"`,"/RL","LIMITED","/F"]),Vt(["/Run","/TN",$t],{ignoreError:!0}),await Li(),Q.info(ce.dim(`It will start automatically when you log in. Task: ${$t}`)),Q.info(ce.dim(`Logs: ${ie.join(Ge(),"agent.log")}`))}async function Qo(){Vt(["/End","/TN",$t],{ignoreError:!0})?Q.success(ce.green("Mach agent task stopped.")):Q.warn("Mach agent task was not running.")}async function Bc(){await Qo(),Vt(["/Delete","/TN",$t,"/F"],{ignoreError:!0});let e=Ni();pe.existsSync(e)&&pe.unlinkSync(e),Q.success(ce.green("Mach agent task uninstalled."))}async function Bo(){if(process.platform==="darwin")return Tc();if(process.platform==="linux")return xc();if(process.platform==="win32")return Uc();throw new Error(`Background agent install is not supported on ${process.platform}.`)}async function Fo(){if(process.platform==="darwin")return Zo();if(process.platform==="linux")return Lc();if(process.platform==="win32")return Qo();Q.warn(`Background agent service control is not supported on ${process.platform}.`)}async function Fc(){if(process.platform==="darwin")return kc();if(process.platform==="linux")return Mc();if(process.platform==="win32")return Bc();Q.warn(`Background agent uninstall is not supported on ${process.platform}.`)}async function Hc(){let e=await qo(),t=e?!0:await Xo();if(e?Q.success(ce.green(`Mach agent is online at ${Kt}`)):t?Q.warn(`Mach agent port is open, but /health did not respond. Run \`${m.nameLower} agent restart\` if the dashboard still shows offline.`):Q.warn(`Mach agent is not responding at ${Kt}`),process.platform==="darwin"){let n=at(["print",`${Ti()}/${vt}`],{ignoreError:!0});Q.info(ce.dim(`Login service: ${n?"installed/loaded":"not loaded"}`))}else if(process.platform==="linux"){let n=lt(["is-enabled",Rt],{ignoreError:!0}),i=lt(["is-active",Rt],{ignoreError:!0});Q.info(ce.dim(`Login service: ${n?"enabled":"not enabled"} / ${i?"active":"inactive"}`))}else if(process.platform==="win32"){let n=Vt(["/Query","/TN",$t],{ignoreError:!0});Q.info(ce.dim(`Login task: ${n?"installed":"not installed"}`))}}async function jc(){let e=[];try{(await Rn(Yo(),["devices","-l"])).split(`
|
|
1361
|
+
`).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 Rn(Jo(),["-list-avds"])).split(`
|
|
1362
|
+
`).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 Gc(){if(process.platform!=="darwin")return[];try{let e=await Rn("/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 Kc(){if(process.platform!=="darwin")return[];try{let e=await Rn("/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 Vc(){let[e,t,n]=await Promise.all([jc(),Gc(),Kc()]);return[...e,...t,...n]}async function zc(){let e=Date.now();return _n&&e-_n.updatedAt<vc?_n.targets:($n||($n=Vc().then(t=>(_n={targets:t,updatedAt:Date.now()},t)).finally(()=>{$n=null})),$n)}async function Ho(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 Wc(e,t){let n=await _c({method:"GET",url:e,responseType:"stream",timeout:12e4}),i=pe.createWriteStream(t);n.data.pipe(i),await new Promise((r,o)=>{i.on("finish",r),i.on("error",o)})}async function Yc(e,t,n){let i=n||(t.toLowerCase().includes(".apk")?"android":"ios"),r=t.toLowerCase().includes(".ipa"),o=pe.mkdtempSync(ie.join(je.tmpdir(),`${et}-install-`)),s=ie.join(o,i==="android"?"install.apk":r?"install.ipa":"install.zip");try{if(await Wc(t,s),i==="android"){Dn(Yo(),["-s",e,"install","-r",s],{stdio:"pipe"});return}if(process.platform!=="darwin")throw new Error("iOS local install requires macOS.");yt(`unzip -o ${JSON.stringify(s)} -d ${JSON.stringify(o)}`,{stdio:"pipe"});let l="";try{l=yt(`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=yt(`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{yt(`/usr/bin/xcrun devicectl device install app --device ${JSON.stringify(e)} ${JSON.stringify(l)}`,{stdio:"pipe"})}catch(a){try{yt(`/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{pe.rmSync(o,{recursive:!0,force:!0})}}function Jc(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 yt(`/usr/bin/xcrun simctl boot ${JSON.stringify(e)}`,{stdio:"pipe"}),Uo("open",["-a","Simulator"],{detached:!0,stdio:"ignore"}).unref(),"Simulator booting..."}if(t==="android")return Uo(Jo(),["-avd",e],{detached:!0,stdio:"ignore",windowsHide:!0}).unref(),"Emulator booting in background...";throw new Error("Invalid platform.")}async function qc(){process.platform!=="darwin"&&Q.warn("Running on non-macOS \u2014 iOS discovery unavailable, Android only.");let e=Pn.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:${et}`);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:et,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 Ho(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 Yc(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 Ho(i),l=Jc(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(et,"127.0.0.1",()=>{Q.success(ce.green(`Local device agent running on http://localhost:${et}`)),Q.info(ce.dim("Keep this running while using the Install Hub on the dashboard.")),Q.info(ce.dim("Press Ctrl+C to stop."))}),e.on("error",i=>{i.code==="EADDRINUSE"?Q.error(`Port ${et} is already in use \u2014 agent may already be running.`):Q.error(`Agent error: ${i.message}`),process.exit(1)}),await new Promise(()=>{})}async function es(e="start"){let t=String(e||"start").toLowerCase();if(t==="start"||t==="run"){await qc();return}if(t==="install"){await Bo();return}if(t==="status"){await Hc();return}if(t==="stop"){await Fo();return}if(t==="uninstall"){await Fc();return}if(t==="restart"){await Fo(),await Bo();return}Q.error(`Unknown agent action: ${e}`),Q.info(ce.dim(`Use: ${m.nameLower} agent start | install | status | restart | stop | uninstall`)),process.exit(1)}import{createRequire as Rf}from"module";import{text as Zc,password as Qc,spinner as eu,isCancel as is}from"@clack/prompts";import Fi from"chalk";import zt from"fs";import ts from"path";import Xc from"os";var Mi=ts.join(Xc.homedir(),m.configDir),Ui=ts.join(Mi,"config.json");function Bi(){if(!zt.existsSync(Ui))return{};try{return JSON.parse(zt.readFileSync(Ui,"utf-8"))}catch{return{}}}function ns(e){zt.existsSync(Mi)||zt.mkdirSync(Mi,{recursive:!0});let n={...Bi(),...e};zt.writeFileSync(Ui,JSON.stringify(n,null,2))}async function rs(){let e=Bi(),t=await Zc({message:"Enter your email:",placeholder:"user@example.com",initialValue:e.lastLoginEmail,validate(r){if(r.length===0)return"Email is required!"}});if(is(t))return;let n=await Qc({message:"Enter your password:",validate(r){if(r.length===0)return"Password is required!"}});if(is(n))return;let i=eu();i.start("Authenticating...");try{let o=await(await fetch(`${bt}/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:t,password:n})})).json();o.status==="success"&&o.user.token?(Zi({id:o.user.id,email:t,token:o.user.token,refreshToken:o.user.refreshToken}),ns({lastLoginEmail:t}),i.stop(Fi.green("Login successful!"))):i.stop(Fi.red("Login failed: "+(o.message||"Unknown error")))}catch(r){i.stop(Fi.red("Network error: "+r.message))}}import{log as On,outro as tu}from"@clack/prompts";import Wt from"chalk";async function os(){let e=Qi(),t=`${m.envPrefix}TOKEN`;e?On.success(Wt.green(`Logged out. Removed saved credentials from ~/${m.configDir}/credentials.json.`)):On.warn(Wt.yellow(`No saved ${m.name} credentials found.`)),process.env[t]&&(On.warn(Wt.yellow(`${t} is still set in this shell. Commands will continue to authenticate with that token until you unset it.`)),On.info(Wt.dim(`Run: unset ${t}`))),tu(Wt.blue("---"))}import{outro as nu,select as iu,spinner as ru,isCancel as ou}from"@clack/prompts";import Cn from"chalk";import Hi from"fs";import su from"path";var ss=e=>e==="1234567890"||e==="ABC123DEFG"||e==="XXXXXXXXXX"?"":typeof e=="string"?e:"",au=()=>process.versions.node.split(".")[0]||"24";async function as(){if(!Pe()){console.log(Cn.red(`You are not logged in. Run \`${m.nameLower} login\` first.`));return}let t=ru();t.start("Fetching projects...");try{let{data:n}=await P.get("/projects");if(t.stop("Projects loaded."),n.status!=="success"||!n.projects||n.projects.length===0){console.log(Cn.yellow(`No projects found. Run \`${m.nameLower} init\` to create one.`));return}let i=n.projects.map(h=>({value:h.projectId,label:`${h.name} (${h.slug})`})),r=await iu({message:"Select a project to link:",options:i});if(ou(r))return;let o=su.join(process.cwd(),m.configFileName),s={};if(Hi.existsSync(o))try{s=JSON.parse(Hi.readFileSync(o,"utf-8"))}catch{}let l=n.projects.find(h=>h.projectId===r),a=s.android?.package||Ze("android"),c=s.ios?.bundleIdentifier||Ze("ios"),u=s.android||{},d=s.submit?.production?.android||{},f=s.submit?.production?.ios||{},p={projectId:r,name:l?.name,slug:l?.slug,nodeVersion:s.nodeVersion||au(),scheme:l?.slug?.toLowerCase()||"app",android:{...u,package:a||"",versionCode:u.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:{...d,track:d.track||"internal",releaseStatus:d.releaseStatus||"completed"},ios:{ascAppId:ss(f.ascAppId),appleTeamId:ss(f.appleTeamId)}}}};Hi.writeFileSync(o,JSON.stringify(p,null,2)),nu(Cn.green(`Linked to project ${p.name} (${p.slug})`))}catch(n){t.stop(Cn.red("Error fetching projects: "+n.message))}}import{outro as lu,text as Nn,select as du,spinner as cu,isCancel as Yt}from"@clack/prompts";import Jt from"chalk";import uu from"fs";import fu from"path";import{randomUUID as pu}from"crypto";var mu=()=>process.versions.node.split(".")[0]||"24";async function ls(){if(!Pe()){console.log(Jt.red(`You are not logged in. Run \`${m.nameLower} login\` first.`));return}let t=await Nn({message:"Project Name:",placeholder:"My Awesome App",validate(l){if(l.length===0)return"Name is required!"}});if(Yt(t))return;let n=await Nn({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(Yt(n))return;let i=await du({message:"Platform:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"},{value:"web",label:"Web"},{value:"all",label:"All Platforms"}]});if(Yt(i))return;let r="";if(i==="android"||i==="all"){let l=Ze("android");if(r=await Nn({message:"Android Package Name:",initialValue:l||"",placeholder:"com.example.app",validate(a){if(a.length===0)return"Package name is required for Android!"}}),Yt(r))return}let o="";if(i==="ios"||i==="all"){let l=Ze("ios");if(o=await Nn({message:"iOS Bundle Identifier:",initialValue:l||"",placeholder:"com.example.app",validate(a){if(a.length===0)return"Bundle ID is required for iOS!"}}),Yt(o))return}let s=cu();s.start("Creating project...");try{let l=pu(),c={projectId:l,name:t,slug:n,storageType:"managed",platforms:i==="all"?["android","ios","web"]:[i]},{data:u}=await P.post("/projects",c);if(u.status==="success"){s.stop(Jt.green("Project created successfully!"));let d=fu.join(process.cwd(),m.configFileName);uu.writeFileSync(d,JSON.stringify({projectId:l,name:t,slug:n,nodeVersion:mu(),...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)),lu(Jt.green(`Initialized project ${t} and linked locally!`))}else s.stop(Jt.red("creation failed: "+u.message))}catch(l){s.stop(Jt.red("Network error: "+l.message))}}import{spinner as ji,log as Re}from"@clack/prompts";import qt from"chalk";import Tn from"fs";import ds from"path";function Gi(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"}`}function gu(e){let t=String(e??"");return t===""?'""':/^[A-Za-z0-9_./:@%+-]+$/.test(t)?t:JSON.stringify(t)}function hu(e,t){return`${[`# Generated by ${m.nameLower} env pull --environment ${t}`,"# Do not commit this file.","",...Object.keys(e).sort((i,r)=>i.localeCompare(r)).map(i=>`${i}=${gu(e[i])}`)].join(`
|
|
1351
1363
|
`)}
|
|
1352
|
-
`}async function
|
|
1353
|
-
`))}else
|
|
1354
|
-
Profile Settings:`)),De.info(`${
|
|
1355
|
-
Environment Variables:`)),Object.entries(i.env).forEach(([r,o])=>{De.info(` ${r}=${o}`)}))):De.warn(`Profile '${n}' not found.`),De.info(
|
|
1364
|
+
`}async function cs(e,t,n={}){let i=Pe();if(!i){Re.error(`You are not logged in. Run \`${m.nameLower} login\` first.`);return}let r=ds.join(process.cwd(),m.configFileName);if(!Tn.existsSync(r)){Re.error(`No ${m.configFileName} found. Run \`${m.nameLower} init\` or \`${m.nameLower} link\` first.`);return}let o;try{o=JSON.parse(Tn.readFileSync(r,"utf-8"))}catch{Re.error(`Failed to parse ${m.configFileName}`);return}let{projectId:s}=o;if(!s){Re.error(`${m.configFileName} is missing projectId.`);return}e==="set"?await yu(s,t,i):e==="list"?await Su(s,i):e==="pull"||e==="download"||e==="export"?await bu(s,n):Re.error(`Unknown env action: ${e}. Use 'set', 'list', or 'pull'.`)}async function yu(e,t,n){if(t.length===0){Re.error(`Usage: ${m.nameLower} env set KEY=VALUE [KEY2=VALUE2 ...]`);return}let i=ji();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){Re.warn(`Invalid format for argument: ${s}. Expected KEY=VALUE.`),o++;continue}try{let u={key:l.trim(),value:c,type:"env",environment:"global",visibility:"secret"},{data:d}=await P.post(`/projects/${e}/secrets`,u);d.status==="success"?r++:(Re.error(`Failed to set ${l}: ${d.message}`),o++)}catch(u){Re.error(Gi(u,e,"set",l)),o++}}i.stop(`Set ${r} variable(s). ${o>0?`${o} failed.`:""}`)}async function Su(e,t){let n=ji();n.start("Fetching environment variables...");try{let{data:i}=await P.get(`/projects/${e}/secrets`);if(i.status==="success"){n.stop("Fetched variables.");let r=i.secrets||[];r.length===0?Re.info("No environment variables found for this project."):(Re.info(qt.bold("Environment Variables (Global & Scoped):")),r.forEach(o=>{let s=o.visibility==="plain"?o.value:"********";console.log(` ${qt.cyan(o.key)} = ${s} ${qt.gray(`[${o.environment}]`)}`)}))}else n.stop(qt.red(`Failed to fetch variables: ${i.message}`))}catch(i){n.stop("Failed to fetch variables."),Re.error(Gi(i,e,"list"))}}async function bu(e,t){let n=(t.environment||"development").trim(),i=t.out||".env.local",r=ds.resolve(process.cwd(),i);if(Tn.existsSync(r)&&!t.overwrite){Re.error(`${i} already exists. Re-run with \`--overwrite\` to replace it.`);return}let o=ji();o.start(`Downloading ${n} environment variables...`);try{let{data:s}=await P.get(`/projects/${e}/secrets/export?env=${encodeURIComponent(n)}`);if(s.status!=="success"){o.stop(qt.red(`Failed to download variables: ${s.message||"Unknown API error"}`));return}let l=s.secrets||{},a=hu(l,n);Tn.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."),Re.error(Gi(s,e,"pull"))}}import{spinner as Eu,log as St,outro as Au}from"@clack/prompts";import Ki from"chalk";import us from"fs";import Iu from"path";import{execSync as wu}from"child_process";import _u from"adm-zip";import $u from"axios";import{randomUUID as vu}from"crypto";async function fs(e){St.info(Ki.magenta("\u{1F680} Starting Over-The-Air (OTA) Update via Mach..."));let t=$e();(!t||!t.projectId)&&(St.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(us.readFileSync("./package.json","utf-8")).version||"1.0.0"}catch{St.warn("Could not read package.json version. Defaulting to 1.0.0")}let o=Eu();o.start(`Compiling JavaScript bundles for OTA (Channel: ${i}, Runtime: ${r})...`);try{wu("npx expo export --platform all",{stdio:"ignore"})}catch(c){o.stop("Compilation failed."),St.error(`Failed to export JS bundles using Expo: ${c.message}`),process.exit(1)}o.message("Zipping artifact payload...");let s=Iu.join(process.cwd(),"dist");us.existsSync(s)||(o.stop("Missing dist folder."),St.error("The `dist` directory was not created. Export failed."),process.exit(1));let l=new _u;l.addLocalFolder(s,"dist");let a=l.toBuffer();o.message("Uploading payload to Mach Cloud...");try{let c=vu(),u=await P.post("/builds/source-upload-url",{projectId:n,buildId:c});if(u.data.status!=="success")throw new Error("Could not secure upload bucket URL");let{uploadUrl:d,key:f}=u.data;await $u.put(d,a,{headers:{"Content-Type":"application/zip"},maxBodyLength:1/0,maxContentLength:1/0}),o.message(`Promoting Update to ${i}...`),await P.post("/updates/publish",{projectId:n,channelName:i,runtimeVersion:r,platform:"android",updateId:`${c}-android`,manifestKey:f}),await P.post("/updates/publish",{projectId:n,channelName:i,runtimeVersion:r,platform:"ios",updateId:`${c}-ios`,manifestKey:f}),o.stop("Update Live!"),Au(Ki.green(`\u2713 OTA Update natively shipped to the '${i}' channel.`)),St.info(Ki.dim(`Any app running runtime '${r}' will download this bundle smoothly.`))}catch(c){o.stop("Update failed during Cloud Sync."),St.error(`Upload error: ${c.message}`),process.exit(1)}}import{intro as Ru,outro as ps,log as Pt}from"@clack/prompts";import Je from"chalk";async function ms(){Ru(Je.blue(`${m.name} CLI - User Profile`));let e=Pe();if(!e){Pt.warn(Je.yellow("You are not logged in.")),Pt.info(`Run \`${m.nameLower} login\` to authenticate.`),ps();return}Pt.info(`${Je.bold("Logged in as:")} ${Je.green(e.email)}`);try{await P.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(`${Je.bold("Token status:")} Valid (Expires in ~${a}h / ${l}m)`)}else Pt.warn(`${Je.bold("Token status:")} ${Je.red("Expired")} (Auto-refresh failed)`)}}}catch{Pt.warn(`${Je.bold("Token status:")} ${Je.red("Unreachable")} (Session might be truly expired)${bt}`)}ps(Je.blue("---"))}import{spawn as Ou}from"child_process";import{log as dt}from"@clack/prompts";import Ce from"chalk";import Cu from"fs";import Pu from"net";async function Du(e){return new Promise(t=>{let n=Pu.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 gs(e,t=20){let n=e;for(;n<e+t;){if(!await Du(n))return n;n++}throw new Error(`Could not find an available port after ${t} attempts starting from ${e}.`)}var hs=async e=>{dt.info(Ce.blue(`Starting ${m.name} Dev Orchestrator...`));let t=$e(),n=e.buildProfile||"development",i=t?nt(t,n):null,r={...process.env};if(t?.projectId)try{dt.info(Ce.dim(`Fetching managed secrets for profile: ${n}...`));let d=await P.get(`/projects/${t.projectId}/secrets/export?env=${n}`);d.data?.status==="success"&&d.data.secrets&&(Object.assign(r,d.data.secrets),dt.info(Ce.magenta(`\u2713 Injected secrets from ${m.name} Dashboard.`)))}catch{dt.warn("Could not fetch managed secrets. Running with local env only.")}t&&Object.assign(r,Et(t,m.envPrefix)),i&&(Object.assign(r,Et(i,`${m.envPrefix}PROFILE_`)),i.env&&Object.assign(r,i.env));let o=!1;try{let d=JSON.parse(Cu.readFileSync("package.json","utf-8"));o=!!(d.dependencies?.expo||d.devDependencies?.expo)}catch{dt.warn("Could not parse package.json. Defaulting to Bare React Native mode.")}let s=Number(e.port||i?.port||8081),l=await gs(s);l!==s&&dt.info(Ce.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 d=[`${Ce.cyan("i")} open iOS simulator`,`${Ce.cyan("a")} open Android emulator/device`,`${Ce.cyan("w")} open web`,`${Ce.cyan("r")} reload app`];dt.info([Ce.bold("Launch controls"),...d.map(f=>` ${f}`),"",Ce.dim("Direct launch: mach start --ios | --android | --web"),Ce.dim(`Metro URL: http://localhost:${l}`)].join(`
|
|
1365
|
+
`))}else dt.info(Ce.dim(`Metro URL: http://localhost:${l}`));let u=Ou(a,c,{stdio:"inherit",env:r});return new Promise((d,f)=>{u.on("exit",p=>{p===0?d():f(new Error(`Dev server exited with code ${p}`))}),u.on("error",p=>{f(p)})})};import{log as De}from"@clack/prompts";import Ke from"chalk";var ys=async e=>{let t=$e();t||(De.error(Ke.red(`No ${m.configFileName} found in the current directory.`)),process.exit(1));let n=e.profile||"development",i=nt(t,n);if(e.json){console.log(JSON.stringify({project:t,resolved:i},null,2));return}De.info(Ke.bgBlue.white(` Resolved ${m.name} Config [${n}] `)),De.info(Ke.dim("----------------------------------------")),De.info(`${Ke.blue("Project ID:")} ${t.projectId}`),De.info(`${Ke.blue("Name:")} ${t.name}`),De.info(`${Ke.blue("Scheme:")} ${t.scheme}`),i?(De.info(Ke.dim(`
|
|
1366
|
+
Profile Settings:`)),De.info(`${Ke.cyan("Distribution:")} ${i.distribution||"none"}`),De.info(`${Ke.cyan("Development Client:")} ${i.developmentClient||"false"}`),i.env&&Object.keys(i.env).length>0&&(De.info(Ke.dim(`
|
|
1367
|
+
Environment Variables:`)),Object.entries(i.env).forEach(([r,o])=>{De.info(` ${r}=${o}`)}))):De.warn(`Profile '${n}' not found.`),De.info(Ke.dim("----------------------------------------"))};import{log as Ne,spinner as Qt,text as Ss,select as bs,confirm as Nu,isCancel as Xt,cancel as Zt,outro as en,note as Tu}from"@clack/prompts";import re from"chalk";import{execSync as ku}from"child_process";async function xu(){try{let e=ku("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 Es=e=>e?.trim().toUpperCase()||void 0;function As(e){let t=$e(),n=t?tr(t):{},i=Es(e.teamId),r=i||n.teamId;return{...n,teamId:r,developerTeamId:i||n.developerTeamId||r}}async function Lu(e){let t=e.udid,n=e.name,i=As(e),r=i.teamId;if(!t){let s=Qt();s.start("Scanning for connected iOS devices...");let l=await xu();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 bs({message:"Select a device to register:",options:l.map(u=>({value:u.udid,label:`${u.name} (${u.model})`,hint:u.udid.substring(0,12)+"..."}))});if(Xt(a)){Zt("Cancelled");return}t=a;let c=l.find(u=>u.udid===t);n=n||c.name}else{Ne.info(re.dim("No connected devices found. Enter UDID manually."));let a=await Ss({message:"Device UDID:",placeholder:"00008101-XXXXXXXXXXXX",validate(c){if(c.length<10)return"UDID seems too short"}});if(Xt(a)){Zt("Cancelled");return}t=a}}if(!n){let s=await Ss({message:"Device name:",placeholder:"Nitesh's iPhone",validate(l){if(l.length===0)return"Name is required"}});if(Xt(s)){Zt("Cancelled");return}n=s}let o=Qt();o.start("Registering device...");try{await P.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)}en(re.blue("---"))}async function Mu(e={}){let t=Es(e.teamId),n=Qt();n.start("Fetching registered devices...");try{let r=(await P.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 \`${m.nameLower} device register\` to add one.`)),en(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)}`});Tu(` ${re.bold("Name".padEnd(24))} ${"UDID".padEnd(28)} ${"Team".padEnd(12)} ${"Via".padEnd(10)} Date
|
|
1356
1368
|
`+o.join(`
|
|
1357
|
-
`),"Registered Devices")}catch(i){n.stop(re.red("Failed to fetch devices")),Ne.error(i.response?.data?.message||i.message)}
|
|
1358
|
-
`),
|
|
1359
|
-
`),
|
|
1360
|
-
`),
|
|
1361
|
-
`),
|
|
1362
|
-
`);/__DEV__/.test(h)||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:
|
|
1363
|
-
Running expo prebuild for deeper analysis...`));try{
|
|
1364
|
-
Skipping manifest/plist checks \u2014 no android/ios dirs. Use --prebuild to generate them.`)),o;for(let
|
|
1369
|
+
`),"Registered Devices")}catch(i){n.stop(re.red("Failed to fetch devices")),Ne.error(i.response?.data?.message||i.message)}en(re.blue("---"))}async function Uu(e){let t=e.udid,n=As(e).teamId;if(!t){let o=Qt();o.start("Fetching registered devices...");try{let l=(await P.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.")),en(re.blue("---"));return}let a=await bs({message:"Select device to remove:",options:l.map(u=>({value:u.deviceKey||u.udid,label:u.name,hint:`${u.udid.substring(0,12)}...${u.teamId?` \xB7 ${u.teamId}`:""}`}))});if(Xt(a)){Zt("Cancelled");return}let c=l.find(u=>(u.deviceKey||u.udid)===a);t=c?.udid||a,n=c?.teamId||n}catch(s){o.stop(re.red("Failed to fetch devices")),Ne.error(s.response?.data?.message||s.message);return}}let i=await Nu({message:`Remove device ${re.dim(t.substring(0,12)+"...")}?`});if(Xt(i)||!i){Zt("Cancelled");return}let r=Qt();r.start("Removing device...");try{await P.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)}en(re.blue("---"))}async function kn(e,t){switch(e){case"register":await Lu(t);break;case"list":await Mu(t);break;case"remove":await Uu(t);break;default:Ne.error(`Unknown action: ${e}`)}}import{log as ke,spinner as qs}from"@clack/prompts";import ze from"chalk";import Kn from"path";import rn from"fs";import bf from"os";import Ef from"axios";var Te=(o=>(o.CRITICAL="critical",o.HIGH="high",o.MEDIUM="medium",o.LOW="low",o.INFO="info",o))(Te||{}),Ve=(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))(Ve||{});import{spinner as Fs,log as nn}from"@clack/prompts";import Oe from"chalk";import{execSync as df}from"child_process";import Hs from"fs";import js from"path";import ct from"fs";import tn from"path";import{execSync as Bu}from"child_process";var Is={"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"}},Fu={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 Hu(e){try{let n=Bu("npx expo config --type introspect --json 2>/dev/null",{cwd:e,encoding:"utf-8",timeout:3e4});return JSON.parse(n)}catch{}let t=tn.join(e,"app.json");if(ct.existsSync(t))try{let n=JSON.parse(ct.readFileSync(t,"utf-8"));return n.expo||n}catch{}return null}function ju(e){let t=[],n=tn.join(e,"node_modules");if(!ct.existsSync(n))return t;let i=/<uses-permission\s+android:name="([^"]+)"/g;function r(o,s){let l=tn.join(o,"android","src","main","AndroidManifest.xml");if(!ct.existsSync(l))return;let a=ct.readFileSync(l,"utf-8"),c;for(;(c=i.exec(a))!==null;)t.push({pkg:s,permission:c[1]});i.lastIndex=0}for(let o of ct.readdirSync(n)){if(o.startsWith("."))continue;let s=tn.join(n,o);if(o.startsWith("@")){if(!ct.statSync(s).isDirectory())continue;for(let l of ct.readdirSync(s))r(tn.join(s,l),`${o}/${l}`)}else r(s,o)}return t}async function ws(e,t){let n=[],i=1,r=Hu(e),o=r?.android?.permissions||[],s=r?.android?.blockedPermissions||[];for(let c of o){let u=Is[c];u&&n.push({id:`PERM-${String(i++).padStart(3,"0")}`,title:`${c.split(".").pop()} declared`,description:u.description,severity:u.severity,category:"permissions",file:"app.config.ts",recommendation:"Remove from permissions if not needed, or add justification."})}let l=ju(e);for(let{pkg:c,permission:u}of l){let d=Is[u];d&&(s.includes(u)||o.includes(u)||n.push({id:`PERM-${String(i++).padStart(3,"0")}`,title:`${u.split(".").pop()} injected by ${c}`,description:`${d.description}. Auto-injected via ${c} AndroidManifest.xml`,severity:d.severity,category:"permissions",file:`node_modules/${c}/android/src/main/AndroidManifest.xml`,recommendation:`Add "${u}" to blockedPermissions if not needed.`,autoFixable:!0}))}let a=r?.ios?.infoPlist||{};for(let[c,u]of Object.entries(Fu))c in a&&n.push({id:`PERM-${String(i++).padStart(3,"0")}`,title:`iOS: ${c} declared`,description:u.description,severity:u.severity,category:"permissions",file:"app.config.ts",recommendation:`Remove ${c} from infoPlist if the app does not use this capability.`});return{category:"permissions",label:"Permission Audit",findings:n,durationMs:0}}import Vi from"fs";import xn from"path";var Gu=[{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"}],Ku=new Set([".ts",".tsx",".js",".jsx"]),Vu=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function _s(e){let t=[],n=Vi.readdirSync(e,{withFileTypes:!0});for(let i of n){if(Vu.has(i.name))continue;let r=xn.join(e,i.name);i.isDirectory()?t.push(..._s(r)):Ku.has(xn.extname(i.name))&&t.push(r)}return t}function zu(e){let t=e.trim();return t.startsWith("//")||t.startsWith("*")||t.startsWith("/*")}function Wu(e){return/process\.env\./i.test(e)||/import\.meta\.env/i.test(e)}async function $s(e,t){let n=[],i=xn.join(e,"src"),r=Vi.existsSync(i)?i:e,o=_s(r);for(let s of o){let a=Vi.readFileSync(s,"utf-8").split(`
|
|
1370
|
+
`),c=xn.relative(e,s);for(let u=0;u<a.length;u++){let d=a[u];if(!zu(d)&&!Wu(d))for(let{id:f,pattern:p,severity:h,label:D}of Gu)p.lastIndex=0,p.test(d)&&n.push({id:f,title:D,description:`Potential ${D.toLowerCase()} found in source code`,severity:h,category:"secrets",file:c,line:u+1,recommendation:`Move to environment variables or a secrets manager. Use \`${m.nameLower} env set\` for managed secrets.`})}}return{category:"secrets",label:"Secrets Detection",findings:n,durationMs:0}}import{execSync as Yu}from"child_process";var Ju={critical:"critical",high:"high",moderate:"medium",low:"low",info:"info"};async function vs(e,t){let n=[],i=1,r;try{r=Yu("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 c=Ju[a.severity]||"info",u=Array.isArray(a.via)?a.via.map(d=>typeof d=="string"?d:d.title||d.name).join(", "):String(a.via);n.push({id:`DEP-${String(i++).padStart(3,"0")}`,title:`${l} \u2014 ${a.severity}`,description:`Via: ${u}. Range: ${a.range||"unknown"}`,severity:c,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 Ln from"fs";import Mn from"path";var qu=/(?:token|password|credential|secret|apiKey|api_key|session|auth|jwt|refresh_token|access_token|private_key|pin|otp)/i,Rs=/AsyncStorage\s*\.\s*(?:setItem|mergeItem)\s*\(\s*['"`]([^'"`]+)['"`]/g,Xu=/from\s+['"]@react-native-async-storage\/async-storage['"]|from\s+['"]react-native['"].*AsyncStorage/,Zu=new Set([".ts",".tsx",".js",".jsx"]),Qu=new Set(["node_modules",".expo",".git","android","ios","dist","build"]);function Ps(e){let t=[];if(!Ln.existsSync(e))return t;let n=Ln.readdirSync(e,{withFileTypes:!0});for(let i of n){if(Qu.has(i.name))continue;let r=Mn.join(e,i.name);i.isDirectory()?t.push(...Ps(r)):Zu.has(Mn.extname(i.name))&&t.push(r)}return t}async function Ds(e,t){let n=[],i=1,r=Mn.join(e,"src"),o=Ln.existsSync(r)?r:e,s=Ps(o);for(let l of s){let a=Ln.readFileSync(l,"utf-8");if(!Xu.test(a))continue;let c=a.split(`
|
|
1371
|
+
`),u=Mn.relative(e,l);for(let d=0;d<c.length;d++){let f=c[d];Rs.lastIndex=0;let p;for(;(p=Rs.exec(f))!==null;){let h=p[1];qu.test(h)&&n.push({id:`STOR-${String(i++).padStart(3,"0")}`,title:`AsyncStorage used for "${h}"`,description:`Sensitive data key "${h}" stored in AsyncStorage (unencrypted).`,severity:"high",category:"storage",file:u,line:d+1,recommendation:"Use expo-secure-store (SecureStore) for sensitive data instead of AsyncStorage."})}}}return{category:"storage",label:"Insecure Storage",findings:n,durationMs:0}}import Un from"fs";import Bn from"path";var Os=/['"`](http:\/\/(?!localhost|127\.0\.0\.1|10\.|192\.168\.|0\.0\.0\.0|172\.(?:1[6-9]|2\d|3[01])\.)[^'"`\s]+)['"`]/g,ef=/\/api\/|\/v[0-9]+\/|\/graphql|\/rest\//i,tf=new Set([".ts",".tsx",".js",".jsx"]),nf=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function Cs(e){let t=[];if(!Un.existsSync(e))return t;let n=Un.readdirSync(e,{withFileTypes:!0});for(let i of n){if(nf.has(i.name))continue;let r=Bn.join(e,i.name);i.isDirectory()?t.push(...Cs(r)):tf.has(Bn.extname(i.name))&&t.push(r)}return t}async function Ns(e,t){let n=[],i=1,r=Bn.join(e,"src"),o=Un.existsSync(r)?r:e,s=Cs(o);for(let l of s){let c=Un.readFileSync(l,"utf-8").split(`
|
|
1372
|
+
`),u=Bn.relative(e,l);for(let d=0;d<c.length;d++){let f=c[d],p=f.trim();if(p.startsWith("//")||p.startsWith("*"))continue;Os.lastIndex=0;let h;for(;(h=Os.exec(f))!==null;){let D=h[1],N=ef.test(D);n.push({id:`NET-${String(i++).padStart(3,"0")}`,title:`Insecure HTTP URL${N?" (API endpoint)":""}`,description:`Plain HTTP URL found: ${D}`,severity:N?"high":"medium",category:"network",file:u,line:d+1,recommendation:"Use HTTPS instead of HTTP for all network requests."})}}}return{category:"network",label:"HTTP URLs",findings:n,durationMs:0}}import Fn from"fs";import Hn from"path";var Ts=/(?:debug|debugMode|devMode|enableDebug)\s*[:=]\s*true/gi,ks=/console\.(?:log|warn|info|debug)\s*\([^)]*(?:token|password|secret|credential|key|auth)/gi,rf=new Set([".ts",".tsx",".js",".jsx"]),of=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function xs(e){let t=[];if(!Fn.existsSync(e))return t;let n=Fn.readdirSync(e,{withFileTypes:!0});for(let i of n){if(of.has(i.name))continue;let r=Hn.join(e,i.name);i.isDirectory()?t.push(...xs(r)):rf.has(Hn.extname(i.name))&&t.push(r)}return t}async function Ls(e,t){let n=[],i=1,r=Hn.join(e,"src"),o=Fn.existsSync(r)?r:e,s=xs(o);for(let l of s){let c=Fn.readFileSync(l,"utf-8").split(`
|
|
1373
|
+
`),u=Hn.relative(e,l);for(let d=0;d<c.length;d++){let f=c[d],p=f.trim();if(!(p.startsWith("//")||p.startsWith("*"))&&(Ts.lastIndex=0,Ts.test(f)&&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:u,line:d+1,recommendation:"Use __DEV__ or environment variables instead of hardcoded debug flags."}),ks.lastIndex=0,ks.test(f))){let h=c.slice(Math.max(0,d-3),d).join(`
|
|
1374
|
+
`);/__DEV__/.test(h)||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:u,line:d+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 Ms from"fs";import zi from"path";var sf=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 af(e){let t=[zi.join(e,"android","app","src","main","AndroidManifest.xml"),zi.join(e,"android","AndroidManifest.xml")];for(let n of t)if(Ms.existsSync(n))return n;return null}async function Us(e,t){let n=[],i=1,r=af(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=Ms.readFileSync(r,"utf-8"),s=zi.relative(e,r),l=/<(activity|service|receiver|provider)\s+([^>]*?)(?:\/>|>)/gs,a;for(;(a=l.exec(o))!==null;){let c=a[1],u=a[2],f=u.match(/android:name="([^"]+)"/)?.[1]||"unknown";if(sf.has(f))continue;let p=/android:exported="true"/.test(u),h=/android:permission="/.test(u);p&&!h&&n.push({id:`MAN-${String(i++).padStart(3,"0")}`,title:`Exported ${c}: ${f.split(".").pop()}`,description:`${f} 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 jn from"fs";import Wi from"path";function lf(e){let t=Wi.join(e,"ios");if(!jn.existsSync(t))return null;let n=jn.readdirSync(t,{withFileTypes:!0});for(let i of n){if(!i.isDirectory()||i.name==="Pods"||i.name.startsWith("."))continue;let r=Wi.join(t,i.name,"Info.plist");if(jn.existsSync(r))return r}return null}async function Bs(e,t){let n=[],i=1,r=lf(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=jn.readFileSync(r,"utf-8"),s=Wi.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 c=a.match(/<key>NSExceptionDomains<\/key>\s*<dict>([\s\S]*?)<\/dict>/);if(c){let u=c[1].match(/<key>([^<]+)<\/key>/g);if(u)for(let d of u){let f=d.replace(/<\/?key>/g,"");f!=="NSExceptionDomains"&&n.push({id:`ATS-${String(i++).padStart(3,"0")}`,title:`ATS exception: ${f}`,description:`ATS exception configured for ${f}`,severity:"low",category:"ats",file:s,recommendation:`Verify that the ATS exception for ${f} is necessary. Use HTTPS where possible.`})}}}return{category:"ats",label:"iOS ATS Config",findings:n,durationMs:0}}var cf=[{category:"permissions",label:"Permission Audit",fn:ws,requiresPrebuild:!1},{category:"secrets",label:"Secrets Detection",fn:$s,requiresPrebuild:!1},{category:"dependencies",label:"Dependency CVEs",fn:vs,requiresPrebuild:!1},{category:"storage",label:"Insecure Storage",fn:Ds,requiresPrebuild:!1},{category:"network",label:"HTTP URLs",fn:Ns,requiresPrebuild:!1},{category:"debug",label:"Debug/Dev Flags",fn:Ls,requiresPrebuild:!1},{category:"manifest",label:"Android Manifest",fn:Us,requiresPrebuild:!0},{category:"ats",label:"iOS ATS Config",fn:Bs,requiresPrebuild:!0}];async function Gs(e,t){let n=cf;t.category&&(n=n.filter(s=>s.category===t.category),n.length===0&&(nn.error(Oe.red(`Unknown category: ${t.category}`)),nn.info(Oe.dim(`Available: ${Object.values(Ve).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=Fs();l.start(Oe.dim(`Running ${s.label}...`));try{let a=Date.now(),c=await s.fn(e,t);c.durationMs=Date.now()-a,o.push(c);let u=c.findings.length;l.stop(u>0?Oe.yellow(`${s.label} \u2014 ${u} 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=js.join(e,"android"),l=js.join(e,"ios"),a=Hs.existsSync(s)||Hs.existsSync(l);if(!a&&t.prebuild){t.json||nn.info(Oe.dim(`
|
|
1375
|
+
Running expo prebuild for deeper analysis...`));try{df("npx expo prebuild --no-install",{cwd:e,stdio:"pipe"})}catch{return nn.warn(Oe.yellow("Prebuild failed \u2014 skipping manifest/plist checks.")),o}}else if(!a)return t.json||nn.info(Oe.dim(`
|
|
1376
|
+
Skipping manifest/plist checks \u2014 no android/ios dirs. Use --prebuild to generate them.`)),o;for(let c of r){let u=Fs();u.start(Oe.dim(`Running ${c.label}...`));try{let d=Date.now(),f=await c.fn(e,t);f.durationMs=Date.now()-d,o.push(f);let p=f.findings.length;u.stop(p>0?Oe.yellow(`${c.label} \u2014 ${p} finding(s)`):Oe.green(`${c.label} \u2014 clean`))}catch(d){u.stop(Oe.red(`${c.label} \u2014 error`)),o.push({category:c.category,label:c.label,findings:[],durationMs:0,error:d.message})}}}return o}import he from"chalk";import{log as me}from"@clack/prompts";var Dt={critical:he.bgRed.white.bold,high:he.red.bold,medium:he.yellow.bold,low:he.blue,info:he.dim},Gn={critical:0,high:1,medium:2,low:3,info:4};function uf(e,t){if(!t)return!0;let n=Gn[t];return n===void 0?!0:Gn[e]<=n}function Ks(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(c=>uf(c.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((c,u)=>Gn[c.severity]-Gn[u.severity]);for(let c of a){let u=Dt[c.severity](` ${c.severity.toUpperCase()} `);me.info(` ${u} ${he.bold(c.id)} ${c.title}`),me.info(he.dim(` ${c.description}`)),c.file&&me.info(he.dim(` File: ${c.file}${c.line?`:${c.line}`:""}`)),me.info(he.cyan(` Fix: ${c.recommendation}`)),me.info(""),i[c.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(` ${Dt.critical(` ${i.critical} Critical `)} ${Dt.high(` ${i.high} High `)} ${Dt.medium(` ${i.medium} Medium `)} ${Dt.low(` ${i.low} Low `)} ${Dt.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 Vs(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 ff}from"@clack/prompts";import ue from"chalk";import tt from"fs";import pf from"os";import Ot from"path";import{execSync as mf}from"child_process";var zs=16384,gf=1,hf=Buffer.from([127,69,76,70]);async function Ws(e){ge.info(ue.bold.underline("16KB Page Alignment Check")),console.log("");let t=Ot.resolve(e);if(!tt.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=ff();n.start("Extracting and analyzing native libraries...");let i=tt.mkdtempSync(Ot.join(pf.tmpdir(),"mach-16kb-"));try{try{mf(`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=Ys(Ot.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 c=Ot.relative(i,a),u=Sf(c),d=Ot.basename(a),f=yf(a);f!==null&&o.push({name:d,filePath:c,arch:u,align:f,compatible:f>=zs})}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"}
|
|
1365
1377
|
`)),s.length>0){ge.info(ue.red.bold(`Incompatible libraries:
|
|
1366
|
-
`));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 = ${Gs})`))}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{Qe.rmSync(i,{recursive:!0,force:!0})}catch{}}}function df(e){let t=Qe.openSync(e,"r");try{let n=Buffer.alloc(64);if(Qe.readSync(t,n,0,64,0),!n.subarray(0,4).equals(lf))return null;let i=n[4]===2,r=n[5]===1,o=(f,p)=>r?f.readUInt16LE(p):f.readUInt16BE(p),s=(f,p)=>r?f.readUInt32LE(p):f.readUInt32BE(p),l=(f,p)=>Number(r?f.readBigUInt64LE(p):f.readBigUInt64BE(p)),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 f=0;f<c;f++){let p=Buffer.alloc(d);if(Qe.readSync(t,p,0,d,a+f*d),s(p,0)!==af)continue;let O;i?O=l(p,48):O=s(p,28),O>0&&(u===null||O<u)&&(u=O)}return u??0}catch{return null}finally{Qe.closeSync(t)}}function Vs(e){let t=[];if(!Qe.existsSync(e))return t;let n=Qe.readdirSync(e,{withFileTypes:!0});for(let i of n){let r=Dt.join(e,i.name);i.isDirectory()?t.push(...Vs(r)):i.name.endsWith(".so")&&t.push(r)}return t}function cf(e){return e.includes("arm64-v8a")?"arm64-v8a":e.includes("x86_64")?"x86_64":"unknown"}var Ys=async e=>{if(Pe()||(ke.error(Ve.red(`You are not logged in. Run \`${m.nameLower} login\` first.`)),process.exit(1)),e.apk){await pf(e);return}let n=process.cwd(),i=Gn.join(n,"package.json");nn.existsSync(i)||(ke.error(Ve.red("No package.json found. Run this command from a project root.")),process.exit(1));let r=JSON.parse(nn.readFileSync(i,"utf-8")),o=!!(r.dependencies?.expo||r.devDependencies?.expo);e.json||(ke.info(Ve.dim(`Project: ${r.name||"unknown"} v${r.version||"0.0.0"}`)),ke.info(Ve.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 Fs(n,s);e.json?console.log(JSON.stringify(js(l,r),null,2)):Hs(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)},zs=["16kb"];async function pf(e){let t=e.category?.toLowerCase();t&&!zs.includes(t)&&(ke.error(Ve.red(`Unknown APK check category: "${t}"`)),ke.info(Ve.dim(`Available APK checks: ${zs.join(", ")}`)),process.exit(1));let n=await mf(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 mf(e){if(e.startsWith("build:")){let n=e.slice(6);return await gf(n)}if(e.startsWith("http://")||e.startsWith("https://"))return await Js(e);let t=Gn.resolve(e);return nn.existsSync(t)?t:(ke.error(Ve.red(`APK file not found: ${t}`)),null)}async function gf(e){let t=Ws();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(Ve.red("This build does not have an APK artifact.")),ke.info(Ve.dim("Make sure the build produced an APK (not just an AAB).")),null):(t.stop(`Found build: ${i.buildId||e}`),await Js(r.url))}catch(n){return t.stop("Failed to fetch build"),ke.error(Ve.red(n.message)),null}}async function Js(e){let t=Ws();t.start("Downloading APK...");try{let n=nn.mkdtempSync(Gn.join(uf.tmpdir(),`${m.nameLower}-audit-`)),i=Gn.join(n,"app.apk"),r=await ff.get(e,{responseType:"arraybuffer"});nn.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(Ve.red(`Failed to download APK: ${n.message}`)),null}}var Sf=console.log;console.log=()=>{};yf();console.log=Sf;we(be.bgCyan.black(m.cliTag("Production Build Orchestrator")));var Ef=bf(import.meta.url),Af=Ef("../package.json"),Xs=(e,t=[])=>t.concat(e),oe=new hf;oe.name(m.nameLower).description(`${m.name} CLI: Powerful Cloud Infrastructure Tools`).version(Af.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 Xo(e)});oe.command("host").description("Setup AWS S3 static hosting and CloudFront").action(async()=>{we(be.bgCyan.black(m.cliTag("Hosting"))),await or()});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(m.cliTag("Sitemap Generator"))),await dr(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)").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("--maestro-env <name>","Forward an environment variable to the managed Maestro runner; repeat or comma-separate names",Xs,[]).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(m.cliTag("Cloud Build"))),await An(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("--maestro-env <name>","Forward an environment variable to the managed Maestro runner; repeat or comma-separate names",Xs,[]).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(m.cliTag("Maestro Testing"))),await jr(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(m.cliTag("OTA Update"))),await ds(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(m.cliTag("Store Submission"))),await gn(e)});oe.command("login").description(`Login to ${m.name} Dashboard`).action(async()=>{we(be.bgCyan.black(m.cliTag("Login"))),await ts()});oe.command("logout").description(`Logout from ${m.name} on this machine`).action(async()=>{we(be.bgCyan.black(m.cliTag("Logout"))),await ns()});oe.command("link").description(`Link local directory to a ${m.name} Project`).action(async()=>{we(be.bgCyan.black(m.cliTag("Link Project"))),await rs()});oe.command("me").description("Display currently logged in user details").action(async()=>{await us()});oe.command("init").description(`Create a new ${m.name} Project`).action(async()=>{we(be.bgCyan.black(m.cliTag("Init Project"))),await os()});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(m.cliTag("Env Manager"))),await as(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(m.cliTag("Dev Server"))),await ps(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 ms(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(m.cliTag("Credentials Setup"))),await Nt(e),qs(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(m.cliTag("Service Credentials"))),await ir(e),qs(be.green("Done!"))});var Wi=oe.command("device").description("Manage registered iOS test devices");Wi.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 Tn("register",e)});Wi.command("list").description("List all registered devices").option("--team-id <id>","Filter by Apple Developer Team ID").action(async e=>{await Tn("list",e)});Wi.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 Tn("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(m.cliTag(e.apk?"APK Audit":"Security Audit"))),await Ys(e)});var If=new Set(["login","logout","agent"]);oe.hook("preAction",(e,t)=>{let n=t.name(),i=t.opts?.()||{};n==="maestro"&&(i.local||i.localRunner)||If.has(n)||Qi()});oe.on("command:*",()=>{console.error(`Invalid command: %s
|
|
1378
|
+
`));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 = ${zs})`))}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{tt.rmSync(i,{recursive:!0,force:!0})}catch{}}}function yf(e){let t=tt.openSync(e,"r");try{let n=Buffer.alloc(64);if(tt.readSync(t,n,0,64,0),!n.subarray(0,4).equals(hf))return null;let i=n[4]===2,r=n[5]===1,o=(f,p)=>r?f.readUInt16LE(p):f.readUInt16BE(p),s=(f,p)=>r?f.readUInt32LE(p):f.readUInt32BE(p),l=(f,p)=>Number(r?f.readBigUInt64LE(p):f.readBigUInt64BE(p)),a,c,u;i?(a=l(n,32),c=o(n,54),u=o(n,56)):(a=s(n,28),c=o(n,42),u=o(n,44));let d=null;for(let f=0;f<u;f++){let p=Buffer.alloc(c);if(tt.readSync(t,p,0,c,a+f*c),s(p,0)!==gf)continue;let D;i?D=l(p,48):D=s(p,28),D>0&&(d===null||D<d)&&(d=D)}return d??0}catch{return null}finally{tt.closeSync(t)}}function Ys(e){let t=[];if(!tt.existsSync(e))return t;let n=tt.readdirSync(e,{withFileTypes:!0});for(let i of n){let r=Ot.join(e,i.name);i.isDirectory()?t.push(...Ys(r)):i.name.endsWith(".so")&&t.push(r)}return t}function Sf(e){return e.includes("arm64-v8a")?"arm64-v8a":e.includes("x86_64")?"x86_64":"unknown"}var Xs=async e=>{if(Pe()||(ke.error(ze.red(`You are not logged in. Run \`${m.nameLower} login\` first.`)),process.exit(1)),e.apk){await Af(e);return}let n=process.cwd(),i=Kn.join(n,"package.json");rn.existsSync(i)||(ke.error(ze.red("No package.json found. Run this command from a project root.")),process.exit(1));let r=JSON.parse(rn.readFileSync(i,"utf-8")),o=!!(r.dependencies?.expo||r.devDependencies?.expo);e.json||(ke.info(ze.dim(`Project: ${r.name||"unknown"} v${r.version||"0.0.0"}`)),ke.info(ze.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 Gs(n,s);e.json?console.log(JSON.stringify(Vs(l,r),null,2)):Ks(l,e.severity);let a=l.some(u=>u.findings.some(d=>d.severity==="critical")),c=l.some(u=>u.findings.some(d=>d.severity==="high"));(a||c)&&process.exit(1)},Js=["16kb"];async function Af(e){let t=e.category?.toLowerCase();t&&!Js.includes(t)&&(ke.error(ze.red(`Unknown APK check category: "${t}"`)),ke.info(ze.dim(`Available APK checks: ${Js.join(", ")}`)),process.exit(1));let n=await If(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 If(e){if(e.startsWith("build:")){let n=e.slice(6);return await wf(n)}if(e.startsWith("http://")||e.startsWith("https://"))return await Zs(e);let t=Kn.resolve(e);return rn.existsSync(t)?t:(ke.error(ze.red(`APK file not found: ${t}`)),null)}async function wf(e){let t=qs();t.start(`Fetching APK from build ${e}...`);try{let n=await P.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(ze.red("This build does not have an APK artifact.")),ke.info(ze.dim("Make sure the build produced an APK (not just an AAB).")),null):(t.stop(`Found build: ${i.buildId||e}`),await Zs(r.url))}catch(n){return t.stop("Failed to fetch build"),ke.error(ze.red(n.message)),null}}async function Zs(e){let t=qs();t.start("Downloading APK...");try{let n=rn.mkdtempSync(Kn.join(bf.tmpdir(),`${m.nameLower}-audit-`)),i=Kn.join(n,"app.apk"),r=await Ef.get(e,{responseType:"arraybuffer"});rn.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(ze.red(`Failed to download APK: ${n.message}`)),null}}var vf=console.log;console.log=()=>{};$f();console.log=vf;we(be.bgCyan.black(m.cliTag("Production Build Orchestrator")));var Pf=Rf(import.meta.url),Df=Pf("../package.json"),ea=(e,t=[])=>t.concat(e),oe=new _f;oe.name(m.nameLower).description(`${m.name} CLI: Powerful Cloud Infrastructure Tools`).version(Df.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 es(e)});oe.command("host").description("Setup AWS S3 static hosting and CloudFront").action(async()=>{we(be.bgCyan.black(m.cliTag("Hosting"))),await sr()});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(m.cliTag("Sitemap Generator"))),await cr(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)").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 xe("--build-id <id>","Internal build ID").hideHelp()).addOption(new xe("--project-id <id>","Internal project ID").hideHelp()).addOption(new xe("--fail-only","Internal: mark an existing build failed").hideHelp()).addOption(new xe("--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("--maestro-env <name>","Forward an environment variable to the managed Maestro runner; repeat or comma-separate names",ea,[]).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(m.cliTag("Cloud Build"))),await In(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("--maestro-env <name>","Forward an environment variable to the managed Maestro runner; repeat or comma-separate names",ea,[]).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 xe("--local-runner","Internal: execute a managed Maestro run on this machine").hideHelp()).addOption(new xe("--test-run-id <id>","Internal test run ID").hideHelp()).addOption(new xe("--project-id <id>","Internal project ID").hideHelp()).addOption(new xe("--runner-token <token>","Internal runner token").hideHelp()).action(async e=>{we(be.bgCyan.black(m.cliTag("Maestro Testing"))),await Vr(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(m.cliTag("OTA Update"))),await fs(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 xe("--submit-id <id>","Internal submission ID").hideHelp()).addOption(new xe("--project-id <id>","Internal project ID").hideHelp()).addOption(new xe("--package-name <name>","Internal Android package name").hideHelp()).addOption(new xe("--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(m.cliTag("Store Submission"))),await hn(e)});oe.command("login").description(`Login to ${m.name} Dashboard`).action(async()=>{we(be.bgCyan.black(m.cliTag("Login"))),await rs()});oe.command("logout").description(`Logout from ${m.name} on this machine`).action(async()=>{we(be.bgCyan.black(m.cliTag("Logout"))),await os()});oe.command("link").description(`Link local directory to a ${m.name} Project`).action(async()=>{we(be.bgCyan.black(m.cliTag("Link Project"))),await as()});oe.command("me").description("Display currently logged in user details").action(async()=>{await ms()});oe.command("init").description(`Create a new ${m.name} Project`).action(async()=>{we(be.bgCyan.black(m.cliTag("Init Project"))),await ls()});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(m.cliTag("Env Manager"))),await cs(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(m.cliTag("Dev Server"))),await hs(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 ys(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(m.cliTag("Credentials Setup"))),await Tt(e),Qs(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(m.cliTag("Service Credentials"))),await rr(e),Qs(be.green("Done!"))});var Yi=oe.command("device").description("Manage registered iOS test devices");Yi.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 kn("register",e)});Yi.command("list").description("List all registered devices").option("--team-id <id>","Filter by Apple Developer Team ID").action(async e=>{await kn("list",e)});Yi.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 kn("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(m.cliTag(e.apk?"APK Audit":"Security Audit"))),await Xs(e)});var Of=new Set(["login","logout","agent"]);oe.hook("preAction",(e,t)=>{let n=t.name(),i=t.opts?.()||{};n==="maestro"&&(i.local||i.localRunner)||Of.has(n)||er()});oe.on("command:*",()=>{console.error(`Invalid command: %s
|
|
1367
1379
|
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);
|