@radhya/mach 2.0.6 → 2.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/index.js +120 -115
- 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 er,b as $e,c as et,d as tr,e as nr,f as Et,g as ir,i as Nt}from"./chunk-UZNUPNFP.js";import{a as m,b as Xi,c as Pe,d as Zi,e as Qi,f as bt,g as ze,h as R}from"./chunk-HIP5BA3H.js";import{Command as hf,Option as Le}from"commander";import{configDotenv as yf}from"dotenv";import{intro as we,outro as qs}from"@clack/prompts";import be from"chalk";import{text as rr,confirm as Zs,spinner as Qs,isCancel as Wn,cancel as Tt,note as ea,outro as ta}from"@clack/prompts";import kt from"chalk";async function or(){try{let e=await rr({message:"Enter Bucket Name:",placeholder:"e.g. my-app-dev",validate(r){if(r.length===0)return"Bucket name is required"}});Wn(e)&&(Tt("Operation cancelled."),process.exit(0));let t=await rr({message:"Enter Region:",initialValue:"ap-south-1"});Wn(t)&&(Tt("Operation cancelled."),process.exit(0));let n=await Zs({message:"Do you want to create a CloudFront Distribution for this bucket?",initialValue:!0});Wn(n)&&(Tt("Operation cancelled."),process.exit(0));let i=Qs();i.start("Setting up hosting infrastructure...");try{let r=await R.post("/hosting/setup",{bucketName:e,region:t,createCloudFront:n});if(r.data.status!=="success")throw new Error(r.data.message||"Hosting setup failed");i.stop("Hosting setup complete!");let o=r.data,s=`Bucket Name: ${kt.cyan(o.bucketName)}
|
|
3
|
+
`;s+=`Region: ${kt.cyan(o.region)}
|
|
4
|
+
`,s+=`S3 Website URL: ${kt.blue(o.s3WebsiteUrl)}`,o.cloudFrontId&&(s+=`
|
|
5
|
+
|
|
6
|
+
CloudFront ID: ${kt.cyan(o.cloudFrontId)}`,s+=`
|
|
7
|
+
CloudFront URL: ${kt.blue(o.cloudFrontUrl)}`),ea(s,"Setup Complete!"),ta("You are all set!")}catch(r){i.stop("Setup failed"),Tt(`Error: ${r.response?.data?.message||r.message}`)}}catch(e){Tt(`An unexpected error occurred: ${e.message}`)}}import{readdir as na,writeFile as ia,access as ra,mkdir as oa}from"fs/promises";import{join as sr}from"path";import{spinner as sa,text as ar,isCancel as lr,cancel as Yn,note as aa,outro as la}from"@clack/prompts";import da from"chalk";async function ca(){let e=["./app","./src/app"];for(let t of e)try{return await ra(t),t}catch{}return null}async function dr(e){try{let n=await ca()||"./app",i=await ar({message:"Enter path to your app directory:",placeholder:n,initialValue:n,validate(c){if(c.length===0)return"Path is required"}});lr(i)&&(Yn("Operation cancelled."),process.exit(0));let r=await ar({message:"Enter your website base URL:",placeholder:"https://example.com",validate(c){if(c.length===0)return"Base URL is required";if(!c.startsWith("http"))return"URL must start with http:// or https://"}});lr(r)&&(Yn("Operation cancelled."),process.exit(0));let o=sa();o.start("Scanning app directory for routes...");let s=await cr(i);o.stop(`Found ${s.length} routes`);let l=ua(s,r),a=e.output||"./public/sitemap.xml";o.start(`Writing sitemap to ${a}...`);let d=a.substring(0,a.lastIndexOf("/"));if(d)try{await oa(d,{recursive:!0})}catch{}await ia(a,l,"utf-8"),o.stop("Sitemap generated successfully!"),aa(`Routes included:
|
|
8
|
+
${s.map(c=>` \u2022 ${c.path}`).join(`
|
|
9
|
+
`)}`,"Sitemap Summary"),la(`Sitemap saved to ${da.cyan(a)}`)}catch(t){Yn(`An error occurred: ${t.message}`)}}async function cr(e,t=""){let n=[];try{let i=await na(e,{withFileTypes:!0});for(let r of i){let o=sr(e,r.name);if(!(r.name.startsWith("_")||r.name.startsWith("."))){if(r.isDirectory()){let s=await cr(o,sr(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 ua(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 Ud}from"crypto";import ve from"path";import Sn from"axios";import Bd from"os";import{spinner as Pi,select as lo,confirm as co,isCancel as bn,cancel as uo,log as _}from"@clack/prompts";import $ from"chalk";import de from"fs";import{execSync as fo}from"child_process";import po from"adm-zip";import{spinner as ya,log as an}from"@clack/prompts";import fr from"chalk";import pr from"fs";import mr from"path";var ur=`#!/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
|
|
533
|
+
`;import fa from"crypto";var pa="mach-env-v2-js-bundle-cache",ma=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"]),ga=["PRESIGNED_","KEYSTORE_PASSWORD_"],ha=e=>!e||ma.has(e)?!1:!ga.some(t=>e.startsWith(t)),ut=(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])=>ha(n)).sort(([n],[i])=>n.localeCompare(i));return fa.createHash("sha256").update(JSON.stringify({version:pa,entries:t})).digest("hex")};var Jn=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`"),qn=e=>["1","true","yes","on"].includes(String(e||"").trim().toLowerCase()),Sa=e=>/(^|[-_])(maestro|e2e|test|emulator)([-_]|$)/i.test(e),ba=(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||Sa(t)||qn(n.MACH_PROFILE_ANDROID_EMULATOR)||qn(n.MACH_ANDROID_INCLUDE_EMULATOR_ABIS)||qn(n.MACH_PROFILE_ANDROID_INCLUDE_EMULATOR_ABIS)?"armeabi-v7a,arm64-v8a,x86_64":"armeabi-v7a,arm64-v8a")},gr=async(e,t,n={},i,r)=>{let o=ya(),s=e.buildProfile||"production",l=s==="production",a=e.apk===!0,d=e.developmentClient?"assembleDebug":l?"bundleRelease":"assembleRelease",c=e.buildCommand||(a?"assembleRelease":d),u=e.nodeVersion?[`echo "[NODE] Switching to Node ${e.nodeVersion}..."`,`CURRENT_MAJOR=$(node -e "process.stdout.write(process.version.split('.')[0].replace('v',''))" 2>/dev/null || echo "0")`,`if [ "$CURRENT_MAJOR" != "${e.nodeVersion}" ]; then`,` curl -fsSL https://deb.nodesource.com/setup_${e.nodeVersion}.x | bash - 2>&1`," apt-get install -y nodejs 2>&1",' echo "[NODE] Installed Node $(node -v)"',"else",' echo "[NODE] Already on Node $(node -v) \u2014 no switch needed"',"fi"].join(`
|
|
534
|
+
`):"",f;if(r){let M=mr.isAbsolute(r)?r:mr.resolve(process.cwd(),r);pr.existsSync(M)?(f=pr.readFileSync(M,"utf-8"),an.info(fr.magenta(`\u2713 Loaded preBuild hook: ${r}`))):an.warn(`preBuild script not found at ${M} \u2014 skipping`)}let p=ba(e,s,n),h={...ut(n,s,e),MACH_ANDROID_RELEASE_ABIS:p},O=At(h),N=ur.replace(/\{\{BUILD_ID\}\}/g,t).replace(/\{\{BUILD_COMMAND\}\}/g,c).replace("{{NODE_VERSION_SETUP}}",u).replace("{{ENV_VARS}}",`
|
|
535
535
|
export MACH_APP_NAME="${Jn(h.MACH_APP_NAME)}"
|
|
536
536
|
export MACH_BUILD_PROFILE="${Jn(s)}"
|
|
537
537
|
export MACH_ANDROID_RELEASE_ABIS="${Jn(p)}"
|
|
538
538
|
export MACH_ENV_FINGERPRINT="${O}"
|
|
539
539
|
export EXPO_NO_DOTENV=1
|
|
540
540
|
{{ENV_VARS}}
|
|
541
|
-
`);if(e.dryRun){an.info("User Data Script (dry run):"),console.log(
|
|
541
|
+
`);if(e.dryRun){an.info("User Data Script (dry run):"),console.log(N);return}o.start("Requesting cloud build instance...");try{let M=await R.post("/builds/launch-android",{projectId:i,buildId:t,platform:e.platform,buildProfile:e.buildProfile,buildCommand:c,instanceType:e.instanceType,ami:e.ami,keepInstance:e.keepInstance,region:e.region,subnet:e.subnet,securityGroup:e.securityGroup,projectSecrets:n,dryRun:e.dryRun,userDataScript:N,preBuildScriptContent:f});if(M.data.status!=="success")throw new Error(M.data.message||"Failed to launch build instance");let P=M.data.instanceId;return o.stop("Build Started"),an.success(fr.green(`Build initiated on cloud instance (${P}).`)),{instanceId:P}}catch(M){o.stop("Android Build Failed");let P=M.response?.data?.message||M.message;throw new Error(`Failed to launch Android build: ${P}`)}};import{spinner as Ea,log as It}from"@clack/prompts";import tt from"chalk";import Aa from"fs";import{execSync as Lt}from"child_process";var hr=`#!/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
|
-
`:
|
|
1132
|
+
`;var yr=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`"),Sr=async(e,t,n={},i)=>{let r=Ea();e.sshHost||(e.sshHost="localhost",It.message(tt.yellow("No SSH host provided, defaulting to localhost."))),r.start(`Connecting to remote Mac at ${tt.cyan(e.sshHost)}...`);let o=e.sshUser||process.env.USER||"ubuntu",s=e.sshKey,l=`${o}@${e.sshHost}`,a=`ssh ${s?`-i ${s}`:""} -o StrictHostKeyChecking=no ${l}`,d=`scp ${s?`-i ${s}`:""} -o StrictHostKeyChecking=no`;try{let c=o==="ubuntu"?"/home/ubuntu":`/Users/${o}`,u=(n.PROJECT_ID||"default_project").replace(/[^a-zA-Z0-9-_]/g,"_"),f=`${c}/${m.remoteWorkspacesDir}/${u}`;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(`${d} ${p} ${l}:${f}/source.zip`,{stdio:"inherit"});let h=e.iosApiKeyPath?`${f}/api_key.p8`:"",O="";e.iosApiKeyPath&&(r.message("Uploading App Store Connect API key..."),Lt(`${d} ${e.iosApiKeyPath} ${l}:${h}`),e.iosApiKeyId&&e.iosApiKeyIssuer&&(O=`-authenticationKeyID ${e.iosApiKeyId} -authenticationKeyIssuerID ${e.iosApiKeyIssuer} -authenticationKeyPath ${h}`));let N={};if(i)try{let v=await R.post(`/builds/${i}/${t}/build-urls`,{platform:"ios"});v.data.status==="success"&&(N=v.data.urls)}catch(v){It.warn(tt.yellow(`Could not fetch build URLs: ${v.message}`))}let M="";if(N.credentials&&N.credentials.length>0)for(let v of N.credentials)v.type==="p12"?M+=`curl -sf -o "$CERT_DIR/${v.name}" "${v.downloadUrl}" || true
|
|
1133
|
+
`:v.type==="mobileprovision"&&(M+=`curl -sf -o "$PROV_TEMP/${v.name}" "${v.downloadUrl}" || true
|
|
1134
1134
|
`);r.message("Generating macOS build script...");let P=process.env.CODEARTIFACT_AUTH_TOKEN?`export CODEARTIFACT_AUTH_TOKEN="${process.env.CODEARTIFACT_AUTH_TOKEN}"
|
|
1135
|
-
`:"";if(n)for(let[
|
|
1136
|
-
`}let
|
|
1135
|
+
`:"";if(n)for(let[v,A]of Object.entries(n)){let x=A.replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");P+=`export ${v}="${x}"
|
|
1136
|
+
`}let F=e.buildProfile||"production",S=ut(n,F,e),Y=At(S),ee=[P,N.logUpload?`export PRESIGNED_LOG_UPLOAD="${N.logUpload}"`:"",N.doneMarker?`export PRESIGNED_DONE_MARKER="${N.doneMarker}"`:"",N.cacheDerivedDataDownload?`export PRESIGNED_CACHE_DD_DOWNLOAD="${N.cacheDerivedDataDownload}"`:"",N.cacheDerivedDataUpload?`export PRESIGNED_CACHE_DD_UPLOAD="${N.cacheDerivedDataUpload}"`:"",N.cacheNodeModulesDownload?`export PRESIGNED_CACHE_NODE_DOWNLOAD="${N.cacheNodeModulesDownload}"`:"",N.cacheNodeModulesUpload?`export PRESIGNED_CACHE_NODE_UPLOAD="${N.cacheNodeModulesUpload}"`:"",N.cachePodsDownload?`export PRESIGNED_CACHE_PODS_DOWNLOAD="${N.cachePodsDownload}"`:"",N.cachePodsUpload?`export PRESIGNED_CACHE_PODS_UPLOAD="${N.cachePodsUpload}"`:"",N.artifactIpaUpload?`export PRESIGNED_ARTIFACT_IPA_UPLOAD="${N.artifactIpaUpload}"`:"",N.artifactAppZipUpload?`export PRESIGNED_ARTIFACT_APP_ZIP_UPLOAD="${N.artifactAppZipUpload}"`:"",`export BUILD_ID="${t}"`,`export MACH_BUILD_PROFILE="${yr(F)}"`,`export MACH_APP_NAME="${yr(S.MACH_APP_NAME)}"`,`export MACH_ENV_FINGERPRINT="${Y}"`,"export EXPO_NO_DOTENV=1",`export ${m.envPrefix}PROJECT_ID="${u}"`,n.MATCH_ENCRYPTION_PASSPHRASE?`export MATCH_PASSWORD="${n.MATCH_ENCRYPTION_PASSPHRASE}"`:"",n.APPLE_TEAM_ID?`export FASTLANE_TEAM_ID="${n.APPLE_TEAM_ID}"`:"",`export MATCH_KEYCHAIN_NAME="${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
|
-
`):"",
|
|
1138
|
+
`):"",T=hr,E={"{{REMOTE_DIR}}":f,"{{ENV_VARS}}":ee,"{{CREDENTIAL_DOWNLOADS}}":M,"{{IOS_SCHEME}}":e.iosScheme||"","{{IOS_CONFIG}}":e.iosConfiguration||"Release","{{TEAM_ID}}":e.iosTeamId||"","{{AUTH_PARAMS}}":O,"{{IS_SIMULATOR}}":e.simulator?"true":"false","{{BUILD_ID}}":t,"{{EXPORT_METHOD}}":e.iosExportMethod||"ad-hoc","{{NODE_VERSION_SETUP}}":g};Object.entries(E).forEach(([v,A])=>{T=T.split(v).join(A)});let k=`/tmp/${m.nameLower}-mac-build-${t}.sh`;if(Aa.writeFileSync(k,T),Lt(`${d} ${k} ${l}:${f}/build.sh`),r.stop("Remote script uploaded."),It.info(tt.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 A=(await R.get(`/builds/${i}/${t}/artifacts`)).data.artifacts||[],x=e.simulator===!0;if(A.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!"),A.length>0){It.success("Build Artifacts Ready:");for(let U of A)console.log(`
|
|
1139
1139
|
${tt.yellow(U.name)}:
|
|
1140
1140
|
${tt.cyan(U.downloadUrl)}`);console.log(`
|
|
1141
|
-
${tt.dim("Note: Links are valid for 7 days.")}`)}else L&&At.warn("Simulator build completed. No artifacts uploaded.")}catch(R){r.stop("Could not fetch artifacts"),At.warn(tt.yellow(`Artifact listing failed: ${R.message}`))}}}catch(u){throw r.stop("iOS Build Failed"),u}};import Sa from"crypto";import Me from"axios";import Sr from"fs";var We=6e4,ba=12e4,Xn=4,qe=e=>encodeURIComponent(e),Ea=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||!Aa(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 Ea(s)}throw n}function Aa(e){let t=e.response?.status;return t?t===408||t===409||t===425||t===429||t>=500:!0}async function br(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,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:We}))).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:We}))).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:We}))).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 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 Er(e){let{packageName:t,serviceAccount:n,aabPath:i,track:r,releaseStatus:o,userFraction:s,changesNotSentForReview:l}=e,a;try{let u={Authorization:`Bearer ${await ln(n)}`,Connection:"close"},d=qe(t);if(a=(await Ue("create edit",()=>Me.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${d}/edits`,{},{headers:u,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=Sr.statSync(i),O=await Ue("upload AAB",()=>Me.post(`https://androidpublisher.googleapis.com/upload/androidpublisher/v3/applications/${d}/edits/${p}/bundles`,Sr.createReadStream(i),{headers:{...u,"Content-Type":"application/octet-stream","Content-Length":h.size},maxBodyLength:1/0,maxContentLength:1/0,params:{uploadType:"media"},timeout:ba})),T=Number(O.data.versionCode);if(!T)throw new Error("Google Play upload succeeded but did not return a versionCode.");let x={versionCodes:[String(T)],status:o};return(o==="inProgress"||o==="halted")&&typeof s=="number"&&(x.userFraction=s),await Ue("update track",()=>Me.put(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${d}/edits/${p}/tracks/${qe(r)}`,{releases:[x]},{headers:u,timeout:We})),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:We})),{editId:a,versionCode:T,track:r,releaseStatus:o,userFraction:s}}catch(c){if(a)try{let d=await ln(n);await Ue("delete edit",()=>Me.delete(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${qe(t)}/edits/${qe(a)}`,{headers:{Authorization:`Bearer ${d}`,Connection:"close"},timeout:We}))}catch{}let u=c.response?.data?.error?.message||c.message;throw new Error(`Google Play API Error: ${u}`)}}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=Sa.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:We}))).data.access_token}import Ia from"crypto";import Ar from"axios";var Qn="https://api.appstoreconnect.apple.com/v1",Ir=6e4,Zn=4,wa=e=>new Promise(t=>setTimeout(t,e));function _a(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=Ia.createSign("SHA256");l.update(s);let a=l.sign({key:n,dsaEncoding:"ieee-p1363"}).toString("base64url");return`${s}.${a}`}function $a(e){let t=e.response?.status;return t?t===408||t===409||t===425||t===429||t>=500:!0}async function wr(e,t){let n;for(let i=1;i<=Zn;i++)try{return await t()}catch(r){if(n=r,i>=Zn||!$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(`[App Store Connect] ${e} failed (attempt ${i}/${Zn}); retrying in ${Math.round(s/1e3)}s...`),await wa(s)}throw n}function _r(e){return{Authorization:`Bearer ${_a(e.keyId,e.issuerId,e.privateKey)}`,"Content-Type":"application/json",Connection:"close"}}function va(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 Ra(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 Pa(e){let t=dn(e);return!t||t.length===0?"1":(t[t.length-1]+=1,t.join("."))}async function Da(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 wr("lookup app by bundle ID",()=>Ar.get(`${Qn}/apps`,{headers:_r(e),params:{"filter[bundleId]":n,limit:1},timeout:Ir}))).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 $r(e){let t={keyId:e.keyId,issuerId:e.issuerId,privateKey:e.privateKey};try{let n=await Da(t,e.ascAppId,e.bundleId),i=`${Qn}/builds`,r="0",o,s=0;for(;i&&s<10;){s+=1;let l=await wr("list builds",()=>Ar.get(i,{headers:_r(t),params:i===`${Qn}/builds`?{"filter[app]":n,"fields[builds]":"version,uploadedDate",sort:"-uploadedDate",limit:200}:void 0,timeout:Ir})),a=l.data?.data||[];for(let c of a){let u=String(c.attributes?.version||"").trim();dn(u)&&Ra(u,r)>0&&(r=u,o=c.attributes?.uploadedDate)}i=l.data?.links?.next}return{appId:n,latestBuildNumber:r,nextBuildNumber:Pa(r),latestUploadedDate:o}}catch(n){throw new Error(`App Store Connect API Error: ${va(n)}`)}}import{spinner as cn,log as A,isCancel as un,confirm as Oa,select as ti}from"@clack/prompts";import b from"chalk";import y from"fs";import I from"path";import{execFileSync as Lt,execSync as ee,spawn as Dr}from"child_process";import Ae from"os";import Ca from"crypto";var Or=(e,t)=>t.filter(n=>y.existsSync(I.join(e,n))).reduce((n,i)=>n.update(y.readFileSync(I.join(e,i))),Ca.createHash("sha256")).digest("hex").slice(0,16),Na=e=>Or(e,["package.json","yarn.lock","package-lock.json","bun.lockb"]),Ta=e=>Or(e,["Podfile","Podfile.lock"]),ka=e=>{let t=I.join(e,"fingerprint.json");try{return JSON.parse(y.readFileSync(t,"utf-8"))}catch{return{}}},vr=(e,t)=>{y.mkdirSync(e,{recursive:!0}),y.writeFileSync(I.join(e,"fingerprint.json"),JSON.stringify(t,null,2))},La=7200*1e3,xa=(e,t)=>{y.mkdirSync(e,{recursive:!0});let n=I.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<La)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()}))},Ma=(e,t)=>{let n=I.join(e,"build.lock");try{y.existsSync(n)&&JSON.parse(y.readFileSync(n,"utf-8")).buildId===t&&y.unlinkSync(n)}catch{}},Rr=15e5,Pr=(e,t)=>{let n=e+t;return n.length>Rr?n.slice(-Rr):n},Cr=e=>e.replace(/\u001b\[[0-9;]*m/g,""),Nr=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),Ua=e=>{let t=new Set,n=[];e.forEach((r,o)=>{Nr(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},Ba=(e,t,n,i)=>{let r=Cr(i).replace(/\r/g,`
|
|
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,`
|
|
1142
1142
|
`).split(`
|
|
1143
|
-
`).map(a=>a.trimEnd()).filter(Boolean),o=r.filter(
|
|
1143
|
+
`).map(a=>a.trimEnd()).filter(Boolean),o=r.filter(Tr),s=o.length>0?ja(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(
|
|
1146
|
+
`)}`:""].join("")},Ka=e=>e==="xcodebuild"&&process.env.MACH_XCODE_FULL_LOGS!=="1",Va=e=>{let t=Nr(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{}},za=(e,t)=>{try{if(!y.existsSync(e))return;for(let n of y.readdirSync(e))t(n)&&Be(w.join(e,n))}catch{}},ei=e=>{I.info(b.dim("Clearing Metro/Hermes JS transform caches..."));let t=Ae.tmpdir();za(t,n=>n==="metro-cache"||n.startsWith("metro-")||n.startsWith("haste-map-")||n.startsWith("react-native-packager-cache-")),Be(w.join(e,".expo")),Be(w.join(e,"node_modules/.cache/metro")),Be(w.join(Ae.homedir(),".cache/metro")),Be(w.join(Ae.homedir(),".cache/react-native-packager")),Be(w.join(Ae.homedir(),"Library/Caches/metro")),Be(w.join(Ae.homedir(),"Library/Caches/react-native-packager"))},Wa=e=>/Internal inconsistency error|never received target ended message/i.test(String(e?.message||e)),Ya=e=>{I.warn(b.yellow("Xcode build system hit an internal inconsistency. Clearing simulator build state and retrying once...")),Be(w.join(e,"Build")),Be(w.join(e,"Index.noindex")),Be(w.join(e,"ModuleCache.noindex")),Be(w.join(e,"SourcePackages"))},Ja=(e,t,n,i,r)=>{let o=a=>{let d=a.filter(u=>u?.id&&String(u?.platform||"").includes("iOS Simulator")&&!u?.error),c=d.find(u=>/iphone/i.test(u.name||""))||d[0];return c?.id?`id=${c.id}`:void 0},s=a=>{let d=[],c=!1;for(let u of a.split(`
|
|
1147
|
+
`)){if(/Ineligible destinations/i.test(u)&&(c=!0),c||!u.includes("platform:iOS Simulator")||u.includes("error:"))continue;let f=u.match(/\bid:([^,}]+)/)?.[1]?.trim(),p=u.match(/\bname:([^,}]+)/)?.[1]?.trim();f&&d.push({id:f,name:p,platform:"iOS Simulator"})}return o(d)},l=[t?"-workspace":"-project",t||n,"-scheme",i,"-configuration",r,"-sdk","iphonesimulator","-showdestinations"];try{let a=xt("xcodebuild",[...l,"-json"],{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}),d=JSON.parse(a),c=Array.isArray(d.destinations)?d.destinations:Array.isArray(d.availableDestinations)?d.availableDestinations:[],u=o(c);if(u)return u}catch{}try{let a=xt("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="",d=Ka(e),c=Date.now(),u=["/opt/homebrew/bin","/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin",w.join(Ae.homedir(),".npm-global/bin")],p=[...(process.env.PATH||"").split(":"),...u].filter((P,F,S)=>P&&S.indexOf(P)===F).join(":");process.env[`${m.envPrefix}DEBUG`]&&console.log(b.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(b.magenta(`[ENVIRONMENT] node: ${process.execPath}
|
|
1148
1148
|
`)),r(b.magenta(`[ENVIRONMENT] PATH: ${p}
|
|
1149
1149
|
`)),r(b.magenta(`[ENVIRONMENT] command: ${e} ${t.join(" ")}
|
|
1150
|
-
`)));let O=e;if(["node","npm","npx","pod"].includes(e)){let P=
|
|
1151
|
-
`)))}let
|
|
1150
|
+
`)));let O=e;if(["node","npm","npx","pod"].includes(e)){let P=w.dirname(process.execPath),F=w.join(P,e);y.existsSync(F)&&(O=F,r&&r(b.dim(`[EXEC] Using absolute path: ${O}
|
|
1151
|
+
`)))}let N=Or(O,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 M=(P,F)=>{if(!d){F.write(P);return}let S=P.replace(/\r/g,`
|
|
1152
1152
|
`).split(`
|
|
1153
|
-
`).filter(
|
|
1153
|
+
`).filter(Va);if(S.length>0){F.write(`${S.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),
|
|
1161
|
-
`)),n.BUILD_NUMBER=
|
|
1162
|
-
`)}}catch(g){
|
|
1163
|
-
`)}if(await
|
|
1164
|
-
`),
|
|
1165
|
-
`),
|
|
1166
|
-
`),y.rmSync(
|
|
1155
|
+
`),c=Date.now();return}let Y=Date.now();Y-c>3e4&&(F.write(`[xcodebuild] still running; detailed output is streamed to Mach logs.
|
|
1156
|
+
`),c=Y)};N.stdout.on("data",P=>{let F=P.toString();a=Dr(a,F),M(F,process.stdout),r&&r(F)}),N.stderr.on("data",P=>{let F=P.toString();a=Dr(a,F),M(F,process.stderr),r&&r(F)}),N.on("close",P=>{P===0?s(P):l(new Error(Ga(e,t,P,a)))}),N.on("error",P=>l(P))}),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(" ")},ft=(e,t)=>{let n=[];try{if(!y.existsSync(e))return n;let i=y.readdirSync(e);for(let r of i){let o=w.join(e,r);try{let s=y.statSync(o);if(t.some(a=>r.endsWith(a))){n.push(w.resolve(o));continue}s.isDirectory()&&(n=n.concat(ft(o,t)))}catch{}}}catch{}return n},Xa=/^\d+(?:\.\d+){0,2}$/,ni=e=>{let t=String(e||"").trim();return!t||t==="undefined"||t==="null"?null:Xa.test(t)?t:null},kr=(e,t)=>{let n=ni(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)=>xt("/usr/libexec/PlistBuddy",["-c",`Print :${t}`,e],{encoding:"utf-8"}).trim(),Za=e=>{let t=w.join(e,"Info.plist");if(!y.existsSync(t))throw new Error(`Could not validate iOS build number: ${t} not found.`);return kr(Lr(t,"CFBundleVersion"),t)},Qa=e=>{let n=xt("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: ${w.basename(e)} has no Payload/*.app/Info.plist.`);let i=y.mkdtempSync(w.join(Ae.tmpdir(),`${m.nameLower}-ipa-plist-`));try{let r=w.join(i,"Info.plist"),o=xt("unzip",["-p",e,n.trim()]);return y.writeFileSync(r,o),kr(Lr(r,"CFBundleVersion"),`${w.basename(e)}:${n.trim()}`)}finally{y.rmSync(i,{recursive:!0,force:!0})}},ii=async(e,t,n={},i,r={})=>{let o=cn(),s=Date.now(),l=e.platform,a=e.buildProfile||"production",d=()=>ut(n,a,e),c=async(g,T={})=>{if(i)for(let E=1;E<=3;E++)try{await R.patch(`/builds/${i}/${t}`,{status:g,...T});return}catch(k){let v=k?.response?.data?.message||k?.message||String(k);console.error(`[reportStatus] attempt ${E}/3 failed (status=${g}): ${v}`),E<3&&await new Promise(A=>setTimeout(A,2e3))}},u=new AbortController,{signal:f}=u,p=null;i&&(p=setInterval(async()=>{try{(await R.get(`/builds/${i}/${t}`)).data.status==="cancelled"&&(I.warn(b.yellow(`
|
|
1158
|
+
\u{1F6D1} Build cancelled from dashboard. Terminating...`)),u.abort(),p&&clearInterval(p))}catch{}},5e3));let h=w.join(process.cwd(),".mach-cache"),O="setup",N="",M=null,P=async()=>{if(!N||!i)return;let g=N;N="";try{let T=g;Object.values(n).forEach(E=>{if(E&&E.length>5){let k=E.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");T=T.replace(new RegExp(k,"g"),"[SECRET]")}}),await R.post(`/builds/${i}/${t}/logs`,{log:T,step:O})}catch{}},F=async()=>{M&&(clearTimeout(M),M=null),await P(),Ha(h,t),p&&(clearInterval(p),p=null);try{let g=w.join(Ae.tmpdir(),`${m.buildPrefix}-${t}.keychain-db`);y.existsSync(g)&&(te(`security delete-keychain "${g}"`,{stdio:"ignore"}),I.info(b.dim("\u{1F511} Build keychain deleted.")))}catch{}try{let g=w.join(Ae.homedir(),"Library/MobileDevice/Provisioning Profiles");if(y.existsSync(g)){let T=y.readdirSync(g).filter(E=>E.includes(t)||E.startsWith(`${m.nameLower}-temp-${t}`));for(let E of T)y.unlinkSync(w.join(g,E))}}catch{}},S=async g=>{i&&(N+=g,N.length>=8192?(M&&(clearTimeout(M),M=null),await P()):M||(M=setTimeout(()=>{M=null,P()},2e3)))},Y=async g=>{O=g,await S(`[STEP_START:${g}] ${Math.floor(Date.now()/1e3)}
|
|
1159
|
+
`)},ee=async(g,T,E,k)=>await Fe(g,T,E,k,v=>{S(v)},f);I.info(b.blue(`\u{1F680} Starting local build for ${l} (${a})...`));try{Fa(h,t)}catch(g){throw await c("failed",{error:g.message}),g}if(await c("building"),await Y("setup"),l==="ios"&&!e.simulator&&n.MACH_IOS_BUILD_NUMBER_LOCKED==="1"&&n.BUILD_NUMBER)I.info(b.dim(`Auto build number: ${n.BUILD_NUMBER}`)),await S(`[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,E=await R.post(`/projects/${i}/next-build-number`,{platform:"ios",startFrom:T});if(E.data.status==="success"){let k=ni(String(E.data.buildNumber||""));if(!k)throw new Error(`Dashboard returned invalid iOS build number: "${E.data.buildNumber||""}"`);let v=parseInt(k,10),A=T>0&&Number.isFinite(v)&&v<T?String(T):k;A!==k&&(I.warn(b.yellow(`Dashboard build counter returned ${k}; using minimum ${A}.`)),await S(`[BUILD_NUMBER] Dashboard returned ${k}; using minimum ${A}
|
|
1161
|
+
`)),n.BUILD_NUMBER=A,I.info(b.dim(`Auto build number: ${n.BUILD_NUMBER}`)),await S(`[BUILD_NUMBER] ${n.BUILD_NUMBER}
|
|
1162
|
+
`)}}catch(g){I.warn(b.yellow(`Could not fetch auto build number: ${g.message}`))}await Y("lock"),e.developmentClient?(I.info(b.blue("\u2139\uFE0F Configuring build to INCLUDE expo-dev-client (Development Client mode)...")),delete process.env.EXPO_NO_DEV_CLIENT,delete process.env.EXPO_AUTOLINKING_EXCLUDE):(I.info(b.blue("\u2139\uFE0F Configuring build to EXCLUDE expo-dev-client (Production/Staging mode)...")),process.env.EXPO_NO_DEV_CLIENT="1",process.env.EXPO_AUTOLINKING_EXCLUDE="expo-dev-client");try{await Y("clone"),I.info(b.dim("Preparing source...")),await Y("read_config");let g=w.join(process.cwd(),m.configFileName);if(y.existsSync(g)){let B=JSON.parse(y.readFileSync(g,"utf-8"))?.build?.[a]||{};await S(`[CONFIG] Profile: ${a}, distribution: ${B.distribution||"not set"}, simulator: ${B.simulator||!1}
|
|
1163
|
+
`)}if(await Y("read_package"),e.nodeVersion){let H=process.env.NVM_DIR||w.join(Ae.homedir(),".nvm"),B=w.join(H,"versions","node"),q;if(y.existsSync(B)){let C=y.readdirSync(B).sort().reverse(),j=e.nodeVersion.startsWith("v")?e.nodeVersion:`v${e.nodeVersion}`,X=C.find(ae=>ae===j||ae.startsWith(j+".")||ae.startsWith(`v${e.nodeVersion}.`));X&&(q=w.join(B,X,"bin"))}if(q&&y.existsSync(q)){let C=process.env.PATH||"";process.env.PATH=`${q}:${C}`,await S(`[NODE] Switched to Node ${e.nodeVersion} \u2014 using ${q}
|
|
1164
|
+
`),I.info(b.green(`\u2713 Node switched to ${e.nodeVersion} (${q})`))}else await S(`[NODE] Warning: Node ${e.nodeVersion} not found in nvm. Run: nvm install ${e.nodeVersion} on the build machine.
|
|
1165
|
+
`),I.warn(b.yellow(`Node ${e.nodeVersion} not found in nvm \u2014 using system default`))}await Y("deps"),o.start("Checking dependencies...");let T=Ua(h),E=xa(process.cwd()),k=y.existsSync("node_modules"),v=y.existsSync("yarn.lock"),A=y.existsSync("bun.lockb");k&&T.node&&T.node!==E&&(o.stop("Dependency fingerprint changed \u2014 clearing node_modules for clean install..."),await S(`[CACHE] package.json/lockfile changed \u2014 wiping node_modules
|
|
1166
|
+
`),y.rmSync(w.join(process.cwd(),"node_modules"),{recursive:!0,force:!0}),k=!1);let x="npm",U=["install","--prefer-offline"];v?(x="yarn",U=["install","--prefer-offline"]):A&&(x="bun",U=["install"]),k?o.stop("Cached node_modules found. Syncing dependencies..."):o.stop("No cached dependencies. Running fresh install..."),e.preBuild&&(I.info(b.blue("Running pre-install hook...")),I.info(b.dim(`> ${e.preBuild}`)),await Y("prebuild"),await ee("bash",[e.preBuild],process.cwd(),d())),I.info(b.dim(`Running ${x} ${U.join(" ")}...`)),await ee(x,U,process.cwd(),d()),T.node=E,Rr(h,T);let z=JSON.parse(y.readFileSync("package.json","utf-8")),L=z.dependencies?.expo||z.devDependencies?.expo,W=e.iosBundleIdentifier||"",D=e.name||"";if(L){o.start(`Enforcing ${m.name} configuration...`);let H=w.join(process.cwd(),"app.json"),B=null;if(y.existsSync(H)){B=y.readFileSync(H,"utf-8");let C=JSON.parse(B);C.expo=C.expo||{},D||(D=C.expo.name||""),l==="ios"&&!W&&(W=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 q=["exec","--","expo","prebuild","--platform",l,"--no-install"];try{if(await Y("prebuild"),await ee("npm",q,process.cwd(),d()),l==="ios"&&y.existsSync("ios")){await Y("pods"),I.info(b.blue("Running pod install..."));try{let C=w.resolve("ios"),j=w.join(C,"Podfile");if(!y.existsSync(j))throw new Error("ios/Podfile not found. Skipping pod install.");let X=y.readFileSync(j,"utf-8"),ae=e.iosDeploymentTarget||"13.4";if(!e.developmentClient&&(I.info(b.blue("\u2139\uFE0F Patching Podfile to EXCLUDE expo-dev-client...")),X.includes("use_expo_modules!")&&!X.includes("exclude:"))){let ct=/use_expo_modules!(\s*)$/m;ct.test(X)?X=X.replace(ct,'use_expo_modules!(exclude: ["expo-dev-client"])$1'):X=X.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
|
-
`,Je=/post_install\s+do\s+\|installer\|/;if(Je.test(X))
|
|
1180
|
-
${Se}`),y.writeFileSync(
|
|
1179
|
+
`,Je=/post_install\s+do\s+\|installer\|/;if(Je.test(X))I.info(b.dim(`Injecting deployment target (${ae}) into existing post_install hook...`)),X=X.replace(Je,`post_install do |installer|
|
|
1180
|
+
${Se}`),y.writeFileSync(j,X);else{I.info(b.dim(`Appending new post_install hook for deployment target (${ae})...`));let ct=`
|
|
1181
1181
|
post_install do |installer|
|
|
1182
1182
|
${Se}
|
|
1183
1183
|
end
|
|
1184
|
-
`;y.appendFileSync(
|
|
1185
|
-
`),
|
|
1186
|
-
\u2713 Local build completed successfully in ${ye}`)),await
|
|
1187
|
-
\u{1F4E6} Generated Artifacts:`)),J.forEach(
|
|
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),on=[
|
|
1184
|
+
`;y.appendFileSync(j,ct)}let Ot="/opt/homebrew/bin/pod",rn=y.existsSync(Ot)?Ot:"pod",on=Ma(C);y.existsSync(w.join(C,"Pods"))&&T.pods&&T.pods!==on&&(await S(`[CACHE] Podfile/Podfile.lock changed \u2014 wiping ios/Pods
|
|
1185
|
+
`),I.info(b.dim("Podfile fingerprint changed \u2014 clearing Pods for clean install...")),y.rmSync(w.join(C,"Pods"),{recursive:!0,force:!0})),I.info(b.dim(`Using pod command: ${rn} in ${C}`)),await ee(rn,["install"],C,d()),T.pods=on,Rr(h,T)}catch(C){let j=C.message||"Unknown error";I.warn(b.yellow(`Native "pod" command failed: ${j}`)),I.info(b.dim("Falling back to npm exec pod-install...")),I.info(b.magenta(`${m.nameUpper}_DEBUG: Executing pod-install override via npx --yes pod-install@latest`)),await ee("npx",["--yes","pod-install@latest","ios"],process.cwd(),d())}if(y.existsSync("ios/Pods")){I.info(b.dim("Disabling signing for Pod targets to prevent conflicts..."));try{te(`find ios/Pods -name "project.pbxproj" -exec sed -i '' 's/buildSettings = {/buildSettings = { CODE_SIGNING_ALLOWED = NO; CODE_SIGNING_REQUIRED = NO; PROVISIONING_PROFILE_SPECIFIER = ""; EXPANDED_CODE_SIGN_IDENTITY = "";/g' {} +`,{stdio:"ignore"})}catch{}}}}finally{B&&y.writeFileSync(H,B)}o.stop(`Expo prebuild complete (${m.name} config enforced).`)}let J=[];if(l==="android")await Y("build"),J=await el(e,a,n,H=>S(H),f);else if(l==="ios"){await Y("signing"),I.info(b.dim("Preparing credentials..."));let H=r?.distributionType;J=await tl(e,t,a,n,i,B=>S(B),f,H,B=>Y(B))}e.postBuild&&(I.info(b.blue("Running post-build hook...")),I.info(b.dim(`> ${e.postBuild}`)),await ee(e.postBuild,[],process.cwd(),d()));let ye=qa(Date.now()-s);if(I.success(b.green(`
|
|
1186
|
+
\u2713 Local build completed successfully in ${ye}`)),await c("building",{...W&&{bundleId:W},...D&&{appName:D}}),J.length>0&&(I.info(b.cyan(`
|
|
1187
|
+
\u{1F4E6} Generated Artifacts:`)),J.forEach(H=>{let B=w.resolve(H);I.info(b.dim(` - ${H}`)),I.info(b.gray(` Path: ${B}`))}),e.interactive)){let H=await ka({message:"Install on connected device?"});if(!un(H)&&H){if(l==="android"){let B=J.find(q=>q.endsWith(".apk"))||J[0];await il(B,q=>S(q))}else if(l==="ios"){let B=J.find(C=>C.endsWith(".ipa"))||J.find(C=>C.endsWith(".app"))||J[0],q=Xe("ios");e.simulator?await rl(B,q||"",C=>S(C)):await ol(B,q||"",C=>S(C))}}}await Y("upload");let Ee=[];for(let H of J)try{let B=w.join(Ae.tmpdir(),`${t}-${w.basename(H)}`);y.copyFileSync(H,B),Ee.push(B),I.info(b.dim(` \u{1F4CB} Preserved artifact: ${w.basename(H)}`))}catch{I.warn(b.yellow(` Failed to preserve artifact: ${w.basename(H)}`))}J=Ee,I.info(b.dim("\u{1F9F9} Cleaning workspace (preserving dependency cache)..."));try{let H=process.cwd(),B=new Set(["node_modules"]),q=y.readdirSync(H),C=0;for(let j of q)if(!B.has(j)){if(j==="ios"){let X=w.join(H,"ios"),ae=y.readdirSync(X);for(let Se of ae)if(Se!=="Pods")try{y.rmSync(w.join(X,Se),{recursive:!0,force:!0}),C++}catch{}continue}try{y.rmSync(w.join(H,j),{recursive:!0,force:!0}),C++}catch{}}I.info(b.dim(` Cleaned ${C} items. Cached: node_modules${y.existsSync(w.join(H,"ios","Pods"))?", ios/Pods":""}`)),I.info(b.green("\u{1F512} Security: No source code retained on build server. Only public dependencies cached."))}catch{I.warn(b.yellow("Post-build cleanup encountered errors (non-fatal)."))}try{let B=w.join(Ae.homedir(),m.workspacesDir),q=te(`df -k "${B}" | tail -1 | awk '{print $4}'`,{encoding:"utf8"}).trim(),C=parseInt(q,10)*1024;if(C<53687091200&&y.existsSync(B)){I.info(b.dim(` \u26A0\uFE0F Low disk space (${(C/1024/1024/1024).toFixed(0)} GB free). Running cache eviction...`));let j=w.basename(process.cwd()),X=y.readdirSync(B).filter(ae=>ae!==j).map(ae=>{let Se=w.join(B,ae);try{let Je=y.statSync(Se);return Je.isDirectory()?{name:ae,dir:Se,mtime:Je.mtimeMs}:null}catch{return null}}).filter(Boolean);X.sort((ae,Se)=>ae.mtime-Se.mtime);for(let ae of X){if(C>=53687091200)break;try{y.rmSync(ae.dir,{recursive:!0,force:!0}),I.info(b.dim(` \u{1F5D1}\uFE0F Evicted stale workspace: ${ae.name}`));let Se=te(`df -k "${B}" | tail -1 | awk '{print $4}'`,{encoding:"utf8"}).trim();if(parseInt(Se,10)*1024>=53687091200)break}catch{}}}}catch{}return await F(),J}catch(g){throw await F(),g.message==="Command aborted"?(I.warn(b.yellow(`
|
|
1188
|
+
\u274C Build aborted.`)),await c("failed",{error:"Aborted by user"}),g):(I.error(b.red(`
|
|
1189
|
+
\u2717 Local build failed: ${g.message}`)),await c("failed",{error:g.message}),g)}},el=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(b.blue(`Running Android build: ${l}...`));let a=o.includes("android/")?"android":".",d=(o.includes("android/"),"./gradlew"),c=[l],u={...n,EXPO_NO_DOTENV:"1",MACH_BUILD_PROFILE:t,MACH_APP_NAME:e.appName||e.name||"App"};if(n.ANDROID_VERSION_CODE){let p=w.join(a,"app/build.gradle");if(y.existsSync(p)){let h=n.ANDROID_VERSION_CODE,O=y.readFileSync(p,"utf-8");O=O.replace(/versionCode\s+\d+/,`versionCode ${h}`),y.writeFileSync(p,O),I.info(b.green(`\u2713 Applied Android versionCode ${h}`))}c.push(`-Pandroid.injected.version.code=${n.ANDROID_VERSION_CODE}`)}for(let p of["app/build","build",".cxx"]){let h=w.join(a,p);y.existsSync(h)&&y.rmSync(h,{recursive:!0,force:!0})}ei(process.cwd()),await Fe(d,c,a,u,i,r);let f=w.join(a,"app/build/outputs");return ft(f,[".apk",".aab"])},tl=async(e,t,n,i={},r,o,s,l,a)=>{if(process.platform!=="darwin")throw new Error("iOS builds can only be run on macOS.");let d=w.resolve(process.cwd(),y.existsSync("ios")?"ios":"."),c=y.readdirSync(d),u=c.find(E=>E.endsWith(".xcworkspace")),f=c.find(E=>E.endsWith(".xcodeproj")),p=ut(i,n,e),h=ni(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 O=h?[`BUILD_NUMBER=${h}`,`CURRENT_PROJECT_VERSION=${h}`]:[];if(h&&(p.BUILD_NUMBER=h,p.CURRENT_PROJECT_VERSION=h,I.info(b.dim(`Using iOS build number: ${h}`))),!u&&!f)throw new Error("Could not find Xcode workspace or project in ios/ directory.");try{let E=te("xcode-select -p").toString().trim();I.info(b.dim(`Using Xcode at: ${E}`))}catch{I.warn(b.dim("Could not detect Xcode path."))}I.info(b.blue("Running iOS build via xcodebuild..."));let N=u?u.replace(".xcworkspace",""):f?.replace(".xcodeproj",""),M=e.iosScheme||N||e.scheme,P=e.developmentClient?"Debug":e.iosConfiguration||"Release",F=(r||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),S=w.join(Ae.homedir(),`Library/Developer/Xcode/DerivedData/${m.nameLower}`,F);y.mkdirSync(S,{recursive:!0});let Y=At(p),ee=w.join(S,".mach-env-hash"),g=w.join(S,"Build"),T=y.existsSync(ee)?y.readFileSync(ee,"utf-8").trim():"";if(y.existsSync(g)){let E=T&&T!==Y?"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(b.dim(E)),y.rmSync(g,{recursive:!0,force:!0})}if(y.writeFileSync(ee,Y),ei(process.cwd()),e.simulator){let E=Ja(d,u,f,M,P),k=E?["-destination",E]:[];I.info(b.dim(E?`Building for simulator (Scheme: ${M}, Config: ${P}, Destination: ${E})...`:`Building for simulator (Scheme: ${M}, Config: ${P}; xcodebuild will choose destination)...`));let v=[u?"-workspace":"-project",u||f,"-scheme",M,"-configuration",P,"-sdk","iphonesimulator",...k,"-derivedDataPath",S,...O,"COMPILER_INDEX_STORE_ENABLE=NO","CODE_SIGNING_ALLOWED=NO","CODE_SIGNING_REQUIRED=NO"];try{await Fe("xcodebuild",v,d,p,o,s)}catch(U){if(!Wa(U))throw U;Ya(S),ei(process.cwd()),await Fe("xcodebuild",v,d,p,o,s)}let A=w.join(S,"Build/Products",`${P}-iphonesimulator`),x=ft(A,[".app"]);if(x.length>0){let U=x[0],z=w.basename(U,".app"),L=w.join(A,`${z}_simulator.zip`);return I.info(b.dim(`Creating simulator artifact: ${L}...`)),te(`cd "${A}" && zip -r "${L}" "${w.basename(U)}"`),[L]}return[]}else{I.info(b.dim(`Archiving (Scheme: ${M}, Config: ${P})...`));let E=w.join(d,"build.xcarchive"),k=w.join(d,"export");y.rmSync(E,{recursive:!0,force:!0}),y.rmSync(k,{recursive:!0,force:!0});let v=i.IOS_DIST_P12,A=i.IOS_PROVISIONING_PROFILE,x=i.IOS_P12_PASSWORD||"",U=[],z,L,W={isAppStore:!1,isDevelopment:!1};if(v&&A){I.info(b.blue("\u{1F510} CI/CD Signing: Importing certificates..."));try{let C=`${m.buildPrefix}-${t}.keychain-db`,j=w.join(Ae.tmpdir(),C),X=m.keychainPassword;te(`security create-keychain -p "${X}" "${j}" 2>/dev/null || true`),te(`security set-keychain-settings -t 3600 -l "${j}"`),te(`security unlock-keychain -p "${X}" "${j}"`);let ae=w.join(Ae.tmpdir(),`cert-${t}.p12`),Se=Buffer.from(v,"base64");y.writeFileSync(ae,Se),I.info(b.dim(`P12 data size: ${Se.length} bytes, first bytes: ${Se.slice(0,4).toString("hex")}`)),(Se.length<100||Se[0]!==48)&&(I.warn(b.yellow("\u26A0\uFE0F P12 data looks corrupted or was not decrypted correctly.")),I.warn(b.yellow(" This usually means MACH_ENCRYPTION_KEY on the Remote API differs from when credentials were uploaded.")));let Je=[x,"",m.keychainPassword],Ot=!1;for(let _e of Je)try{te(`security import "${ae}" -k "${j}" -P "${_e}" -A -T /usr/bin/codesign -T /usr/bin/security`,{stdio:"pipe"}),Ot=!0,I.info(b.dim(`\u2713 P12 imported successfully with password: ${_e?"[set]":"[empty]"}`));break}catch(xe){I.info(b.dim(` P12 import attempt with password ${_e?`"${_e.substring(0,3)}..."`:"[empty]"} failed: ${xe.message?.split(`
|
|
1190
|
+
`)[0]||"unknown"}`))}if(!Ot)throw new Error("Failed to import P12.");y.unlinkSync(ae),te(`security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "${X}" "${j}"`);let rn=te("security list-keychains -d user",{encoding:"utf-8"}).split(`
|
|
1191
|
+
`).map(_e=>_e.trim().replace(/^"|"$/g,"")).filter(_e=>_e.length>0),on=[j,...rn].map(_e=>`"${_e}"`).join(" ");te(`security list-keychains -d user -s ${on}`),te(`security default-keychain -s "${j}"`);let sn=w.join(Ae.homedir(),"Library/MobileDevice/Provisioning Profiles");y.mkdirSync(sn,{recursive:!0});let ct=Buffer.from(A,"base64"),Kn=w.join(sn,`${m.nameLower}-temp-${t}.mobileprovision`);y.writeFileSync(Kn,ct);let Vn=ct.toString("utf-8"),Yi=/<key>get-task-allow<\/key>\s*<true\/>/.test(Vn);W={isAppStore:!Vn.includes("<key>ProvisionedDevices</key>")&&!Yi,isDevelopment:Yi};try{let xe=te(`security cms -D -i "${Kn}"`,{encoding:"utf-8"}).match(/<key>UUID<\/key>\s*<string>([^<]+)<\/string>/);L=xe?xe[1]:void 0}catch{let xe=Vn.match(/<key>UUID<\/key>\s*<string>([^<]+)<\/string>/);L=xe?xe[1]:void 0}L||(I.warn("Could not extract UUID from provisioning profile. Using fallback."),L=`${m.nameLower}-${t}`);let zn=w.join(sn,`${L}.mobileprovision`);y.existsSync(zn)&&y.unlinkSync(zn),y.renameSync(Kn,zn);try{let _e=te(`security find-identity -v -p codesigning "${j}"`,{encoding:"utf-8"}),xe=Array.from(_e.matchAll(/"((?:Apple|iPhone) (?:Distribution|Developer|Development)[^"]*)"/g),Ct=>Ct[1]),Ji=W.isDevelopment?xe.find(Ct=>/\b(Development|Developer)\b/.test(Ct)):xe.find(Ct=>/\bDistribution\b/.test(Ct)),qi=xe[0];(Ji||qi)&&(z=Ji||qi,I.info(b.blue(`Identity auto-detected from keychain: "${z}"`)))}catch{}z||(z=W.isDevelopment?"Apple Development":"Apple Distribution",I.info(b.blue(`Identity fallback (profile heuristic): "${z}"`))),I.info(b.dim(`Profile type: ${W.isDevelopment?"Development":W.isAppStore?"App Store":"Ad-Hoc"}`)),I.info(b.dim(`Identity Detection: get-task-allow=${W.isDevelopment}, Selected Identity="${z}"`)),U.push("CODE_SIGN_STYLE=Manual"),U.push(`CODE_SIGN_IDENTITY="${z}"`),U.push(`PROVISIONING_PROFILE_SPECIFIER=${L}`),e.iosTeamId&&U.push(`DEVELOPMENT_TEAM=${e.iosTeamId}`)}catch(C){throw I.error(`Signing setup failed: ${C.message}`),C}}else U.push("-allowProvisioningUpdates"),e.iosTeamId&&U.push(`DEVELOPMENT_TEAM=${e.iosTeamId}`);a&&await a("archive"),I.info(b.blue(`Archive detected Identity: "${z}"`)),I.info(b.blue(`Archive detected UUID: "${L}"`)),await Fe("xcodebuild",["archive",u?"-workspace":"-project",u||f,"-scheme",M,"-configuration",P,"-archivePath",E,"-derivedDataPath",S,...O,...U],d,p,o,s);let D=ft(w.join(E,"Products","Applications"),[".app"]);for(let C of D){let j=Za(C);I.info(b.dim(`Validated iOS CFBundleVersion ${j} in ${w.basename(C)}`))}let J;L?(W.isAppStore?J="app-store":W.isDevelopment?J="development":J="ad-hoc",I.info(b.blue(`Export method from profile: "${J}"`))):(J=e.distribution==="store"?"app-store":e.distribution==="internal"?"ad-hoc":"development",I.warn(b.yellow(`No profile UUID detected. Export method from distribution flag: "${J}"`)));let ye=e.iosExportMethod||J,Ee=e.iosBundleIdentifier||Xe("ios"),H=w.join(d,"ExportOptions.plist"),B=`<?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>
|
|
@@ -1197,51 +1197,56 @@ end
|
|
|
1197
1197
|
<key>destination</key>
|
|
1198
1198
|
<string>export</string>
|
|
1199
1199
|
<key>signingStyle</key>
|
|
1200
|
-
<string>${
|
|
1200
|
+
<string>${L?"manual":"automatic"}</string>
|
|
1201
1201
|
<key>thinning</key>
|
|
1202
1202
|
<string><none></string>
|
|
1203
1203
|
${e.iosTeamId?`<key>teamID</key><string>${e.iosTeamId}</string>`:""}
|
|
1204
|
-
${Ee&&
|
|
1204
|
+
${Ee&&L?`
|
|
1205
1205
|
<key>provisioningProfiles</key>
|
|
1206
1206
|
<dict>
|
|
1207
1207
|
<key>${Ee}</key>
|
|
1208
|
-
<string>${
|
|
1208
|
+
<string>${L}</string>
|
|
1209
1209
|
</dict>`:""}
|
|
1210
1210
|
</dict>
|
|
1211
|
-
</plist>`;if(y.writeFileSync(
|
|
1212
|
-
${B}`)),a&&await a("export"),
|
|
1211
|
+
</plist>`;if(y.writeFileSync(H,B),process.env[`${m.envPrefix}DEBUG`]&&I.info(b.magenta(`[${m.nameUpper}_DEBUG] ExportOptions.plist:
|
|
1212
|
+
${B}`)),a&&await a("export"),I.info(b.blue(`Exporting with Bundle ID: "${Ee}"`)),I.info(b.blue(`Exporting with Method: "${ye}"`)),o){o(b.magenta(`
|
|
1213
1213
|
[DIAGNOSTIC] Checking available signing identities...
|
|
1214
|
-
`));try{let
|
|
1215
|
-
`))}catch(
|
|
1216
|
-
`))}}await Fe("xcodebuild",["-exportArchive","-archivePath",
|
|
1217
|
-
`),o&&o(`[IPA VALID] CFBundleVersion ${
|
|
1218
|
-
`)}catch(
|
|
1219
|
-
`),new Error(X)}return q}},Xe=e=>{try{let t=
|
|
1220
|
-
`).slice(1).map(s=>s.trim()).filter(s=>s.length>0&&!s.startsWith("*")).map(s=>s.split(" ")[0]).length===0){
|
|
1221
|
-
`).filter(a=>a.trim().length>0)}catch{}if(l.length>0){let a=await ti({message:"Select an emulator to launch:",options:l.map(
|
|
1222
|
-
`).find(a=>a.includes("android.intent.action.MAIN")&&a.includes("android.intent.category.LAUNCHER"))?
|
|
1214
|
+
`));try{let C=te("security find-identity -v -p codesigning",{encoding:"utf-8"});o(b.magenta(`${C}
|
|
1215
|
+
`))}catch(C){o(b.red(`[DIAGNOSTIC] Failed to list identities: ${C.message}
|
|
1216
|
+
`))}}await Fe("xcodebuild",["-exportArchive","-archivePath",E,"-exportPath",k,"-exportOptionsPlist",H],d,p,o,s),a&&await a("validate");let q=ft(k,[".ipa"]);for(let C of q)try{te(`unzip -t "${C}"`,{stdio:"pipe"});let j=Qa(C);o&&o(`[IPA VALID] ${w.basename(C)} \u2014 archive integrity OK
|
|
1217
|
+
`),o&&o(`[IPA VALID] CFBundleVersion ${j}
|
|
1218
|
+
`)}catch(j){let X=`IPA validation failed for ${w.basename(C)}: ${j.message||"archive may be corrupt"}`;throw o&&o(`[IPA CORRUPT] ${X}
|
|
1219
|
+
`),new Error(X)}return q}},Xe=e=>{try{let t=w.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=w.resolve(process.cwd(),y.existsSync("ios")?"ios":"."),i=ft(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=ft(n,[".xcodeproj"]);if(r.length>0){let s=w.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},nl=()=>{try{return te("emulator -version",{stdio:"ignore"}),"emulator"}catch{let t=Ae.homedir(),n=[w.join(t,"Library/Android/sdk/emulator/emulator"),w.join(t,"Android/Sdk/emulator/emulator"),"/usr/local/lib/android/sdk/emulator/emulator"];for(let i of n)if(y.existsSync(i))return i}return"emulator"},il=async(e,t)=>{let n=cn();try{if(te("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(b.yellow("No Android devices or emulators found."));let s=nl(),l=[];try{l=te(`${s} -list-avds`).toString().split(`
|
|
1221
|
+
`).filter(a=>a.trim().length>0)}catch{}if(l.length>0){let a=await ti({message:"Select an emulator to launch:",options:l.map(u=>({value:u,label:u}))});if(un(a))return;n.start(`Launching emulator ${a}...`),Or(s,["-avd",a],{detached:!0,stdio:"ignore"}).unref();let d=0,c=!1;for(;d<60;){try{if(te("adb shell getprop sys.boot_completed",{stdio:"pipe"}).toString().trim()==="1"){c=!0;break}}catch{}await new Promise(u=>setTimeout(u,2e3)),d++}if(!c)throw n.stop("Emulator launch timed out."),new Error("Emulator launch timed out. Please try launching it manually.");n.stop("Emulator launched.")}else throw new Error("No devices found and no emulators available to launch. (Make sure Android SDK is installed)")}n.start("Installing APK on device..."),await Fe("adb",["install","-r",e],process.cwd(),{},t),n.stop("Installation complete.");let o=Xe("android");if(o){I.info(b.blue(`\u{1F680} Launching ${o}...`));try{te(`adb shell dumpsys package ${o}`).toString().split(`
|
|
1222
|
+
`).find(a=>a.includes("android.intent.action.MAIN")&&a.includes("android.intent.category.LAUNCHER"))?te(`adb shell monkey -p ${o} -c android.intent.category.LAUNCHER 1`,{stdio:"ignore"}):te(`adb shell monkey -p ${o} -c android.intent.category.LAUNCHER 1`,{stdio:"ignore"})}catch{I.warn("Could not auto-launch app. You may need to open it manually.")}}}catch(i){n.stop("Installation failed."),I.error(b.red(`Failed to install APK: ${i.message}`))}},rl=async(e,t,n)=>{let i=cn();try{if(!te("xcrun simctl list devices booted").toString().includes("(Booted)")){I.warn(b.yellow("No iOS Simulator is currently booted."));let o=te("xcrun simctl list devices --json").toString(),s=JSON.parse(o).devices,l=[];Object.keys(s).forEach(u=>{s[u].forEach(f=>{f.isAvailable&&l.push({...f,runtime:u})})});let a=await ti({message:"Select a simulator to launch:",options:l.map(u=>({value:u.udid,label:`${u.name} (${u.runtime.split(".").pop()})`}))});if(un(a))return;i.start(`Booting ${a}...`),te(`xcrun simctl boot ${a}`),te(`open -a Simulator --args -CurrentDeviceUDID ${a}`);let d=0,c=!1;for(;d<30;){try{if(te("xcrun simctl list devices booted").toString().includes(a)){c=!0;break}}catch{}await new Promise(u=>setTimeout(u,2e3)),d++}if(!c)throw i.stop("Simulator boot timed out."),new Error("Simulator boot timed out.");i.stop("Simulator booted.")}i.start("Installing on iOS Simulator..."),await Fe("xcrun",["simctl","install","booted",e],process.cwd(),{},n),i.stop("Installation complete."),I.info(b.blue(`\u{1F680} Launching ${t}...`)),await Fe("xcrun",["simctl","launch","booted",t],process.cwd(),{},n)}catch(r){i.stop("Installation failed."),I.error(b.red(`Failed to install on Simulator: ${r.message}`))}},ol=async(e,t,n)=>{let i=cn();i.start("Scanning for connected iOS devices...");try{let r=te("xcrun devicectl list devices --json-output -").toString(),s=(JSON.parse(r).result?.devices||[]).filter(a=>a.connectionProperties?.transportType==="wired"||a.connectionProperties?.transportType==="localNetwork");if(s.length===0)throw i.stop("No connected iOS devices found."),new Error("Please connect your iPhone via USB or ensure it is on the same Wi-Fi for wireless debugging.");let l=s[0].identifier;if(s.length>1){i.stop();let a=await ti({message:"Select a device to install on:",options:s.map(d=>({value:d.identifier,label:`${d.deviceProperties?.name||d.name||d.model?.name} (${d.model?.name||"iPhone"}) - ${d.identifier}`}))});if(un(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(b.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(b.red(`Failed to install on device: ${r.message}`)),I.info(b.dim('Make sure your device is unlocked and "Developer Mode" is enabled in Settings -> Privacy & Security.'))}};import K from"fs";import di from"os";import Z from"path";import{spawn as sl,spawnSync as nt}from"child_process";import{randomUUID as al}from"crypto";import{pipeline as ll}from"stream/promises";import{isCancel as si,log as G,select as Hr,spinner as Ut,text as dl}from"@clack/prompts";import Mt from"axios";import V from"chalk";import fn from"adm-zip";async function jr(e){if(e.localRunner){let n=await ml(e);process.exitCode=n?n.exitCode:1;return}if(e.local){let n=await gl(e);n&&(process.exitCode=n.exitCode);return}let t=await ui(e);if(t&&(G.success(V.green(`Maestro run ${t.status||"queued"}: ${t.testRunId}`)),t.launchDeferredReason&&G.warn(V.yellow(t.launchDeferredReason)),t.dashboardUrl&&G.info(V.dim("View test run: ")+V.white.underline(t.dashboardUrl)),e.wait)){let n=await hl(e,t);n&&(process.exitCode=n.status==="passed"?0:1)}}var cl=new Set(["passed","failed","cancelled","interrupted"]),xr=Number(process.env.MACH_FLOW_UPLOAD_MAX_ATTEMPTS||4),ul=Number(process.env.MACH_FLOW_UPLOAD_TIMEOUT_MS||12e4);function ci(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 fl(e){let t=ci(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 pl(e){let t={};for(let[i,r]of Object.entries(process.env))i.startsWith("MAESTRO_TEST_")&&r!==void 0&&(t[i]=r);let n=ci(e);for(let i of n){let r=process.env[i];r!==void 0&&(t[i]=r)}return t}async function ml(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=K.mkdtempSync(Z.join(di.tmpdir(),"mach-maestro-runner-")),s=Z.join(o,"mach-maestro-output"),l=Z.join(o,"runner.log");if(K.mkdirSync(s,{recursive:!0}),!t||!n||!i)return G.error(V.red("--local-runner requires --project-id, --test-run-id, and a runner token.")),{status:"failed",exitCode:1,attempts:0,flows:".maestro",platform:e.platform};let a=null,d=null,c=f=>{K.appendFileSync(l,`${f}${f.endsWith(`
|
|
1223
1223
|
`)?"":`
|
|
1224
|
-
`}`)},u=async(d,f)=>{try{await xt.post(`${r}/internal/tests/${encodeURIComponent(n)}/runner`,{projectId:t,runnerToken:i,status:d,error:f,logPreview:bl(l),junitUrl:a?.urls?.junitDownloadUrl,logsUrl:a?.urls?.logsDownloadUrl,artifactsUrl:a?.urls?.artifactsDownloadUrl})}catch(p){c(`[WARN] Could not post runner update: ${p.message||p}`)}};try{c(`Mach Maestro local runner starting for ${n}`);let d=await xt.post(`${r}/internal/tests/${encodeURIComponent(n)}/runner-payload`,{projectId:t,runnerToken:i});if(d.data?.status!=="success"||!d.data?.payload)throw new Error(d.data?.message||"Runner payload was not returned.");a=d.data.payload;let f=Object.keys(a.env||{});c(`Using Maestro env vars: ${f.length>0?f.join(", "):"none"}`);let p={...process.env,...a.env||{}};await u("running");let h=a.platform==="android"?"app.apk":"app.zip",O=Q.join(o,h),T=Q.join(o,"source.zip"),x=Q.join(o,"source");Y.mkdirSync(x,{recursive:!0}),c("Downloading app artifact..."),await si(a.artifactUrl,O),c("Downloading Maestro source..."),await si(a.urls.sourceUrl,T),new fn(T).extractAllTo(x,!0);let P=El(x,a.flowPath||".maestro");if(!Y.existsSync(P))throw new Error(`Maestro flow path not found: ${a.flowPath||".maestro"}`);if(a.platform==="ios"){await _l(a.device||"iphone_15",l);let C=$l(O,o);Rl(C,l),ai("xcrun",["simctl","install","booted",C],l)}else ai("adb",["install","-r",O],l);let S=Math.max(0,Math.min(10,Number(a.retries??1)))+1,z=Q.join(s,"report.xml"),te=Il(l);if(!te)throw new Error("Maestro CLI not found on this runner. Install Maestro or set MAESTRO_BIN to the full maestro path.");let g=1;for(let C=1;C<=S&&(c(`Running Maestro attempt ${C}/${S}...`),g=Ut(te,["test","--platform",a.platform,P,"--format","junit","--output",z,"--test-output-dir",s],l,void 0,p),g!==0);C+=1);return await Mr(a.urls,o,s,l),g===0?(await u("passed"),j.success(K.green(`Managed Maestro run passed: ${n}`)),{status:"passed",exitCode:0,attempts:S,flows:a.flowPath,platform:a.platform}):(await u("failed",`Maestro exited with code ${g}`),j.error(K.red(`Managed Maestro run failed with exit code ${g}`)),{status:"failed",exitCode:g,attempts:S,flows:a.flowPath,platform:a.platform})}catch(d){let f=d.message||String(d);return c(`MACH_MAESTRO_RUN_FAILED: ${f}`),a?.urls&&await Mr(a.urls,o,s,l),await u("failed",f),j.error(K.red(`Managed Maestro runner failed: ${f}`)),{status:"failed",exitCode:1,attempts:0,flows:a?.flowPath||".maestro",platform:a?.platform||e.platform}}}async function cl(e){let t=e.maestroFlows||".maestro",n=Hr(e.maestroRetries);if(n===null)return null;let i=Q.resolve(t);if(!Y.existsSync(i))return j.error(K.red(`Maestro flows not found: ${t}`)),{status:"failed",exitCode:1,attempts:0,flows:t,platform:e.platform};let r=await hl(e);if(r?.url){if(!await Sl(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&&j.warn(K.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=ll(e.maestroEnv),a=Object.keys(l);if(a.length>0){j.info(K.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){j.info(K.dim(`Running local Maestro attempt ${p}/${c}...`));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";j.error(K.red(`Local Maestro failed to start: ${O}`)),j.info(K.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 Nl(e,f),d==="passed"?j.success(K.green("Local Maestro run passed")):j.error(K.red(`Local Maestro run failed with exit code ${u}`)),f}async function ci(e){let t=$e(`./${m.configFileName}`),n=e.projectId||t?.projectId,i=String(e.profile||e.buildProfile||"production").toLowerCase();if(!n)return j.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 Ur({message:"Select platform for the latest build:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"}]});if(oi(d))return null;r=d}let o=await gl(e);if(!o)return null;if(o.kind==="latest"&&!r)return j.error("Pass --platform when using --latest."),null;if(o.kind==="artifact-url"&&!r)return j.error("Pass --platform when using --artifact-url."),null;let s=Hr(e.maestroRetries);if(s===null)return null;let l=di(e.maestroEnv),a=al(e.maestroEnv);!e.quiet&&l.length>0&&j.info(K.dim(`Forwarding Maestro env vars by name: ${l.join(", ")}`));let c=await fl(e,n);if(c===null)return null;let u=Mt();e.quiet||u.start("Queuing Maestro run...");try{let d=await v.post("/tests/maestro",{projectId:n,platform:r,profile:i,latest:o.kind==="latest",buildId:o.kind==="build-id"?o.value:e.buildId,buildUrl:o.kind==="build-url"?o.value:e.buildUrl,artifactUrl:o.kind==="artifact-url"?o.value:e.artifactUrl,flowSourceKey: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||`${ze}/tests/${f.testRunId}`,launchDeferredReason:f.launchDeferredReason};return Kr(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 j.error(K.red(`Maestro queue failed: ${f}`)),null}}async function ul(e,t){let n=xr(e.waitTimeout,60,"--wait-timeout"),i=xr(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(j.info(K.dim(`Waiting for Maestro run ${t.testRunId} to finish...`));Date.now()-s<=r;){let a=await ml(t.projectId,t.testRunId);if(!a)return null;if(a.status&&a.status!==l&&(l=a.status,j.info(K.dim(`Maestro status: ${l}`))),ol.has(String(a.status)))return Kr(e,a),a.status==="passed"?j.success(K.green(`Maestro run passed: ${a.testRunId}`)):(j.error(K.red(`Maestro run ${a.status}: ${a.testRunId}`)),a.error&&j.error(K.red(String(a.error)))),a;await ui(o)}return j.error(K.red(`Timed out waiting for Maestro run ${t.testRunId} after ${n} minute(s).`)),{...t,status:"timeout"}}async function fl(e,t){if(e.maestroUseBuildSource)return;let n=e.maestroFlows||".maestro",i=Q.resolve(n);if(!Y.existsSync(i))return e.maestroFlows?(j.error(K.red(`Maestro flows not found: ${n}`)),null):void 0;let r=Q.relative(process.cwd(),i);if(!r||r.startsWith("..")||Q.isAbsolute(r))return j.error(K.red("Managed Maestro flow uploads must be inside the current project directory.")),null;let o=Mt();e.quiet||o.start(`Uploading Maestro flows from ${r}...`);try{let s=await v.post("/tests/maestro/source-upload-url",{projectId:t,uploadId:nl()});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(Y.statSync(i).isDirectory())l.addLocalFolder(i,r);else{let u=Q.dirname(r);l.addLocalFile(i,u==="."?void 0:u,Q.basename(r))}let c=l.toBuffer();return await pl(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 j.error(K.red(`Maestro flow upload failed: ${l}`)),null}}function Fr(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 pl(e,t,n,i,r){let o;for(let s=1;s<=Lr;s+=1)try{await xt.put(e,t,{headers:{"Content-Type":n},maxBodyLength:1/0,maxContentLength:1/0,timeout:sl});return}catch(l){if(o=l,!Fr(l)||s>=Lr)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 ui(a)}throw o}async function ml(e,t){try{let n=await v.get(`/tests/${encodeURIComponent(t)}`,{params:{projectId:e}});if(n.data.status!=="success")throw new Error(n.data.message||"Failed to fetch Maestro run");let i=n.data.testRun;return{testRunId:i.testRunId,status:i.status,projectId:e,buildId:i.buildId,platform:i.platform,dashboardUrl:i.dashboardUrl||`${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 j.error(K.red(`Could not fetch Maestro run status: ${i}`)),null}}async function gl(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 Ur({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(oi(t))return null;if(t==="latest")return{kind:"latest"};let n=await rl({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 oi(n)?null:{kind:t,value:String(n).trim()}}function xr(e,t,n){if(e==null||e==="")return t;let i=Number(e);return!Number.isFinite(i)||i<=0?(j.error(`${n} must be a positive number.`),null):i}function ui(e){return new Promise(t=>setTimeout(t,e))}function Hr(e){if(e==null||e==="")return 1;let t=Number(e);return!Number.isInteger(t)||t<0||t>10?(j.error("--maestro-retries must be an integer between 0 and 10."),null):t}async function hl(e){if(e.artifactUrl)return{url:e.artifactUrl,platform:e.platform||pi(e.artifactUrl),name:Gr(e.artifactUrl)};let t=e.buildId||Cl(e.buildUrl);return t?jr(t,e.platform):e.latest?yl(e):null}async function jr(e,t){let n=Mt();n.start(`Resolving build ${e}...`);try{let i=await v.get(`/public/builds/${encodeURIComponent(e)}`);if(i.data.status!=="success")throw new Error(i.data.message||"Build lookup failed");let r=t||i.data.build?.platform,o=Ol(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||pi(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 j.error(K.red(`Local Maestro artifact lookup failed: ${r}`)),null}}async function yl(e){let t=$e(`./${m.configFileName}`),n=e.projectId||t?.projectId,i=String(e.profile||e.buildProfile||"production").toLowerCase();if(!n)return j.error(`No projectId found. Run \`${m.nameLower} link\` first or pass --build-id/--artifact-url.`),null;if(!e.platform)return j.error("Pass --platform when using --latest with --local."),null;let r=Mt();r.start("Resolving latest build...");try{let o=await v.get(`/builds/${n}`,{params:{limit:100}}),l=(Array.isArray(o.data.builds)?o.data.builds:[]).find(a=>a.status==="success"&&a.platform===e.platform&&String(a.buildProfile||a.buildType||"production").toLowerCase()===i);if(!l?.buildId)throw new Error(`No successful ${e.platform} build found for profile ${i}.`);return r.stop(`Latest build resolved: ${l.buildId}`),jr(l.buildId,e.platform)}catch(o){r.stop("Could not resolve latest build");let s=o.response?.data?.message||o.message||"Unknown error";return j.error(K.red(`Latest build lookup failed: ${s}`)),null}}async function Sl(e){let t=e.platform||pi(e.url);if(!t)return j.error(K.red("Could not infer platform for local install. Pass --platform android or --platform ios.")),!1;let n=Y.mkdtempSync(Q.join(li.tmpdir(),"mach-maestro-")),i=e.name||Gr(e.url)||(t==="android"?"app.apk":"app.zip"),r=Q.join(n,i),o=Mt();o.start(`Downloading ${i}...`);try{await si(e.url,r),o.stop("Artifact downloaded")}catch(s){return o.stop("Artifact download failed"),j.error(K.red(s.message||"Failed to download artifact")),!1}return t==="android"?Pl(r):Dl(r,n)}async function si(e,t){let n=await xt.get(e,{responseType:"stream"});await il(n.data,Y.createWriteStream(t))}function bl(e,t=12e3){try{return Y.readFileSync(e,"utf-8").slice(-t)}catch{return""}}function El(e,t){let n=Q.resolve(e,t||".maestro"),i=Q.relative(e,n);if(i.startsWith("..")||Q.isAbsolute(i))throw new Error("Maestro flow path must stay inside the build source.");return n}function Ut(e,t,n,i,r=process.env){Y.appendFileSync(n,`
|
|
1225
|
-
$ ${
|
|
1226
|
-
`);let o=nt(e,t,{cwd:i,encoding:"utf-8",env:r});return o.stdout&&
|
|
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=nt("/usr/bin/plutil",["-extract","CFBundleIdentifier","raw","-o","-",n],{encoding:"utf-8",env:process.env}),r=String(i.stdout||"").trim();return i.status!==0||!r?(
|
|
1235
|
-
`),null):r}function
|
|
1236
|
-
`),
|
|
1237
|
-
`)
|
|
1238
|
-
`)}
|
|
1239
|
-
`)
|
|
1240
|
-
`)}}function Pl(e){if(!e.endsWith(".apk"))return j.error(K.red("Local Android Maestro runs need an APK artifact.")),!1;j.info(K.dim("Installing APK on local Android device/emulator..."));let t=nt("adb",["install","-r",e],{stdio:"inherit",env:process.env});return t.error?(j.error(K.red(`adb failed to start: ${t.error.message}`)),!1):t.status!==0?(j.error(K.red(`adb install failed with exit code ${t.status??1}`)),!1):!0}function Dl(e,t){if(e.endsWith(".ipa"))return j.error(K.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=Q.join(t,"ios-app");Y.mkdirSync(r,{recursive:!0}),new fn(e).extractAllTo(r,!0);let o=fi(r);if(!o)return j.error(K.red("Could not find a .app bundle inside the downloaded zip.")),!1;n=o}if(!n.endsWith(".app"))return j.error(K.red("Local iOS Maestro runs need an iOS Simulator .app bundle or .app.zip artifact.")),!1;j.info(K.dim("Installing app on booted iOS Simulator..."));let i=nt("xcrun",["simctl","install","booted",n],{stdio:"inherit",env:process.env});return i.error?(j.error(K.red(`xcrun failed to start: ${i.error.message}`)),!1):i.status!==0?(j.error(K.red(`iOS Simulator install failed with exit code ${i.status??1}`)),!1):!0}function fi(e){let t=Y.readdirSync(e,{withFileTypes:!0});for(let n of t){let i=Q.join(e,n.name);if(n.isDirectory()&&n.name.endsWith(".app"))return i;if(n.isDirectory()){let r=fi(i);if(r)return r}}return null}function Ol(e,t){let n=String(t||"").toLowerCase();return n==="android"?e.find(i=>It(i,".apk")):n==="ios"?e.find(i=>It(i,".app.zip"))||e.find(i=>It(i,".zip")):e.find(i=>It(i,".apk"))||e.find(i=>It(i,".app.zip"))||e.find(i=>It(i,".zip"))}function It(e,t){return String(e?.name||e?.downloadUrl||e?.url||"").toLowerCase().endsWith(t)}function pi(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 Gr(e){if(e)try{return Q.basename(new URL(e).pathname)||void 0}catch{return Q.basename(e)||void 0}}function Cl(e){return e?e.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i)?.[0]:void 0}function Kr(e,t){if(!e.jsonOutput)return;let n=Q.resolve(e.jsonOutput),i={...t,updatedAt:new Date().toISOString()};try{let r=Q.dirname(n);r&&r!=="."&&Y.mkdirSync(r,{recursive:!0}),Y.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){j.warn(K.yellow(`Could not write Maestro metadata JSON: ${r.message}`))}}function Nl(e,t){if(!e.jsonOutput)return;let n=Q.resolve(e.jsonOutput),i={mode:"local",...t,updatedAt:new Date().toISOString()};try{let r=Q.dirname(n);r&&r!=="."&&Y.mkdirSync(r,{recursive:!0}),Y.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){j.warn(K.yellow(`Could not write Maestro metadata JSON: ${r.message}`))}}import{spinner as ot,text as Bt,select as Si,isCancel as it,cancel as bi,log as Xr}from"@clack/prompts";import ne from"chalk";import se from"fs";import Ie from"path";import{spawn as Tl,spawnSync as pt}from"child_process";import Zr from"axios";import gt from"os";import Ii from"crypto";var kl=5e3,Ll=12,Qr=100,mi=24,Vr=8e3,xl={completed:"completed",draft:"draft",halted:"halted",inprogress:"inProgress","in-progress":"inProgress"},Ml=e=>e?.type==="google_service_account",mn=e=>e?.bundleId||e?.packageName||e?.meta?.packageName||e?.meta?.bundleId,eo=e=>e.submitArgs||process.argv.slice(3).join(" ");async function gn(e){let t=ot(),n=Pe(),i=Ul(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 E=await Si({message:"Select platform to submit:",options:[{value:"ios",label:"iOS (App Store Connect / TestFlight)"},{value:"android",label:"Android (Google Play Console)"}]});if(it(E)){bi("Operation cancelled");return}s=E}if(s=String(s).toLowerCase(),s!=="ios"&&s!=="android"){le(`Platform ${s} is not supported. Use 'ios' or 'android'.`),process.exitCode=1;return}let l=s==="ios"&&!e.local&&e.sshHost?ed(i,o,e):null;if(s==="ios"&&!e.local&&!l){await Bl(i,o,e);return}let a=e.submitId,c=!!(e.local&&a),u=a||null,d=async(E,L={})=>{u&&await Gl(r,u,{status:E,...L})},f=s==="android"?e.packageName||e.androidPackage||Xl(i,o):void 0,p=s==="ios"?e.bundleId||e.iosBundleIdentifier||Ql(i,o):void 0,h,O,T,x=!1;try{s==="android"&&(h=e.track||i.submit?.[o]?.android?.track||i.submit?.production?.android?.track||"internal",O=td(i,o,e.releaseStatus),T=id(i,o,e.rollout),x=rd(i,o,e.changesNotSentForReview),od(O,T))}catch(E){le(E.message),process.exitCode=1;return}if(s==="android"&&!c&&(u=await Fl(i,r,s,o,e,{packageName:f,track:h,releaseStatus:O,rollout:T,changesNotSentForReview:x}),!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:O,rollout:T,startTime:Date.now(),...c?Vl():{}});let P=null,G=null;try{G=await sd(r,s,e,n?.token),P=G?.filePath||null}catch(E){await d("failed",{error:`Failed to resolve submission artifact: ${E.message}`,endTime:Date.now()}),le(`Failed to resolve submission artifact: ${E.message}`),process.exitCode=1;return}if(!P){let E=ld(s,e);await d("failed",{error:E,endTime:Date.now()}),le(E),process.exitCode=1;return}await d("running",{buildId:G?.buildId,artifactName:G?.artifactName,artifactSource:G?.source}),fe(`Using artifact: ${ne.green(Ie.basename(P))} `),t.start("Fetching submission credentials from Dashboard...");let S;try{let L=(await v.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 U=L.filter(Ml),V=s==="ios"?L.filter(k=>k.type==="asc_api_key"):Zl(U,f);if(V.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 k=U.map(mn).filter(Boolean).join(", ");k&&fe(`Found Google Play service credential(s) for: ${k}`),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(S=Wl(V,e.credentialId),!S&&s==="ios"&&p&&(S=Yl(V,p)),S||V.length===1)S=S||V[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"),Jl()){let W=V.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 d("failed",{error:"Multiple submission credentials found; --credential-id is required in CI.",endTime:Date.now()}),process.exitCode=1;return}let k=await Si({message:`Choose a ${s==="ios"?"App Store Connect":"Google Play"} credential:`,options:V.map(W=>({value:W.credentialId,label:W.name,hint:`${W.keyId?`ID: ${W.keyId}`:""} ${W.issuerId?`(Issuer: ${W.issuerId.substring(0,8)}...)`:""}`}))});if(it(k)){bi("Submission cancelled"),await d("failed",{error:"Submission cancelled while selecting credential.",endTime:Date.now()}),process.exitCode=1;return}S=V.find(W=>W.credentialId===k),fe(`Using selected: ${ne.green(S.name)}`)}}catch(E){t.stop("Failed to fetch credentials"),le(`API Error: ${E.message} `),await d("failed",{error:`Failed to fetch credentials: ${E.message}`,endTime:Date.now()}),process.exitCode=1;return}let z=se.mkdtempSync(Ie.join(gt.tmpdir(),`${m.nameLower}-submit-`)),te=S.keyId||S.meta?.keyId,g=S.issuerId||S.meta?.issuerId,C=S.type==="asc_api_key"?`AuthKey_${te}.p8`:"service-account.json",w=Ie.join(z,C);t.start("Downloading secure key...");try{let E=await v.get(`/credentials/${S.credentialId}/download`,{params:{projectId:r,format:"raw"}});if(E.data.status!=="success"||!E.data.downloadUrl)throw new Error("Failed to get secure download URL");let L=await Zr.get(E.data.downloadUrl,{responseType:"arraybuffer"});se.writeFileSync(w,Buffer.from(L.data)),t.stop("Key downloaded to secure temp storage")}catch(E){t.stop("Download failed"),le(`Failed to download key: ${E.message}`);try{se.rmSync(z,{recursive:!0,force:!0})}catch{}await d("failed",{error:`Failed to download credential key: ${E.message}`,endTime:Date.now()}),process.exitCode=1;return}fe(ne.blue(`Initiating ${s==="ios"?"TestFlight":"Google Play"} submission...`));let M=!1,R;try{if(s==="ios"){if(!te){let L=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(L)){await d("failed",{error:"Submission cancelled while entering ASC Key ID.",endTime:Date.now()}),process.exitCode=1;return}te=L}if(!g||g==="undefined"){let L=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(L)){await d("failed",{error:"Submission cancelled while entering ASC Issuer ID.",endTime:Date.now()}),process.exitCode=1;return}g=L}fe(`Using ASC Key ID: ${te}`),fe(`Using ASC Issuer ID: ${g}`);let E=l?await cd(P,w,g,te,p,l):await dd(P,w,g,te,p);Ai(`${s==="ios"?"App Store":"Google Play"} submission successful!`),M=!0}else R=await gd(P,w,h||"internal",f,O||"completed",T,x,o),Ai("Google Play submission successful!"),M=!0}catch(E){le(`Submission failed: ${E.message}`),await d("failed",{error:E.message,endTime:Date.now()}),rt(e,{status:"failed",projectId:r,submitId:u,platform:s,profile:o,buildId:G?.buildId||e.buildId,artifactName:G?.artifactName,error:E.message,dashboardUrl:u?mt(u,r):void 0}),process.exitCode=1}finally{M&&(await d("success",{endTime:Date.now(),versionCode:R?.versionCode,track:h,releaseStatus:O}),rt(e,{status:"success",projectId:r,submitId:u,platform:s,profile:o,buildId:G?.buildId||e.buildId,artifactName:G?.artifactName,versionCode:R?.versionCode,track:h,releaseStatus:O,dashboardUrl:u?mt(u,r):void 0})),Od(z),P&&P.includes(`${m.nameLower}-artifact-`)}}function Ul(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 Bl(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||Ii.randomUUID(),o=!!n.latest||!n.buildId,s=Hl({...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:eo(n),runnerArgs:s,runnerCommand:[m.nameLower,"submit",...s].map(ql).join(" "),appName:e.name,startTime:Date.now()},a=ot();a.start("Queuing iOS submit on macOS runner...");try{let c=await v.post("/submissions",l),u=c.data?.submission||c.data?.submit||{},d=c.data?.dashboardUrl||mt(r,i);a.stop("iOS submit queued"),fe(`Submission ID: ${ne.cyan(r)}`),fe(`Dashboard: ${ne.blue.underline(d)}`),rt(n,{status:"pending",projectId:i,submitId:r,platform:"ios",profile:t,latest:o,buildId:n.buildId,dashboardUrl:d}),await jl(i,r,n)}catch(c){a.stop("Could not queue iOS submit"),le(zl(c)),process.exitCode=1}}async function Fl(e,t,n,i,r,o={}){let s=r.submitId||Ii.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:eo(r),appName:e.name,startTime:Date.now(),...o};try{let c=await v.post("/submissions",a),u=c.data?.submission||c.data?.submit||{},d=c.data?.dashboardUrl||u.dashboardUrl||mt(s,t);return fe(`Submission ID: ${ne.cyan(s)}`),fe(`Dashboard: ${ne.blue.underline(d)}`),rt(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(ne.yellow(`Could not create submission tracking record: ${u}`)),null}}function Hl(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 v.get(`/submissions/${e}/${t}`),l=s.data?.submission||s.data?.submit||s.data,a=String(l?.status||"pending").toLowerCase();r=0;let c=Array.isArray(l?.logs)?l.logs:[];for(let u=o;u<c.length;u++){let d=c[u];d&&console.log(ne.dim(String(d)))}if(o=c.length,["success","completed","succeeded"].includes(a)){n.quiet||i.stop("iOS submit completed"),Ai("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||mt(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),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:u,dashboardUrl:l?.dashboardUrl||mt(t,e)}),process.exitCode=1;return}n.quiet||i.message(`iOS submit ${a}...`),await Ei(kl)}catch(s){if(r++,r>=Ll){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 Ei(Math.min(2e3*r,15e3))}}async function Gl(e,t,n){let i;for(let r=1;r<=3;r++)try{await v.patch(`/submissions/${e}/${t}`,n);return}catch(o){if(i=o,r>=3||!Kl(o))break;await Ei(1e3*r)}Xr.warn(ne.dim(`Could not report submission status: ${i?.message||i}`))}function Kl(e){let t=e.response?.status;return!t||t===408||t===409||t===425||t===429||t>=500}function Vl(){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 zl(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(`
|
|
1241
|
-
`):n||e.message||String(e)}function mt(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||mt(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){Xr.warn(ne.yellow(`Could not write submission metadata JSON: ${r.message}`))}}function Wl(e,t){return t&&e.find(n=>n.credentialId===t||n.id===t||n.keyId===t||n.meta?.keyId===t)||null}function Yl(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 Jl(){return process.env.CI==="true"||process.env.CI==="1"||!process.stdin.isTTY}function Ei(e){return new Promise(t=>setTimeout(t,e))}function ql(e){return/^[a-zA-Z0-9_./:=@-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function Xl(e,t){if(e.submit?.[t]?.android?.package)return e.submit[t].android.package;let n=er(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 Zl(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 Ql(e,t){return e.submit?.[t]?.ios?.bundleIdentifier?e.submit[t].ios.bundleIdentifier:e.submit?.[t]?.ios?.bundleId?e.submit[t].ios.bundleId:tr(e,t)}function ed(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 td(e,t,n){let i=n||e.submit?.[t]?.android?.releaseStatus||e.submit?.production?.android?.releaseStatus||"completed";return nd(i)}function nd(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 id(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 rd(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 od(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 sd(e,t,n,i){let r=n.buildId?"id":n.latest?"latest":null;if(!r){let s=await Si({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 bi("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 v.get(`/builds/${e}`,{params:{limit:50}});if(l.data.status!=="success")throw new Error(l.data.message);let a=l.data.builds||[],c=s?.toLowerCase(),u=S=>S.platform?.toLowerCase()===t.toLowerCase()&&S.status?.toLowerCase()==="success",d=S=>c?[S.buildProfile,S.profile,S.profileName,S.buildType].filter(Boolean).some(z=>String(z).toLowerCase()===c):!0,f=a.filter(S=>u(S)&&d(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 v.get(`/builds/${e}/${p.buildId}/artifacts`);S.data.status==="success"&&S.data.artifacts?.length>0?(O=S.data.artifacts.map(z=>({...z,url:z.url||z.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 x=t==="ios",P=O.find(S=>{let z=(S.type||"").toLowerCase(),te=(S.name||"").toLowerCase();if(console.log(ne.dim(` - Checking: ${S.name} (Type: ${S.type}, HasLink: ${!!(S.url||S.downloadUrl)})`)),z)return z===(x?"ipa":"aab");let g=x?".ipa":".aab",C=(S.url||S.downloadUrl||"").toLowerCase();return te.endsWith(g)||C.includes(g)});if(!P||!(P.url||P.downloadUrl))return le("Build found but artifact URL is missing."),null;let G=P.url||P.downloadUrl;return{filePath:await gi(G,x?"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 v.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 v.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=pn(a.artifacts);ad(u)||(u=await Wr(e,l,u));let d=zr(u,t);if(d||(u=await Wr(e,l,u),d=zr(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 gi(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 Bt({message:"Enter Artifact URL:",validate:l=>l.startsWith("http")?void 0:"Must be a valid URL"});return it(s)?null:{filePath:await gi(s,t),source:"url"}}return null}function pn(e){return(e||[]).map(t=>({...t,url:t.url||t.downloadUrl}))}function ad(e){return e.some(t=>!!(t.url||t.downloadUrl))}function zr(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 ld(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 Wr(e,t,n){try{let i=await v.get(`/builds/${e}/${t}/artifacts`);if(i.data.status==="success"&&i.data.artifacts?.length>0){let r=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 v.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 gi(e,t,n=3){let i=ot();i.start("Downloading artifact...");let r=se.mkdtempSync(Ie.join(gt.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 Zr({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 dd(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=to(t,n,i),l=yd();return o.start("Uploading to TestFlight (pilot)..."),new Promise((a,c)=>{let u=bd(),d=Tl(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(Ed(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=Pd(f);p.logs=u.lines(),c(p)})})}async function cd(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=to(t,n,i),a=`${o.sshUser}@${o.sshHost}`,c=ud(o),u=fd(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..."),hi("scp",[...u,e,`${a}:${d}/app.ipa`],"IPA upload to remote runner"),hi("scp",[...u,l,`${a}:${d}/api_key.json`],"ASC key upload to remote runner"),f=Ie.join(gt.tmpdir(),`${m.nameLower}-ios-submit-${Date.now()}.sh`),se.writeFileSync(f,md(d)),hi("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 ${Ft(`${d}/submit.sh`)} && bash ${Ft(`${d}/submit.sh`)}`,h=pt("ssh",[...c,p],{stdio:"inherit"});if(h.error)throw wi("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{pt("ssh",[...c,`rm -rf ${Ft(d)}`],{stdio:"ignore"})}catch{}}}function to(e,t,n){let i=se.readFileSync(e,"utf8"),r;try{r=Ii.createPrivateKey(i).export({type:"pkcs8",format:"pem"})}catch{fe("Key normalization failed, falling back to manual re-wrapping..."),r=`-----BEGIN PRIVATE KEY-----
|
|
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
|
+
$ ${Rl(e,t)}
|
|
1226
|
+
`);let o=nt(e,t,{cwd:i,encoding:"utf-8",env:r});return o.stdout&&K.appendFileSync(n,o.stdout),o.stderr&&K.appendFileSync(n,o.stderr),o.error?(K.appendFileSync(n,`${o.error.message}
|
|
1227
|
+
`),1):typeof o.status=="number"?o.status:1}function li(e,t,n,i){let r=pt(e,t,n,i);if(r!==0)throw new Error(`${e} ${t.join(" ")} failed with exit code ${r}`)}function Pl(e){try{return K.accessSync(e,K.constants.X_OK),!0}catch{return!1}}function Dl(e){let t=[process.env.MAESTRO_BIN,Z.join(di.homedir(),".maestro","bin","maestro"),"/opt/homebrew/bin/maestro","/usr/local/bin/maestro"].filter(Boolean),n=nt("/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&&Pl(r))return e&&K.appendFileSync(e,`Using Maestro CLI at ${r}
|
|
1229
|
+
`),r;return e&&K.appendFileSync(e,`Maestro CLI not found. Checked: ${t.join(", ")}
|
|
1230
|
+
`),null}function Ol(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 Cl(e,t){if((nt("xcrun",["simctl","list","devices","booted"],{encoding:"utf-8"}).stdout||"").includes("(Booted)")){K.appendFileSync(t,`Using already booted iOS Simulator.
|
|
1231
|
+
`);return}let i=Ol(e),r=nt("xcrun",["simctl","list","devices","--json"],{encoding:"utf-8"});if(r.status!==0||!r.stdout)throw new Error("Could not list iOS simulators.");let o=JSON.parse(r.stdout),s=Object.values(o.devices||{}).flatMap(d=>Array.isArray(d)?d:[]).filter(d=>d?.isAvailable),l=s.find(d=>d.name===i)||s.find(d=>String(d.name||"").toLowerCase().includes(i.toLowerCase()))||s.find(d=>String(d.name||"").startsWith("iPhone"));if(!l?.udid)throw new Error(`No available iOS Simulator found for ${i}.`);K.appendFileSync(t,`Booting iOS Simulator ${l.name} (${l.udid})...
|
|
1232
|
+
`),pt("xcrun",["simctl","boot",l.udid],t)!==0&&K.appendFileSync(t,`simctl boot returned non-zero; continuing to bootstatus in case it was already booting.
|
|
1233
|
+
`),li("xcrun",["simctl","bootstatus",l.udid,"-b"],t)}function Nl(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=Z.join(t,"ios-app");K.mkdirSync(n,{recursive:!0}),new fn(e).extractAllTo(n,!0);let i=pi(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 zr(e,t){let n=Z.join(e,"Info.plist");if(!K.existsSync(n))return K.appendFileSync(t,`Could not find Info.plist in ${e}; skipping uninstall.
|
|
1234
|
+
`),null;let i=nt("/usr/bin/plutil",["-extract","CFBundleIdentifier","raw","-o","-",n],{encoding:"utf-8",env:process.env}),r=String(i.stdout||"").trim();return i.status!==0||!r?(K.appendFileSync(t,`Could not read CFBundleIdentifier from Info.plist; skipping uninstall.
|
|
1235
|
+
`),null):r}function ri(e,t,n){let i=Z.join(e,n);pt("xcrun",["simctl","io","booted","screenshot",i],t)!==0&&K.appendFileSync(t,`[WARN] Could not capture iOS simulator screenshot: ${n}
|
|
1236
|
+
`)}function Tl(e,t){let n=Z.join(e,"ios-simulator-recording.mp4");K.appendFileSync(t,`Starting iOS simulator recording: ${n}
|
|
1237
|
+
`);let i=sl("xcrun",["simctl","io","booted","recordVideo",n],{stdio:["ignore","pipe","pipe"],env:process.env});return i.stdout?.on("data",r=>{K.appendFileSync(t,r)}),i.stderr?.on("data",r=>{K.appendFileSync(t,r)}),i.on("error",r=>{K.appendFileSync(t,`[WARN] Could not start iOS simulator recording: ${r.message}
|
|
1238
|
+
`)}),i}async function Br(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||(K.appendFileSync(t,`Stopping iOS simulator recording...
|
|
1239
|
+
`),e.kill("SIGINT")),setTimeout(()=>{!i&&!e.killed&&(K.appendFileSync(t,`[WARN] iOS simulator recording did not stop after SIGINT; sending SIGKILL.
|
|
1240
|
+
`),e.kill("SIGKILL")),r()},5e3).unref?.()})}function kl(e,t){let n=zr(e,t);if(!n)return;K.appendFileSync(t,`Uninstalling existing iOS app data for ${n} if present...
|
|
1241
|
+
`),pt("xcrun",["simctl","uninstall","booted",n],t)!==0&&K.appendFileSync(t,`No existing app install removed for ${n}; continuing.
|
|
1242
|
+
`)}async function oi(e,t,n){if(!K.existsSync(e))return;let i=K.readFileSync(e),r;for(let o=1;o<=3;o+=1)try{await Mt.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,!Gr(s)||o>=3)break;await fi(2e3*o)}throw r}async function Fr(e,t,n,i){let r=Z.join(n,"report.xml"),o=Z.join(t,"artifacts.tar.gz");try{await oi(r,e.junitUploadUrl,"application/xml")}catch(s){K.appendFileSync(i,`[WARN] Failed to upload JUnit report: ${s.message||s}
|
|
1243
|
+
`)}try{await oi(i,e.logUploadUrl,"text/plain")}catch(s){K.appendFileSync(i,`[WARN] Failed to upload runner log: ${s.message||s}
|
|
1244
|
+
`)}try{pt("tar",["-czf",o,"-C",t,Z.basename(n)],i),await oi(o,e.artifactsUploadUrl,"application/gzip")}catch(s){K.appendFileSync(i,`[WARN] Failed to upload Maestro artifacts: ${s.message||s}
|
|
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-----
|
|
1242
1247
|
${(i.replace(/-----BEGIN[^-]*-----/g,"").replace(/-----END[^-]*-----/g,"").replace(/\s+/g,"").match(/.{1,64}/g)||[]).join(`
|
|
1243
1248
|
`)}
|
|
1244
|
-
-----END PRIVATE KEY-----`}let o=Ie.join(
|
|
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 Sd(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 bd(e){let t=["-o","StrictHostKeyChecking=no","-o","ServerAliveInterval=30"];return e.sshKey&&t.push("-i",e.sshKey),t}function Ed(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 yi(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 Ft(e){return`'${e.replace(/'/g,"'\\''")}'`}function Ad(e){let t=Ft(`${e}/app.ipa`),n=Ft(`${e}/api_key.json`);return`#!/bin/bash
|
|
1245
1250
|
set -euo pipefail
|
|
1246
1251
|
|
|
1247
1252
|
export PATH="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:$HOME/.local/share/fastlane/3.4.0/bin:$PATH"
|
|
@@ -1269,39 +1274,39 @@ fastlane pilot upload \\
|
|
|
1269
1274
|
--api_key_path ${n} \\
|
|
1270
1275
|
--skip_submission true \\
|
|
1271
1276
|
--skip_waiting_for_build_processing true
|
|
1272
|
-
`}async function
|
|
1277
|
+
`}async function Id(e,t,n="internal",i,r="completed",o,s=!1,l="production"){let a=ot();if(!i||i==="*")throw new Error("Android package name is required for Google Play submission.");let d=o!==void 0?` (${o} rollout)`:"";a.start(`Uploading to Google Play ${n} track with ${r} release status${d}...`);try{let c=JSON.parse(se.readFileSync(t,"utf-8"));wd(c);let u=await Ar({packageName:i,serviceAccount:c,aabPath:e,track:n,releaseStatus:r,userFraction:o,changesNotSentForReview:s});return a.stop(`AAB uploaded to ${n} track (versionCode ${u.versionCode})`),u}catch(c){throw a.stop("Google Play upload failed"),new Error(xd(c,n,i,l))}}function wd(e){if(!e?.client_email||!e?.private_key)throw new Error("Invalid Google service account JSON: missing client_email or private_key.")}function Si(){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 _d(){let e=Si(),t=Zr(e);if(t)return t;if(process.env.MACH_SKIP_FASTLANE_INSTALL!=="1"){$d(e);let n=Zr(Si());if(n)return n}return{command:"fastlane",env:Si()}}function Zr(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 $d(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(ne.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(ne.yellow("Automatic fastlane install failed; Mach will try PATH resolution once more."))}function vd(e=io){let t=[],n="",i=r=>{let o=ao(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 Rd(e,t){let n=new Error(Pd(e,t));return n.logs=so(t),n.exitCode=e,n}function Pd(e,t){let n=`fastlane pilot failed with exit code ${e??"unknown"}.`,i=Dd(t);return i.length===0?n:`${n}
|
|
1273
1278
|
|
|
1274
1279
|
Fastlane output:
|
|
1275
1280
|
${i.join(`
|
|
1276
|
-
`)}`}function
|
|
1277
|
-
`),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
|
|
1278
|
-
`))}function
|
|
1281
|
+
`)}`}function Dd(e){let t=so(e);if(t.length===0)return[];let n=Qr(t.filter(Cd)),i=Od(t);if(i)return[i,...eo(n,gi-1,Jr)];let r=n.length>0?n:t.slice(-gi);return eo(Qr(r),gi,Jr)}function Od(e){let t=e.join(`
|
|
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 Cd(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 Qr(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 eo(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 so(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=ao(r);o&&t.push(o)}}return t.slice(-io)}function ao(e){return Td(Nd(e).trimEnd()).trim()}function Nd(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 Td(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(kd(i),"g"),"[REDACTED]"));return t}function kd(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ld(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(`
|
|
1283
|
+
`))}function xd(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(`
|
|
1279
1284
|
`);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(`
|
|
1280
1285
|
`);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(`
|
|
1281
1286
|
`);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(`
|
|
1282
1287
|
`);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(`
|
|
1283
1288
|
`);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(`
|
|
1284
|
-
`);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 Od(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 Ai(e){console.log(ne.green(`\u2713 ${e}`))}var _i=8,Td=6,co=Number(process.env.MACH_ARTIFACT_UPLOAD_MAX_ATTEMPTS||2),$i=Number(process.env.MACH_ARTIFACT_UPLOAD_TIMEOUT_MS||12e4),kd=[{value:"production",label:"production",hint:"Store / release build"},{value:"staging",label:"staging",hint:"Internal testing build"},{value:"development",label:"development",hint:"Development build"}],wo=e=>new Promise(t=>setTimeout(t,e)),Ld=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},Md=()=>{let e=$e(`./${m.configFileName}`),t=e?.build&&typeof e.build=="object"?e.build:{},n=Object.keys(t);return n.length===0?kd:n.map(i=>({value:i,label:i,hint:xd(t[i])}))},Ud=async e=>{let t=Ld(e);if(!e.platform&&t){let n=await ro({message:"Select platform",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"}]});bn(n)&&(so("Build cancelled."),process.exit(0)),e.platform=n}if(!e.buildProfile&&t){let n=Md(),i=await ro({message:"Select build profile",options:n,initialValue:n.find(r=>r.value==="production")?.value||n[0]?.value});bn(i)&&(so("Build cancelled."),process.exit(0)),e.buildProfile=i}e.buildProfile||(e.buildProfile="production")},uo=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},_o=(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,"")}},Bd=(e,t)=>!!e&&t.some(n=>new RegExp(`(?:^|\\s)${n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:\\s|$)`).test(e)),Fd=e=>{let n=_o(e,["--platform"])||e?.split(/\s+/).find(i=>i==="ios"||i==="android");return n==="ios"||n==="android"?n:void 0},Hd=async e=>{if(!(!e.projectId||!e.buildId))try{let t=await v.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||Fd(i);(r==="ios"||r==="android")&&(e.platform=r)}if(e.buildProfile||(e.buildProfile=n.buildProfile||n.profile||n.profileName||_o(i,["--profile","--build-profile","-p"])),e.simulator===void 0){let r=uo(n.simulator??n.isSimulator);r!==void 0?e.simulator=r:Bd(i,["--simulator"])&&(e.simulator=!0)}if(e.developmentClient===void 0){let r=uo(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]}`},Gd=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=Td)=>{let i;for(let r=1;r<=n;r++)try{return await t()}catch(o){if(i=o,!Gd(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 wo(s)}throw i},Kd=async(e,t,n)=>{let i=ve.basename(e),r=de.statSync(e).size,o=Math.round($i/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()},$i);try{await Sn.put(t,l,{headers:{"Content-Type":n,"Content-Length":r,Connection:"close"},maxBodyLength:1/0,maxContentLength:1/0,timeout:$i,timeoutErrorMessage:`Artifact upload timed out after ${o}s`,signal:s.signal})}finally{clearTimeout(a)}},co)}catch(s){throw new Error(`${i} (${jd(r)}) failed after ${co} upload attempt(s): ${s.message||s}`)}return r},Vd=e=>{let t=e.response?.status;return t?t===408||t===429||t>=500:!0},Ht=e=>e.credentialId||e.id,zd=async(e,t)=>{let n=Ht(e);if(!n)return e.downloadUrl;let i=await v.get(`/credentials/${n}/download`,{params:{projectId:t,format:"raw"}});return i.data?.status==="success"&&i.data?.downloadUrl?i.data.downloadUrl:e.downloadUrl},$o=async(e,t)=>{let n=e.downloadUrl;for(let i=1;i<=_i;i++)try{if((!n||i>1)&&(n=await zd(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||!Vd(r))throw r;let o=Math.min(1500*i*i,15e3);_.warn($.dim(` - Temporary network error downloading ${e.name}. Retrying... (${i}/${_i})`)),await wo(o)}throw new Error(`Failed to download credential ${e.name||Ht(e)||"unknown"}.`)},fo=async(e,t)=>{let n=await $o(e,t);return Buffer.from(n,"base64").toString("utf8")},Wd=(e,t)=>{try{return JSON.parse(e)}catch{throw new Error(`${t} is not valid JSON.`)}},Yd=e=>/ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|ECONNABORTED|socket hang up|network|timeout/i.test(e),Jd=(e,t)=>t?.ios?.buildNumber??t?.iosBuildNumber??e?.ios?.buildNumber??e?.expo?.ios?.buildNumber,qd=(e,t,n)=>t?.ios?.ascAppId??t?.ascAppId??e?.ios?.ascAppId??e?.submit?.[n]?.ios?.ascAppId??e?.submit?.production?.ios?.ascAppId,po=e=>e.bundleId||e.bundleIdentifier||e.meta?.bundleId||e.meta?.bundleIdentifier,mo=(e,t)=>{let n=e.filter(i=>i.type==="asc_api_key");if(n.length!==0){if(t){let i=n.find(o=>po(o)===t);if(i)return i;let r=n.find(o=>po(o)==="*");if(r)return r}return n[0]}},Xd=e=>typeof e=="string"&&e.trim().toLowerCase()==="auto",vo=(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()?vo(o,t,n):r.name===t&&n.push(o)}return n},Zd=(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},Qd=(e,t)=>{let n=ve.resolve(process.cwd(),de.existsSync("ios")?"ios":"."),i=vo(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:Zd(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},go=(e,t,n)=>{let i=En(e.distributionType||e.meta?.distributionType,n);return i?i===En(t,n):!0},ho=(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},ec=e=>{let t=e.toLowerCase();return t==="development"||t==="dev"||t.startsWith("development-")||t.startsWith("dev-")||t.endsWith("-development")||t.endsWith("-dev")},tc=e=>{let t=e.toLowerCase();return t.includes("staging")||t.includes("stage")||t.includes("preview")||t.includes("adhoc")||t.includes("ad-hoc")},nc=(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":ec(t)?"development":(tc(t),"adhoc")},Ro=e=>e.bundleId||e.bundleIdentifier||e.packageName||e.meta?.bundleId||e.meta?.bundleIdentifier||e.meta?.packageName,yo=(e,t)=>{if(!t)return!0;let n=Ro(e);return!n||n==="*"||n===t},So=(e,t)=>{let n=Ro(e);return!t||!n?0:n===t?2:n==="*"?1:-1},Po=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}},ic=(e,t)=>{if(e===t||e==="*")return!0;if(e.endsWith(".*")){let n=e.slice(0,-2);return t.startsWith(`${n}.`)}return!1},rc=(e,t)=>{if(!t)return!0;let n=Po(e);if(n)return ic(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 v.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 Hd(e),await Ud(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=Ri(),n=e.buildId||Cd(),i=e.projectId,r=Date.now(),o=!!i,s=async l=>{if(i)try{await v.patch(`/builds/${i}/${n}`,{status:"failed",error:l})}catch{}};if(e.local&&e.buildId){e.quiet||t.start(`Preparing isolated workspace for build: ${e.buildId}`);try{let l=await v.get(`/builds/${i}/${e.buildId}/source-url`);if(l.data.status!=="success")throw new Error("Failed to get source download URL from API");let a=await Sn.get(l.data.downloadUrl,{responseType:"stream"}),c=(i||e.projectId||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),u=ve.join(Nd.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 x=de.readdirSync(u);for(let P of x){if(d.has(P))continue;if(P==="ios"){let S=ve.join(u,"ios");try{let z=de.readdirSync(S);for(let te of z)if(!f.has(te))try{de.rmSync(ve.join(S,te),{recursive:!0,force:!0})}catch{}}catch{}continue}let G=ve.join(u,P);try{de.rmSync(G,{recursive:!0,force:!0})}catch{}}}let p=ve.join(u,"source.zip"),h=a.data,O=de.createWriteStream(p);await new Promise((x,P)=>{h.pipe(O),h.on("error",G=>P(G)),O.on("finish",()=>x())}),new lo(p).extractAllTo(u,!0);try{de.unlinkSync(p)}catch{}process.chdir(u),_.info($.green(`\u2713 Persistent workspace ready: ${u}`)),_.info($.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=ao("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={},c={},u=null,d=$e(`./${m.configFileName}`);if(d){u=d,i=d.projectId;let g=e.buildProfile||"production",C=et(d,g);!C&&e.buildProfile&&(_.error(`Build profile '${g}' not found in ${m.configFileName}`),process.exit(1));let w=C||{};process.env.MACH_DEBUG&&_.info($.dim(`Build profile: ${g} | Platform: ${e.platform} | Distribution: ${w.distribution||"store"} | Environment: ${w.environment||g}`)),w.env&&(c=w.env,_.info($.blue(`Use Build Profile: ${g}`)));let M=e.platform,R=w[M]||{},E=["developmentClient","simulator","distribution","buildCommand","apk","iosScheme","preBuild","postBuild","scheme","environment","androidPackage","iosBundleIdentifier","name","iosDeploymentTarget","iosApiKeyId","iosApiKeyIssuer","iosApiKeyPath","iosTeamId","iosConfiguration","iosExportMethod","branch","repo","instanceType","ami","bucket","region","nodeVersion"];e.name=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 L=k=>k==="androidPackage"?R.androidPackage??R.package??w.androidPackage??w.android?.package:k==="iosBundleIdentifier"?R.iosBundleIdentifier??R.bundleIdentifier??w.iosBundleIdentifier??w.ios?.bundleIdentifier:R[k]!==void 0?R[k]:w[k];for(let k of E){let W=L(k),D=k==="androidPackage"||k==="iosBundleIdentifier";W!==void 0&&(e[k]===void 0||D)&&(e[k]=W)}if(e.platform==="ios"&&!(R.iosBundleIdentifier??R.bundleIdentifier??w.iosBundleIdentifier??w.ios?.bundleIdentifier)){let W=Qd(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=k=>{if(!k)return k;if(k.startsWith("scripts.")){let W=k.split(".")[1],D=d.scripts?.[W];if(D)return D;_.warn(`Script reference not found: ${k}`)}return k};e.buildCommand=U(e.buildCommand),e.preBuild=U(e.preBuild),e.postBuild=U(e.postBuild),!e.scheme&&d.scheme&&(e.scheme=d.scheme);let V={...bt(d,m.envPrefix),...bt(w,`${m.envPrefix}PROFILE_`)};a={...a,...c,...V},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($.yellow(`Check: Using 'production' Team ID for '${g}' build.`)),e.iosTeamId=d.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=ao("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 T=e.platform==="ios"?"iOS":"Android",x=e.platform==="ios"&&e.simulator?" (Simulator)":"",P=`${T}${x} 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",C=e.environment||g;_.info($.blue(`Fetching managed secrets for profile: ${g} (environment: ${C})...`));let M=(await v.get(`/projects/${i}/secrets/export?env=${C}`)).data;M.status==="success"&&M.secrets&&(a={...a,...M.secrets},Object.keys(M.secrets).length>0&&_.info($.magenta(`\u2713 Injected ${Object.keys(M.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=nc(e,h),C=e.platform==="ios"?e.iosBundleIdentifier:e.androidPackage,w=e.platform==="ios"?"bundle":"package";_.info($.dim(` Credential target: ${w} ${C||"not set"} (${g})`));let M=await v.get("/credentials/resolve",{params:{projectId:i,platform:e.platform,bundleId:C,distributionType:g,teamId:e.platform==="ios"?e.iosTeamId:void 0}});if(M.data.status==="success"&&M.data.credentials){let R=M.data.credentials;_.info($.magenta(`\u2713 Found ${R.length} relevant credentials.`));let E=R.filter(D=>e.platform==="ios"&&D.type==="ios_profile"?go(D,g,e.platform)?yo(D,C):!1:e.platform==="android"&&D.type==="android_keystore"?yo(D,C):!!go(D,g,e.platform)).sort((D,J)=>So(J,C)*10+ho(J,g,e.platform)-(So(D,C)*10+ho(D,g,e.platform)));_.info($.dim(` Filtered to ${E.length} credentials for distributionType: ${g}`));let L=!1,U=!1,V=!1,k=[];for(let D of E)if(!(D.type==="ios_cert"&&L||D.type==="ios_profile"&&U||D.type==="android_keystore"&&V)&&["ios_cert","ios_profile","android_keystore"].includes(D.type)&&(D.downloadUrl||Ht(D)))try{let ye=await $o(D,i);if(D.type==="ios_cert"&&!L)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`)),L=!0;else if(D.type==="ios_profile"&&!U){if(!rc(ye,C)){let Ee=Po(ye)||"unknown";throw new Error(`Provisioning profile ${D.name||Ht(D)||"unknown"} is for a different bundle ID. Expected ${C}, found ${Ee}. Upload a ${g} profile for ${C}.`)}a.IOS_PROVISIONING_PROFILE=ye,_.info($.dim(` - Injected ${D.name} as IOS_PROVISIONING_PROFILE`)),U=!0}else if(D.type==="android_keystore"&&!V){a.ANDROID_KEYSTORE_BASE64=ye;let Ee=D.keystorePassword||D.password,F=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 H=["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]);H&&a[H]&&(a.ANDROID_STORE_PASSWORD=a[H])}if(F?(a.ANDROID_KEY_PASSWORD=F,_.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(N=>!!a[N]);q&&(a.ANDROID_KEY_ALIAS=a[q])}_.info($.dim(` - Injected ${D.name} as ANDROID_KEYSTORE_BASE64`)),V=!0}}catch(ye){k.push(`${D.name||D.type}: ${ye.message}`)}let W=e.platform==="ios"?e.simulator||L&&U:V||!E.some(D=>D.type==="android_keystore");if(k.length>0&&!W)throw new Error(`Credential setup failed:
|
|
1285
|
-
${
|
|
1286
|
-
`)}`);
|
|
1287
|
-
\u{1F517} Download Links:`));for(let
|
|
1288
|
-
\u2713 Build completed and reported to dashboard.`)),e.maestro&&!
|
|
1289
|
-
${
|
|
1290
|
-
\u{1F3BC} Queuing managed Maestro test...`)),await
|
|
1291
|
-
Auto-submit: submitting the successful build...`));try{let r=await
|
|
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(D=>`- ${D}`).join(`
|
|
1291
|
+
`)}`);L.length>0&&_.warn($.dim(` Skipped ${L.length} stale or unusable credential(s).`))}if(e.platform==="ios"&&!e.simulator){let v=e.buildProfile||"production",A=et(u,v)||{},x=nc(u,A),U=rc(x),z=e.distribution!==void 0?e.distribution==="store":O==="Store",L=x===void 0&&z,W=e.autoVersion||U&&z||L,D=e.autoVersion||U&&z;if(U&&!z&&_.info($.dim(` Skipping App Store Connect buildNumber lookup for ${e.distribution||"non-store"} build. Pass --auto-version to force it.`)),W){let J=e.iosBundleIdentifier||u.ios?.bundleIdentifier||u.expo?.ios?.bundleIdentifier,ye=ic(u,A,v),Ee=k.data.credentials||[],H=So(Ee,J);if(!H&&(D||L)){let B=await R.get(`/credentials/${i}`);H=So(B.data.credentials||[],J)}if(H){t.start("Resolving latest iOS buildNumber from App Store Connect...");try{let B=H.keyId||H.meta?.keyId,q=H.issuerId||H.meta?.issuerId;if(!B||!q)throw new Error("App Store Connect credential is missing keyId or issuerId.");let C=await ho(H,i),j=await vr({keyId:B,issuerId:q,privateKey:C,ascAppId:ye,bundleId:J}),X=/^\d+$/.test(j.latestBuildNumber);X?(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(X?`\u2713 Latest iOS buildNumber on App Store Connect: ${$.green(j.latestBuildNumber)} (Mach will assign >= ${j.nextBuildNumber})`:`\u2713 Resolved iOS buildNumber: ${$.green(j.nextBuildNumber)} (Latest on App Store Connect: ${j.latestBuildNumber})`)}catch(B){t.stop("iOS buildNumber lookup failed");let q=B.response?.data?.error?.message||B.message;if(D)throw new Error(`Auto-versioning failed: ${q}. Fix App Store Connect API key permissions or remove ios.buildNumber="auto".`);_.warn($.yellow(`Could not check App Store Connect buildNumber: ${q}. Falling back to Mach counter.`))}}else if(D)throw new Error(`Auto-versioning failed: App Store Connect API key not found. Upload it with '${m.nameLower} credentials:service --platform ios'.`)}}if(e.platform==="android"){let v=e.buildProfile||"production",A=et(u,v)||{},z=((A.android||{}).versionCode??A.androidVersionCode??u.android?.versionCode??u.expo?.android?.versionCode)==="auto",L=e.distribution!==void 0?e.distribution==="store":O==="Store",W=e.autoVersion||z&&L;if(z&&!W&&_.info($.dim(` Skipping Google Play versionCode lookup for ${e.distribution||"non-store"} build. Pass --auto-version to force it.`)),W){t.start("Resolving latest versionCode from Google Play...");try{let D=e.androidPackage||u.android?.package||u.expo?.android?.package||u.name,J=(k.data.credentials||[]).find(q=>q.type==="google_service_account"&&(!q.bundleId||q.bundleId===D));if(!J){let C=((await R.get(`/credentials/${i}`)).data.credentials||[]).filter(j=>j.type==="google_service_account");if(J=C.find(j=>j.type==="google_service_account"&&j.bundleId===D),!J&&C.length>0){let j=C.map(X=>X.bundleId).filter(Boolean).join(", ");throw new Error(`Google Service Account not found for package ${D}. Found service credential(s) for: ${j}.`)}}if(!J)throw new Error(`Google Service Account not found for package ${D}. Upload it under this package in Dashboard or run '${m.nameLower} credentials:service --platform android --package-name ${D}'.`);let ye=await ho(J,i),Ee=ec(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 Er(D,Ee);if(H==null)throw new Error("Could not retrieve any version information from Google Play.");let B=H+1;a.ANDROID_VERSION_CODE=B.toString(),t.stop(`\u2713 Resolved versionCode: ${$.green(B)} (Latest on Play Store: ${H})`)}catch(D){t.stop("Version resolution failed");let J=D.response?.data?.error?.message||D.message,ye=tc(J)?"This looks like a temporary network error while contacting Mach or Google Play. Retry the command, or build and submit as separate steps if it continues.":'Fix Google Play service account permissions or remove android.versionCode="auto".';throw new Error(`Auto-versioning failed: ${J}. ${ye}`)}}}if(e.platform==="ios"&&!e.simulator){let v=!!a.IOS_DIST_P12,A=!!a.IOS_PROVISIONING_PROFILE;if(!v||!A){let x=[...v?[]:["Distribution Certificate"],...A?[]:["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($.red(`Missing iOS credentials: ${x}`)),e.quiet&&process.exit(1);let U=e.yes||await co({message:"Would you like to generate these credentials now?",initialValue:!0});if(U&&!bn(U))return await Nt({platform:"ios",profile:h}),e.quiet||_.info($.green("\u2713 Credentials setup complete! Restarting build phase...")),An(e);e.quiet||_.info($.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($.red("Missing Android credentials: Signing Keystore")),e.quiet&&process.exit(1);let A=e.yes||await co({message:"Would you like to automatically create and upload an Android Keystore for this profile now?",initialValue:!0});if(A&&!bn(A))return await Nt({platform:"android",profile:h}),e.quiet||_.info($.green("\u2713 Android Keystore setup complete! Restarting build phase...")),An(e);e.quiet||_.info($.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($.red(g.message)),process.exit(1)),e.platform==="ios"&&e.local&&e.buildId&&(_.error($.red(`Failed to resolve iOS credentials: ${g.message}`)),process.exit(1)),_.warn(`Failed to resolve credentials: ${g.message}`)}}let F=!!(e.local&&e.buildId),S=!!(e.local||e.sshHost),Y=!S&&!F;if(F){_.info($.magenta("\u{1F3D7}\uFE0F Runner Mode: Executing isolated build task..."));let g=await ii({...e,interactive:!1},n,a,i,{branch:f,version:p,summary:P,buildType:O});await ee(g),process.exit(0)}async function ee(g){let T=async E=>{if(i)try{await hn("Report failed build status",()=>R.patch(`/builds/${i}/${n}`,{status:"failed",error:E,endTime:Date.now()}),3)}catch(k){_.warn($.yellow(`Could not report failed build status: ${k.message}`))}};if(i&&g.length>0){let E=Pi(),k=[];e.quiet||E.start("Uploading artifacts to Dashboard...");try{for(let v of g){let A=ve.basename(v),x=de.statSync(v).size,U=ve.extname(A).toLowerCase(),z="application/octet-stream",L=await hn(`Create artifact upload URL for ${A}`,()=>R.post(`/builds/${i}/${n}/artifact-upload-url`,{fileName:A,fileType:z}));if(L.data.status!=="success")throw new Error(`Failed to get upload URL for ${A}`);await Xd(v,L.data.uploadUrl,z),k.push({name:A,url:L.data.downloadUrl,size:x,type:U.substring(1)})}e.quiet||E.stop("Artifacts uploaded.")}catch(v){e.quiet||E.stop("Failed to upload artifacts.");let A=`Artifact upload failed: ${v.message}`;throw _.error($.red(A)),await T(A),new Error(A)}if(i&&k.length>0)try{_.info($.cyan(`
|
|
1292
|
+
\u{1F517} Download Links:`));for(let v of k)_.info($.dim(` - ${v.name}: `)+$.blue.underline(v.url));await hn("Finalize build in dashboard",()=>R.patch(`/builds/${i}/${n}`,{status:"success",artifacts:k,endTime:Date.now()})),In(e,{status:"success",projectId:i,buildId:n,platform:e.platform,profile:h,branch:f,version:p,buildType:O,developmentClient:!!e.developmentClient,summary:P,artifacts:k}),_.success($.green(`
|
|
1293
|
+
\u2713 Build completed and reported to dashboard.`)),e.maestro&&!F&&await wo(i,n,e,h),e.autoSubmit&&!F&&await Ri(i,n,e,h)}catch(v){let A=`Build artifact uploaded but dashboard finalization failed: ${v.message}`;throw _.error($.red(`
|
|
1294
|
+
${A}`)),await T(A),new Error(A)}}else if(i){let E="Build completed but produced no uploadable artifacts.";throw _.error($.red(E)),await T(E),new Error(E)}}if(S){if(_.info($.cyan(`\u{1F680} Direct Build Mode: Executing on ${e.sshHost||"local"}...`)),i&&!o){let g=process.argv.slice(3).join(" ");await R.post("/builds",{projectId:i,buildId:n,platform:e.platform,status:"building",branch:f,version:p,summary:P,startTime:r,buildType:O,buildProfile:h,buildArgs:g,simulator:!!e.simulator,developmentClient:!!e.developmentClient,..._o(e,n,h,c)}),$o(e)}if(e.sshHost&&e.platform==="ios")await Sr(e,n,a,i),e.autoSubmit&&await Ri(i,n,e,h);else{let g=await ii({...e,interactive:!!e.local},n,a,i,{branch:f,version:p,summary:P,buildType:O});await ee(g)}return}if(Y&&(_.info($.blue("\u{1F6F0}\uFE0F Cloud Initiator Mode: Preparing orchestration...")),!e.dryRun)){e.quiet||t.start("Zipping and uploading local source...");let g=await R.post("/builds/source-upload-url",{projectId:i,buildId:n});if(g.data.status!=="success")throw t.stop("Failed to get upload URL."),new Error("Failed to get source upload URL from API");let T=new po,E=de.readdirSync("."),k=["node_modules",".git","dist","build","builds",".gradle",".idea","android/build","ios/build","ios/Pods",`.${m.nameLower}_cli`];for(let x of E){if(k.includes(x))continue;de.statSync(x).isDirectory()?T.addLocalFolder(x,x):T.addLocalFile(x)}let v=T.toBuffer();e.quiet||t.message(`Uploading source (${(v.length/1024/1024).toFixed(1)} MB)...`);let A=!1;for(let x=1;x<=3;x++)try{await Sn.put(g.data.uploadUrl,v,{headers:{"Content-Type":"application/zip"},maxBodyLength:1/0,maxContentLength:1/0,timeout:12e4}),A=!0;break}catch(U){if(x<3)t.message(`Upload attempt ${x} failed (${U.code||U.message}), retrying...`),await new Promise(z=>setTimeout(z,2e3*x));else throw U}if(e.quiet||t.stop("Source uploaded"),i){let x=process.argv.slice(3).join(" ");await R.post("/builds",{projectId:i,buildId:n,platform:e.platform,status:"pending",branch:f,version:p,summary:P,startTime:r,buildType:O,buildProfile:h,buildArgs:x,simulator:!!e.simulator,developmentClient:!!e.developmentClient,..._o(e,n,h,c)}),_.info($.green("\u2713 Cloud build registered.")),$o(e)}e.platform==="android"&&await gr(e,n,a,i,e.preBuild),e.quiet||_.info($.cyan("\u{1F4E1} Connecting to build stream...")),await mc(i,n,e),e.maestro&&await wo(i,n,e,h),e.autoSubmit&&await Ri(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($.red(`\u2717 Build failed: ${a}`)),process.exit(1)}};async function wo(e,t,n,i){_.info($.cyan(`
|
|
1295
|
+
\u{1F3BC} Queuing managed Maestro test...`)),await ui({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 Ri(e,t,n,i){if(!e){_.error($.red("Auto-submit requires a linked Mach project. Run `mach link` or pass --project-id.")),process.exitCode=1;return}_.info($.cyan(`
|
|
1296
|
+
Auto-submit: submitting the successful build...`));try{let r=await fc(e,t);if(r?.autoSubmit){let o=r.submissionId?`${ze}/submissions/${r.submissionId}?projectId=${encodeURIComponent(e)}`:void 0,s=String(r.status||"").toLowerCase(),l=String(r.autoSubmitStatus||"").toLowerCase(),a=r.submissionId||["success","completed","succeeded"].includes(s)||["starting","submitted","failed","skipped"].includes(l);if(r.submissionId?(_.info($.green(`Auto-submit is already queued by Mach backend: ${r.submissionId}`)),_.info($.dim(`Dashboard: ${o}`))):r.autoSubmitStatus==="failed"?_.warn($.yellow(`Backend auto-submit failed: ${r.autoSubmitError||"Unknown error"}`)):a&&_.info($.green("Auto-submit is registered with Mach backend; skipping local duplicate submit.")),a){rt(n,{status:r.autoSubmitStatus||"pending",projectId:e,submitId:r.submissionId,platform:n.platform,profile:i,buildId:t,dashboardUrl:o});return}}await gn({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:To(n,t,i)})}catch(r){_.error($.red(`Auto-submit failed: ${r.message||r}`)),process.exitCode=1}}function To(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 fc(e,t){try{let i=(await R.get(`/builds/${e}/${t}`)).data?.build;if(i?.autoSubmit)return i}catch(n){_.warn($.dim(`Could not check backend auto-submit status: ${n.message}`))}return null}function ko(e){for(let t of Object.keys(e))e[t]===void 0&&delete e[t];return e}function pc(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 ko({track:o,releaseStatus:s,rollout:l,changesNotSentForReview:a===void 0?!1:a===!0||a==="true"||a==="1"})}function _o(e,t,n,i){if(!e.autoSubmit||e.dryRun)return{};let r=e.platform==="android"?pc(e,n,i):{};return{autoSubmit:!0,autoSubmitStatus:"pending",autoSubmitOptions:ko({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:To(e,t,n)})}}function $o(e){!e.autoSubmit||e.dryRun||e.quiet||(_.info($.green("\u2713 Auto-submit has been registered with the build.")),_.info($.dim(" You can close this terminal; submission will start after build success.")))}function vo(e){return`${ze}/build/${e}`}function In(e,t){if(!e.jsonOutput)return;let n=ve.resolve(e.jsonOutput),i={...t,url:t.url||vo(t.buildId),dashboardUrl:t.dashboardUrl||vo(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($.yellow(`Could not write build metadata JSON: ${r.message}`))}}async function mc(e,t,n){let i=Pi(),r="pending",o=0,s=0;for(n.quiet||i.start("Connecting to build stream...");;){try{let a=(await R.get(`/builds/${e}/${t}`)).data.build;if(a){if(r=a.status,r==="building")n.quiet||i.message("Build in progress...");else if(r==="failed")n.quiet||i.stop("Build failed."),In(n,{status:"failed",projectId:e,buildId:t,platform:n.platform,profile:a.buildProfile,buildType:a.buildType,developmentClient:!!a.developmentClient,version:a.version,summary:a.summary,error:a.error||"Unknown error",artifacts:a.artifacts||[]}),_.error($.red(`
|
|
1292
1297
|
\u2717 Build failed: ${a.error||"Unknown error"}`)),process.exit(1);else if(r==="completed"||r==="success"){n.quiet||i.stop("Build successful!"),In(n,{status:r,projectId:e,buildId:t,platform:n.platform,profile:a.buildProfile,buildType:a.buildType,developmentClient:!!a.developmentClient,version:a.version,summary:a.summary,artifacts:a.artifacts||[]}),_.success($.green(`
|
|
1293
1298
|
\u2713 Build completed successfully!`));try{n.quiet||(_.info($.magenta(`
|
|
1294
|
-
\u{1F4F1} Installation Hub:`)),_.info($.dim(" - View & Install Build: ")+$.white.underline(`${ze}/build/${t}`)))}catch{}return}else if(r!=="pending"){n.quiet||i.stop(`Build status: ${r}`);return}}try{let
|
|
1295
|
-
`);if(
|
|
1296
|
-
\u2717 Lost connection to Dashboard API.`)),process.exit(1))}await new Promise(l=>setTimeout(l,3e3))}}import*as Rn from"http";import*as
|
|
1299
|
+
\u{1F4F1} Installation Hub:`)),_.info($.dim(" - View & Install Build: ")+$.white.underline(`${ze}/build/${t}`)))}catch{}return}else if(r!=="pending"){n.quiet||i.stop(`Build status: ${r}`);return}}try{let c=(await R.get(`/builds/${e}/${t}/logs`)).data;if(c&&typeof c=="string"&&!n.quiet){let u=c.split(`
|
|
1300
|
+
`);if(u.length>o){for(let f=o;f<u.length;f++)u[f].trim()&&console.log($.dim(` ${u[f]}`));o=u.length}}}catch{}s=0}catch{s++,s>10&&(i.stop("Connection lost."),_.error($.red(`
|
|
1301
|
+
\u2717 Lost connection to Dashboard API.`)),process.exit(1))}await new Promise(l=>setTimeout(l,3e3))}}import*as Rn from"http";import*as Bo from"net";import{execFile as gc,execFileSync as Pn,execSync as yt,spawn as Lo}from"child_process";import ce from"chalk";import{log as Q}from"@clack/prompts";import hc from"axios";import pe from"fs";import He from"os";import ie from"path";var Ze=7070,Gt=`http://127.0.0.1:${Ze}`,$t="com.radhya.mach.agent",_t="Mach Agent",vt=`${$t}.service`,yc=5e3,Sc=3e3,wn=null,_n=null,je=()=>ie.join(He.homedir(),m.configDir),Fo=()=>ie.join(He.homedir(),"Library","LaunchAgents"),$n=()=>ie.join(Fo(),`${$t}.plist`),Ho=()=>ie.join(He.homedir(),".config","systemd","user"),Oi=()=>ie.join(Ho(),vt),Ci=()=>ie.join(je(),"agent.cmd");function Ni(){return`gui/${process.getuid?.()||Number(yt("id -u").toString().trim())}`}function jo(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function jt(e){return`<string>${jo(e)}</string>`}function Ti(){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 ki(){let e=Go(),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:He.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 Go(){let e=[process.env.ANDROID_HOME,process.env.ANDROID_SDK_ROOT];if(process.platform==="darwin")e.push(ie.join(He.homedir(),"Library","Android","sdk"));else if(process.platform==="linux")e.push(ie.join(He.homedir(),"Android","Sdk"),ie.join(He.homedir(),"Android","sdk"),"/opt/android-sdk","/usr/lib/android-sdk");else if(process.platform==="win32"){let t=process.env.LOCALAPPDATA,n=process.env.USERPROFILE||He.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 bc(e){return process.platform==="win32"&&!e.toLowerCase().endsWith(".exe")?`${e}.exe`:e}function Ko(e,t){let n=bc(e);for(let i of Go()){let r=ie.join(i,t,n);if(pe.existsSync(r))return r}return n}function Vo(){return Ko("adb","platform-tools")}function zo(){return Ko("emulator","emulator")}function Di(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}"`}function Ec(){if(process.platform!=="linux")throw new Error("Linux service install requires Linux.");pe.mkdirSync(je(),{recursive:!0}),pe.mkdirSync(Ho(),{recursive:!0});let e=Ti(),t=ki(),n=Object.entries(t).map(([r,o])=>`Environment=${Di(`${r}=${o}`)}`).join(`
|
|
1297
1302
|
`),i=`[Unit]
|
|
1298
1303
|
Description=Mach local device agent
|
|
1299
1304
|
After=default.target
|
|
1300
1305
|
|
|
1301
1306
|
[Service]
|
|
1302
1307
|
Type=simple
|
|
1303
|
-
ExecStart=${e.map(
|
|
1304
|
-
WorkingDirectory=${
|
|
1308
|
+
ExecStart=${e.map(Di).join(" ")}
|
|
1309
|
+
WorkingDirectory=${Di(He.homedir())}
|
|
1305
1310
|
${n}
|
|
1306
1311
|
Restart=on-failure
|
|
1307
1312
|
RestartSec=5
|
|
@@ -1310,12 +1315,12 @@ StandardError=append:%h/${m.configDir}/agent.error.log
|
|
|
1310
1315
|
|
|
1311
1316
|
[Install]
|
|
1312
1317
|
WantedBy=default.target
|
|
1313
|
-
`;return pe.writeFileSync(
|
|
1314
|
-
`),l=i.map(
|
|
1318
|
+
`;return pe.writeFileSync(Oi(),i),Oi()}function at(e,t={}){try{return Pn("systemctl",["--user",...e],{stdio:t.ignoreError?"ignore":"pipe"}),!0}catch(n){if(t.ignoreError)return!1;throw n}}function Ac(){if(process.platform!=="win32")throw new Error("Windows agent script requires Windows.");pe.mkdirSync(je(),{recursive:!0});let e=ki(),[t,n,...i]=Ti(),r=ie.join(je(),"agent.log"),o=ie.join(je(),"agent.error.log"),s=Object.entries(e).map(([d,c])=>`set "${d}=${c}"`).join(`\r
|
|
1319
|
+
`),l=i.map(d=>`"${d.replace(/"/g,'\\"')}"`).join(" "),a=`@echo off\r
|
|
1315
1320
|
${s}\r
|
|
1316
1321
|
cd /d "${He.homedir()}"\r
|
|
1317
1322
|
"${t}" "${n}" ${l} >> "${r}" 2>> "${o}"\r
|
|
1318
|
-
`;return pe.writeFileSync(
|
|
1323
|
+
`;return pe.writeFileSync(Ci(),a),Ci()}function Kt(e,t={}){try{return Pn("schtasks.exe",e,{stdio:t.ignoreError?"ignore":"pipe"}),!0}catch(n){if(t.ignoreError)return!1;throw n}}function Ic(){if(process.platform!=="darwin")throw new Error("Background agent install currently supports macOS only.");pe.mkdirSync(je(),{recursive:!0}),pe.mkdirSync(Fo(),{recursive:!0});let e=Ti(),t=ki(),n=ie.join(je(),"agent.log"),i=ie.join(je(),"agent.error.log"),r=Object.entries(t).map(([l,a])=>` <key>${jo(l)}</key>
|
|
1319
1324
|
${jt(a)}`).join(`
|
|
1320
1325
|
`),o=e.map(l=>` ${jt(l)}`).join(`
|
|
1321
1326
|
`),s=`<?xml version="1.0" encoding="UTF-8"?>
|
|
@@ -1323,7 +1328,7 @@ cd /d "${He.homedir()}"\r
|
|
|
1323
1328
|
<plist version="1.0">
|
|
1324
1329
|
<dict>
|
|
1325
1330
|
<key>Label</key>
|
|
1326
|
-
${jt(
|
|
1331
|
+
${jt($t)}
|
|
1327
1332
|
<key>ProgramArguments</key>
|
|
1328
1333
|
<array>
|
|
1329
1334
|
${o}
|
|
@@ -1340,23 +1345,23 @@ ${r}
|
|
|
1340
1345
|
${jt(i)}
|
|
1341
1346
|
</dict>
|
|
1342
1347
|
</plist>
|
|
1343
|
-
`;return pe.writeFileSync($n(),s),$n()}function st(e,t={}){try{return Pn("launchctl",e,{stdio:t.ignoreError?"ignore":"pipe"}),!0}catch(n){if(t.ignoreError)return!1;throw n}}function
|
|
1344
|
-
`).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 vn(
|
|
1345
|
-
`).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 Pc(){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 Dc(){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 Oc(){let[e,t,n]=await Promise.all([Rc(),Pc(),Dc()]);return[...e,...t,...n]}async function Cc(){let e=Date.now();return wn&&e-wn.updatedAt<uc?wn.targets:(_n||(_n=Oc().then(t=>(wn={targets:t,updatedAt:Date.now()},t)).finally(()=>{_n=null})),_n)}async function ko(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 Nc(e,t){let n=await dc({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 Tc(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 Nc(t,s),i==="android"){Pn(Ho(),["-s",e,"install","-r",s],{stdio:"pipe"});return}if(process.platform!=="darwin")throw new Error("iOS local install requires macOS.");ht(`unzip -o ${JSON.stringify(s)} -d ${JSON.stringify(o)}`,{stdio:"pipe"});let l="";try{l=ht(`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=ht(`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{ht(`/usr/bin/xcrun devicectl device install app --device ${JSON.stringify(e)} ${JSON.stringify(l)}`,{stdio:"pipe"})}catch(a){try{ht(`/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 kc(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 ht(`/usr/bin/xcrun simctl boot ${JSON.stringify(e)}`,{stdio:"pipe"}),Co("open",["-a","Simulator"],{detached:!0,stdio:"ignore"}).unref(),"Simulator booting..."}if(t==="android")return Co(jo(),["-avd",e],{detached:!0,stdio:"ignore",windowsHide:!0}).unref(),"Emulator booting in background...";throw new Error("Invalid platform.")}async function Lc(){process.platform!=="darwin"&&Z.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"){Cc().then(s=>{r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"success",targets:s}))}).catch(s=>{r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"error",message:s.message}))});return}if(i.method==="GET"&&o.pathname==="/health"){r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"success",service:"mach-agent",port: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 ko(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 Tc(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 ko(i),l=kc(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",()=>{Z.success(ce.green(`Local device agent running on http://localhost:${Ze}`)),Z.info(ce.dim("Keep this running while using the Install Hub on the dashboard.")),Z.info(ce.dim("Press Ctrl+C to stop."))}),e.on("error",i=>{i.code==="EADDRINUSE"?Z.error(`Port ${Ze} is already in use \u2014 agent may already be running.`):Z.error(`Agent error: ${i.message}`),process.exit(1)}),await new Promise(()=>{})}async function Wo(e="start"){let t=String(e||"start").toLowerCase();if(t==="start"||t==="run"){await Lc();return}if(t==="install"){await No();return}if(t==="status"){await vc();return}if(t==="stop"){await To();return}if(t==="uninstall"){await $c();return}if(t==="restart"){await To(),await No();return}Z.error(`Unknown agent action: ${e}`),Z.info(ce.dim(`Use: ${m.nameLower} agent start | install | status | restart | stop | uninstall`)),process.exit(1)}import{createRequire as ff}from"module";import{text as Mc,password as Uc,spinner as Bc,isCancel as qo}from"@clack/prompts";import Ui from"chalk";import Vt from"fs";import Yo from"path";import xc from"os";var Li=Yo.join(xc.homedir(),m.configDir),xi=Yo.join(Li,"config.json");function Mi(){if(!Vt.existsSync(xi))return{};try{return JSON.parse(Vt.readFileSync(xi,"utf-8"))}catch{return{}}}function Jo(e){Vt.existsSync(Li)||Vt.mkdirSync(Li,{recursive:!0});let n={...Mi(),...e};Vt.writeFileSync(xi,JSON.stringify(n,null,2))}async function Xo(){let e=Mi(),t=await Mc({message:"Enter your email:",placeholder:"user@example.com",initialValue:e.lastLoginEmail,validate(r){if(r.length===0)return"Email is required!"}});if(qo(t))return;let n=await Uc({message:"Enter your password:",validate(r){if(r.length===0)return"Password is required!"}});if(qo(n))return;let i=Bc();i.start("Authenticating...");try{let o=await(await fetch(`${St}/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:t,password:n})})).json();o.status==="success"&&o.user.token?(qi({id:o.user.id,email:t,token:o.user.token,refreshToken:o.user.refreshToken}),Jo({lastLoginEmail:t}),i.stop(Ui.green("Login successful!"))):i.stop(Ui.red("Login failed: "+(o.message||"Unknown error")))}catch(r){i.stop(Ui.red("Network error: "+r.message))}}import{log as Dn,outro as Fc}from"@clack/prompts";import zt from"chalk";async function Zo(){let e=Xi(),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}`))),Fc(zt.blue("---"))}import{outro as Hc,select as jc,spinner as Gc,isCancel as Kc}from"@clack/prompts";import On from"chalk";import Bi from"fs";import Vc from"path";var Qo=e=>e==="1234567890"||e==="ABC123DEFG"||e==="XXXXXXXXXX"?"":typeof e=="string"?e:"",zc=()=>process.versions.node.split(".")[0]||"24";async function es(){if(!Pe()){console.log(On.red(`You are not logged in. Run \`${m.nameLower} login\` first.`));return}let t=Gc();t.start("Fetching projects...");try{let{data:n}=await v.get("/projects");if(t.stop("Projects loaded."),n.status!=="success"||!n.projects||n.projects.length===0){console.log(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(Kc(r))return;let o=Vc.join(process.cwd(),m.configFileName),s={};if(Bi.existsSync(o))try{s=JSON.parse(Bi.readFileSync(o,"utf-8"))}catch{}let l=n.projects.find(h=>h.projectId===r),a=s.android?.package||Xe("android"),c=s.ios?.bundleIdentifier||Xe("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||zc(),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:Qo(f.ascAppId),appleTeamId:Qo(f.appleTeamId)}}}};Bi.writeFileSync(o,JSON.stringify(p,null,2)),Hc(On.green(`Linked to project ${p.name} (${p.slug})`))}catch(n){t.stop(On.red("Error fetching projects: "+n.message))}}import{outro as Wc,text as Cn,select as Yc,spinner as Jc,isCancel as Wt}from"@clack/prompts";import Yt from"chalk";import qc from"fs";import Xc from"path";import{randomUUID as Zc}from"crypto";var Qc=()=>process.versions.node.split(".")[0]||"24";async function ts(){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 Yc({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=Jc();s.start("Creating project...");try{let l=Zc(),c={projectId:l,name:t,slug:n,storageType:"managed",platforms:i==="all"?["android","ios","web"]:[i]},{data:u}=await v.post("/projects",c);if(u.status==="success"){s.stop(Yt.green("Project created successfully!"));let d=Xc.join(process.cwd(),m.configFileName);qc.writeFileSync(d,JSON.stringify({projectId:l,name:t,slug:n,nodeVersion:Qc(),...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)),Wc(Yt.green(`Initialized project ${t} and linked locally!`))}else s.stop(Yt.red("creation failed: "+u.message))}catch(l){s.stop(Yt.red("Network error: "+l.message))}}import{spinner as Fi,log as Re}from"@clack/prompts";import Jt from"chalk";import Nn from"fs";import ns from"path";function Hi(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 eu(e){let t=String(e??"");return t===""?'""':/^[A-Za-z0-9_./:@%+-]+$/.test(t)?t:JSON.stringify(t)}function tu(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}=${eu(e[i])}`)].join(`
|
|
1348
|
+
`;return pe.writeFileSync($n(),s),$n()}function st(e,t={}){try{return Pn("launchctl",e,{stdio:t.ignoreError?"ignore":"pipe"}),!0}catch(n){if(t.ignoreError)return!1;throw n}}function wc(e){return new Promise(t=>setTimeout(t,e))}function vn(e,t,n=yc){return new Promise((i,r)=>{gc(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 Wo(){if(typeof fetch=="function"){let e=new AbortController,t=setTimeout(()=>e.abort(),3e3);try{return(await fetch(`${Gt}/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=Rn.get(`${Gt}/health`,r=>{r.resume(),n(r.statusCode===200)});i.setTimeout(3e3,()=>{i.destroy(),n(!1)}),i.on("error",()=>n(!1))})}async function _c(e=8e3){let t=Date.now()+e;for(;Date.now()<t;){if(await Wo())return!0;await wc(250)}return!1}async function Yo(){return new Promise(e=>{let t=!1,n=Bo.createConnection({host:"127.0.0.1",port:Ze}),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 _c()){Q.success(ce.green("Mach agent installed and started."));return}if(await Yo()){Q.warn(`Mach agent service is installed, but port ${Ze} 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 ${Gt}.`)}async function $c(){let e=Ic(),t=Ni();st(["bootout",t,e],{ignoreError:!0}),st(["bootstrap",t,e],{ignoreError:!0})||st(["load","-w",e]),st(["enable",`${t}/${$t}`],{ignoreError:!0}),st(["kickstart","-k",`${t}/${$t}`],{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(je(),"agent.log")}`))}async function Jo(){let e=$n(),t=Ni();st(["bootout",t,e],{ignoreError:!0})||st(["unload","-w",e],{ignoreError:!0})?Q.success(ce.green("Mach agent service stopped.")):Q.warn("Mach agent service was not loaded.")}async function vc(){await Jo();let e=$n();pe.existsSync(e)&&pe.unlinkSync(e),Q.success(ce.green("Mach agent service uninstalled."))}async function Rc(){let e=Ec();at(["daemon-reload"]),at(["enable","--now",vt]),await Li(),Q.info(ce.dim(`It will start automatically when you log in. Service: ${e}`)),Q.info(ce.dim(`Logs: ${ie.join(je(),"agent.log")}`))}async function Pc(){at(["stop",vt],{ignoreError:!0})?Q.success(ce.green("Mach agent service stopped.")):Q.warn("Mach agent service was not running.")}async function Dc(){at(["disable","--now",vt],{ignoreError:!0}),at(["daemon-reload"],{ignoreError:!0});let e=Oi();pe.existsSync(e)&&pe.unlinkSync(e),at(["daemon-reload"],{ignoreError:!0}),Q.success(ce.green("Mach agent service uninstalled."))}async function Oc(){let e=Ac();Kt(["/Create","/TN",_t,"/SC","ONLOGON","/TR",`"${e}"`,"/RL","LIMITED","/F"]),Kt(["/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(je(),"agent.log")}`))}async function qo(){Kt(["/End","/TN",_t],{ignoreError:!0})?Q.success(ce.green("Mach agent task stopped.")):Q.warn("Mach agent task was not running.")}async function Cc(){await qo(),Kt(["/Delete","/TN",_t,"/F"],{ignoreError:!0});let e=Ci();pe.existsSync(e)&&pe.unlinkSync(e),Q.success(ce.green("Mach agent task uninstalled."))}async function xo(){if(process.platform==="darwin")return $c();if(process.platform==="linux")return Rc();if(process.platform==="win32")return Oc();throw new Error(`Background agent install is not supported on ${process.platform}.`)}async function Mo(){if(process.platform==="darwin")return Jo();if(process.platform==="linux")return Pc();if(process.platform==="win32")return qo();Q.warn(`Background agent service control is not supported on ${process.platform}.`)}async function Nc(){if(process.platform==="darwin")return vc();if(process.platform==="linux")return Dc();if(process.platform==="win32")return Cc();Q.warn(`Background agent uninstall is not supported on ${process.platform}.`)}async function Tc(){let e=await Wo(),t=e?!0:await Yo();if(e?Q.success(ce.green(`Mach agent is online at ${Gt}`)):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 ${Gt}`),process.platform==="darwin"){let n=st(["print",`${Ni()}/${$t}`],{ignoreError:!0});Q.info(ce.dim(`Login service: ${n?"installed/loaded":"not loaded"}`))}else if(process.platform==="linux"){let n=at(["is-enabled",vt],{ignoreError:!0}),i=at(["is-active",vt],{ignoreError:!0});Q.info(ce.dim(`Login service: ${n?"enabled":"not enabled"} / ${i?"active":"inactive"}`))}else if(process.platform==="win32"){let n=Kt(["/Query","/TN",_t],{ignoreError:!0});Q.info(ce.dim(`Login task: ${n?"installed":"not installed"}`))}}async function kc(){let e=[];try{(await vn(Vo(),["devices","-l"])).split(`
|
|
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 vn(zo(),["-list-avds"])).split(`
|
|
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(`
|
|
1346
1351
|
`)}
|
|
1347
|
-
`}async function
|
|
1348
|
-
`))}else lt.info(Ce.dim(`Metro URL: http://localhost:${l}`));let
|
|
1352
|
+
`}async function as(e,t,n={}){let i=Pe();if(!i){Re.error(`You are not logged in. Run \`${m.nameLower} login\` first.`);return}let r=ss.join(process.cwd(),m.configFileName);if(!Nn.existsSync(r)){Re.error(`No ${m.configFileName} found. Run \`${m.nameLower} init\` or \`${m.nameLower} link\` first.`);return}let o;try{o=JSON.parse(Nn.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 du(s,t,i):e==="list"?await cu(s,i):e==="pull"||e==="download"||e==="export"?await uu(s,n):Re.error(`Unknown env action: ${e}. Use 'set', 'list', or 'pull'.`)}async function du(e,t,n){if(t.length===0){Re.error(`Usage: ${m.nameLower} env set KEY=VALUE [KEY2=VALUE2 ...]`);return}let i=Hi();i.start("Setting environment variables...");let r=0,o=0;for(let s of t){let[l,...a]=s.split("="),d=a.join("=");if(!l||d===void 0){Re.warn(`Invalid format for argument: ${s}. Expected KEY=VALUE.`),o++;continue}try{let c={key:l.trim(),value:d,type:"env",environment:"global",visibility:"secret"},{data:u}=await R.post(`/projects/${e}/secrets`,c);u.status==="success"?r++:(Re.error(`Failed to set ${l}: ${u.message}`),o++)}catch(c){Re.error(ji(c,e,"set",l)),o++}}i.stop(`Set ${r} variable(s). ${o>0?`${o} failed.`:""}`)}async function cu(e,t){let n=Hi();n.start("Fetching environment variables...");try{let{data:i}=await R.get(`/projects/${e}/secrets`);if(i.status==="success"){n.stop("Fetched variables.");let r=i.secrets||[];r.length===0?Re.info("No environment variables found for this project."):(Re.info(Jt.bold("Environment Variables (Global & Scoped):")),r.forEach(o=>{let s=o.visibility==="plain"?o.value:"********";console.log(` ${Jt.cyan(o.key)} = ${s} ${Jt.gray(`[${o.environment}]`)}`)}))}else n.stop(Jt.red(`Failed to fetch variables: ${i.message}`))}catch(i){n.stop("Failed to fetch variables."),Re.error(ji(i,e,"list"))}}async function uu(e,t){let n=(t.environment||"development").trim(),i=t.out||".env.local",r=ss.resolve(process.cwd(),i);if(Nn.existsSync(r)&&!t.overwrite){Re.error(`${i} already exists. Re-run with \`--overwrite\` to replace it.`);return}let o=Hi();o.start(`Downloading ${n} environment variables...`);try{let{data:s}=await R.get(`/projects/${e}/secrets/export?env=${encodeURIComponent(n)}`);if(s.status!=="success"){o.stop(Jt.red(`Failed to download variables: ${s.message||"Unknown API error"}`));return}let l=s.secrets||{},a=lu(l,n);Nn.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(ji(s,e,"pull"))}}import{spinner as fu,log as St,outro as pu}from"@clack/prompts";import Gi from"chalk";import ls from"fs";import mu from"path";import{execSync as gu}from"child_process";import hu from"adm-zip";import yu from"axios";import{randomUUID as Su}from"crypto";async function ds(e){St.info(Gi.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(ls.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=fu();o.start(`Compiling JavaScript bundles for OTA (Channel: ${i}, Runtime: ${r})...`);try{gu("npx expo export --platform all",{stdio:"ignore"})}catch(d){o.stop("Compilation failed."),St.error(`Failed to export JS bundles using Expo: ${d.message}`),process.exit(1)}o.message("Zipping artifact payload...");let s=mu.join(process.cwd(),"dist");ls.existsSync(s)||(o.stop("Missing dist folder."),St.error("The `dist` directory was not created. Export failed."),process.exit(1));let l=new hu;l.addLocalFolder(s,"dist");let a=l.toBuffer();o.message("Uploading payload to Mach Cloud...");try{let d=Su(),c=await R.post("/builds/source-upload-url",{projectId:n,buildId:d});if(c.data.status!=="success")throw new Error("Could not secure upload bucket URL");let{uploadUrl:u,key:f}=c.data;await yu.put(u,a,{headers:{"Content-Type":"application/zip"},maxBodyLength:1/0,maxContentLength:1/0}),o.message(`Promoting Update to ${i}...`),await R.post("/updates/publish",{projectId:n,channelName:i,runtimeVersion:r,platform:"android",updateId:`${d}-android`,manifestKey:f}),await R.post("/updates/publish",{projectId:n,channelName:i,runtimeVersion:r,platform:"ios",updateId:`${d}-ios`,manifestKey:f}),o.stop("Update Live!"),pu(Gi.green(`\u2713 OTA Update natively shipped to the '${i}' channel.`)),St.info(Gi.dim(`Any app running runtime '${r}' will download this bundle smoothly.`))}catch(d){o.stop("Update failed during Cloud Sync."),St.error(`Upload error: ${d.message}`),process.exit(1)}}import{intro as bu,outro as cs,log as Rt}from"@clack/prompts";import Ye from"chalk";async function us(){bu(Ye.blue(`${m.name} CLI - User Profile`));let e=Pe();if(!e){Rt.warn(Ye.yellow("You are not logged in.")),Rt.info(`Run \`${m.nameLower} login\` to authenticate.`),cs();return}Rt.info(`${Ye.bold("Logged in as:")} ${Ye.green(e.email)}`);try{await R.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);Rt.info(`${Ye.bold("Token status:")} Valid (Expires in ~${a}h / ${l}m)`)}else Rt.warn(`${Ye.bold("Token status:")} ${Ye.red("Expired")} (Auto-refresh failed)`)}}}catch{Rt.warn(`${Ye.bold("Token status:")} ${Ye.red("Unreachable")} (Session might be truly expired)${bt}`)}cs(Ye.blue("---"))}import{spawn as Iu}from"child_process";import{log as lt}from"@clack/prompts";import Ce from"chalk";import wu from"fs";import Eu from"net";async function Au(e){return new Promise(t=>{let n=Eu.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 fs(e,t=20){let n=e;for(;n<e+t;){if(!await Au(n))return n;n++}throw new Error(`Could not find an available port after ${t} attempts starting from ${e}.`)}var ps=async e=>{lt.info(Ce.blue(`Starting ${m.name} Dev Orchestrator...`));let t=$e(),n=e.buildProfile||"development",i=t?et(t,n):null,r={...process.env};if(t?.projectId)try{lt.info(Ce.dim(`Fetching managed secrets for profile: ${n}...`));let u=await R.get(`/projects/${t.projectId}/secrets/export?env=${n}`);u.data?.status==="success"&&u.data.secrets&&(Object.assign(r,u.data.secrets),lt.info(Ce.magenta(`\u2713 Injected secrets from ${m.name} Dashboard.`)))}catch{lt.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 u=JSON.parse(wu.readFileSync("package.json","utf-8"));o=!!(u.dependencies?.expo||u.devDependencies?.expo)}catch{lt.warn("Could not parse package.json. Defaulting to Bare React Native mode.")}let s=Number(e.port||i?.port||8081),l=await fs(s);l!==s&<.info(Ce.yellow(`Port ${s} is busy. ${m.name} is using ${l} instead.`));let a=process.platform==="win32"?"npx.cmd":"npx",d=[];if(o?(d=["expo","start","--port",String(l)],e.clear&&d.push("--clear"),e.tunnel&&d.push("--tunnel"),e.lan&&d.push("--lan"),e.localhost&&d.push("--localhost"),e.ios&&d.push("--ios"),e.android&&d.push("--android"),e.web&&d.push("--web")):(d=["react-native","start","--port",String(l)],e.clear&&d.push("--clear")),o){let u=[`${Ce.cyan("i")} open iOS simulator`,`${Ce.cyan("a")} open Android emulator/device`,`${Ce.cyan("w")} open web`,`${Ce.cyan("r")} reload app`];lt.info([Ce.bold("Launch controls"),...u.map(f=>` ${f}`),"",Ce.dim("Direct launch: mach start --ios | --android | --web"),Ce.dim(`Metro URL: http://localhost:${l}`)].join(`
|
|
1353
|
+
`))}else lt.info(Ce.dim(`Metro URL: http://localhost:${l}`));let c=Iu(a,d,{stdio:"inherit",env:r});return new Promise((u,f)=>{c.on("exit",p=>{p===0?u():f(new Error(`Dev server exited with code ${p}`))}),c.on("error",p=>{f(p)})})};import{log as De}from"@clack/prompts";import Ge from"chalk";var ms=async e=>{let t=$e();t||(De.error(Ge.red(`No ${m.configFileName} found in the current directory.`)),process.exit(1));let n=e.profile||"development",i=et(t,n);if(e.json){console.log(JSON.stringify({project:t,resolved:i},null,2));return}De.info(Ge.bgBlue.white(` Resolved ${m.name} Config [${n}] `)),De.info(Ge.dim("----------------------------------------")),De.info(`${Ge.blue("Project ID:")} ${t.projectId}`),De.info(`${Ge.blue("Name:")} ${t.name}`),De.info(`${Ge.blue("Scheme:")} ${t.scheme}`),i?(De.info(Ge.dim(`
|
|
1349
1354
|
Profile Settings:`)),De.info(`${Ge.cyan("Distribution:")} ${i.distribution||"none"}`),De.info(`${Ge.cyan("Development Client:")} ${i.developmentClient||"false"}`),i.env&&Object.keys(i.env).length>0&&(De.info(Ge.dim(`
|
|
1350
|
-
Environment Variables:`)),Object.entries(i.env).forEach(([r,o])=>{De.info(` ${r}=${o}`)}))):De.warn(`Profile '${n}' not found.`),De.info(Ge.dim("----------------------------------------"))};import{log as Ne,spinner as Zt,text as
|
|
1355
|
+
Environment Variables:`)),Object.entries(i.env).forEach(([r,o])=>{De.info(` ${r}=${o}`)}))):De.warn(`Profile '${n}' not found.`),De.info(Ge.dim("----------------------------------------"))};import{log as Ne,spinner as Zt,text as gs,select as hs,confirm as _u,isCancel as qt,cancel as Xt,outro as Qt,note as $u}from"@clack/prompts";import re from"chalk";import{execSync as vu}from"child_process";async function Ru(){try{let e=vu("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 ys=e=>e?.trim().toUpperCase()||void 0;function Ss(e){let t=$e(),n=t?er(t):{},i=ys(e.teamId),r=i||n.teamId;return{...n,teamId:r,developerTeamId:i||n.developerTeamId||r}}async function Pu(e){let t=e.udid,n=e.name,i=Ss(e),r=i.teamId;if(!t){let s=Zt();s.start("Scanning for connected iOS devices...");let l=await Ru();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 hs({message:"Select a device to register:",options:l.map(c=>({value:c.udid,label:`${c.name} (${c.model})`,hint:c.udid.substring(0,12)+"..."}))});if(qt(a)){Xt("Cancelled");return}t=a;let d=l.find(c=>c.udid===t);n=n||d.name}else{Ne.info(re.dim("No connected devices found. Enter UDID manually."));let a=await gs({message:"Device UDID:",placeholder:"00008101-XXXXXXXXXXXX",validate(d){if(d.length<10)return"UDID seems too short"}});if(qt(a)){Xt("Cancelled");return}t=a}}if(!n){let s=await gs({message:"Device name:",placeholder:"Nitesh's iPhone",validate(l){if(l.length===0)return"Name is required"}});if(qt(s)){Xt("Cancelled");return}n=s}let o=Zt();o.start("Registering device...");try{await R.post("/devices",{udid:t,name:n,platform:"ios",addedVia:"cli",teamId:r,teamName:i.teamName,developerTeamId:i.developerTeamId,appStoreConnectTeamId:i.appStoreConnectTeamId,providerId:i.providerId,providerName:i.providerName}),o.stop(re.green("Device registered!")),Ne.info(` ${re.bold("Name:")} ${n}`),Ne.info(` ${re.bold("UDID:")} ${re.dim(t)}`),r&&Ne.info(` ${re.bold("Team:")} ${re.dim(r)}`)}catch(s){o.stop(re.red("Failed to register device")),Ne.error(s.response?.data?.message||s.message)}Qt(re.blue("---"))}async function Du(e={}){let t=ys(e.teamId),n=Zt();n.start("Fetching registered devices...");try{let r=(await R.get("/devices",t?{params:{teamId:t}}:void 0)).data.devices||[];if(n.stop(`${r.length} device(s) registered${t?` for team ${t}`:""}`),r.length===0){Ne.info(re.dim(`No devices registered yet. Run \`${m.nameLower} device register\` to add one.`)),Qt(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)}`});$u(` ${re.bold("Name".padEnd(24))} ${"UDID".padEnd(28)} ${"Team".padEnd(12)} ${"Via".padEnd(10)} Date
|
|
1351
1356
|
`+o.join(`
|
|
1352
|
-
`),"Registered Devices")}catch(i){n.stop(re.red("Failed to fetch devices")),Ne.error(i.response?.data?.message||i.message)}Qt(re.blue("---"))}async function
|
|
1353
|
-
`),
|
|
1354
|
-
`),
|
|
1355
|
-
`),
|
|
1356
|
-
`),
|
|
1357
|
-
`);/__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:
|
|
1358
|
-
Running expo prebuild for deeper analysis...`));try{
|
|
1359
|
-
Skipping manifest/plist checks \u2014 no android/ios dirs. Use --prebuild to generate them.`)),o;for(let
|
|
1357
|
+
`),"Registered Devices")}catch(i){n.stop(re.red("Failed to fetch devices")),Ne.error(i.response?.data?.message||i.message)}Qt(re.blue("---"))}async function Ou(e){let t=e.udid,n=Ss(e).teamId;if(!t){let o=Zt();o.start("Fetching registered devices...");try{let l=(await R.get("/devices",n?{params:{teamId:n}}:void 0)).data.devices||[];if(o.stop(`${l.length} device(s) found`),l.length===0){Ne.info(re.dim("No devices to remove.")),Qt(re.blue("---"));return}let a=await hs({message:"Select device to remove:",options:l.map(c=>({value:c.deviceKey||c.udid,label:c.name,hint:`${c.udid.substring(0,12)}...${c.teamId?` \xB7 ${c.teamId}`:""}`}))});if(qt(a)){Xt("Cancelled");return}let d=l.find(c=>(c.deviceKey||c.udid)===a);t=d?.udid||a,n=d?.teamId||n}catch(s){o.stop(re.red("Failed to fetch devices")),Ne.error(s.response?.data?.message||s.message);return}}let i=await _u({message:`Remove device ${re.dim(t.substring(0,12)+"...")}?`});if(qt(i)||!i){Xt("Cancelled");return}let r=Zt();r.start("Removing device...");try{await R.delete(`/devices/${encodeURIComponent(t)}`,n?{params:{teamId:n}}:void 0),r.stop(re.green("Device removed"))}catch(o){r.stop(re.red("Failed to remove device")),Ne.error(o.response?.data?.message||o.message)}Qt(re.blue("---"))}async function Tn(e,t){switch(e){case"register":await Pu(t);break;case"list":await Du(t);break;case"remove":await Ou(t);break;default:Ne.error(`Unknown action: ${e}`)}}import{log as ke,spinner as Ws}from"@clack/prompts";import Ve from"chalk";import Gn from"path";import nn from"fs";import uf from"os";import ff from"axios";var Te=(o=>(o.CRITICAL="critical",o.HIGH="high",o.MEDIUM="medium",o.LOW="low",o.INFO="info",o))(Te||{}),Ke=(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))(Ke||{});import{spinner as Ms,log as tn}from"@clack/prompts";import Oe from"chalk";import{execSync as ef}from"child_process";import Us from"fs";import Bs from"path";import dt from"fs";import en from"path";import{execSync as Cu}from"child_process";var bs={"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"}},Nu={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 Tu(e){try{let n=Cu("npx expo config --type introspect --json 2>/dev/null",{cwd:e,encoding:"utf-8",timeout:3e4});return JSON.parse(n)}catch{}let t=en.join(e,"app.json");if(dt.existsSync(t))try{let n=JSON.parse(dt.readFileSync(t,"utf-8"));return n.expo||n}catch{}return null}function ku(e){let t=[],n=en.join(e,"node_modules");if(!dt.existsSync(n))return t;let i=/<uses-permission\s+android:name="([^"]+)"/g;function r(o,s){let l=en.join(o,"android","src","main","AndroidManifest.xml");if(!dt.existsSync(l))return;let a=dt.readFileSync(l,"utf-8"),d;for(;(d=i.exec(a))!==null;)t.push({pkg:s,permission:d[1]});i.lastIndex=0}for(let o of dt.readdirSync(n)){if(o.startsWith("."))continue;let s=en.join(n,o);if(o.startsWith("@")){if(!dt.statSync(s).isDirectory())continue;for(let l of dt.readdirSync(s))r(en.join(s,l),`${o}/${l}`)}else r(s,o)}return t}async function Es(e,t){let n=[],i=1,r=Tu(e),o=r?.android?.permissions||[],s=r?.android?.blockedPermissions||[];for(let d of o){let c=bs[d];c&&n.push({id:`PERM-${String(i++).padStart(3,"0")}`,title:`${d.split(".").pop()} declared`,description:c.description,severity:c.severity,category:"permissions",file:"app.config.ts",recommendation:"Remove from permissions if not needed, or add justification."})}let l=ku(e);for(let{pkg:d,permission:c}of l){let u=bs[c];u&&(s.includes(c)||o.includes(c)||n.push({id:`PERM-${String(i++).padStart(3,"0")}`,title:`${c.split(".").pop()} injected by ${d}`,description:`${u.description}. Auto-injected via ${d} AndroidManifest.xml`,severity:u.severity,category:"permissions",file:`node_modules/${d}/android/src/main/AndroidManifest.xml`,recommendation:`Add "${c}" to blockedPermissions if not needed.`,autoFixable:!0}))}let a=r?.ios?.infoPlist||{};for(let[d,c]of Object.entries(Nu))d in a&&n.push({id:`PERM-${String(i++).padStart(3,"0")}`,title:`iOS: ${d} declared`,description:c.description,severity:c.severity,category:"permissions",file:"app.config.ts",recommendation:`Remove ${d} from infoPlist if the app does not use this capability.`});return{category:"permissions",label:"Permission Audit",findings:n,durationMs:0}}import Ki from"fs";import kn from"path";var Lu=[{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"}],xu=new Set([".ts",".tsx",".js",".jsx"]),Mu=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function As(e){let t=[],n=Ki.readdirSync(e,{withFileTypes:!0});for(let i of n){if(Mu.has(i.name))continue;let r=kn.join(e,i.name);i.isDirectory()?t.push(...As(r)):xu.has(kn.extname(i.name))&&t.push(r)}return t}function Uu(e){let t=e.trim();return t.startsWith("//")||t.startsWith("*")||t.startsWith("/*")}function Bu(e){return/process\.env\./i.test(e)||/import\.meta\.env/i.test(e)}async function Is(e,t){let n=[],i=kn.join(e,"src"),r=Ki.existsSync(i)?i:e,o=As(r);for(let s of o){let a=Ki.readFileSync(s,"utf-8").split(`
|
|
1358
|
+
`),d=kn.relative(e,s);for(let c=0;c<a.length;c++){let u=a[c];if(!Uu(u)&&!Bu(u))for(let{id:f,pattern:p,severity:h,label:O}of Lu)p.lastIndex=0,p.test(u)&&n.push({id:f,title:O,description:`Potential ${O.toLowerCase()} found in source code`,severity:h,category:"secrets",file:d,line:c+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 Fu}from"child_process";var Hu={critical:"critical",high:"high",moderate:"medium",low:"low",info:"info"};async function ws(e,t){let n=[],i=1,r;try{r=Fu("npm audit --json 2>/dev/null",{cwd:e,encoding:"utf-8",timeout:6e4})}catch(l){if(r=l.stdout||"",!r)return{category:"dependencies",label:"Dependency CVEs",findings:[],durationMs:0,error:"Failed to run npm audit. Ensure npm is available and dependencies are installed."}}let o;try{o=JSON.parse(r)}catch{return{category:"dependencies",label:"Dependency CVEs",findings:[],durationMs:0,error:"Failed to parse npm audit output."}}let s=o.vulnerabilities||{};for(let[l,a]of Object.entries(s)){let d=Hu[a.severity]||"info",c=Array.isArray(a.via)?a.via.map(u=>typeof u=="string"?u:u.title||u.name).join(", "):String(a.via);n.push({id:`DEP-${String(i++).padStart(3,"0")}`,title:`${l} \u2014 ${a.severity}`,description:`Via: ${c}. Range: ${a.range||"unknown"}`,severity:d,category:"dependencies",recommendation:a.fixAvailable?`Run \`npm audit fix\` or update ${l} to a patched version.`:"No fix available yet. Monitor for updates or evaluate alternatives.",autoFixable:!!a.fixAvailable})}return{category:"dependencies",label:"Dependency CVEs",findings:n,durationMs:0}}import Ln from"fs";import xn from"path";var ju=/(?:token|password|credential|secret|apiKey|api_key|session|auth|jwt|refresh_token|access_token|private_key|pin|otp)/i,_s=/AsyncStorage\s*\.\s*(?:setItem|mergeItem)\s*\(\s*['"`]([^'"`]+)['"`]/g,Gu=/from\s+['"]@react-native-async-storage\/async-storage['"]|from\s+['"]react-native['"].*AsyncStorage/,Ku=new Set([".ts",".tsx",".js",".jsx"]),Vu=new Set(["node_modules",".expo",".git","android","ios","dist","build"]);function $s(e){let t=[];if(!Ln.existsSync(e))return t;let n=Ln.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}async function vs(e,t){let n=[],i=1,r=xn.join(e,"src"),o=Ln.existsSync(r)?r:e,s=$s(o);for(let l of s){let a=Ln.readFileSync(l,"utf-8");if(!Gu.test(a))continue;let d=a.split(`
|
|
1359
|
+
`),c=xn.relative(e,l);for(let u=0;u<d.length;u++){let f=d[u];_s.lastIndex=0;let p;for(;(p=_s.exec(f))!==null;){let h=p[1];ju.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:c,line:u+1,recommendation:"Use expo-secure-store (SecureStore) for sensitive data instead of AsyncStorage."})}}}return{category:"storage",label:"Insecure Storage",findings:n,durationMs:0}}import Mn from"fs";import Un from"path";var Rs=/['"`](http:\/\/(?!localhost|127\.0\.0\.1|10\.|192\.168\.|0\.0\.0\.0|172\.(?:1[6-9]|2\d|3[01])\.)[^'"`\s]+)['"`]/g,zu=/\/api\/|\/v[0-9]+\/|\/graphql|\/rest\//i,Wu=new Set([".ts",".tsx",".js",".jsx"]),Yu=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function Ps(e){let t=[];if(!Mn.existsSync(e))return t;let n=Mn.readdirSync(e,{withFileTypes:!0});for(let i of n){if(Yu.has(i.name))continue;let r=Un.join(e,i.name);i.isDirectory()?t.push(...Ps(r)):Wu.has(Un.extname(i.name))&&t.push(r)}return t}async function Ds(e,t){let n=[],i=1,r=Un.join(e,"src"),o=Mn.existsSync(r)?r:e,s=Ps(o);for(let l of s){let d=Mn.readFileSync(l,"utf-8").split(`
|
|
1360
|
+
`),c=Un.relative(e,l);for(let u=0;u<d.length;u++){let f=d[u],p=f.trim();if(p.startsWith("//")||p.startsWith("*"))continue;Rs.lastIndex=0;let h;for(;(h=Rs.exec(f))!==null;){let O=h[1],N=zu.test(O);n.push({id:`NET-${String(i++).padStart(3,"0")}`,title:`Insecure HTTP URL${N?" (API endpoint)":""}`,description:`Plain HTTP URL found: ${O}`,severity:N?"high":"medium",category:"network",file:c,line:u+1,recommendation:"Use HTTPS instead of HTTP for all network requests."})}}}return{category:"network",label:"HTTP URLs",findings:n,durationMs:0}}import Bn from"fs";import Fn from"path";var Os=/(?:debug|debugMode|devMode|enableDebug)\s*[:=]\s*true/gi,Cs=/console\.(?:log|warn|info|debug)\s*\([^)]*(?:token|password|secret|credential|key|auth)/gi,Ju=new Set([".ts",".tsx",".js",".jsx"]),qu=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function Ns(e){let t=[];if(!Bn.existsSync(e))return t;let n=Bn.readdirSync(e,{withFileTypes:!0});for(let i of n){if(qu.has(i.name))continue;let r=Fn.join(e,i.name);i.isDirectory()?t.push(...Ns(r)):Ju.has(Fn.extname(i.name))&&t.push(r)}return t}async function Ts(e,t){let n=[],i=1,r=Fn.join(e,"src"),o=Bn.existsSync(r)?r:e,s=Ns(o);for(let l of s){let d=Bn.readFileSync(l,"utf-8").split(`
|
|
1361
|
+
`),c=Fn.relative(e,l);for(let u=0;u<d.length;u++){let f=d[u],p=f.trim();if(!(p.startsWith("//")||p.startsWith("*"))&&(Os.lastIndex=0,Os.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:c,line:u+1,recommendation:"Use __DEV__ or environment variables instead of hardcoded debug flags."}),Cs.lastIndex=0,Cs.test(f))){let h=d.slice(Math.max(0,u-3),u).join(`
|
|
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:c,line:u+1,recommendation:"Wrap in __DEV__ check or remove sensitive data from console output."})}}}return{category:"debug",label:"Debug/Dev Flags",findings:n,durationMs:0}}import ks from"fs";import Vi from"path";var Xu=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 Zu(e){let t=[Vi.join(e,"android","app","src","main","AndroidManifest.xml"),Vi.join(e,"android","AndroidManifest.xml")];for(let n of t)if(ks.existsSync(n))return n;return null}async function Ls(e,t){let n=[],i=1,r=Zu(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=ks.readFileSync(r,"utf-8"),s=Vi.relative(e,r),l=/<(activity|service|receiver|provider)\s+([^>]*?)(?:\/>|>)/gs,a;for(;(a=l.exec(o))!==null;){let d=a[1],c=a[2],f=c.match(/android:name="([^"]+)"/)?.[1]||"unknown";if(Xu.has(f))continue;let p=/android:exported="true"/.test(c),h=/android:permission="/.test(c);p&&!h&&n.push({id:`MAN-${String(i++).padStart(3,"0")}`,title:`Exported ${d}: ${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 Hn from"fs";import zi from"path";function Qu(e){let t=zi.join(e,"ios");if(!Hn.existsSync(t))return null;let n=Hn.readdirSync(t,{withFileTypes:!0});for(let i of n){if(!i.isDirectory()||i.name==="Pods"||i.name.startsWith("."))continue;let r=zi.join(t,i.name,"Info.plist");if(Hn.existsSync(r))return r}return null}async function xs(e,t){let n=[],i=1,r=Qu(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=Hn.readFileSync(r,"utf-8"),s=zi.relative(e,r),l=o.match(/<key>NSAppTransportSecurity<\/key>\s*<dict>([\s\S]*?)<\/dict>/);if(l){let a=l[1];/<key>NSAllowsArbitraryLoads<\/key>\s*<true\s*\/>/.test(a)&&n.push({id:`ATS-${String(i++).padStart(3,"0")}`,title:"ATS disabled \u2014 NSAllowsArbitraryLoads",description:"App Transport Security is completely disabled. All HTTP connections are allowed.",severity:"critical",category:"ats",file:s,recommendation:"Remove NSAllowsArbitraryLoads or set to false. Use domain-specific exceptions only if absolutely necessary."});let d=a.match(/<key>NSExceptionDomains<\/key>\s*<dict>([\s\S]*?)<\/dict>/);if(d){let c=d[1].match(/<key>([^<]+)<\/key>/g);if(c)for(let u of c){let f=u.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 tf=[{category:"permissions",label:"Permission Audit",fn:Es,requiresPrebuild:!1},{category:"secrets",label:"Secrets Detection",fn:Is,requiresPrebuild:!1},{category:"dependencies",label:"Dependency CVEs",fn:ws,requiresPrebuild:!1},{category:"storage",label:"Insecure Storage",fn:vs,requiresPrebuild:!1},{category:"network",label:"HTTP URLs",fn:Ds,requiresPrebuild:!1},{category:"debug",label:"Debug/Dev Flags",fn:Ts,requiresPrebuild:!1},{category:"manifest",label:"Android Manifest",fn:Ls,requiresPrebuild:!0},{category:"ats",label:"iOS ATS Config",fn:xs,requiresPrebuild:!0}];async function Fs(e,t){let n=tf;t.category&&(n=n.filter(s=>s.category===t.category),n.length===0&&(tn.error(Oe.red(`Unknown category: ${t.category}`)),tn.info(Oe.dim(`Available: ${Object.values(Ke).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=Ms();l.start(Oe.dim(`Running ${s.label}...`));try{let a=Date.now(),d=await s.fn(e,t);d.durationMs=Date.now()-a,o.push(d);let c=d.findings.length;l.stop(c>0?Oe.yellow(`${s.label} \u2014 ${c} finding(s)`):Oe.green(`${s.label} \u2014 clean`))}catch(a){l.stop(Oe.red(`${s.label} \u2014 error`)),o.push({category:s.category,label:s.label,findings:[],durationMs:0,error:a.message})}}if(r.length>0){let s=Bs.join(e,"android"),l=Bs.join(e,"ios"),a=Us.existsSync(s)||Us.existsSync(l);if(!a&&t.prebuild){t.json||tn.info(Oe.dim(`
|
|
1363
|
+
Running expo prebuild for deeper analysis...`));try{ef("npx expo prebuild --no-install",{cwd:e,stdio:"pipe"})}catch{return tn.warn(Oe.yellow("Prebuild failed \u2014 skipping manifest/plist checks.")),o}}else if(!a)return t.json||tn.info(Oe.dim(`
|
|
1364
|
+
Skipping manifest/plist checks \u2014 no android/ios dirs. Use --prebuild to generate them.`)),o;for(let d of r){let c=Ms();c.start(Oe.dim(`Running ${d.label}...`));try{let u=Date.now(),f=await d.fn(e,t);f.durationMs=Date.now()-u,o.push(f);let p=f.findings.length;c.stop(p>0?Oe.yellow(`${d.label} \u2014 ${p} finding(s)`):Oe.green(`${d.label} \u2014 clean`))}catch(u){c.stop(Oe.red(`${d.label} \u2014 error`)),o.push({category:d.category,label:d.label,findings:[],durationMs:0,error:u.message})}}}return o}import he from"chalk";import{log as me}from"@clack/prompts";var Pt={critical:he.bgRed.white.bold,high:he.red.bold,medium:he.yellow.bold,low:he.blue,info:he.dim},jn={critical:0,high:1,medium:2,low:3,info:4};function nf(e,t){if(!t)return!0;let n=jn[t];return n===void 0?!0:jn[e]<=n}function Hs(e,t){let n=0,i={critical:0,high:0,medium:0,low:0,info:0};for(let s of e){let l=s.findings.filter(d=>nf(d.severity,t));if(l.length===0&&!s.error)continue;if(me.info(""),me.info(he.bold(` ${s.label}`)+he.dim(` ${l.length} finding(s)`)),me.info(he.dim(" "+"\u2500".repeat(60))),s.error){me.error(he.red(` Error: ${s.error}`));continue}let a=[...l].sort((d,c)=>jn[d.severity]-jn[c.severity]);for(let d of a){let c=Pt[d.severity](` ${d.severity.toUpperCase()} `);me.info(` ${c} ${he.bold(d.id)} ${d.title}`),me.info(he.dim(` ${d.description}`)),d.file&&me.info(he.dim(` File: ${d.file}${d.line?`:${d.line}`:""}`)),me.info(he.cyan(` Fix: ${d.recommendation}`)),me.info(""),i[d.severity]++,n++}}me.info(""),me.info(he.bold(" Summary")),me.info(he.dim(" "+"\u2500".repeat(60))),me.info(` Total: ${he.bold(String(n))} finding(s)`),me.info(` ${Pt.critical(` ${i.critical} Critical `)} ${Pt.high(` ${i.high} High `)} ${Pt.medium(` ${i.medium} Medium `)} ${Pt.low(` ${i.low} Low `)} ${Pt.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 js(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 rf}from"@clack/prompts";import ue from"chalk";import Qe from"fs";import of from"os";import Dt from"path";import{execSync as sf}from"child_process";var Gs=16384,af=1,lf=Buffer.from([127,69,76,70]);async function Ks(e){ge.info(ue.bold.underline("16KB Page Alignment Check")),console.log("");let t=Dt.resolve(e);if(!Qe.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=rf();n.start("Extracting and analyzing native libraries...");let i=Qe.mkdtempSync(Dt.join(of.tmpdir(),"mach-16kb-"));try{try{sf(`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=Vs(Dt.join(i,"lib"));if(r.length===0)return n.stop("Analysis complete."),ge.info(ue.yellow("No arm64-v8a or x86_64 native libraries found in the APK.")),ge.info(ue.dim("16KB alignment check only applies to arm64-v8a and x86_64 architectures.")),!0;let o=[];for(let a of r){let d=Dt.relative(i,a),c=cf(d),u=Dt.basename(a),f=df(a);f!==null&&o.push({name:u,filePath:d,arch:c,align:f,compatible:f>=Gs})}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"}
|
|
1360
1365
|
`)),s.length>0){ge.info(ue.red.bold(`Incompatible libraries:
|
|
1361
|
-
`));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 = ${Bs})`))}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 tf(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(ef))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(Qe.readSync(t,p,0,c,a+f*c),s(p,0)!==Qu)continue;let O;i?O=l(p,48):O=s(p,28),O>0&&(d===null||O<d)&&(d=O)}return d??0}catch{return null}finally{Qe.closeSync(t)}}function Hs(e){let t=[];if(!Qe.existsSync(e))return t;let n=Qe.readdirSync(e,{withFileTypes:!0});for(let i of n){let r=Pt.join(e,i.name);i.isDirectory()?t.push(...Hs(r)):i.name.endsWith(".so")&&t.push(r)}return t}function nf(e){return e.includes("arm64-v8a")?"arm64-v8a":e.includes("x86_64")?"x86_64":"unknown"}var Ks=async e=>{if(Pe()||(ke.error(Ve.red(`You are not logged in. Run \`${m.nameLower} login\` first.`)),process.exit(1)),e.apk){await sf(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 xs(n,s);e.json?console.log(JSON.stringify(Us(l,r),null,2)):Ms(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 sf(e){let t=e.category?.toLowerCase();t&&!js.includes(t)&&(ke.error(Ve.red(`Unknown APK check category: "${t}"`)),ke.info(Ve.dim(`Available APK checks: ${js.join(", ")}`)),process.exit(1));let n=await af(e.apk);n||process.exit(1);let i=!t,r=!1;(i||t==="16kb")&&(await Fs(n)||(r=!0)),r&&process.exit(1)}async function af(e){if(e.startsWith("build:")){let n=e.slice(6);return await lf(n)}if(e.startsWith("http://")||e.startsWith("https://"))return await Vs(e);let t=Gn.resolve(e);return nn.existsSync(t)?t:(ke.error(Ve.red(`APK file not found: ${t}`)),null)}async function lf(e){let t=Gs();t.start(`Fetching APK from build ${e}...`);try{let n=await v.get(`/build/${e}`);if(n.data.status!=="success")throw new Error(n.data.message);let i=n.data.build;if(!i)throw new Error("Build not found");let r=i.artifacts?.find(o=>o.type?o.type==="apk":o.name?.endsWith(".apk")||o.url?.includes(".apk"));return!r||!r.url?(t.stop("No APK artifact found"),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 Vs(r.url))}catch(n){return t.stop("Failed to fetch build"),ke.error(Ve.red(n.message)),null}}async function Vs(e){let t=Gs();t.start("Downloading APK...");try{let n=nn.mkdtempSync(Gn.join(rf.tmpdir(),`${m.nameLower}-audit-`)),i=Gn.join(n,"app.apk"),r=await of.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 uf=console.log;console.log=()=>{};cf();console.log=uf;we(be.bgCyan.black(m.cliTag("Production Build Orchestrator")));var pf=ff(import.meta.url),mf=pf("../package.json"),Ws=(e,t=[])=>t.concat(e),oe=new df;oe.name(m.nameLower).description(`${m.name} CLI: Powerful Cloud Infrastructure Tools`).version(mf.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 Wo(e)});oe.command("host").description("Setup AWS S3 static hosting and CloudFront").action(async()=>{we(be.bgCyan.black(m.cliTag("Hosting"))),await rr()});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 lr(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",Ws,[]).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",Ws,[]).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 Br(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 os(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 Xo()});oe.command("logout").description(`Logout from ${m.name} on this machine`).action(async()=>{we(be.bgCyan.black(m.cliTag("Logout"))),await Zo()});oe.command("link").description(`Link local directory to a ${m.name} Project`).action(async()=>{we(be.bgCyan.black(m.cliTag("Link Project"))),await es()});oe.command("me").description("Display currently logged in user details").action(async()=>{await as()});oe.command("init").description(`Create a new ${m.name} Project`).action(async()=>{we(be.bgCyan.black(m.cliTag("Init Project"))),await ts()});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 is(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 ds(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 cs(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 Ct(e),zs(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 nr(e),zs(be.green("Done!"))});var zi=oe.command("device").description("Manage registered iOS test devices");zi.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)});zi.command("list").description("List all registered devices").option("--team-id <id>","Filter by Apple Developer Team ID").action(async e=>{await Tn("list",e)});zi.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 Ks(e)});var gf=new Set(["login","logout","agent"]);oe.hook("preAction",(e,t)=>{let n=t.name(),i=t.opts?.()||{};n==="maestro"&&(i.local||i.localRunner)||gf.has(n)||Zi()});oe.on("command:*",()=>{console.error(`Invalid command: %s
|
|
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
|
|
1362
1367
|
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);
|