@radhya/mach 2.0.37 → 2.0.38
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 +11 -1
- package/dist/index.js +139 -139
- 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: ${
|
|
2
|
+
import{a as Jt,b as He,c as Co,d as xt,e as ve,f as xe,g as Zn,h as Qn,i as Yt,j as ko,l as hn}from"./chunk-ZPETQEMG.js";import{a as m,b as Do,c as ke,d as Oo,e as Wt,f as dt,g as ot,h as k}from"./chunk-S64YFTRR.js";import{Command as ih,Option as Je}from"commander";import{configDotenv as rh}from"dotenv";import{intro as de,outro as Sc}from"@clack/prompts";import se from"chalk";import{text as To,confirm as vc,spinner as $c,isCancel as Qi,cancel as yn,note as _c,outro as Rc}from"@clack/prompts";import Sn from"chalk";async function No(){try{let e=await To({message:"Enter Bucket Name:",placeholder:"e.g. my-app-dev",validate(r){if(r.length===0)return"Bucket name is required"}});Qi(e)&&(yn("Operation cancelled."),process.exit(0));let t=await To({message:"Enter Region:",initialValue:"ap-south-1"});Qi(t)&&(yn("Operation cancelled."),process.exit(0));let n=await vc({message:"Do you want to create a CloudFront Distribution for this bucket?",initialValue:!0});Qi(n)&&(yn("Operation cancelled."),process.exit(0));let i=$c();i.start("Setting up hosting infrastructure...");try{let r=await k.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: ${Sn.cyan(o.bucketName)}
|
|
3
|
+
`;s+=`Region: ${Sn.cyan(o.region)}
|
|
4
|
+
`,s+=`S3 Website URL: ${Sn.blue(o.s3WebsiteUrl)}`,o.cloudFrontId&&(s+=`
|
|
5
5
|
|
|
6
|
-
CloudFront ID: ${
|
|
7
|
-
CloudFront URL: ${
|
|
6
|
+
CloudFront ID: ${Sn.cyan(o.cloudFrontId)}`,s+=`
|
|
7
|
+
CloudFront URL: ${Sn.blue(o.cloudFrontUrl)}`),_c(s,"Setup Complete!"),Rc("You are all set!")}catch(r){i.stop("Setup failed"),yn(`Error: ${r.response?.data?.message||r.message}`)}}catch(e){yn(`An unexpected error occurred: ${e.message}`)}}import{readdir as Pc,writeFile as Dc,access as Oc,mkdir as Cc}from"fs/promises";import{join as xo}from"path";import{spinner as kc,text as Lo,isCancel as Mo,cancel as er,note as Tc,outro as Nc}from"@clack/prompts";import xc from"chalk";async function Lc(){let e=["./app","./src/app"];for(let t of e)try{return await Oc(t),t}catch{}return null}async function Uo(e){try{let n=await Lc()||"./app",i=await Lo({message:"Enter path to your app directory:",placeholder:n,initialValue:n,validate(u){if(u.length===0)return"Path is required"}});Mo(i)&&(er("Operation cancelled."),process.exit(0));let r=await Lo({message:"Enter your website base URL:",placeholder:"https://example.com",validate(u){if(u.length===0)return"Base URL is required";if(!u.startsWith("http"))return"URL must start with http:// or https://"}});Mo(r)&&(er("Operation cancelled."),process.exit(0));let o=kc();o.start("Scanning app directory for routes...");let s=await Fo(i);o.stop(`Found ${s.length} routes`);let l=Mc(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 Cc(d,{recursive:!0})}catch{}await Dc(a,l,"utf-8"),o.stop("Sitemap generated successfully!"),Tc(`Routes included:
|
|
8
8
|
${s.map(u=>` \u2022 ${u.path}`).join(`
|
|
9
|
-
`)}`,"Sitemap Summary"),
|
|
9
|
+
`)}`,"Sitemap Summary"),Nc(`Sitemap saved to ${xc.cyan(a)}`)}catch(t){er(`An error occurred: ${t.message}`)}}async function Fo(e,t=""){let n=[];try{let i=await Pc(e,{withFileTypes:!0});for(let r of i){let o=xo(e,r.name);if(!(r.name.startsWith("_")||r.name.startsWith("."))){if(r.isDirectory()){let s=await Fo(o,xo(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 Mc(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 Ip}from"crypto";import Ee from"path";import ui from"axios";import wp from"os";import{spinner as Mr,select as Ys,confirm as qs,isCancel as pi,cancel as Xs,log as O}from"@clack/prompts";import C from"chalk";import pe from"fs";import{execSync as Zs}from"child_process";import Qs from"adm-zip";import{spinner as zc,log as ei}from"@clack/prompts";import Ho from"chalk";import Go from"fs";import Vo from"path";var Bo=`#!/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}}"
|
|
@@ -533,7 +533,7 @@ for pid in "\${cache_pids[@]}"; do wait "$pid" || true; done
|
|
|
533
533
|
echo "Build orchestrator finished. Auto-terminating instance in 5 seconds..."
|
|
534
534
|
sleep 5
|
|
535
535
|
sudo shutdown -h now
|
|
536
|
-
`;import
|
|
536
|
+
`;import jc from"crypto";import{log as Le}from"@clack/prompts";import Me from"chalk";import{execSync as Uc}from"child_process";import Ue from"fs";import qt from"path";var jo={id:"expo",displayName:"Expo",applyLocalProcessEnv:e=>{e.developmentClient?(Le.info(Me.blue("\u2139\uFE0F Configuring Expo build to INCLUDE expo-dev-client (Development Client mode)...")),delete process.env.EXPO_NO_DEV_CLIENT,delete process.env.EXPO_AUTOLINKING_EXCLUDE):(Le.info(Me.blue("\u2139\uFE0F Configuring Expo build to EXCLUDE expo-dev-client (Production/Staging mode)...")),process.env.EXPO_NO_DEV_CLIENT="1",process.env.EXPO_AUTOLINKING_EXCLUDE="expo-dev-client")},localAndroidEnv:(e,t)=>({EXPO_NO_DOTENV:"1",MACH_FRAMEWORK:"expo",MACH_BUILD_PROFILE:t}),remoteEnvSetupScript:()=>`
|
|
537
537
|
export MACH_FRAMEWORK="expo"
|
|
538
538
|
echo "[ENV] MACH_FRAMEWORK=$MACH_FRAMEWORK"
|
|
539
539
|
export EXPO_NO_DOTENV="\${EXPO_NO_DOTENV:-1}"
|
|
@@ -585,7 +585,7 @@ fi
|
|
|
585
585
|
echo "expo.enableHermes=true" >> gradle.properties
|
|
586
586
|
`,androidRemoteReleaseGradlePropertiesScript:()=>`
|
|
587
587
|
echo "expo.enableProguardInReleaseBuilds=true" >> gradle.properties
|
|
588
|
-
`,prepareLocalProject:async e=>{let{platform:t,options:n,cacheMeta:i,cacheMetaDir:r,currentBuildEnv:o,reportStep:s,loggedRun:l,configureXcodeNodeBinary:a,podsFingerprint:d,writeCacheMeta:u}=e,c=n.iosBundleIdentifier||"",p=n.name||"",f=
|
|
588
|
+
`,prepareLocalProject:async e=>{let{platform:t,options:n,cacheMeta:i,cacheMetaDir:r,currentBuildEnv:o,reportStep:s,loggedRun:l,configureXcodeNodeBinary:a,podsFingerprint:d,writeCacheMeta:u}=e,c=n.iosBundleIdentifier||"",p=n.name||"",f=qt.join(process.cwd(),"app.json"),g=null;Le.info(Me.blue(`Running Expo prebuild for ${t}...`));try{if(Ue.existsSync(f)){g=Ue.readFileSync(f,"utf-8");let h=JSON.parse(g);h.expo=h.expo||{},p||(p=h.expo.name||""),t==="ios"&&!c&&(c=h.expo?.ios?.bundleIdentifier||""),n.name&&(h.expo.name=n.name),n.scheme&&(h.expo.scheme=n.scheme),t==="ios"&&n.iosBundleIdentifier?(h.expo.ios=h.expo.ios||{},h.expo.ios.bundleIdentifier=n.iosBundleIdentifier):t==="android"&&n.androidPackage&&(h.expo.android=h.expo.android||{},h.expo.android.package=n.androidPackage),Ue.writeFileSync(f,JSON.stringify(h,null,2))}let y=["exec","--","expo","prebuild","--platform",t,"--no-install"];if(await s("prebuild"),await l("npm",y,process.cwd(),o()),t!=="ios"||!Ue.existsSync("ios"))return{appName:p,bundleId:c};await s("pods"),Le.info(Me.blue("Running pod install..."));try{let h=qt.resolve("ios"),v=qt.join(h,"Podfile");if(!Ue.existsSync(v))throw new Error("ios/Podfile not found. Skipping pod install.");let I=o();a(h,I);let N=Ue.readFileSync(v,"utf-8"),w=n.iosDeploymentTarget||"13.4";if(!n.developmentClient&&(Le.info(Me.blue("\u2139\uFE0F Patching Podfile to EXCLUDE expo-dev-client...")),N.includes("use_expo_modules!")&&!N.includes("exclude:"))){let P=/use_expo_modules!(\s*)$/m;P.test(N)?N=N.replace(P,'use_expo_modules!(exclude: ["expo-dev-client"])$1'):N=N.replace("use_expo_modules!",'use_expo_modules!(exclude: ["expo-dev-client"])')}let U=`
|
|
589
589
|
installer.generated_projects.each do |project|
|
|
590
590
|
project.targets.each do |target|
|
|
591
591
|
target.build_configurations.each do |config|
|
|
@@ -598,13 +598,13 @@ echo "expo.enableProguardInReleaseBuilds=true" >> gradle.properties
|
|
|
598
598
|
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '${w}'
|
|
599
599
|
end
|
|
600
600
|
end
|
|
601
|
-
`,V=/post_install\s+do\s+\|installer\|/;if(V.test(
|
|
602
|
-
${U}`),Ue.writeFileSync(
|
|
601
|
+
`,V=/post_install\s+do\s+\|installer\|/;if(V.test(N))Le.info(Me.dim(`Injecting deployment target (${w}) into existing post_install hook...`)),N=N.replace(V,`post_install do |installer|
|
|
602
|
+
${U}`),Ue.writeFileSync(v,N);else{Le.info(Me.dim(`Appending new post_install hook for deployment target (${w})...`));let P=`
|
|
603
603
|
post_install do |installer|
|
|
604
604
|
${U}
|
|
605
605
|
end
|
|
606
|
-
`;Ue.appendFileSync(
|
|
607
|
-
`),Le.info(Me.dim("Podfile fingerprint changed \u2014 clearing Pods for clean install...")),Ue.rmSync(
|
|
606
|
+
`;Ue.appendFileSync(v,P)}let J="/opt/homebrew/bin/pod",A=Ue.existsSync(J)?J:"pod",_=d(h);Ue.existsSync(qt.join(h,"Pods"))&&i.pods&&i.pods!==_&&(await e.reportLog(`[CACHE] Podfile/Podfile.lock changed \u2014 wiping ios/Pods
|
|
607
|
+
`),Le.info(Me.dim("Podfile fingerprint changed \u2014 clearing Pods for clean install...")),Ue.rmSync(qt.join(h,"Pods"),{recursive:!0,force:!0})),Le.info(Me.dim(`Using pod command: ${A} in ${h}`)),await l(A,["install"],h,I),i.pods=_,u(r,i)}catch(h){let v=h.message||"Unknown error";Le.warn(Me.yellow(`Native "pod" command failed: ${v}`)),Le.info(Me.dim("Falling back to npm exec pod-install..."));let I=o();a(qt.resolve("ios"),I),Le.info(Me.magenta(`${m.nameUpper}_DEBUG: Executing pod-install override via npx --yes pod-install@latest`)),await l("npx",["--yes","pod-install@latest","ios"],process.cwd(),I)}if(Ue.existsSync("ios/Pods")){Le.info(Me.dim("Disabling signing for Pod targets to prevent conflicts..."));try{Uc(`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{}}return{appName:p,bundleId:c}}finally{g&&Ue.writeFileSync(f,g)}}};import{log as Lt}from"@clack/prompts";import Mt from"chalk";import ut from"fs";import bn from"path";var Fc=(e,t)=>!ut.existsSync(e)||!ut.existsSync(t)?!1:ut.readFileSync(e,"utf-8")!==ut.readFileSync(t,"utf-8"),tr={id:"react-native",displayName:"React Native",applyLocalProcessEnv:e=>{delete process.env.EXPO_NO_DEV_CLIENT,delete process.env.EXPO_AUTOLINKING_EXCLUDE,delete process.env.EXPO_NO_DOTENV},localAndroidEnv:(e,t)=>({MACH_FRAMEWORK:"react-native",MACH_BUILD_PROFILE:t}),remoteEnvSetupScript:()=>`
|
|
608
608
|
export MACH_FRAMEWORK="react-native"
|
|
609
609
|
echo "[ENV] MACH_FRAMEWORK=$MACH_FRAMEWORK"
|
|
610
610
|
unset EXPO_NO_DOTENV
|
|
@@ -619,17 +619,17 @@ echo "[PREBUILD] React Native framework configured. Skipping Expo prebuild."
|
|
|
619
619
|
:
|
|
620
620
|
`,androidRemoteReleaseGradlePropertiesScript:()=>`
|
|
621
621
|
:
|
|
622
|
-
`,prepareLocalProject:async e=>{let{platform:t,cacheMeta:n,cacheMetaDir:i,currentBuildEnv:r,reportStep:o,reportLog:s,loggedRun:l,configureXcodeNodeBinary:a,podsFingerprint:d,writeCacheMeta:u}=e;if(t!=="ios")return{};let c=
|
|
623
|
-
`),
|
|
624
|
-
`),
|
|
625
|
-
`):"",f;if(r){let I=
|
|
626
|
-
export MACH_APP_NAME="${
|
|
627
|
-
export MACH_BUILD_PROFILE="${
|
|
628
|
-
export MACH_ANDROID_RELEASE_ABIS="${
|
|
622
|
+
`,prepareLocalProject:async e=>{let{platform:t,cacheMeta:n,cacheMetaDir:i,currentBuildEnv:r,reportStep:o,reportLog:s,loggedRun:l,configureXcodeNodeBinary:a,podsFingerprint:d,writeCacheMeta:u}=e;if(t!=="ios")return{};let c=bn.resolve("ios"),p=bn.join(c,"Podfile");if(!ut.existsSync(p))throw new Error("React Native iOS build requires ios/Podfile. Commit the ios directory for vanilla React Native projects.");await o("pods"),Lt.info(Mt.blue("Running React Native pod install..."));let f=r();a(c,f);let g=bn.join(c,"Pods"),y=bn.join(c,"Podfile.lock"),h=bn.join(g,"Manifest.lock"),v=ut.existsSync(g),I=d(c);v&&n.reactNativePods&&n.reactNativePods!==I?(await s(`[CACHE] React Native Podfile/Podfile.lock changed - wiping ios/Pods
|
|
623
|
+
`),Lt.info(Mt.dim("React Native Podfile fingerprint changed - clearing Pods for clean install...")),ut.rmSync(g,{recursive:!0,force:!0})):v&&Fc(y,h)&&(await s(`[CACHE] React Native Pods Manifest.lock is out of sync - wiping ios/Pods
|
|
624
|
+
`),Lt.info(Mt.dim("React Native Pods manifest is out of sync - clearing Pods for clean install...")),ut.rmSync(g,{recursive:!0,force:!0}));let N="/opt/homebrew/bin/pod",w=ut.existsSync(N)?N:"pod";try{Lt.info(Mt.dim(`Using pod command: ${w} in ${c}`)),await l(w,["install"],c,f)}catch(U){let V=U.message||"Unknown error";Lt.warn(Mt.yellow(`Native "pod" command failed: ${V}`)),Lt.info(Mt.dim("Falling back to npx pod-install..."));let J=r();a(c,J),Lt.info(Mt.magenta(`${m.nameUpper}_DEBUG: Executing pod-install fallback via npx --yes pod-install@latest`)),await l("npx",["--yes","pod-install@latest","ios"],process.cwd(),J)}return n.reactNativePods=d(c),u(i,n),{}}};var Bc={expo:jo,"react-native":tr};function pt(e){if(!e)return tr;if(e!=="flutter")return Bc[e];throw new Error('Flutter builds are not implemented yet. Set framework to "expo" or "react-native" for this build.')}var Hc="mach-env-v2-js-bundle-cache",Gc=new Set(["BUILD_ID","BUILD_NUMBER","ANDROID_VERSION_CODE","MACH_TOKEN","MACH_DEBUG","MACH_S3_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"]),Vc=["PRESIGNED_","KEYSTORE_PASSWORD_"],Kc=e=>!e||Gc.has(e)?!1:!Vc.some(t=>e.startsWith(t)),Ut=(e,t,n)=>{let i=pt(n.framework);return{...e,...i.localAndroidEnv(n,t),MACH_APP_NAME:n.appName||n.name||"App"}},Xt=e=>{let t=Object.entries(e).filter(([n])=>Kc(n)).sort(([n],[i])=>n.localeCompare(i));return jc.createHash("sha256").update(JSON.stringify({version:Hc,entries:t})).digest("hex")};var nr=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`"),ir=e=>["1","true","yes","on"].includes(String(e||"").trim().toLowerCase()),Wc=e=>/(^|[-_])(maestro|e2e|test|emulator)([-_]|$)/i.test(e),Jc=(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||Wc(t)||ir(n.MACH_PROFILE_ANDROID_EMULATOR)||ir(n.MACH_ANDROID_INCLUDE_EMULATOR_ABIS)||ir(n.MACH_PROFILE_ANDROID_INCLUDE_EMULATOR_ABIS)?"armeabi-v7a,arm64-v8a,x86_64":"armeabi-v7a,arm64-v8a")},Ko=async(e,t,n={},i,r)=>{let o=zc(),s=pt(e.framework),l=e.buildProfile||"production",a=l==="production",d=e.apk===!0,u=e.developmentClient?"assembleDebug":a?"bundleRelease":"assembleRelease",c=e.buildCommand||(d?"assembleRelease":u),p=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(`
|
|
625
|
+
`):"",f;if(r){let I=Vo.isAbsolute(r)?r:Vo.resolve(process.cwd(),r);Go.existsSync(I)?(f=Go.readFileSync(I,"utf-8"),ei.info(Ho.magenta(`\u2713 Loaded preBuild hook: ${r}`))):ei.warn(`preBuild script not found at ${I} \u2014 skipping`)}let g=Jc(e,l,n),y={...Ut(n,l,e),MACH_ANDROID_RELEASE_ABIS:g},h=Xt(y),v=Bo.replace(/\{\{BUILD_ID\}\}/g,t).replace(/\{\{BUILD_COMMAND\}\}/g,c).replace("{{NODE_VERSION_SETUP}}",p).replace("{{ENV_VARS}}",`
|
|
626
|
+
export MACH_APP_NAME="${nr(y.MACH_APP_NAME)}"
|
|
627
|
+
export MACH_BUILD_PROFILE="${nr(l)}"
|
|
628
|
+
export MACH_ANDROID_RELEASE_ABIS="${nr(g)}"
|
|
629
629
|
export MACH_ENV_FINGERPRINT="${h}"
|
|
630
630
|
${s.remoteEnvSetupScript().trim()}
|
|
631
631
|
{{ENV_VARS}}
|
|
632
|
-
`).replace("{{FRAMEWORK_ANDROID_VERSION_CODE}}",s.androidRemoteVersionCodeScript().trim()).replace("{{FRAMEWORK_ANDROID_PREBUILD}}",s.androidRemotePrebuildScript().trim()).replace("{{FRAMEWORK_ANDROID_GRADLE_PROPERTIES}}",s.androidRemoteGradlePropertiesScript().trim()).replace("{{FRAMEWORK_ANDROID_RELEASE_GRADLE_PROPERTIES}}",s.androidRemoteReleaseGradlePropertiesScript().trim());if(e.dryRun){
|
|
632
|
+
`).replace("{{FRAMEWORK_ANDROID_VERSION_CODE}}",s.androidRemoteVersionCodeScript().trim()).replace("{{FRAMEWORK_ANDROID_PREBUILD}}",s.androidRemotePrebuildScript().trim()).replace("{{FRAMEWORK_ANDROID_GRADLE_PROPERTIES}}",s.androidRemoteGradlePropertiesScript().trim()).replace("{{FRAMEWORK_ANDROID_RELEASE_GRADLE_PROPERTIES}}",s.androidRemoteReleaseGradlePropertiesScript().trim());if(e.dryRun){ei.info("User Data Script (dry run):"),console.log(v);return}o.start("Requesting cloud build instance...");try{let I=await k.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:v,preBuildScriptContent:f});if(I.data.status!=="success")throw new Error(I.data.message||"Failed to launch build instance");let N=I.data.instanceId;return o.stop("Build Started"),ei.success(Ho.green(`Build initiated on cloud instance (${N}).`)),{instanceId:N}}catch(I){o.stop("Android Build Failed");let N=I.response?.data?.message||I.message;throw new Error(`Failed to launch Android build: ${N}`)}};import{spinner as Yc,log as Ft}from"@clack/prompts";import ft from"chalk";import qc from"fs";import{execSync as An}from"child_process";var zo=`#!/bin/bash
|
|
633
633
|
# --- Mach Cloud Build Script (iOS) ---
|
|
634
634
|
# All S3 operations use presigned URLs via curl \u2014 zero AWS credentials on Mac.
|
|
635
635
|
|
|
@@ -1309,53 +1309,53 @@ touch done
|
|
|
1309
1309
|
if [ ! -z "$PRESIGNED_DONE_MARKER" ]; then
|
|
1310
1310
|
curl -X PUT -T done "$PRESIGNED_DONE_MARKER" --silent
|
|
1311
1311
|
fi
|
|
1312
|
-
`;var
|
|
1312
|
+
`;var Wo=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`"),Jo=async(e,t,n={},i)=>{let r=Yc(),o=pt(e.framework);e.sshHost||(e.sshHost="localhost",Ft.message(ft.yellow("No SSH host provided, defaulting to localhost."))),r.start(`Connecting to remote Mac at ${ft.cyan(e.sshHost)}...`);let s=e.sshUser||process.env.USER||"ubuntu",l=e.sshKey,a=`${s}@${e.sshHost}`,d=`ssh ${l?`-i ${l}`:""} -o StrictHostKeyChecking=no ${a}`,u=`scp ${l?`-i ${l}`:""} -o StrictHostKeyChecking=no`;try{let c=s==="ubuntu"?"/home/ubuntu":`/Users/${s}`,p=(n.PROJECT_ID||"default_project").replace(/[^a-zA-Z0-9-_]/g,"_"),f=`${c}/${m.remoteWorkspacesDir}/${p}`;r.message(`Preparing stable workspace: ${f}...`),An(`${d} "mkdir -p ${f}"`,{stdio:"inherit"}),r.message("Transferring source code...");let g=`/tmp/${m.nameLower}-source-${t}.zip`;An(`${u} ${g} ${a}:${f}/source.zip`,{stdio:"inherit"});let y=e.iosApiKeyPath?`${f}/api_key.p8`:"",h="";e.iosApiKeyPath&&(r.message("Uploading App Store Connect API key..."),An(`${u} ${e.iosApiKeyPath} ${a}:${y}`),e.iosApiKeyId&&e.iosApiKeyIssuer&&(h=`-authenticationKeyID ${e.iosApiKeyId} -authenticationKeyIssuerID ${e.iosApiKeyIssuer} -authenticationKeyPath ${y}`));let v={};if(i)try{let S=await k.post(`/builds/${i}/${t}/build-urls`,{platform:"ios"});S.data.status==="success"&&(v=S.data.urls)}catch(S){Ft.warn(ft.yellow(`Could not fetch build URLs: ${S.message}`))}let I="";if(v.credentials&&v.credentials.length>0)for(let S of v.credentials)S.type==="p12"?I+=`curl -sf -o "$CERT_DIR/${S.name}" "${S.downloadUrl}" || true
|
|
1313
1313
|
`:S.type==="mobileprovision"&&(I+=`curl -sf -o "$PROV_TEMP/${S.name}" "${S.downloadUrl}" || true
|
|
1314
|
-
`);r.message("Generating macOS build script...");let
|
|
1315
|
-
`:"";if(n)for(let[S,R]of Object.entries(n)){let M=R.replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");
|
|
1316
|
-
`}let w=e.buildProfile||"production",U=
|
|
1314
|
+
`);r.message("Generating macOS build script...");let N=process.env.CODEARTIFACT_AUTH_TOKEN?`export CODEARTIFACT_AUTH_TOKEN="${process.env.CODEARTIFACT_AUTH_TOKEN}"
|
|
1315
|
+
`:"";if(n)for(let[S,R]of Object.entries(n)){let M=R.replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");N+=`export ${S}="${M}"
|
|
1316
|
+
`}let w=e.buildProfile||"production",U=Ut(n,w,e),V=Xt(U);Ft.info(ft.dim(`iOS remote build config: simulator=${String(!!e.simulator)}, configuration=${e.iosConfiguration||"Release"}, scheme=${e.iosScheme||"auto"}`));let J=[N,v.logUpload?`export PRESIGNED_LOG_UPLOAD="${v.logUpload}"`:"",v.doneMarker?`export PRESIGNED_DONE_MARKER="${v.doneMarker}"`:"",v.cacheDerivedDataDownload?`export PRESIGNED_CACHE_DD_DOWNLOAD="${v.cacheDerivedDataDownload}"`:"",v.cacheDerivedDataUpload?`export PRESIGNED_CACHE_DD_UPLOAD="${v.cacheDerivedDataUpload}"`:"",v.cacheNodeModulesDownload?`export PRESIGNED_CACHE_NODE_DOWNLOAD="${v.cacheNodeModulesDownload}"`:"",v.cacheNodeModulesUpload?`export PRESIGNED_CACHE_NODE_UPLOAD="${v.cacheNodeModulesUpload}"`:"",v.cachePodsDownload?`export PRESIGNED_CACHE_PODS_DOWNLOAD="${v.cachePodsDownload}"`:"",v.cachePodsUpload?`export PRESIGNED_CACHE_PODS_UPLOAD="${v.cachePodsUpload}"`:"",v.artifactIpaUpload?`export PRESIGNED_ARTIFACT_IPA_UPLOAD="${v.artifactIpaUpload}"`:"",v.artifactAppZipUpload?`export PRESIGNED_ARTIFACT_APP_ZIP_UPLOAD="${v.artifactAppZipUpload}"`:"",`export BUILD_ID="${t}"`,`export MACH_BUILD_PROFILE="${Wo(w)}"`,`export MACH_APP_NAME="${Wo(U.MACH_APP_NAME)}"`,`export MACH_ENV_FINGERPRINT="${V}"`,o.remoteEnvSetupScript().trim(),`export ${m.envPrefix}PROJECT_ID="${p}"`,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(`
|
|
1317
1317
|
`),A=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(`
|
|
1318
|
-
`):"",
|
|
1318
|
+
`):"",_=zo,L={"{{REMOTE_DIR}}":f,"{{ENV_VARS}}":J,"{{CREDENTIAL_DOWNLOADS}}":I,"{{IOS_SCHEME}}":e.iosScheme||"","{{IOS_CONFIG}}":e.iosConfiguration||"Release","{{TEAM_ID}}":e.iosTeamId||"","{{AUTH_PARAMS}}":h,"{{IS_SIMULATOR}}":e.simulator?"true":"false","{{BUILD_ID}}":t,"{{EXPORT_METHOD}}":e.iosExportMethod||"ad-hoc","{{NODE_VERSION_SETUP}}":A,"{{FRAMEWORK_PREBUILD}}":o.iosRemotePrebuildScript().trim()};Object.entries(L).forEach(([S,R])=>{_=_.split(S).join(R)});let P=`/tmp/${m.nameLower}-mac-build-${t}.sh`;if(qc.writeFileSync(P,_),An(`${u} ${P} ${a}:${f}/build.sh`),r.stop("Remote script uploaded."),Ft.info(ft.cyan("Executing remote build. This might take a while...")),An(`${d} "bash ${f}/build.sh"`,{stdio:"inherit"}),r.stop("Remote build finished!"),i){r.start("Fetching artifact links...");try{let R=(await k.get(`/builds/${i}/${t}/artifacts`)).data.artifacts||[],M=e.simulator===!0;if(R.length===0&&!M)throw r.stop("Build Failed!"),new Error("Build completed but no artifacts were generated. Check build logs for errors.");if(r.stop("Build Successful!"),R.length>0){Ft.success("Build Artifacts Ready:");for(let B of R)console.log(`
|
|
1319
1319
|
${ft.yellow(B.name)}:
|
|
1320
1320
|
${ft.cyan(B.downloadUrl)}`);console.log(`
|
|
1321
|
-
${ft.dim("Note: Links are valid for 7 days.")}`)}else M&&
|
|
1321
|
+
${ft.dim("Note: Links are valid for 7 days.")}`)}else M&&Ft.warn("Simulator build completed. No artifacts uploaded.")}catch(S){r.stop("Could not fetch artifacts"),Ft.warn(ft.yellow(`Artifact listing failed: ${S.message}`))}}}catch(c){throw r.stop("iOS Build Failed"),c}};import{spinner as ni,log as T,isCancel as ii,confirm as Xc,select as or}from"@clack/prompts";import D from"chalk";import b from"fs";import E from"path";import{execFileSync as mt,execSync as te,spawn as es}from"child_process";import Re from"os";import Zc from"crypto";var ts=(e,t)=>t.filter(n=>b.existsSync(E.join(e,n))).reduce((n,i)=>n.update(b.readFileSync(E.join(e,i))),Zc.createHash("sha256")).digest("hex").slice(0,16),Qc=e=>ts(e,["package.json","yarn.lock","package-lock.json","bun.lockb"]),ed=e=>ts(e,["Podfile","Podfile.lock"]),td=e=>{let t=E.join(e,"fingerprint.json");try{return JSON.parse(b.readFileSync(t,"utf-8"))}catch{return{}}},Yo=(e,t)=>{b.mkdirSync(e,{recursive:!0}),b.writeFileSync(E.join(e,"fingerprint.json"),JSON.stringify(t,null,2))},nd=7200*1e3,id=(e,t)=>{b.mkdirSync(e,{recursive:!0});let n=E.join(e,"build.lock");if(b.existsSync(n))try{let i=JSON.parse(b.readFileSync(n,"utf-8")),r=Date.now()-(i.timestamp||0);if(r<nd)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}b.writeFileSync(n,JSON.stringify({buildId:t,pid:process.pid,timestamp:Date.now()}))},rd=(e,t)=>{let n=E.join(e,"build.lock");try{b.existsSync(n)&&JSON.parse(b.readFileSync(n,"utf-8")).buildId===t&&b.unlinkSync(n)}catch{}},qo=15e5,Xo=(e,t)=>{let n=e+t;return n.length>qo?n.slice(-qo):n},ns=e=>e.replace(/\u001b\[[0-9;]*m/g,""),is=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),od=e=>{let t=new Set,n=[];e.forEach((r,o)=>{is(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},sd=(e,t,n,i)=>{let r=ns(i).replace(/\r/g,`
|
|
1322
1322
|
`).split(`
|
|
1323
|
-
`).map(a=>a.trimEnd()).filter(Boolean),o=r.filter(
|
|
1323
|
+
`).map(a=>a.trimEnd()).filter(Boolean),o=r.filter(is),s=o.length>0?od(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?`
|
|
1324
1324
|
${l}:
|
|
1325
1325
|
${s.join(`
|
|
1326
|
-
`)}`:""].join("")},
|
|
1327
|
-
`)){if(/Ineligible destinations/i.test(c)&&(u=!0),u||!c.includes("platform:iOS Simulator")||c.includes("error:"))continue;let p=c.match(/\bid:([^,}]+)/)?.[1]?.trim(),f=c.match(/\bname:([^,}]+)/)?.[1]?.trim();p&&d.push({id:p,name:f,platform:"iOS Simulator"})}return o(d)},l=[t?"-workspace":"-project",t||n,"-scheme",i,"-configuration",r,"-sdk","iphonesimulator","-showdestinations"];try{let a=mt("xcodebuild",[...l,"-json"],{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}),d=JSON.parse(a),u=Array.isArray(d.destinations)?d.destinations:Array.isArray(d.availableDestinations)?d.availableDestinations:[],c=o(u);if(c)return c}catch{}try{let a=mt("xcodebuild",l,{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]});return s(a)}catch{}},gt=(e,t,n=process.cwd(),i={},r,o)=>new Promise((s,l)=>{let a="",d=
|
|
1326
|
+
`)}`:""].join("")},ad=e=>e==="xcodebuild"&&process.env.MACH_XCODE_FULL_LOGS!=="1",ld=e=>{let t=ns(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},Ge=e=>{try{b.existsSync(e)&&b.rmSync(e,{recursive:!0,force:!0})}catch{}},cd=(e,t)=>{try{if(!b.existsSync(e))return;for(let n of b.readdirSync(e))t(n)&&Ge(E.join(e,n))}catch{}},rr=e=>{T.info(D.dim("Clearing Metro/Hermes JS transform caches..."));let t=Re.tmpdir();cd(t,n=>n==="metro-cache"||n.startsWith("metro-")||n.startsWith("haste-map-")||n.startsWith("react-native-packager-cache-")),Ge(E.join(e,".expo")),Ge(E.join(e,"node_modules/.cache/metro")),Ge(E.join(Re.homedir(),".cache/metro")),Ge(E.join(Re.homedir(),".cache/react-native-packager")),Ge(E.join(Re.homedir(),"Library/Caches/metro")),Ge(E.join(Re.homedir(),"Library/Caches/react-native-packager"))},dd=e=>/Internal inconsistency error|never received target ended message/i.test(String(e?.message||e)),ud=e=>{T.warn(D.yellow("Xcode build system hit an internal inconsistency. Clearing simulator build state and retrying once...")),Ge(E.join(e,"Build")),Ge(E.join(e,"Index.noindex")),Ge(E.join(e,"ModuleCache.noindex")),Ge(E.join(e,"SourcePackages"))},pd=e=>{let t=String(e?.message||e);return/Permission denied/i.test(t)&&/Pods\/.*\.sh/i.test(t)},rs=e=>{let t=E.join(e,"Pods"),i=[E.join(t,"Target Support Files"),t].filter(l=>b.existsSync(l)),r=new Set,o=0,s=l=>{let a=l;try{a=b.realpathSync(l)}catch{}if(r.has(a))return;r.add(a);let d;try{d=b.readdirSync(l,{withFileTypes:!0})}catch{return}for(let u of d){let c=E.join(l,u.name);if(u.isDirectory()){s(c);continue}if(!(!u.isFile()||!u.name.endsWith(".sh")))try{let p=b.statSync(c),f=p.mode|493;f!==p.mode&&(b.chmodSync(c,f),o+=1)}catch{}}};for(let l of i)s(l);return o>0&&T.info(D.dim(`Repaired executable permissions on ${o} CocoaPods script${o===1?"":"s"}.`)),o},fd=(e,t,n,i,r)=>{let o=a=>{let d=a.filter(c=>c?.id&&String(c?.platform||"").includes("iOS Simulator")&&!c?.error),u=d.find(c=>/iphone/i.test(c.name||""))||d[0];return u?.id?`id=${u.id}`:void 0},s=a=>{let d=[],u=!1;for(let c of a.split(`
|
|
1327
|
+
`)){if(/Ineligible destinations/i.test(c)&&(u=!0),u||!c.includes("platform:iOS Simulator")||c.includes("error:"))continue;let p=c.match(/\bid:([^,}]+)/)?.[1]?.trim(),f=c.match(/\bname:([^,}]+)/)?.[1]?.trim();p&&d.push({id:p,name:f,platform:"iOS Simulator"})}return o(d)},l=[t?"-workspace":"-project",t||n,"-scheme",i,"-configuration",r,"-sdk","iphonesimulator","-showdestinations"];try{let a=mt("xcodebuild",[...l,"-json"],{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}),d=JSON.parse(a),u=Array.isArray(d.destinations)?d.destinations:Array.isArray(d.availableDestinations)?d.availableDestinations:[],c=o(u);if(c)return c}catch{}try{let a=mt("xcodebuild",l,{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]});return s(a)}catch{}},gt=(e,t,n=process.cwd(),i={},r,o)=>new Promise((s,l)=>{let a="",d=ad(e),u=Date.now(),c=["/opt/homebrew/bin","/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin",E.join(Re.homedir(),".npm-global/bin")],f=[...(process.env.PATH||"").split(":"),...c].filter((I,N,w)=>I&&w.indexOf(I)===N).join(":");process.env[`${m.envPrefix}DEBUG`]&&console.log(D.magenta(`[${m.nameUpper}_DEBUG] Execution PATH: ${f}`));let g={...process.env,...i,PATH:f,LANG:"en_US.UTF-8",LC_ALL:"en_US.UTF-8"};r&&process.env[`${m.envPrefix}DEBUG`]&&(r(D.magenta(`[ENVIRONMENT] node: ${process.execPath}
|
|
1328
1328
|
`)),r(D.magenta(`[ENVIRONMENT] PATH: ${f}
|
|
1329
1329
|
`)),r(D.magenta(`[ENVIRONMENT] command: ${e} ${t.join(" ")}
|
|
1330
|
-
`)));let y=e;if(["node","npm","npx","pod"].includes(e)){let I=E.dirname(process.execPath),
|
|
1331
|
-
`)))}let h=
|
|
1330
|
+
`)));let y=e;if(["node","npm","npx","pod"].includes(e)){let I=E.dirname(process.execPath),N=E.join(I,e);b.existsSync(N)&&(y=N,r&&r(D.dim(`[EXEC] Using absolute path: ${y}
|
|
1331
|
+
`)))}let h=es(y,t,{stdio:"pipe",cwd:n,shell:!0,env:g,detached:process.platform!=="win32"});if(o){if(o.aborted){if(h.pid)try{process.kill(-h.pid,"SIGTERM")}catch{h.kill()}return l(new Error("Command aborted"))}o.addEventListener("abort",()=>{if(h.pid)try{process.kill(-h.pid,"SIGTERM")}catch{h.kill()}l(new Error("Command aborted"))})}let v=(I,N)=>{if(!d){N.write(I);return}let w=I.replace(/\r/g,`
|
|
1332
1332
|
`).split(`
|
|
1333
|
-
`).filter(
|
|
1333
|
+
`).filter(ld);if(w.length>0){N.write(`${w.join(`
|
|
1334
1334
|
`)}
|
|
1335
|
-
`),u=Date.now();return}let U=Date.now();U-u>3e4&&(
|
|
1336
|
-
`),u=U)};h.stdout.on("data",I=>{let
|
|
1337
|
-
`).find(r=>/^Payload\/[^/]+\.app\/Info\.plist$/.test(r.trim()));if(!n)throw new Error(`Could not validate iOS build number: ${E.basename(e)} has no Payload/*.app/Info.plist.`);let i=b.mkdtempSync(E.join(Re.tmpdir(),`${m.nameLower}-ipa-plist-`));try{let r=E.join(i,"Info.plist"),o=mt("unzip",["-p",e,n.trim()]);return b.writeFileSync(r,o),
|
|
1335
|
+
`),u=Date.now();return}let U=Date.now();U-u>3e4&&(N.write(`[xcodebuild] still running; detailed output is streamed to Mach logs.
|
|
1336
|
+
`),u=U)};h.stdout.on("data",I=>{let N=I.toString();a=Xo(a,N),v(N,process.stdout),r&&r(N)}),h.stderr.on("data",I=>{let N=I.toString();a=Xo(a,N),v(N,process.stderr),r&&r(N)}),h.on("close",I=>{I===0?s(I):l(new Error(sd(e,t,I,a)))}),h.on("error",I=>l(I))}),ti=async(e,t,n,i,r)=>{try{await gt("xcodebuild",e,t,n,i,r)}catch(o){if(!pd(o))throw o;T.warn(D.yellow("CocoaPods script permission denied. Repairing Pods script permissions and retrying xcodebuild once...")),rs(t),await gt("xcodebuild",e,t,n,i,r)}},md=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(" ")},Bt=(e,t)=>{let n=[];try{if(!b.existsSync(e))return n;let i=b.readdirSync(e);for(let r of i){let o=E.join(e,r);try{let s=b.statSync(o);if(t.some(a=>r.endsWith(a))){n.push(E.resolve(o));continue}s.isDirectory()&&(n=n.concat(Bt(o,t)))}catch{}}}catch{}return n},gd=/^\d+(?:\.\d+){0,2}$/,os=e=>{let t=String(e||"").trim();return!t||t==="undefined"||t==="null"?null:gd.test(t)?t:null},ss=(e,t)=>{let n=os(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},sr=(e,t)=>mt("/usr/libexec/PlistBuddy",["-c",`Print :${t}`,e],{encoding:"utf-8"}).trim(),Zt=(e,t)=>{try{return sr(e,t)}catch{return""}},Zo=e=>String(e||"").replace(/\.app$/i,"").replace(/[^a-z0-9]/gi,"").toLowerCase(),hd=e=>{try{return b.statSync(e).isDirectory()}catch{return!1}},yd=(e,t,n)=>{if(!b.existsSync(e))throw new Error(`iOS simulator build output directory was not found: ${e}`);let i=b.readdirSync(e).filter(d=>d.endsWith(".app")).map(d=>E.join(e,d)).filter(hd);if(i.length===0){let u=Bt(e,[".app"]).map(c=>E.relative(e,c)).join(", ");throw new Error(`No top-level iOS simulator .app product was found in ${e}.`+(u?` Nested .app bundles found but ignored: ${u}`:""))}let r=new Set([t,n.iosScheme,n.scheme,n.appName].filter(Boolean).map(d=>Zo(String(d))).filter(Boolean)),o=i.map(d=>{let u=E.join(d,"Info.plist"),c=b.existsSync(u)?Zt(u,"CFBundleName"):"",p=b.existsSync(u)?Zt(u,"CFBundleDisplayName"):"",f=b.existsSync(u)?Zt(u,"CFBundleExecutable"):"",g=b.existsSync(u)?Zt(u,"CFBundleIdentifier"):"",y=f?E.join(d,f):"";return{appPath:d,bundleIdentifier:g,executable:f,isValid:b.existsSync(u)&&!!f&&b.existsSync(y),names:[E.basename(d,".app"),c,p,f].map(Zo).filter(Boolean)}}),s=o.filter(d=>d.isValid);if(s.length===0)throw new Error(`No valid iOS simulator .app product was found in ${e}. Candidates: `+o.map(d=>E.basename(d.appPath)).join(", "));let a=s.find(d=>d.names.some(u=>r.has(u)))||(s.length===1?s[0]:null);if(!a)throw new Error(`Multiple iOS simulator .app products were found in ${e}: `+s.map(d=>{let u=d.bundleIdentifier?` (${d.bundleIdentifier})`:"";return`${E.basename(d.appPath)}${u}`}).join(", ")+`. Set ios.scheme in ${m.configFileName} so ${m.name} can select the app target safely.`);return a.appPath},Qo=e=>{let t=E.join(e,"Info.plist");if(!b.existsSync(t))throw new Error(`Could not validate iOS build number: ${t} not found.`);return ss(sr(t,"CFBundleVersion"),t)},as=e=>{let t=E.join(e,"Info.plist");if(!b.existsSync(t))throw new Error(`Could not validate iOS app executable: ${t} not found.`);let n=Zt(t,"CFBundleExecutable");if(!n)throw new Error(`Could not validate iOS app executable: CFBundleExecutable missing in ${t}.`);let i=E.join(e,n);if(!b.existsSync(i))throw new Error(`Could not validate iOS app executable: ${i} not found.`);return i},Sd=()=>process.arch==="arm64"?"arm64":"x86_64",ls=e=>{let t=as(e),n="";try{n=mt("lipo",["-info",t],{encoding:"utf-8"}).trim()}catch(r){throw new Error(`Could not inspect iOS simulator executable architecture for ${E.basename(e)}: ${r.message}`)}let i=Sd();if(!new RegExp(`\\b${i}\\b`).test(n))throw new Error(`iOS simulator app ${E.basename(e)} cannot be installed on this runner because its executable does not include the required ${i} simulator architecture. lipo output: ${n}. Check the React Native iOS project ARCHS/EXCLUDED_ARCHS settings for iphonesimulator builds.`);return n},bd=e=>{try{return mt("xcrun",["vtool","-show-build",e],{encoding:"utf-8"}).trim()}catch(t){throw new Error(`Could not inspect iOS executable build platform for ${E.basename(e)}: ${t.message}`)}},cs=e=>{let t=as(e),n=bd(t);if(!/\bplatform\s+IOSSIMULATOR\b/i.test(n))throw new Error(`iOS simulator app ${E.basename(e)} was built for the wrong Apple platform. A simulator artifact must contain PLATFORM IOSSIMULATOR, not an iPhone device binary. vtool output: ${n}`);return n},Ad=e=>{let n=mt("unzip",["-Z1",e],{encoding:"utf-8"}).split(`
|
|
1337
|
+
`).find(r=>/^Payload\/[^/]+\.app\/Info\.plist$/.test(r.trim()));if(!n)throw new Error(`Could not validate iOS build number: ${E.basename(e)} has no Payload/*.app/Info.plist.`);let i=b.mkdtempSync(E.join(Re.tmpdir(),`${m.nameLower}-ipa-plist-`));try{let r=E.join(i,"Info.plist"),o=mt("unzip",["-p",e,n.trim()]);return b.writeFileSync(r,o),ss(sr(r,"CFBundleVersion"),`${E.basename(e)}:${n.trim()}`)}finally{b.rmSync(i,{recursive:!0,force:!0})}},Ed=e=>`'${e.replace(/'/g,"'\\''")}'`,Id=()=>process.execPath&&b.existsSync(process.execPath)?process.execPath:mt("which",["node"],{encoding:"utf-8"}).trim(),ds=(e,t,n)=>{if(!b.existsSync(e))return;let i=Id();t.NODE_BINARY=i;let r=E.join(e,".xcode.env.local");b.writeFileSync(r,`export NODE_BINARY=${Ed(i)}
|
|
1338
1338
|
`);let o=`[NODE] Xcode NODE_BINARY: ${i}
|
|
1339
|
-
`;n&&n(D.dim(o)),
|
|
1340
|
-
\u{1F6D1} Build cancelled from dashboard. Terminating...`)),p.abort(),g&&clearInterval(g))}catch{}},5e3));let y=E.join(process.cwd(),".mach-cache"),h="setup",
|
|
1341
|
-
`)},J=async(A,
|
|
1342
|
-
`)),await V("lock"),d.applyLocalProcessEnv(e);try{await V("clone"),
|
|
1343
|
-
`)}if(await V("read_package"),e.nodeVersion){let ee=process.env.NVM_DIR||E.join(Re.homedir(),".nvm"),X=E.join(ee,"versions","node"),fe;if(b.existsSync(X)){let W=b.readdirSync(X).sort().reverse(),
|
|
1344
|
-
`),
|
|
1345
|
-
`),
|
|
1346
|
-
`),b.rmSync(E.join(process.cwd(),"node_modules"),{recursive:!0,force:!0}),P=!1);let M="npm",B=["install","--prefer-offline"];S?(M="yarn",B=["install","--prefer-offline"]):R&&(M="bun",B=["install"]),P?o.stop("Cached node_modules found. Syncing dependencies..."):o.stop("No cached dependencies. Running fresh install..."),e.preBuild&&(
|
|
1347
|
-
\u2713 Local build completed successfully in ${
|
|
1348
|
-
\u{1F4E6} Generated Artifacts:`)),$.forEach(ee=>{let X=E.resolve(ee);
|
|
1349
|
-
\u274C Build aborted.`)),await c("failed",{error:"Aborted by user",endTime:Date.now()}),A):(
|
|
1350
|
-
\u2717 Local build failed: ${A.message}`)),await c("failed",{error:A.message,endTime:Date.now()}),A)}},
|
|
1351
|
-
`).find(
|
|
1352
|
-
`)[0]||"unknown"}`))}if(!
|
|
1353
|
-
`).map(Ce=>Ce.trim().replace(/^"|"$/g,"")).filter(Ce=>Ce.length>0),
|
|
1339
|
+
`;n&&n(D.dim(o)),T.info(D.dim(o.trim()))},ar=async(e,t,n={},i,r={})=>{let o=ni(),s=Date.now(),l=e.platform,a=e.buildProfile||"production",d=pt(e.framework),u=()=>Ut(n,a,e),c=async(A,_={})=>{if(i)for(let L=1;L<=3;L++)try{await k.patch(`/builds/${i}/${t}`,{status:A,..._});return}catch(P){let S=P?.response?.data?.message||P?.message||String(P);console.error(`[reportStatus] attempt ${L}/3 failed (status=${A}): ${S}`),L<3&&await new Promise(R=>setTimeout(R,2e3))}},p=new AbortController,{signal:f}=p,g=null;i&&(g=setInterval(async()=>{try{(await k.get(`/builds/${i}/${t}`)).data.status==="cancelled"&&(T.warn(D.yellow(`
|
|
1340
|
+
\u{1F6D1} Build cancelled from dashboard. Terminating...`)),p.abort(),g&&clearInterval(g))}catch{}},5e3));let y=E.join(process.cwd(),".mach-cache"),h="setup",v="",I=null,N=async()=>{if(!v||!i)return;let A=v;v="";try{let _=A;Object.values(n).forEach(L=>{if(L&&L.length>5){let P=L.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");_=_.replace(new RegExp(P,"g"),"[SECRET]")}}),await k.post(`/builds/${i}/${t}/logs`,{log:_,step:h})}catch{}},w=async()=>{I&&(clearTimeout(I),I=null),await N(),rd(y,t),g&&(clearInterval(g),g=null);try{let A=E.join(Re.tmpdir(),`${m.buildPrefix}-${t}.keychain-db`);b.existsSync(A)&&(te(`security delete-keychain "${A}"`,{stdio:"ignore"}),T.info(D.dim("\u{1F511} Build keychain deleted.")))}catch{}try{let A=E.join(Re.homedir(),"Library/MobileDevice/Provisioning Profiles");if(b.existsSync(A)){let _=b.readdirSync(A).filter(L=>L.includes(t)||L.startsWith(`${m.nameLower}-temp-${t}`));for(let L of _)b.unlinkSync(E.join(A,L))}}catch{}},U=async A=>{i&&(v+=A,v.length>=8192?(I&&(clearTimeout(I),I=null),await N()):I||(I=setTimeout(()=>{I=null,N()},2e3)))},V=async A=>{h=A,await U(`[STEP_START:${A}] ${Math.floor(Date.now()/1e3)}
|
|
1341
|
+
`)},J=async(A,_,L,P)=>await gt(A,_,L,P,S=>{U(S)},f);T.info(D.blue(`\u{1F680} Starting local build for ${l} (${a})...`));try{id(y,t)}catch(A){throw await c("failed",{error:A.message,endTime:Date.now()}),A}await c("building"),await V("setup"),l==="ios"&&!e.simulator&&n.MACH_IOS_BUILD_NUMBER_LOCKED==="1"&&n.BUILD_NUMBER&&(T.info(D.dim(`Auto build number: ${n.BUILD_NUMBER}`)),await U(`[BUILD_NUMBER] ${n.BUILD_NUMBER}
|
|
1342
|
+
`)),await V("lock"),d.applyLocalProcessEnv(e);try{await V("clone"),T.info(D.dim("Preparing source...")),await V("read_config");let A=E.join(process.cwd(),m.configFileName);if(b.existsSync(A)){let X=JSON.parse(b.readFileSync(A,"utf-8"))?.build?.[a]||{};await U(`[CONFIG] Profile: ${a}, distribution: ${X.distribution||"not set"}, simulator: ${X.simulator||!1}
|
|
1343
|
+
`)}if(await V("read_package"),e.nodeVersion){let ee=process.env.NVM_DIR||E.join(Re.homedir(),".nvm"),X=E.join(ee,"versions","node"),fe;if(b.existsSync(X)){let W=b.readdirSync(X).sort().reverse(),ae=e.nodeVersion.startsWith("v")?e.nodeVersion:`v${e.nodeVersion}`,be=W.find(me=>me===ae||me.startsWith(ae+".")||me.startsWith(`v${e.nodeVersion}.`));be&&(fe=E.join(X,be,"bin"))}if(fe&&b.existsSync(fe)){let W=process.env.PATH||"";process.env.PATH=`${fe}:${W}`,await U(`[NODE] Switched to Node ${e.nodeVersion} \u2014 using ${fe}
|
|
1344
|
+
`),T.info(D.green(`\u2713 Node switched to ${e.nodeVersion} (${fe})`))}else await U(`[NODE] Warning: Node ${e.nodeVersion} not found in nvm. Run: nvm install ${e.nodeVersion} on the build machine.
|
|
1345
|
+
`),T.warn(D.yellow(`Node ${e.nodeVersion} not found in nvm \u2014 using system default`))}await V("deps"),o.start("Checking dependencies...");let _=td(y),L=Qc(process.cwd()),P=b.existsSync("node_modules"),S=b.existsSync("yarn.lock"),R=b.existsSync("bun.lockb");P&&_.node&&_.node!==L&&(o.stop("Dependency fingerprint changed \u2014 clearing node_modules for clean install..."),await U(`[CACHE] package.json/lockfile changed \u2014 wiping node_modules
|
|
1346
|
+
`),b.rmSync(E.join(process.cwd(),"node_modules"),{recursive:!0,force:!0}),P=!1);let M="npm",B=["install","--prefer-offline"];S?(M="yarn",B=["install","--prefer-offline"]):R&&(M="bun",B=["install"]),P?o.stop("Cached node_modules found. Syncing dependencies..."):o.stop("No cached dependencies. Running fresh install..."),e.preBuild&&(T.info(D.blue("Running pre-install hook...")),T.info(D.dim(`> ${e.preBuild}`)),await V("prebuild"),await J("bash",[e.preBuild],process.cwd(),u())),T.info(D.dim(`Running ${M} ${B.join(" ")}...`)),await J(M,B,process.cwd(),u()),_.node=L,Yo(y,_);let K=await d.prepareLocalProject({platform:l,options:e,cacheMeta:_,cacheMetaDir:y,currentBuildEnv:u,reportStep:V,reportLog:U,loggedRun:J,configureXcodeNodeBinary:ds,podsFingerprint:ed,writeCacheMeta:Yo}),z=K.bundleId||e.iosBundleIdentifier||"",Q=K.appName||e.name||"",$=[];if(l==="android")await V("build"),$=await wd(e,a,n,ee=>U(ee),f);else if(l==="ios"){await V("signing"),T.info(D.dim("Preparing credentials..."));let ee=r?.distributionType;$=await vd(e,t,a,n,i,X=>U(X),f,ee,X=>V(X))}e.postBuild&&(T.info(D.blue("Running post-build hook...")),T.info(D.dim(`> ${e.postBuild}`)),await J(e.postBuild,[],process.cwd(),u()));let ie=md(Date.now()-s);if(T.success(D.green(`
|
|
1347
|
+
\u2713 Local build completed successfully in ${ie}`)),await c("building",{...z&&{bundleId:z},...Q&&{appName:Q}}),$.length>0&&(T.info(D.cyan(`
|
|
1348
|
+
\u{1F4E6} Generated Artifacts:`)),$.forEach(ee=>{let X=E.resolve(ee);T.info(D.dim(` - ${ee}`)),T.info(D.gray(` Path: ${X}`))}),e.interactive)){let ee=await Xc({message:"Install on connected device?"});if(!ii(ee)&&ee){if(l==="android"){let X=$.find(fe=>fe.endsWith(".apk"))||$[0];await _d(X,fe=>U(fe))}else if(l==="ios"){let X=$.find(W=>W.endsWith(".ipa"))||$.find(W=>W.endsWith(".app"))||$[0],fe=ht("ios");e.simulator?await Rd(X,fe||"",W=>U(W)):await Pd(X,fe||"",W=>U(W))}}}await V("upload");let ge=[];for(let ee of $)try{let X=E.join(Re.tmpdir(),`${t}-${E.basename(ee)}`);b.copyFileSync(ee,X),ge.push(X),T.info(D.dim(` \u{1F4CB} Preserved artifact: ${E.basename(ee)}`))}catch{T.warn(D.yellow(` Failed to preserve artifact: ${E.basename(ee)}`))}$=ge,T.info(D.dim("\u{1F9F9} Cleaning workspace (preserving dependency cache)..."));try{let ee=process.cwd(),X=new Set(["node_modules"]),fe=b.readdirSync(ee),W=0;for(let ae of fe)if(!X.has(ae)){if(ae==="ios"){let be=E.join(ee,"ios"),me=b.readdirSync(be);for(let Oe of me)if(Oe!=="Pods")try{b.rmSync(E.join(be,Oe),{recursive:!0,force:!0}),W++}catch{}continue}try{b.rmSync(E.join(ee,ae),{recursive:!0,force:!0}),W++}catch{}}T.info(D.dim(` Cleaned ${W} items. Cached: node_modules${b.existsSync(E.join(ee,"ios","Pods"))?", ios/Pods":""}`)),T.info(D.green("\u{1F512} Security: No source code retained on build server. Only public dependencies cached."))}catch{T.warn(D.yellow("Post-build cleanup encountered errors (non-fatal)."))}try{let X=E.join(Re.homedir(),m.workspacesDir),fe=te(`df -k "${X}" | tail -1 | awk '{print $4}'`,{encoding:"utf8"}).trim(),W=parseInt(fe,10)*1024;if(W<53687091200&&b.existsSync(X)){T.info(D.dim(` \u26A0\uFE0F Low disk space (${(W/1024/1024/1024).toFixed(0)} GB free). Running cache eviction...`));let ae=E.basename(process.cwd()),be=b.readdirSync(X).filter(me=>me!==ae).map(me=>{let Oe=E.join(X,me);try{let zt=b.statSync(Oe);return zt.isDirectory()?{name:me,dir:Oe,mtime:zt.mtimeMs}:null}catch{return null}}).filter(Boolean);be.sort((me,Oe)=>me.mtime-Oe.mtime);for(let me of be){if(W>=53687091200)break;try{b.rmSync(me.dir,{recursive:!0,force:!0}),T.info(D.dim(` \u{1F5D1}\uFE0F Evicted stale workspace: ${me.name}`));let Oe=te(`df -k "${X}" | tail -1 | awk '{print $4}'`,{encoding:"utf8"}).trim();if(parseInt(Oe,10)*1024>=53687091200)break}catch{}}}}catch{}return await w(),$}catch(A){throw await w(),A.message==="Command aborted"?(T.warn(D.yellow(`
|
|
1349
|
+
\u274C Build aborted.`)),await c("failed",{error:"Aborted by user",endTime:Date.now()}),A):(T.error(D.red(`
|
|
1350
|
+
\u2717 Local build failed: ${A.message}`)),await c("failed",{error:A.message,endTime:Date.now()}),A)}},wd=async(e,t,n={},i,r)=>{let o=b.existsSync("android/gradlew")?"android/gradlew":b.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;T.info(D.blue(`Running Android build: ${l}...`));let a=o.includes("android/")?"android":".",d=(o.includes("android/"),"./gradlew"),u=[l],c=pt(e.framework),p={...n,...c.localAndroidEnv(e,t),MACH_APP_NAME:e.appName||e.name||"App"};if(n.ANDROID_VERSION_CODE){let g=E.join(a,"app/build.gradle");if(b.existsSync(g)){let y=n.ANDROID_VERSION_CODE,h=b.readFileSync(g,"utf-8");h=h.replace(/versionCode\s+\d+/,`versionCode ${y}`),b.writeFileSync(g,h),T.info(D.green(`\u2713 Applied Android versionCode ${y}`))}u.push(`-Pandroid.injected.version.code=${n.ANDROID_VERSION_CODE}`)}for(let g of["app/build","build",".cxx"]){let y=E.join(a,g);b.existsSync(y)&&b.rmSync(y,{recursive:!0,force:!0})}rr(process.cwd()),await gt(d,u,a,p,i,r);let f=E.join(a,"app/build/outputs");return Bt(f,[".apk",".aab"])},vd=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=E.resolve(process.cwd(),b.existsSync("ios")?"ios":".");rs(d);let u=b.readdirSync(d),c=u.find(_=>_.endsWith(".xcworkspace")),p=u.find(_=>_.endsWith(".xcodeproj")),f=Ut(i,n,e);ds(d,f,o);let g=os(f.BUILD_NUMBER||f.CURRENT_PROJECT_VERSION);if((f.BUILD_NUMBER||f.CURRENT_PROJECT_VERSION)&&!g)throw new Error(`Invalid iOS BUILD_NUMBER/CURRENT_PROJECT_VERSION: "${f.BUILD_NUMBER||f.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 y=g?[`BUILD_NUMBER=${g}`,`CURRENT_PROJECT_VERSION=${g}`]:[];if(g&&(f.BUILD_NUMBER=g,f.CURRENT_PROJECT_VERSION=g,T.info(D.dim(`Using iOS build number: ${g}`))),!c&&!p)throw new Error("Could not find Xcode workspace or project in ios/ directory.");try{let _=te("xcode-select -p").toString().trim();T.info(D.dim(`Using Xcode at: ${_}`))}catch{T.warn(D.dim("Could not detect Xcode path."))}T.info(D.blue("Running iOS build via xcodebuild..."));let h=c?c.replace(".xcworkspace",""):p?.replace(".xcodeproj",""),v=e.iosScheme||h||e.scheme,I=e.developmentClient?"Debug":e.iosConfiguration||"Release",N=(r||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),w=E.join(Re.homedir(),`Library/Developer/Xcode/DerivedData/${m.nameLower}`,N);b.mkdirSync(w,{recursive:!0});let U=Xt(f),V=E.join(w,".mach-env-hash"),J=E.join(w,"Build"),A=b.existsSync(V)?b.readFileSync(V,"utf-8").trim():"";if(b.existsSync(J)){let _=A&&A!==U?"Build environment changed \u2014 clearing iOS DerivedData build products.":A?"Clearing iOS DerivedData build products to force a fresh JS bundle.":"DerivedData has no environment stamp \u2014 clearing iOS build products.";T.info(D.dim(_)),b.rmSync(J,{recursive:!0,force:!0})}if(b.writeFileSync(V,U),rr(process.cwd()),e.simulator){let _=fd(d,c,p,v,I),L=_||"generic/platform=iOS Simulator",P=["-destination",L];T.info(D.dim(_?`Building for simulator (Scheme: ${v}, Config: ${I}, Destination: ${L})...`:`Building for simulator (Scheme: ${v}, Config: ${I}, Destination: ${L})...`));let S=[c?"-workspace":"-project",c||p,"-scheme",v,"-configuration",I,"-sdk","iphonesimulator",...P,"-derivedDataPath",w,...y,"COMPILER_INDEX_STORE_ENABLE=NO","CODE_SIGNING_ALLOWED=NO","CODE_SIGNING_REQUIRED=NO","ONLY_ACTIVE_ARCH=NO","EXCLUDED_ARCHS=","SUPPORTED_PLATFORMS=iphonesimulator"];try{await ti(S,d,f,o,s)}catch(ge){if(!dd(ge))throw ge;ud(w),rr(process.cwd()),await ti(S,d,f,o,s)}let R=E.join(w,"Build/Products",`${I}-iphonesimulator`),M=yd(R,v,e),B=E.basename(M,".app"),K=Zt(E.join(M,"Info.plist"),"CFBundleIdentifier")||"unknown bundle",z=Qo(M),Q=ls(M),$=cs(M),ie=E.join(R,`${B}_simulator.zip`);return T.info(D.dim(`Selected simulator app: ${E.relative(R,M)} (${K}, build ${z})`)),T.info(D.dim(`Simulator executable architecture: ${Q}`)),T.info(D.dim(`Simulator executable platform: ${$.split(`
|
|
1351
|
+
`).find(ge=>/\bplatform\b/i.test(ge))?.trim()||"IOSSIMULATOR"}`)),T.info(D.dim(`Creating simulator artifact: ${ie}...`)),Ge(ie),mt("zip",["-r",ie,E.basename(M)],{cwd:E.dirname(M),stdio:"pipe"}),[ie]}else{T.info(D.dim(`Archiving (Scheme: ${v}, Config: ${I})...`));let _=E.join(d,"build.xcarchive"),L=E.join(d,"export");b.rmSync(_,{recursive:!0,force:!0}),b.rmSync(L,{recursive:!0,force:!0});let P=i.IOS_DIST_P12,S=i.IOS_PROVISIONING_PROFILE,R=i.IOS_P12_PASSWORD||"",M=[],B,K,z={isAppStore:!1,isDevelopment:!1};if(P&&S){T.info(D.blue("\u{1F510} CI/CD Signing: Importing certificates..."));try{let W=`${m.buildPrefix}-${t}.keychain-db`,ae=E.join(Re.tmpdir(),W),be=m.keychainPassword;te(`security create-keychain -p "${be}" "${ae}" 2>/dev/null || true`),te(`security set-keychain-settings -t 3600 -l "${ae}"`),te(`security unlock-keychain -p "${be}" "${ae}"`);let me=E.join(Re.tmpdir(),`cert-${t}.p12`),Oe=Buffer.from(P,"base64");b.writeFileSync(me,Oe),T.info(D.dim(`P12 data size: ${Oe.length} bytes, first bytes: ${Oe.slice(0,4).toString("hex")}`)),(Oe.length<100||Oe[0]!==48)&&(T.warn(D.yellow("\u26A0\uFE0F P12 data looks corrupted or was not decrypted correctly.")),T.warn(D.yellow(" This usually means MACH_ENCRYPTION_KEY on the Remote API differs from when credentials were uploaded.")));let zt=[R,"",m.keychainPassword],vo=!1;for(let Ce of zt)try{te(`security import "${me}" -k "${ae}" -P "${Ce}" -A -T /usr/bin/codesign -T /usr/bin/security`,{stdio:"pipe"}),vo=!0,T.info(D.dim(`\u2713 P12 imported successfully with password: ${Ce?"[set]":"[empty]"}`));break}catch(Ye){T.info(D.dim(` P12 import attempt with password ${Ce?`"${Ce.substring(0,3)}..."`:"[empty]"} failed: ${Ye.message?.split(`
|
|
1352
|
+
`)[0]||"unknown"}`))}if(!vo)throw new Error("Failed to import P12.");b.unlinkSync(me),te(`security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "${be}" "${ae}"`);let Ic=te("security list-keychains -d user",{encoding:"utf-8"}).split(`
|
|
1353
|
+
`).map(Ce=>Ce.trim().replace(/^"|"$/g,"")).filter(Ce=>Ce.length>0),wc=[ae,...Ic].map(Ce=>`"${Ce}"`).join(" ");te(`security list-keychains -d user -s ${wc}`),te(`security default-keychain -s "${ae}"`);let Yi=E.join(Re.homedir(),"Library/MobileDevice/Provisioning Profiles");b.mkdirSync(Yi,{recursive:!0});let $o=Buffer.from(S,"base64"),qi=E.join(Yi,`${m.nameLower}-temp-${t}.mobileprovision`);b.writeFileSync(qi,$o);let Xi=$o.toString("utf-8"),_o=/<key>get-task-allow<\/key>\s*<true\/>/.test(Xi);z={isAppStore:!Xi.includes("<key>ProvisionedDevices</key>")&&!_o,isDevelopment:_o};try{let Ye=te(`security cms -D -i "${qi}"`,{encoding:"utf-8"}).match(/<key>UUID<\/key>\s*<string>([^<]+)<\/string>/);K=Ye?Ye[1]:void 0}catch{let Ye=Xi.match(/<key>UUID<\/key>\s*<string>([^<]+)<\/string>/);K=Ye?Ye[1]:void 0}K||(T.warn("Could not extract UUID from provisioning profile. Using fallback."),K=`${m.nameLower}-${t}`);let Zi=E.join(Yi,`${K}.mobileprovision`);b.existsSync(Zi)&&b.unlinkSync(Zi),b.renameSync(qi,Zi);try{let Ce=te(`security find-identity -v -p codesigning "${ae}"`,{encoding:"utf-8"}),Ye=Array.from(Ce.matchAll(/"((?:Apple|iPhone) (?:Distribution|Developer|Development)[^"]*)"/g),gn=>gn[1]),Ro=z.isDevelopment?Ye.find(gn=>/\b(Development|Developer)\b/.test(gn)):Ye.find(gn=>/\bDistribution\b/.test(gn)),Po=Ye[0];(Ro||Po)&&(B=Ro||Po,T.info(D.blue(`Identity auto-detected from keychain: "${B}"`)))}catch{}B||(B=z.isDevelopment?"Apple Development":"Apple Distribution",T.info(D.blue(`Identity fallback (profile heuristic): "${B}"`))),T.info(D.dim(`Profile type: ${z.isDevelopment?"Development":z.isAppStore?"App Store":"Ad-Hoc"}`)),T.info(D.dim(`Identity Detection: get-task-allow=${z.isDevelopment}, Selected Identity="${B}"`)),M.push("CODE_SIGN_STYLE=Manual"),M.push(`CODE_SIGN_IDENTITY="${B}"`),M.push(`PROVISIONING_PROFILE_SPECIFIER=${K}`),e.iosTeamId&&M.push(`DEVELOPMENT_TEAM=${e.iosTeamId}`)}catch(W){throw T.error(`Signing setup failed: ${W.message}`),W}}else M.push("-allowProvisioningUpdates"),e.iosTeamId&&M.push(`DEVELOPMENT_TEAM=${e.iosTeamId}`);a&&await a("archive"),T.info(D.blue(`Archive detected Identity: "${B}"`)),T.info(D.blue(`Archive detected UUID: "${K}"`)),await ti(["archive",c?"-workspace":"-project",c||p,"-scheme",v,"-configuration",I,"-archivePath",_,"-derivedDataPath",w,...y,...M],d,f,o,s);let Q=Bt(E.join(_,"Products","Applications"),[".app"]);for(let W of Q){let ae=Qo(W);T.info(D.dim(`Validated iOS CFBundleVersion ${ae} in ${E.basename(W)}`))}let $;K?(z.isAppStore?$="app-store":z.isDevelopment?$="development":$="ad-hoc",T.info(D.blue(`Export method from profile: "${$}"`))):($=e.distribution==="store"?"app-store":e.distribution==="internal"?"ad-hoc":"development",T.warn(D.yellow(`No profile UUID detected. Export method from distribution flag: "${$}"`)));let ie=e.iosExportMethod||$,ge=e.iosBundleIdentifier||ht("ios"),ee=E.join(d,"ExportOptions.plist"),X=`<?xml version="1.0" encoding="UTF-8"?>
|
|
1354
1354
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
1355
1355
|
<plist version="1.0">
|
|
1356
1356
|
<dict>
|
|
1357
1357
|
<key>method</key>
|
|
1358
|
-
<string>${
|
|
1358
|
+
<string>${ie}</string>
|
|
1359
1359
|
<key>destination</key>
|
|
1360
1360
|
<string>export</string>
|
|
1361
1361
|
<key>signingStyle</key>
|
|
@@ -1363,71 +1363,71 @@ ${s.join(`
|
|
|
1363
1363
|
<key>thinning</key>
|
|
1364
1364
|
<string><none></string>
|
|
1365
1365
|
${e.iosTeamId?`<key>teamID</key><string>${e.iosTeamId}</string>`:""}
|
|
1366
|
-
${
|
|
1366
|
+
${ge&&K?`
|
|
1367
1367
|
<key>provisioningProfiles</key>
|
|
1368
1368
|
<dict>
|
|
1369
|
-
<key>${
|
|
1369
|
+
<key>${ge}</key>
|
|
1370
1370
|
<string>${K}</string>
|
|
1371
1371
|
</dict>`:""}
|
|
1372
1372
|
</dict>
|
|
1373
|
-
</plist>`;if(b.writeFileSync(ee,X),process.env[`${m.envPrefix}DEBUG`]&&
|
|
1374
|
-
${X}`)),a&&await a("export"),
|
|
1373
|
+
</plist>`;if(b.writeFileSync(ee,X),process.env[`${m.envPrefix}DEBUG`]&&T.info(D.magenta(`[${m.nameUpper}_DEBUG] ExportOptions.plist:
|
|
1374
|
+
${X}`)),a&&await a("export"),T.info(D.blue(`Exporting with Bundle ID: "${ge}"`)),T.info(D.blue(`Exporting with Method: "${ie}"`)),o){o(D.magenta(`
|
|
1375
1375
|
[DIAGNOSTIC] Checking available signing identities...
|
|
1376
|
-
`));try{let W=
|
|
1376
|
+
`));try{let W=te("security find-identity -v -p codesigning",{encoding:"utf-8"});o(D.magenta(`${W}
|
|
1377
1377
|
`))}catch(W){o(D.red(`[DIAGNOSTIC] Failed to list identities: ${W.message}
|
|
1378
|
-
`))}}await
|
|
1379
|
-
`),o&&o(`[IPA VALID] CFBundleVersion ${
|
|
1380
|
-
`)}catch(
|
|
1381
|
-
`),new Error(be)}return fe}},ht=e=>{try{let t=E.join(process.cwd(),m.configFileName);if(b.existsSync(t)){let n=JSON.parse(b.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(b.existsSync(i)){let o=b.readFileSync(i,"utf-8").match(/applicationId\s+['"]([^'"]+)['"]/);if(o)return o[1]}}else{let n=E.resolve(process.cwd(),b.existsSync("ios")?"ios":"."),i=
|
|
1382
|
-
`).slice(1).map(s=>s.trim()).filter(s=>s.length>0&&!s.startsWith("*")).map(s=>s.split(" ")[0]).length===0){
|
|
1383
|
-
`).filter(a=>a.trim().length>0)}catch{}if(l.length>0){let a=await
|
|
1384
|
-
`).find(a=>a.includes("android.intent.action.MAIN")&&a.includes("android.intent.category.LAUNCHER"))?
|
|
1378
|
+
`))}}await ti(["-exportArchive","-archivePath",_,"-exportPath",L,"-exportOptionsPlist",ee],d,f,o,s),a&&await a("validate");let fe=Bt(L,[".ipa"]);for(let W of fe)try{te(`unzip -t "${W}"`,{stdio:"pipe"});let ae=Ad(W);o&&o(`[IPA VALID] ${E.basename(W)} \u2014 archive integrity OK
|
|
1379
|
+
`),o&&o(`[IPA VALID] CFBundleVersion ${ae}
|
|
1380
|
+
`)}catch(ae){let be=`IPA validation failed for ${E.basename(W)}: ${ae.message||"archive may be corrupt"}`;throw o&&o(`[IPA CORRUPT] ${be}
|
|
1381
|
+
`),new Error(be)}return fe}},ht=e=>{try{let t=E.join(process.cwd(),m.configFileName);if(b.existsSync(t)){let n=JSON.parse(b.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(b.existsSync(i)){let o=b.readFileSync(i,"utf-8").match(/applicationId\s+['"]([^'"]+)['"]/);if(o)return o[1]}}else{let n=E.resolve(process.cwd(),b.existsSync("ios")?"ios":"."),i=Bt(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=b.readFileSync(s,"utf-8").match(/<key>CFBundleIdentifier<\/key>\s*<string>([^<]+)<\/string>/);if(a&&!a[1].includes("$"))return a[1]}let r=Bt(n,[".xcodeproj"]);if(r.length>0){let s=E.join(r[0],"project.pbxproj");if(b.existsSync(s)){let a=b.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(b.existsSync(s)){let a=b.readFileSync(s,"utf-8").match(/"bundleIdentifier":\s*"([^"]+)"/);if(a)return a[1]}}}catch{return null}return null},$d=()=>{try{return te("emulator -version",{stdio:"ignore"}),"emulator"}catch{let t=Re.homedir(),n=[E.join(t,"Library/Android/sdk/emulator/emulator"),E.join(t,"Android/Sdk/emulator/emulator"),"/usr/local/lib/android/sdk/emulator/emulator"];for(let i of n)if(b.existsSync(i))return i}return"emulator"},_d=async(e,t)=>{let n=ni();try{if(te("adb devices").toString().split(`
|
|
1382
|
+
`).slice(1).map(s=>s.trim()).filter(s=>s.length>0&&!s.startsWith("*")).map(s=>s.split(" ")[0]).length===0){T.warn(D.yellow("No Android devices or emulators found."));let s=$d(),l=[];try{l=te(`${s} -list-avds`).toString().split(`
|
|
1383
|
+
`).filter(a=>a.trim().length>0)}catch{}if(l.length>0){let a=await or({message:"Select an emulator to launch:",options:l.map(c=>({value:c,label:c}))});if(ii(a))return;n.start(`Launching emulator ${a}...`),es(s,["-avd",a],{detached:!0,stdio:"ignore"}).unref();let d=0,u=!1;for(;d<60;){try{if(te("adb shell getprop sys.boot_completed",{stdio:"pipe"}).toString().trim()==="1"){u=!0;break}}catch{}await new Promise(c=>setTimeout(c,2e3)),d++}if(!u)throw n.stop("Emulator launch timed out."),new Error("Emulator launch timed out. Please try launching it manually.");n.stop("Emulator launched.")}else throw new Error("No devices found and no emulators available to launch. (Make sure Android SDK is installed)")}n.start("Installing APK on device..."),await gt("adb",["install","-r",e],process.cwd(),{},t),n.stop("Installation complete.");let o=ht("android");if(o){T.info(D.blue(`\u{1F680} Launching ${o}...`));try{te(`adb shell dumpsys package ${o}`).toString().split(`
|
|
1384
|
+
`).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{T.warn("Could not auto-launch app. You may need to open it manually.")}}}catch(i){n.stop("Installation failed."),T.error(D.red(`Failed to install APK: ${i.message}`))}},Rd=async(e,t,n)=>{let i=ni();try{if(!te("xcrun simctl list devices booted").toString().includes("(Booted)")){T.warn(D.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(c=>{s[c].forEach(p=>{p.isAvailable&&l.push({...p,runtime:c})})});let a=await or({message:"Select a simulator to launch:",options:l.map(c=>({value:c.udid,label:`${c.name} (${c.runtime.split(".").pop()})`}))});if(ii(a))return;i.start(`Booting ${a}...`),te(`xcrun simctl boot ${a}`),te(`open -a Simulator --args -CurrentDeviceUDID ${a}`);let d=0,u=!1;for(;d<30;){try{if(te("xcrun simctl list devices booted").toString().includes(a)){u=!0;break}}catch{}await new Promise(c=>setTimeout(c,2e3)),d++}if(!u)throw i.stop("Simulator boot timed out."),new Error("Simulator boot timed out.");i.stop("Simulator booted.")}i.start("Installing on iOS Simulator..."),ls(e),cs(e),await gt("xcrun",["simctl","install","booted",e],process.cwd(),{},n),i.stop("Installation complete."),T.info(D.blue(`\u{1F680} Launching ${t}...`)),await gt("xcrun",["simctl","launch","booted",t],process.cwd(),{},n)}catch(r){i.stop("Installation failed."),T.error(D.red(`Failed to install on Simulator: ${r.message}`))}},Pd=async(e,t,n)=>{let i=ni();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 or({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(ii(a))return;l=a,i.start(`Installing on ${l}...`)}else i.message(`Installing on ${s[0].model.name}...`);await gt("xcrun",["devicectl","device","install","app","--device",l,e],process.cwd(),{},n),i.stop("Installation complete."),T.info(D.blue(`\u{1F680} Launching ${t}...`)),await gt("xcrun",["devicectl","device","launch","app","--device",l,t],process.cwd(),{},n)}catch(r){i.stop("Installation failed."),T.error(D.red(`Failed to install on device: ${r.message}`)),T.info(D.dim('Make sure your device is unlocked and "Developer Mode" is enabled in Settings -> Privacy & Security.'))}};import cr from"fs";import ri from"path";import{spawnSync as Dd}from"child_process";var st=e=>{if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0},us=e=>e==null?void 0:st(String(e)),fs=e=>{if(!cr.existsSync(e))return null;try{return JSON.parse(cr.readFileSync(e,"utf-8"))}catch{return null}},Od=e=>{let t=e.trim();if(!t)return null;try{return JSON.parse(t)}catch{let n=t.indexOf("{"),i=t.lastIndexOf("}");if(n<0||i<=n)return null;try{return JSON.parse(t.slice(n,i+1))}catch{return null}}};function ps(e=process.cwd()){let t=fs(ri.join(e,"package.json"))||{};return st(t.version)}function Cd(e=process.cwd()){let t=fs(ri.join(e,"package.json"))||{},n={...t.dependencies||{},...t.devDependencies||{}};if(n.expo)return"expo";if(n["react-native"])return"react-native"}function dr(e=process.cwd()){let t=process.platform==="win32"?ri.join(e,"node_modules",".bin","expo.cmd"):ri.join(e,"node_modules",".bin","expo"),n=cr.existsSync(t),o=Dd(n?t:"npx",n?["config","--json"]:["--no-install","expo","config","--json"],{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","pipe"],env:{...process.env,EXPO_NO_TELEMETRY:"1"}});return o.error||o.status!==0?null:Od(o.stdout||"")}var kd=e=>{let t=st(e);if(!(!t||t==="manual"))return t},lr=(e,t,n,i={})=>{let r=st(e);if(r)return r;if(!e||typeof e!="object")return;let o=st(e.policy);if(o==="appVersion")return st(t.version);if(o==="sdkVersion")return st(t.sdkVersion);if(o==="nativeVersion"){let s=st(t.version);if(!s||!n)return;let l=n==="ios"?us(i.iosBuildNumber)||us(t.ios?.buildNumber):i.androidVersionCode!==void 0?String(i.androidVersionCode).trim():t.android?.versionCode!==void 0?String(t.android.versionCode).trim():void 0;return!l||l.toLowerCase()==="auto"?s:l?`${s}(${l})`:s}};function Td(e,t,n={},i){let r=t?lr(e[t]?.runtimeVersion,e,t,n):void 0;if(r)return r;let o=lr(e.runtimeVersion,e,t,n);return o||(i?lr({policy:i},e,t,n):void 0)}function Nd(e=process.cwd(),t,n={},i){let r=dr(e);if(r)return Td(r,t,n,i)}function En(e,t={}){let n=t.cwd||process.cwd(),i=st(t.runtimeVersion)||st(e.ota?.runtimeVersion);if(i)return i;let r=kd(e.ota?.runtimeVersionPolicy),o={iosBuildNumber:t.iosBuildNumber,androidVersionCode:t.androidVersionCode};if((t.framework||e.framework||Cd(n))==="expo"){let l=Nd(n,t.platform,o,r);if(l)return l}return ps(n)||"1.0.0"}import x from"fs";import en from"os";import G from"path";import{spawn as Es,spawnSync as qe}from"child_process";import{randomUUID as xd}from"crypto";import{pipeline as Ld}from"stream/promises";import{isCancel as mr,log as F,select as Is,spinner as wn,text as Md}from"@clack/prompts";import In from"axios";import j from"chalk";import oi from"adm-zip";async function ws(e){if(e.localRunner){let n=await Hd(e);process.exitCode=n?n.exitCode:1;return}if(e.local){let n=await Gd(e);n&&(process.exitCode=n.exitCode);return}let t=await Sr(e);if(t&&(F.success(j.green(`Maestro run ${t.status||"queued"}: ${t.testRunId}`)),t.launchDeferredReason&&F.warn(j.yellow(t.launchDeferredReason)),t.dashboardUrl&&F.info(j.dim("View test run: ")+j.white.underline(t.dashboardUrl)),e.wait)){let n=await Vd(e,t);n&&(process.exitCode=n.status==="passed"?0:1)}}var Ud=new Set(["passed","failed","cancelled","interrupted"]),ms=Number(process.env.MACH_FLOW_UPLOAD_MAX_ATTEMPTS||4),Fd=Number(process.env.MACH_FLOW_UPLOAD_TIMEOUT_MS||12e4),vs=process.env.MACH_MAESTRO_FAST_FAIL_RETRY==="1";function yr(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 Bd(e){let t=yr(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 jd(e){let t={};for(let[i,r]of Object.entries(process.env))i.startsWith("MAESTRO_TEST_")&&r!==void 0&&(t[i]=r);let n=yr(e);for(let i of n){let r=process.env[i];r!==void 0&&(t[i]=r)}return t}async function Hd(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||dt).replace(/\/$/,""),o=x.mkdtempSync(G.join(en.tmpdir(),"mach-maestro-runner-")),s=G.join(o,"mach-maestro-output"),l=G.join(o,"runner.log");if(x.mkdirSync(s,{recursive:!0}),!t||!n||!i)return F.error(j.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,u=null,c=f=>{x.appendFileSync(l,`${f}${f.endsWith(`
|
|
1385
1385
|
`)?"":`
|
|
1386
|
-
`}`)},p=async(f,g)=>{try{await An.post(`${r}/internal/tests/${encodeURIComponent(n)}/runner`,{projectId:t,runnerToken:i,status:f,error:g,logPreview:zd(l),junitUrl:a?.urls?.junitDownloadUrl,logsUrl:a?.urls?.logsDownloadUrl,artifactsUrl:a?.urls?.artifactsDownloadUrl})}catch(y){c(`[WARN] Could not post runner update: ${y.message||y}`)}};try{c(`Mach Maestro local runner starting for ${n}`);let f=await An.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 g=Object.keys(a.env||{});c(`Using Maestro env vars: ${g.length>0?g.join(", "):"none"}`);let y={...process.env,...a.env||{}},h=Wd(a.env);h.length>0&&c(`Passing Maestro env vars to test command: ${g.sort().join(", ")}`),await p("running");let _=a.platform==="android"?"app.apk":"app.zip",I=G.join(o,_),T=G.join(o,"source.zip"),w=G.join(o,"source");x.mkdirSync(w,{recursive:!0}),c("Downloading app artifact..."),await ur(a.artifactUrl,I),c(`Downloaded app artifact: ${_} (${ps(x.statSync(I).size)})`),c("Downloading Maestro source..."),await ur(a.urls.sourceUrl,T),c(`Downloaded Maestro source: source.zip (${ps(x.statSync(T).size)})`),new ti(T).extractAllTo(w,!0);let U=Jd(w,a.flowPath||".maestro");if(!x.existsSync(U))throw new Error(`Maestro flow path not found: ${a.flowPath||".maestro"}`);if(c(`Resolved Maestro flow path: ${G.relative(w,U)||"."}`),a.platform==="ios"){await eu(a.device||"iphone_15",l);let P=tu(I,o),S=vs(P,l);c(`Resolved iOS app bundle: ${P}`),c(`Resolved iOS bundle id: ${S||"unknown"}`),iu(P,l),pr("xcrun",["simctl","install","booted",P],l),S&&(u={platform:a.platform,appId:S}),S&&yt("xcrun",["simctl","get_app_container","booted",S,"app"],l),ar(s,l,"ios-before-maestro.png"),a.record&&(d=nu(s,l))}else{let P=su(I,l),S=ou(a.device,l),R=S?["-s",S]:[];c(`Resolved Android application id: ${P||"unknown"}`),pr("adb",[...R,"install","-r",I],l),P&&(u={platform:a.platform,appId:P,deviceId:S||void 0})}let J=Math.max(0,Math.min(10,Number(a.retries??1)))+1,A=G.join(s,"report.xml"),v=Zd(l);if(!v)throw new Error("Maestro CLI not found on this runner. Install Maestro or set MAESTRO_BIN to the full maestro path.");let L=1;for(let P=1;P<=J;P+=1){c(`Running Maestro attempt ${P}/${J}...`);let S=["test","--platform",a.platform,...h,U,"--format","junit","--output",A,"--test-output-dir",s];if(As&&P<J?L=(await $s(v,S,{logPath:l,env:y,fastFailOnFlowFailure:!0})).exitCode:L=yt(v,S,l,void 0,y),L===0)break}return a.platform==="ios"&&ar(s,l,"ios-after-maestro.png"),await fs(d,l),d=null,await hs(a.urls,o,s,l),L===0?(await p("passed"),F.success(j.green(`Managed Maestro run passed: ${n}`)),{status:"passed",exitCode:0,attempts:J,flows:a.flowPath,platform:a.platform}):(await p("failed",`Maestro exited with code ${L}`),F.error(j.red(`Managed Maestro run failed with exit code ${L}`)),{status:"failed",exitCode:L,attempts:J,flows:a.flowPath,platform:a.platform})}catch(f){let g=f.message||String(f);return c(`MACH_MAESTRO_RUN_FAILED: ${g}`),a?.platform==="ios"&&ar(s,l,"ios-after-failure.png"),await fs(d,l),a?.urls&&await hs(a.urls,o,s,l),await p("failed",g),F.error(j.red(`Managed Maestro runner failed: ${g}`)),{status:"failed",exitCode:1,attempts:0,flows:a?.flowPath||".maestro",platform:a?.platform||e.platform}}finally{ru(u,l)}}async function Md(e){let t=e.maestroFlows||".maestro",n=Is(e.maestroRetries);if(n===null)return null;let i=G.resolve(t);if(!x.existsSync(i))return F.error(j.red(`Maestro flows not found: ${t}`)),{status:"failed",exitCode:1,attempts:0,flows:t,platform:e.platform};let r=await Gd(e);if(r?.url){if(!await Kd(r))return{status:"failed",exitCode:1,attempts:0,flows:t,platform:r.platform||e.platform}}else if(e.buildId||e.buildUrl||e.artifactUrl||e.latest)return{status:"failed",exitCode:1,attempts:0,flows:t,platform:e.platform};e.maestroRecord&&F.warn(j.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=xd(e.maestroEnv),a=Object.keys(l);if(a.length>0){F.info(j.dim(`Passing Maestro env vars to local run: ${a.join(", ")}`));for(let[f,g]of Object.entries(l))s.push("-e",`${f}=${g}`)}s.push(t);let d=n+1,u=1;for(let f=1;f<=d;f+=1){if(F.info(j.dim(`Running local Maestro attempt ${f}/${d}...`)),As&&f<d){let g=await $s("maestro",s,{cwd:process.cwd(),env:process.env,echoOutput:!0,fastFailOnFlowFailure:!0});if(g.error){let y=g.error.message||"Failed to run Maestro";F.error(j.red(`Local Maestro failed to start: ${y}`)),F.info(j.dim("Install Maestro locally, then retry: https://maestro.mobile.dev/getting-started/installing-maestro")),u=1;break}u=g.exitCode}else{let g=qe("maestro",s,{cwd:process.cwd(),stdio:"inherit",env:process.env});if(g.error){let y=g.error.message||"Failed to run Maestro";F.error(j.red(`Local Maestro failed to start: ${y}`)),F.info(j.dim("Install Maestro locally, then retry: https://maestro.mobile.dev/getting-started/installing-maestro")),u=1;break}u=typeof g.status=="number"?g.status:1}if(u===0)break}let c=u===0?"passed":"failed",p={status:c,exitCode:u,attempts:d,flows:t,platform:o};return fu(e,p),c==="passed"?F.success(j.green("Local Maestro run passed")):F.error(j.red(`Local Maestro run failed with exit code ${u}`)),p}async function mr(e){let t=ve(`./${m.configFileName}`),n=e.projectId||t?.projectId,i=String(e.profile||e.buildProfile||"production").toLowerCase();if(!n)return F.error(`No projectId found. Run \`${m.nameLower} link\` first or pass an internal project id.`),null;let r=e.platform;if(!r&&e.latest){let c=await Ss({message:"Select platform for the latest build:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"}]});if(dr(c))return null;r=c}let o=await Hd(e);if(!o)return null;if(o.kind==="latest"&&!r)return F.error("Pass --platform when using --latest."),null;if(o.kind==="artifact-url"&&!r)return F.error("Pass --platform when using --artifact-url."),null;let s=Is(e.maestroRetries);if(s===null)return null;let l=fr(e.maestroEnv),a=Nd(e.maestroEnv);!e.quiet&&l.length>0&&F.info(j.dim(`Forwarding Maestro env vars by name: ${l.join(", ")}`));let d=await Fd(e,n);if(d===null)return null;let u=En();e.quiet||u.start("Queuing Maestro run...");try{let c=await N.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(c.data.status!=="success")throw new Error(c.data.message||"Failed to queue Maestro run");let p=c.data.testRun,f={testRunId:p.testRunId,status:p.status,projectId:n,buildId:p.buildId,platform:p.platform,dashboardUrl:p.dashboardUrl||`${ot}/tests/${p.testRunId}`,launchDeferredReason:p.launchDeferredReason};return Ps(e,f),e.quiet||u.stop("Maestro run queued"),f}catch(c){e.quiet||u.stop("Could not queue Maestro run");let p=c.response?.data?.message||c.message||"Unknown error";return F.error(j.red(`Maestro queue failed: ${p}`)),null}}async function Ud(e,t){let n=us(e.waitTimeout,60,"--wait-timeout"),i=us(e.waitInterval,15,"--wait-interval");if(n===null||i===null)return null;let r=n*60*1e3,o=Math.max(5,i)*1e3,s=Date.now(),l=t.status||"queued";for(F.info(j.dim(`Waiting for Maestro run ${t.testRunId} to finish...`));Date.now()-s<=r;){let a=await jd(t.projectId,t.testRunId);if(!a)return null;if(a.status&&a.status!==l&&(l=a.status,F.info(j.dim(`Maestro status: ${l}`))),kd.has(String(a.status)))return Ps(e,a),a.status==="passed"?F.success(j.green(`Maestro run passed: ${a.testRunId}`)):(F.error(j.red(`Maestro run ${a.status}: ${a.testRunId}`)),a.error&&F.error(j.red(String(a.error)))),a;await gr(o)}return F.error(j.red(`Timed out waiting for Maestro run ${t.testRunId} after ${n} minute(s).`)),{...t,status:"timeout"}}async function Fd(e,t){if(e.maestroUseBuildSource)return;let n=e.maestroFlows||".maestro",i=G.resolve(n);if(!x.existsSync(i))return e.maestroFlows?(F.error(j.red(`Maestro flows not found: ${n}`)),null):void 0;let r=G.relative(process.cwd(),i);if(!r||r.startsWith("..")||G.isAbsolute(r))return F.error(j.red("Managed Maestro flow uploads must be inside the current project directory.")),null;let o=En();e.quiet||o.start(`Uploading Maestro flows from ${r}...`);try{let s=await N.post("/tests/maestro/source-upload-url",{projectId:t,uploadId:Dd()});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 ti;if(x.statSync(i).isDirectory())l.addLocalFolder(i,r);else{let u=G.dirname(r);l.addLocalFile(i,u==="."?void 0:u,G.basename(r))}let d=l.toBuffer();return await Bd(s.data.uploadUrl,d,"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 F.error(j.red(`Maestro flow upload failed: ${l}`)),null}}function Es(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 Bd(e,t,n,i,r){let o;for(let s=1;s<=ds;s+=1)try{await An.put(e,t,{headers:{"Content-Type":n},maxBodyLength:1/0,maxContentLength:1/0,timeout:Td});return}catch(l){if(o=l,!Es(l)||s>=ds)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 gr(a)}throw o}async function jd(e,t){try{let n=await N.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||`${ot}/tests/${i.testRunId}`,launchDeferredReason:i.launchDeferredReason,...i.error?{error:i.error}:{}}}catch(n){let i=n.response?.data?.message||n.message||"Unknown error";return F.error(j.red(`Could not fetch Maestro run status: ${i}`)),null}}async function Hd(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 Ss({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(dr(t))return null;if(t==="latest")return{kind:"latest"};let n=await Cd({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 dr(n)?null:{kind:t,value:String(n).trim()}}function us(e,t,n){if(e==null||e==="")return t;let i=Number(e);return!Number.isFinite(i)||i<=0?(F.error(`${n} must be a positive number.`),null):i}function gr(e){return new Promise(t=>setTimeout(t,e))}function Is(e){if(e==null||e==="")return 1;let t=Number(e);return!Number.isInteger(t)||t<0||t>10?(F.error("--maestro-retries must be an integer between 0 and 10."),null):t}async function Gd(e){if(e.artifactUrl)return{url:e.artifactUrl,platform:e.platform||yr(e.artifactUrl),name:Rs(e.artifactUrl)};let t=e.buildId||pu(e.buildUrl);return t?ws(t,e.platform):e.latest?Vd(e):null}async function ws(e,t){let n=En();n.start(`Resolving build ${e}...`);try{let i=await N.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=uu(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||yr(o.name||o.downloadUrl),name:o.name}}catch(i){n.stop("Could not resolve build artifact");let r=i.response?.data?.message||i.message||"Unknown error";return F.error(j.red(`Local Maestro artifact lookup failed: ${r}`)),null}}async function Vd(e){let t=ve(`./${m.configFileName}`),n=e.projectId||t?.projectId,i=String(e.profile||e.buildProfile||"production").toLowerCase();if(!n)return F.error(`No projectId found. Run \`${m.nameLower} link\` first or pass --build-id/--artifact-url.`),null;if(!e.platform)return F.error("Pass --platform when using --latest with --local."),null;let r=En();r.start("Resolving latest build...");try{let o=await N.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}`),ws(l.buildId,e.platform)}catch(o){r.stop("Could not resolve latest build");let s=o.response?.data?.message||o.message||"Unknown error";return F.error(j.red(`Latest build lookup failed: ${s}`)),null}}async function Kd(e){let t=e.platform||yr(e.url);if(!t)return F.error(j.red("Could not infer platform for local install. Pass --platform android or --platform ios.")),!1;let n=x.mkdtempSync(G.join(Zt.tmpdir(),"mach-maestro-")),i=e.name||Rs(e.url)||(t==="android"?"app.apk":"app.zip"),r=G.join(n,i),o=En();o.start(`Downloading ${i}...`);try{await ur(e.url,r),o.stop("Artifact downloaded")}catch(s){return o.stop("Artifact download failed"),F.error(j.red(s.message||"Failed to download artifact")),!1}return t==="android"?cu(r):du(r,n)}async function ur(e,t){let n=await An.get(e,{responseType:"stream"});await Od(n.data,x.createWriteStream(t))}function zd(e,t=12e3){try{return x.readFileSync(e,"utf-8").slice(-t)}catch{return""}}function ps(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 Wd(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 Jd(e,t){let n=G.resolve(e,t||".maestro"),i=G.relative(e,n);if(i.startsWith("..")||G.isAbsolute(i))throw new Error("Maestro flow path must stay inside the build source.");return n}function _s(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 Yd(e){return/\[Failed\]\s+/.test(e)}function qd(e){if(!e.killed){try{e.kill("SIGTERM")}catch{}setTimeout(()=>{try{e.kill("SIGKILL")}catch{}},5e3).unref()}}function $s(e,t,n={}){let{cwd:i,env:r=process.env,logPath:o,echoOutput:s=!1,fastFailOnFlowFailure:l=!1}=n;return o&&x.appendFileSync(o,`
|
|
1387
|
-
$ ${
|
|
1388
|
-
`),new Promise(a=>{let d=!1,u=!1,c="",p=y=>{u||(u=!0,a(y))},f=
|
|
1386
|
+
`}`)},p=async(f,g)=>{try{await In.post(`${r}/internal/tests/${encodeURIComponent(n)}/runner`,{projectId:t,runnerToken:i,status:f,error:g,logPreview:Zd(l),junitUrl:a?.urls?.junitDownloadUrl,logsUrl:a?.urls?.logsDownloadUrl,artifactsUrl:a?.urls?.artifactsDownloadUrl})}catch(y){c(`[WARN] Could not post runner update: ${y.message||y}`)}};try{c(`Mach Maestro local runner starting for ${n}`);let f=await In.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 g=Object.keys(a.env||{});c(`Using Maestro env vars: ${g.length>0?g.join(", "):"none"}`);let y={...process.env,...a.env||{}},h=Qd(a.env);h.length>0&&c(`Passing Maestro env vars to test command: ${g.sort().join(", ")}`),await p("running");let v=a.platform==="android"?"app.apk":"app.zip",I=G.join(o,v),N=G.join(o,"source.zip"),w=G.join(o,"source");x.mkdirSync(w,{recursive:!0}),c("Downloading app artifact..."),await gr(a.artifactUrl,I),c(`Downloaded app artifact: ${v} (${hs(x.statSync(I).size)})`),c("Downloading Maestro source..."),await gr(a.urls.sourceUrl,N),c(`Downloaded Maestro source: source.zip (${hs(x.statSync(N).size)})`),new oi(N).extractAllTo(w,!0);let U=eu(w,a.flowPath||".maestro");if(!x.existsSync(U))throw new Error(`Maestro flow path not found: ${a.flowPath||".maestro"}`);if(c(`Resolved Maestro flow path: ${G.relative(w,U)||"."}`),a.platform==="ios"){await su(a.device||"iphone_15",l);let P=au(I,o),S=Os(P,l);c(`Resolved iOS app bundle: ${P}`),c(`Resolved iOS bundle id: ${S||"unknown"}`),cu(P,l),hr("xcrun",["simctl","install","booted",P],l),S&&(u={platform:a.platform,appId:S}),S&&yt("xcrun",["simctl","get_app_container","booted",S,"app"],l),ur(s,l,"ios-before-maestro.png"),a.record&&(d=lu(s,l))}else{let P=pu(I,l),S=uu(a.device,l),R=S?["-s",S]:[];c(`Resolved Android application id: ${P||"unknown"}`),hr("adb",[...R,"install","-r",I],l),P&&(u={platform:a.platform,appId:P,deviceId:S||void 0})}let J=Math.max(0,Math.min(10,Number(a.retries??1)))+1,A=G.join(s,"report.xml"),_=ru(l);if(!_)throw new Error("Maestro CLI not found on this runner. Install Maestro or set MAESTRO_BIN to the full maestro path.");let L=1;for(let P=1;P<=J;P+=1){c(`Running Maestro attempt ${P}/${J}...`);let S=["test","--platform",a.platform,...h,U,"--format","junit","--output",A,"--test-output-dir",s];if(vs&&P<J?L=(await Ds(_,S,{logPath:l,env:y,fastFailOnFlowFailure:!0})).exitCode:L=yt(_,S,l,void 0,y),L===0)break}return a.platform==="ios"&&ur(s,l,"ios-after-maestro.png"),await ys(d,l),d=null,await As(a.urls,o,s,l),L===0?(await p("passed"),F.success(j.green(`Managed Maestro run passed: ${n}`)),{status:"passed",exitCode:0,attempts:J,flows:a.flowPath,platform:a.platform}):(await p("failed",`Maestro exited with code ${L}`),F.error(j.red(`Managed Maestro run failed with exit code ${L}`)),{status:"failed",exitCode:L,attempts:J,flows:a.flowPath,platform:a.platform})}catch(f){let g=f.message||String(f);return c(`MACH_MAESTRO_RUN_FAILED: ${g}`),a?.platform==="ios"&&ur(s,l,"ios-after-failure.png"),await ys(d,l),a?.urls&&await As(a.urls,o,s,l),await p("failed",g),F.error(j.red(`Managed Maestro runner failed: ${g}`)),{status:"failed",exitCode:1,attempts:0,flows:a?.flowPath||".maestro",platform:a?.platform||e.platform}}finally{du(u,l)}}async function Gd(e){let t=e.maestroFlows||".maestro",n=_s(e.maestroRetries);if(n===null)return null;let i=G.resolve(t);if(!x.existsSync(i))return F.error(j.red(`Maestro flows not found: ${t}`)),{status:"failed",exitCode:1,attempts:0,flows:t,platform:e.platform};let r=await Yd(e);if(r?.url){if(!await Xd(r))return{status:"failed",exitCode:1,attempts:0,flows:t,platform:r.platform||e.platform}}else if(e.buildId||e.buildUrl||e.artifactUrl||e.latest)return{status:"failed",exitCode:1,attempts:0,flows:t,platform:e.platform};e.maestroRecord&&F.warn(j.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=jd(e.maestroEnv),a=Object.keys(l);if(a.length>0){F.info(j.dim(`Passing Maestro env vars to local run: ${a.join(", ")}`));for(let[f,g]of Object.entries(l))s.push("-e",`${f}=${g}`)}s.push(t);let d=n+1,u=1;for(let f=1;f<=d;f+=1){if(F.info(j.dim(`Running local Maestro attempt ${f}/${d}...`)),vs&&f<d){let g=await Ds("maestro",s,{cwd:process.cwd(),env:process.env,echoOutput:!0,fastFailOnFlowFailure:!0});if(g.error){let y=g.error.message||"Failed to run Maestro";F.error(j.red(`Local Maestro failed to start: ${y}`)),F.info(j.dim("Install Maestro locally, then retry: https://maestro.mobile.dev/getting-started/installing-maestro")),u=1;break}u=g.exitCode}else{let g=qe("maestro",s,{cwd:process.cwd(),stdio:"inherit",env:process.env});if(g.error){let y=g.error.message||"Failed to run Maestro";F.error(j.red(`Local Maestro failed to start: ${y}`)),F.info(j.dim("Install Maestro locally, then retry: https://maestro.mobile.dev/getting-started/installing-maestro")),u=1;break}u=typeof g.status=="number"?g.status:1}if(u===0)break}let c=u===0?"passed":"failed",p={status:c,exitCode:u,attempts:d,flows:t,platform:o};return bu(e,p),c==="passed"?F.success(j.green("Local Maestro run passed")):F.error(j.red(`Local Maestro run failed with exit code ${u}`)),p}async function Sr(e){let t=ve(`./${m.configFileName}`),n=e.projectId||t?.projectId,i=String(e.profile||e.buildProfile||"production").toLowerCase();if(!n)return F.error(`No projectId found. Run \`${m.nameLower} link\` first or pass an internal project id.`),null;let r=e.platform;if(!r&&e.latest){let c=await Is({message:"Select platform for the latest build:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"}]});if(mr(c))return null;r=c}let o=await Jd(e);if(!o)return null;if(o.kind==="latest"&&!r)return F.error("Pass --platform when using --latest."),null;if(o.kind==="artifact-url"&&!r)return F.error("Pass --platform when using --artifact-url."),null;let s=_s(e.maestroRetries);if(s===null)return null;let l=yr(e.maestroEnv),a=Bd(e.maestroEnv);!e.quiet&&l.length>0&&F.info(j.dim(`Forwarding Maestro env vars by name: ${l.join(", ")}`));let d=await Kd(e,n);if(d===null)return null;let u=wn();e.quiet||u.start("Queuing Maestro run...");try{let c=await k.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(c.data.status!=="success")throw new Error(c.data.message||"Failed to queue Maestro run");let p=c.data.testRun,f={testRunId:p.testRunId,status:p.status,projectId:n,buildId:p.buildId,platform:p.platform,dashboardUrl:p.dashboardUrl||`${ot}/tests/${p.testRunId}`,launchDeferredReason:p.launchDeferredReason};return ks(e,f),e.quiet||u.stop("Maestro run queued"),f}catch(c){e.quiet||u.stop("Could not queue Maestro run");let p=c.response?.data?.message||c.message||"Unknown error";return F.error(j.red(`Maestro queue failed: ${p}`)),null}}async function Vd(e,t){let n=gs(e.waitTimeout,60,"--wait-timeout"),i=gs(e.waitInterval,15,"--wait-interval");if(n===null||i===null)return null;let r=n*60*1e3,o=Math.max(5,i)*1e3,s=Date.now(),l=t.status||"queued";for(F.info(j.dim(`Waiting for Maestro run ${t.testRunId} to finish...`));Date.now()-s<=r;){let a=await Wd(t.projectId,t.testRunId);if(!a)return null;if(a.status&&a.status!==l&&(l=a.status,F.info(j.dim(`Maestro status: ${l}`))),Ud.has(String(a.status)))return ks(e,a),a.status==="passed"?F.success(j.green(`Maestro run passed: ${a.testRunId}`)):(F.error(j.red(`Maestro run ${a.status}: ${a.testRunId}`)),a.error&&F.error(j.red(String(a.error)))),a;await br(o)}return F.error(j.red(`Timed out waiting for Maestro run ${t.testRunId} after ${n} minute(s).`)),{...t,status:"timeout"}}async function Kd(e,t){if(e.maestroUseBuildSource)return;let n=e.maestroFlows||".maestro",i=G.resolve(n);if(!x.existsSync(i))return e.maestroFlows?(F.error(j.red(`Maestro flows not found: ${n}`)),null):void 0;let r=G.relative(process.cwd(),i);if(!r||r.startsWith("..")||G.isAbsolute(r))return F.error(j.red("Managed Maestro flow uploads must be inside the current project directory.")),null;let o=wn();e.quiet||o.start(`Uploading Maestro flows from ${r}...`);try{let s=await k.post("/tests/maestro/source-upload-url",{projectId:t,uploadId:xd()});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 oi;if(x.statSync(i).isDirectory())l.addLocalFolder(i,r);else{let u=G.dirname(r);l.addLocalFile(i,u==="."?void 0:u,G.basename(r))}let d=l.toBuffer();return await zd(s.data.uploadUrl,d,"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 F.error(j.red(`Maestro flow upload failed: ${l}`)),null}}function $s(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 zd(e,t,n,i,r){let o;for(let s=1;s<=ms;s+=1)try{await In.put(e,t,{headers:{"Content-Type":n},maxBodyLength:1/0,maxContentLength:1/0,timeout:Fd});return}catch(l){if(o=l,!$s(l)||s>=ms)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 br(a)}throw o}async function Wd(e,t){try{let n=await k.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||`${ot}/tests/${i.testRunId}`,launchDeferredReason:i.launchDeferredReason,...i.error?{error:i.error}:{}}}catch(n){let i=n.response?.data?.message||n.message||"Unknown error";return F.error(j.red(`Could not fetch Maestro run status: ${i}`)),null}}async function Jd(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 Is({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(mr(t))return null;if(t==="latest")return{kind:"latest"};let n=await Md({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 mr(n)?null:{kind:t,value:String(n).trim()}}function gs(e,t,n){if(e==null||e==="")return t;let i=Number(e);return!Number.isFinite(i)||i<=0?(F.error(`${n} must be a positive number.`),null):i}function br(e){return new Promise(t=>setTimeout(t,e))}function _s(e){if(e==null||e==="")return 1;let t=Number(e);return!Number.isInteger(t)||t<0||t>10?(F.error("--maestro-retries must be an integer between 0 and 10."),null):t}async function Yd(e){if(e.artifactUrl)return{url:e.artifactUrl,platform:e.platform||Er(e.artifactUrl),name:Cs(e.artifactUrl)};let t=e.buildId||Su(e.buildUrl);return t?Rs(t,e.platform):e.latest?qd(e):null}async function Rs(e,t){let n=wn();n.start(`Resolving build ${e}...`);try{let i=await k.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=yu(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||Er(o.name||o.downloadUrl),name:o.name}}catch(i){n.stop("Could not resolve build artifact");let r=i.response?.data?.message||i.message||"Unknown error";return F.error(j.red(`Local Maestro artifact lookup failed: ${r}`)),null}}async function qd(e){let t=ve(`./${m.configFileName}`),n=e.projectId||t?.projectId,i=String(e.profile||e.buildProfile||"production").toLowerCase();if(!n)return F.error(`No projectId found. Run \`${m.nameLower} link\` first or pass --build-id/--artifact-url.`),null;if(!e.platform)return F.error("Pass --platform when using --latest with --local."),null;let r=wn();r.start("Resolving latest build...");try{let o=await k.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}`),Rs(l.buildId,e.platform)}catch(o){r.stop("Could not resolve latest build");let s=o.response?.data?.message||o.message||"Unknown error";return F.error(j.red(`Latest build lookup failed: ${s}`)),null}}async function Xd(e){let t=e.platform||Er(e.url);if(!t)return F.error(j.red("Could not infer platform for local install. Pass --platform android or --platform ios.")),!1;let n=x.mkdtempSync(G.join(en.tmpdir(),"mach-maestro-")),i=e.name||Cs(e.url)||(t==="android"?"app.apk":"app.zip"),r=G.join(n,i),o=wn();o.start(`Downloading ${i}...`);try{await gr(e.url,r),o.stop("Artifact downloaded")}catch(s){return o.stop("Artifact download failed"),F.error(j.red(s.message||"Failed to download artifact")),!1}return t==="android"?gu(r):hu(r,n)}async function gr(e,t){let n=await In.get(e,{responseType:"stream"});await Ld(n.data,x.createWriteStream(t))}function Zd(e,t=12e3){try{return x.readFileSync(e,"utf-8").slice(-t)}catch{return""}}function hs(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 Qd(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 eu(e,t){let n=G.resolve(e,t||".maestro"),i=G.relative(e,n);if(i.startsWith("..")||G.isAbsolute(i))throw new Error("Maestro flow path must stay inside the build source.");return n}function Ps(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 tu(e){return/\[Failed\]\s+/.test(e)}function nu(e){if(!e.killed){try{e.kill("SIGTERM")}catch{}setTimeout(()=>{try{e.kill("SIGKILL")}catch{}},5e3).unref()}}function Ds(e,t,n={}){let{cwd:i,env:r=process.env,logPath:o,echoOutput:s=!1,fastFailOnFlowFailure:l=!1}=n;return o&&x.appendFileSync(o,`
|
|
1387
|
+
$ ${Ps(e,t)}
|
|
1388
|
+
`),new Promise(a=>{let d=!1,u=!1,c="",p=y=>{u||(u=!0,a(y))},f=Es(e,t,{cwd:i,env:r,stdio:["ignore","pipe","pipe"]}),g=y=>{c+=y;let h=c.split(/\r?\n/);c=h.pop()||"";for(let v of h)if(l&&tu(v)&&!d){d=!0;let I="Mach fast-fail: detected failed Maestro flow; stopping this attempt early to retry...";o&&x.appendFileSync(o,`
|
|
1389
1389
|
${I}
|
|
1390
1390
|
`),s&&process.stderr.write(`${I}
|
|
1391
|
-
`),
|
|
1391
|
+
`),nu(f)}};f.stdout?.on("data",y=>{let h=y.toString();o&&x.appendFileSync(o,h),s&&process.stdout.write(h),g(h)}),f.stderr?.on("data",y=>{let h=y.toString();o&&x.appendFileSync(o,h),s&&process.stderr.write(h),g(h)}),f.on("error",y=>{o&&x.appendFileSync(o,`${y.message}
|
|
1392
1392
|
`),p({exitCode:1,fastFailed:d,error:y})}),f.on("close",(y,h)=>{d&&o&&x.appendFileSync(o,`Maestro attempt stopped after first failed flow${h?` (${h})`:""}.
|
|
1393
1393
|
`),p({exitCode:typeof y=="number"?y:1,fastFailed:d})})})}function yt(e,t,n,i,r=process.env){x.appendFileSync(n,`
|
|
1394
|
-
$ ${
|
|
1394
|
+
$ ${Ps(e,t)}
|
|
1395
1395
|
`);let o=qe(e,t,{cwd:i,encoding:"utf-8",env:r});return o.stdout&&x.appendFileSync(n,o.stdout),o.stderr&&x.appendFileSync(n,o.stderr),o.error?(x.appendFileSync(n,`${o.error.message}
|
|
1396
|
-
`),1):typeof o.status=="number"?o.status:1}function
|
|
1397
|
-
`)[0]?.trim():"";i&&t.unshift(i);for(let r of t)if(r&&
|
|
1396
|
+
`),1):typeof o.status=="number"?o.status:1}function hr(e,t,n,i){let r=yt(e,t,n,i);if(r!==0)throw new Error(`${e} ${t.join(" ")} failed with exit code ${r}`)}function iu(e){try{return x.accessSync(e,x.constants.X_OK),!0}catch{return!1}}function ru(e){let t=[process.env.MAESTRO_BIN,G.join(en.homedir(),".maestro","bin","maestro"),"/opt/homebrew/bin/maestro","/usr/local/bin/maestro"].filter(Boolean),n=qe("/usr/bin/env",["which","maestro"],{encoding:"utf-8",env:process.env}),i=n.status===0?String(n.stdout||"").split(`
|
|
1397
|
+
`)[0]?.trim():"";i&&t.unshift(i);for(let r of t)if(r&&iu(r))return e&&x.appendFileSync(e,`Using Maestro CLI at ${r}
|
|
1398
1398
|
`),r;return e&&x.appendFileSync(e,`Maestro CLI not found. Checked: ${t.join(", ")}
|
|
1399
|
-
`),null}function
|
|
1400
|
-
`);return}let i=
|
|
1399
|
+
`),null}function ou(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 su(e,t){if((qe("xcrun",["simctl","list","devices","booted"],{encoding:"utf-8"}).stdout||"").includes("(Booted)")){x.appendFileSync(t,`Using already booted iOS Simulator.
|
|
1400
|
+
`);return}let i=ou(e),r=qe("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}.`);x.appendFileSync(t,`Booting iOS Simulator ${l.name} (${l.udid})...
|
|
1401
1401
|
`),yt("xcrun",["simctl","boot",l.udid],t)!==0&&x.appendFileSync(t,`simctl boot returned non-zero; continuing to bootstatus in case it was already booting.
|
|
1402
|
-
`),
|
|
1402
|
+
`),hr("xcrun",["simctl","bootstatus",l.udid,"-b"],t)}function au(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=G.join(t,"ios-app");x.mkdirSync(n,{recursive:!0}),new oi(e).extractAllTo(n,!0);let i=Ar(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 Os(e,t){let n=G.join(e,"Info.plist");if(!x.existsSync(n))return x.appendFileSync(t,`Could not find Info.plist in ${e}; skipping uninstall.
|
|
1403
1403
|
`),null;let i=qe("/usr/bin/plutil",["-extract","CFBundleIdentifier","raw","-o","-",n],{encoding:"utf-8",env:process.env}),r=String(i.stdout||"").trim();return i.status!==0||!r?(x.appendFileSync(t,`Could not read CFBundleIdentifier from Info.plist; skipping uninstall.
|
|
1404
|
-
`),null):r}function
|
|
1405
|
-
`)}function
|
|
1406
|
-
`);let i=
|
|
1407
|
-
`)}),i}async function
|
|
1404
|
+
`),null):r}function ur(e,t,n){let i=G.join(e,n);yt("xcrun",["simctl","io","booted","screenshot",i],t)!==0&&x.appendFileSync(t,`[WARN] Could not capture iOS simulator screenshot: ${n}
|
|
1405
|
+
`)}function lu(e,t){let n=G.join(e,"ios-simulator-recording.mp4");x.appendFileSync(t,`Starting iOS simulator recording: ${n}
|
|
1406
|
+
`);let i=Es("xcrun",["simctl","io","booted","recordVideo",n],{stdio:["ignore","pipe","pipe"],env:process.env});return i.stdout?.on("data",r=>{x.appendFileSync(t,r)}),i.stderr?.on("data",r=>{x.appendFileSync(t,r)}),i.on("error",r=>{x.appendFileSync(t,`[WARN] Could not start iOS simulator recording: ${r.message}
|
|
1407
|
+
`)}),i}async function ys(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||(x.appendFileSync(t,`Stopping iOS simulator recording...
|
|
1408
1408
|
`),e.kill("SIGINT")),setTimeout(()=>{!i&&!e.killed&&(x.appendFileSync(t,`[WARN] iOS simulator recording did not stop after SIGINT; sending SIGKILL.
|
|
1409
|
-
`),e.kill("SIGKILL")),r()},5e3).unref?.()})}function
|
|
1409
|
+
`),e.kill("SIGKILL")),r()},5e3).unref?.()})}function cu(e,t){let n=Os(e,t);if(!n)return;x.appendFileSync(t,`Uninstalling existing iOS app data for ${n} if present...
|
|
1410
1410
|
`),yt("xcrun",["simctl","uninstall","booted",n],t)!==0&&x.appendFileSync(t,`No existing app install removed for ${n}; continuing.
|
|
1411
|
-
`)}function
|
|
1411
|
+
`)}function du(e,t){if(!e?.appId)return;if(x.appendFileSync(t,`Cleaning up installed app after Maestro run...
|
|
1412
1412
|
`),e.platform==="ios"){let r=yt("xcrun",["simctl","uninstall","booted",e.appId],t);r===0?x.appendFileSync(t,`Uninstalled iOS app ${e.appId} after Maestro run.
|
|
1413
1413
|
`):x.appendFileSync(t,`Warning: failed to uninstall iOS app ${e.appId} after Maestro run: xcrun simctl uninstall exited with code ${r}
|
|
1414
1414
|
`);return}let n=e.deviceId?["-s",e.deviceId]:[],i=yt("adb",[...n,"uninstall",e.appId],t);i===0?x.appendFileSync(t,`Uninstalled Android app ${e.appId} after Maestro run.
|
|
1415
1415
|
`):x.appendFileSync(t,`Warning: failed to uninstall Android app ${e.appId} after Maestro run: adb uninstall exited with code ${i}
|
|
1416
|
-
`)}function
|
|
1416
|
+
`)}function uu(e,t){let n=qe("adb",["devices"],{encoding:"utf-8",env:process.env});if(n.status!==0||n.error)return x.appendFileSync(t,`[WARN] Could not list Android devices before install; using adb default target.
|
|
1417
1417
|
`),null;let i=String(n.stdout||"").split(`
|
|
1418
1418
|
`).map(r=>r.trim().split(/\s+/)).filter(r=>r.length>=2&&r[1]==="device").map(r=>r[0]).filter(Boolean);return e&&i.includes(e)?(x.appendFileSync(t,`Using Android device ${e} for install and cleanup.
|
|
1419
1419
|
`),e):i.length===1?(x.appendFileSync(t,`Using Android device ${i[0]} for install and cleanup.
|
|
1420
1420
|
`),i[0]):(i.length>1&&x.appendFileSync(t,`[WARN] Multiple Android devices are connected; using adb default target for install and cleanup.
|
|
1421
|
-
`),null)}function
|
|
1422
|
-
`),null)}function
|
|
1423
|
-
`)[0]?.trim()||null}async function
|
|
1424
|
-
`)}try{await
|
|
1425
|
-
`)}try{yt("tar",["-czf",o,"-C",t,G.basename(n)],i),await
|
|
1426
|
-
`)}}function cu(e){if(!e.endsWith(".apk"))return F.error(j.red("Local Android Maestro runs need an APK artifact.")),!1;F.info(j.dim("Installing APK on local Android device/emulator..."));let t=qe("adb",["install","-r",e],{stdio:"inherit",env:process.env});return t.error?(F.error(j.red(`adb failed to start: ${t.error.message}`)),!1):t.status!==0?(F.error(j.red(`adb install failed with exit code ${t.status??1}`)),!1):!0}function du(e,t){if(e.endsWith(".ipa"))return F.error(j.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=G.join(t,"ios-app");x.mkdirSync(r,{recursive:!0}),new ti(e).extractAllTo(r,!0);let o=hr(r);if(!o)return F.error(j.red("Could not find a .app bundle inside the downloaded zip.")),!1;n=o}if(!n.endsWith(".app"))return F.error(j.red("Local iOS Maestro runs need an iOS Simulator .app bundle or .app.zip artifact.")),!1;F.info(j.dim("Installing app on booted iOS Simulator..."));let i=qe("xcrun",["simctl","install","booted",n],{stdio:"inherit",env:process.env});return i.error?(F.error(j.red(`xcrun failed to start: ${i.error.message}`)),!1):i.status!==0?(F.error(j.red(`iOS Simulator install failed with exit code ${i.status??1}`)),!1):!0}function hr(e){let t=x.readdirSync(e,{withFileTypes:!0});for(let n of t){let i=G.join(e,n.name);if(n.isDirectory()&&n.name.endsWith(".app"))return i;if(n.isDirectory()){let r=hr(i);if(r)return r}}return null}function uu(e,t){let n=String(t||"").toLowerCase();return n==="android"?e.find(i=>Xt(i,".apk")):n==="ios"?e.find(i=>Xt(i,".app.zip"))||e.find(i=>Xt(i,".zip")):e.find(i=>Xt(i,".apk"))||e.find(i=>Xt(i,".app.zip"))||e.find(i=>Xt(i,".zip"))}function Xt(e,t){return String(e?.name||e?.downloadUrl||e?.url||"").toLowerCase().endsWith(t)}function yr(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 Rs(e){if(e)try{return G.basename(new URL(e).pathname)||void 0}catch{return G.basename(e)||void 0}}function pu(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 Ps(e,t){if(!e.jsonOutput)return;let n=G.resolve(e.jsonOutput),i={...t,updatedAt:new Date().toISOString()};try{let r=G.dirname(n);r&&r!=="."&&x.mkdirSync(r,{recursive:!0}),x.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){F.warn(j.yellow(`Could not write Maestro metadata JSON: ${r.message}`))}}function fu(e,t){if(!e.jsonOutput)return;let n=G.resolve(e.jsonOutput),i={mode:"local",...t,updatedAt:new Date().toISOString()};try{let r=G.dirname(n);r&&r!=="."&&x.mkdirSync(r,{recursive:!0}),x.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){F.warn(j.yellow(`Could not write Maestro metadata JSON: ${r.message}`))}}import{spinner as wt,text as _n,select as wr,isCancel as Et,cancel as _r,log as Us}from"@clack/prompts";import ie from"chalk";import oe from"fs";import Pe from"path";import{spawn as Su,spawnSync as Ft}from"child_process";import Fs from"axios";import jt from"os";import Rr from"crypto";import mu from"crypto";import Qt from"axios";import Ds from"fs";var wn=6e4,gu=12e4,Sr=4,In=e=>encodeURIComponent(e),hu=e=>new Promise(t=>setTimeout(t,e));async function en(e,t){let n;for(let i=1;i<=Sr;i++)try{return await t()}catch(r){if(n=r,i>=Sr||!yu(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}/${Sr}); retrying in ${Math.round(s/1e3)}s...`),await hu(s)}throw n}function yu(e){let t=e.response?.status;return t?t===408||t===409||t===425||t===429||t>=500:!0}async function Cs(e){let{packageName:t,serviceAccount:n,aabPath:i,track:r,releaseStatus:o,userFraction:s,changesNotSentForReview:l}=e,a;try{let u={Authorization:`Bearer ${await Os(n)}`,Connection:"close"},c=In(t);if(a=(await en("create edit",()=>Qt.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${c}/edits`,{},{headers:u,timeout:wn}))).data.id,!a)throw new Error("Google Play edit insert succeeded but did not return an edit id.");let f=In(a),g=Ds.statSync(i),y=await en("upload AAB",()=>Qt.post(`https://androidpublisher.googleapis.com/upload/androidpublisher/v3/applications/${c}/edits/${f}/bundles`,Ds.createReadStream(i),{headers:{...u,"Content-Type":"application/octet-stream","Content-Length":g.size},maxBodyLength:1/0,maxContentLength:1/0,params:{uploadType:"media"},timeout:gu})),h=Number(y.data.versionCode);if(!h)throw new Error("Google Play upload succeeded but did not return a versionCode.");let _={versionCodes:[String(h)],status:o};return(o==="inProgress"||o==="halted")&&typeof s=="number"&&(_.userFraction=s),await en("update track",()=>Qt.put(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${c}/edits/${f}/tracks/${In(r)}`,{releases:[_]},{headers:u,timeout:wn})),await en("commit edit",()=>Qt.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${c}/edits/${f}:commit`,{},{headers:u,params:l?{changesNotSentForReview:!0}:void 0,timeout:wn})),{editId:a,versionCode:h,track:r,releaseStatus:o,userFraction:s}}catch(d){if(a)try{let c=await Os(n);await en("delete edit",()=>Qt.delete(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${In(t)}/edits/${In(a)}`,{headers:{Authorization:`Bearer ${c}`,Connection:"close"},timeout:wn}))}catch{}let u=d.response?.data?.error?.message||d.message;throw new Error(`Google Play API Error: ${u}`)}}async function Os(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=mu.createSign("RSA-SHA256");a.update(l);let d=a.sign(e.private_key,"base64url"),u=`${l}.${d}`;return(await en("OAuth token exchange",()=>Qt.post("https://oauth2.googleapis.com/token",{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:u},{headers:{Connection:"close"},timeout:wn}))).data.access_token}var bu=5e3,Au=12,Bs=100,br=24,ks=8e3,Eu={completed:"completed",draft:"draft",halted:"halted",inprogress:"inProgress","in-progress":"inProgress"},Iu=e=>e?.type==="google_service_account",ii=e=>e?.bundleId||e?.packageName||e?.meta?.packageName||e?.meta?.bundleId,js=e=>e.submitArgs||process.argv.slice(3).join(" ");async function ri(e){let t=wt(),n=Ne(),i=wu(e);if(!i){process.exitCode=1;return}let r=e.projectId||i.projectId,o=e.profile||e.buildProfile||"production";if(!r){de(`${m.configFileName} is missing projectId. Pass --project-id in runner mode.`),process.exitCode=1;return}i.projectId=r,Ae(ie.dim(`Submit for project: ${i.name||r} | Profile: ${o}`));let s=e.platform;if(!s){let S=await wr({message:"Select platform to submit:",options:[{value:"ios",label:"iOS (App Store Connect / TestFlight)"},{value:"android",label:"Android (Google Play Console)"}]});if(Et(S)){_r("Operation cancelled");return}s=S}if(s=String(s).toLowerCase(),s!=="ios"&&s!=="android"){de(`Platform ${s} is not supported. Use 'ios' or 'android'.`),process.exitCode=1;return}let l=s==="ios"&&!e.local&&e.sshHost?Fu(i,o,e):null;if(s==="ios"&&!e.local&&!l){await _u(i,o,e);return}let a=e.submitId,d=!!(e.local&&a),u=a||null,c=async(S,R={})=>{u&&await Pu(r,u,{status:S,...R})},p=s==="android"?e.packageName||e.androidPackage||Lu(i,o):void 0,f=s==="ios"?e.bundleId||e.iosBundleIdentifier||Uu(i,o):void 0,g,y,h,_=!1;try{s==="android"&&(g=e.track||i.submit?.[o]?.android?.track||i.submit?.production?.android?.track||"internal",y=Bu(i,o,e.releaseStatus),h=Hu(i,o,e.rollout),_=Gu(i,o,e.changesNotSentForReview),Vu(y,h))}catch(S){de(S.message),process.exitCode=1;return}if(s==="android"&&!d&&(u=await $u(i,r,s,o,e,{packageName:p,track:g,releaseStatus:y,rollout:h,changesNotSentForReview:_}),!u)){de("Could not create submission tracking record. Submission was not started."),process.exitCode=1;return}await c("running",{platform:s,profile:o,packageName:p,track:g,releaseStatus:y,rollout:h,startTime:Date.now(),...d?Ou():{}});let I=null,T=null;try{T=await Ku(r,s,e,n?.token),I=T?.filePath||null}catch(S){await c("failed",{error:`Failed to resolve submission artifact: ${S.message}`,endTime:Date.now()}),de(`Failed to resolve submission artifact: ${S.message}`),process.exitCode=1;return}if(!I){let S=Wu(s,e);await c("failed",{error:S,endTime:Date.now()}),de(S),process.exitCode=1;return}await c("running",{buildId:T?.buildId,artifactName:T?.artifactName,artifactSource:T?.source}),Ae(`Using artifact: ${ie.green(Pe.basename(I))} `),t.start("Fetching submission credentials from Dashboard...");let w;try{let R=(await N.get(`/credentials/${r}`)).data.credentials||[];if(s==="android"&&!p){t.stop("Package name missing"),de("Could not resolve Android package name. Set android.package in mach.config.json/app.json."),await c("failed",{error:"Could not resolve Android package name.",endTime:Date.now()}),process.exitCode=1;return}let M=R.filter(Iu),B=s==="ios"?R.filter(K=>K.type==="asc_api_key"):Mu(M,p);if(B.length===0){if(t.stop("Credentials missing"),de(s==="android"?`No Google Play service credential found for package ${p}.`:`No Service Credentials found for ${s}.`),s==="android"){let K=M.map(ii).filter(Boolean).join(", ");K&&Ae(`Found Google Play service credential(s) for: ${K}`),Ae(`Use '${m.nameLower} credentials:service --platform android --package-name ${p}' or upload it under that package in the Dashboard.`)}else Ae(`Use '${m.nameLower} credentials:service --platform ${s}' or use the Dashboard to upload them.`);await c("failed",{error:`No submission credentials found for ${s}.`,endTime:Date.now()}),process.exitCode=1;return}if(w=ku(B,e.credentialId),!w&&s==="ios"&&f&&(w=Tu(B,f)),w||B.length===1)w=w||B[0],t.stop(`Using: ${w.name}`),s==="android"&&ii(w)==="*"&&Ae(ie.yellow(`Using legacy wildcard Google Play credential for ${p}. Upload a package-scoped credential when possible.`));else{if(t.stop("Multiple credentials found"),Nu()){let z=B.map(Q=>`${Q.name||"credential"} (${Q.credentialId||Q.id||"no-id"})`).join(", ");de(`Multiple ${s==="ios"?"App Store Connect":"Google Play"} credentials found. Use --credential-id in CI. Available: ${z}`),await c("failed",{error:"Multiple submission credentials found; --credential-id is required in CI.",endTime:Date.now()}),process.exitCode=1;return}let K=await wr({message:`Choose a ${s==="ios"?"App Store Connect":"Google Play"} credential:`,options:B.map(z=>({value:z.credentialId,label:z.name,hint:`${z.keyId?`ID: ${z.keyId}`:""} ${z.issuerId?`(Issuer: ${z.issuerId.substring(0,8)}...)`:""}`}))});if(Et(K)){_r("Submission cancelled"),await c("failed",{error:"Submission cancelled while selecting credential.",endTime:Date.now()}),process.exitCode=1;return}w=B.find(z=>z.credentialId===K),Ae(`Using selected: ${ie.green(w.name)}`)}}catch(S){t.stop("Failed to fetch credentials"),de(`API Error: ${S.message} `),await c("failed",{error:`Failed to fetch credentials: ${S.message}`,endTime:Date.now()}),process.exitCode=1;return}let U=oe.mkdtempSync(Pe.join(jt.tmpdir(),`${m.nameLower}-submit-`)),V=w.keyId||w.meta?.keyId,J=w.issuerId||w.meta?.issuerId,A=w.type==="asc_api_key"?`AuthKey_${V}.p8`:"service-account.json",v=Pe.join(U,A);t.start("Downloading secure key...");try{let S=await N.get(`/credentials/${w.credentialId}/download`,{params:{projectId:r,format:"raw"}});if(S.data.status!=="success"||!S.data.downloadUrl)throw new Error("Failed to get secure download URL");let R=await Fs.get(S.data.downloadUrl,{responseType:"arraybuffer"});oe.writeFileSync(v,Buffer.from(R.data)),t.stop("Key downloaded to secure temp storage")}catch(S){t.stop("Download failed"),de(`Failed to download key: ${S.message}`);try{oe.rmSync(U,{recursive:!0,force:!0})}catch{}await c("failed",{error:`Failed to download credential key: ${S.message}`,endTime:Date.now()}),process.exitCode=1;return}Ae(ie.blue(`Initiating ${s==="ios"?"TestFlight":"Google Play"} submission...`));let L=!1,P;try{if(s==="ios"){if(!V){let R=await _n({message:"Enter App Store Connect Key ID (e.g. 2X948D...):",validate:M=>M.length>0?void 0:"Key ID is required"});if(Et(R)){await c("failed",{error:"Submission cancelled while entering ASC Key ID.",endTime:Date.now()}),process.exitCode=1;return}V=R}if(!J||J==="undefined"){let R=await _n({message:"Enter App Store Connect Issuer ID (Found on ASC Keys page):",validate:M=>M.length>0?void 0:"Issuer ID is required"});if(Et(R)){await c("failed",{error:"Submission cancelled while entering ASC Issuer ID.",endTime:Date.now()}),process.exitCode=1;return}J=R}Ae(`Using ASC Key ID: ${V}`),Ae(`Using ASC Issuer ID: ${J}`);let S=l?await Yu(I,v,J,V,f,l):await Ju(I,v,J,V,f);vr(`${s==="ios"?"App Store":"Google Play"} submission successful!`),L=!0}else P=await ep(I,v,g||"internal",p,y||"completed",h,_,o),vr("Google Play submission successful!"),L=!0}catch(S){de(`Submission failed: ${S.message}`),await c("failed",{error:S.message,endTime:Date.now()}),It(e,{status:"failed",projectId:r,submitId:u,platform:s,profile:o,buildId:T?.buildId||e.buildId,artifactName:T?.artifactName,error:S.message,dashboardUrl:u?Bt(u,r):void 0}),process.exitCode=1}finally{L&&(await c("success",{endTime:Date.now(),versionCode:P?.versionCode,track:g,releaseStatus:y}),It(e,{status:"success",projectId:r,submitId:u,platform:s,profile:o,buildId:T?.buildId||e.buildId,artifactName:T?.artifactName,versionCode:P?.versionCode,track:g,releaseStatus:y,dashboardUrl:u?Bt(u,r):void 0})),gp(U),I&&I.includes(`${m.nameLower}-artifact-`)}}function wu(e){let t=`./${m.configFileName}`;if(oe.existsSync(t))try{return JSON.parse(oe.readFileSync(t,"utf-8"))}catch(n){return de(`Failed to read ${m.configFileName}: ${n.message}`),null}return e.projectId?{projectId:e.projectId}:(de(`No ${m.configFileName} found. Run \`${m.nameLower} init\` or \`${m.nameLower} link\` first.`),null)}async function _u(e,t,n){let i=n.projectId||e.projectId;if(!i){de(`${m.configFileName} is missing projectId.`),process.exitCode=1;return}let r=n.submitId||Rr.randomUUID(),o=!!n.latest||!n.buildId,s=vu({...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:js(n),runnerArgs:s,runnerCommand:[m.nameLower,"submit",...s].map(xu).join(" "),appName:e.name,startTime:Date.now()},a=wt();a.start("Queuing iOS submit on macOS runner...");try{let d=await N.post("/submissions",l),u=d.data?.submission||d.data?.submit||{},c=d.data?.dashboardUrl||Bt(r,i);a.stop("iOS submit queued"),Ae(`Submission ID: ${ie.cyan(r)}`),Ae(`Dashboard: ${ie.blue.underline(c)}`),It(n,{status:"pending",projectId:i,submitId:r,platform:"ios",profile:t,latest:o,buildId:n.buildId,dashboardUrl:c}),await Ru(i,r,n)}catch(d){a.stop("Could not queue iOS submit"),de(Cu(d)),process.exitCode=1}}async function $u(e,t,n,i,r,o={}){let s=r.submitId||Rr.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:js(r),appName:e.name,startTime:Date.now(),...o};try{let d=await N.post("/submissions",a),u=d.data?.submission||d.data?.submit||{},c=d.data?.dashboardUrl||u.dashboardUrl||Bt(s,t);return Ae(`Submission ID: ${ie.cyan(s)}`),Ae(`Dashboard: ${ie.blue.underline(c)}`),It(r,{status:"running",projectId:t,submitId:s,platform:n,profile:i,latest:l,buildId:r.buildId,dashboardUrl:c}),s}catch(d){let u=d.response?.data?.message||d.response?.data?.error||d.message;return Ae(ie.yellow(`Could not create submission tracking record: ${u}`)),null}}function vu(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 Ru(e,t,n){let i=wt(),r=0,o=0;for(n.quiet||i.start("Waiting for iOS submit runner...");;)try{let s=await N.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 u=o;u<d.length;u++){let c=d[u];c&&console.log(ie.dim(String(c)))}if(o=d.length,["success","completed","succeeded"].includes(a)){n.quiet||i.stop("iOS submit completed"),vr("App Store submission successful!"),It(n,{status:"success",projectId:e,submitId:t,platform:"ios",profile:l?.profile||n.profile||"production",buildId:l?.buildId||n.buildId,artifactName:l?.artifactName,dashboardUrl:l?.dashboardUrl||Bt(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.";de(u),It(n,{status:"failed",projectId:e,submitId:t,platform:"ios",profile:l?.profile||n.profile||"production",buildId:l?.buildId||n.buildId,artifactName:l?.artifactName,error:u,dashboardUrl:l?.dashboardUrl||Bt(t,e)}),process.exitCode=1;return}n.quiet||i.message(`iOS submit ${a}...`),await $r(bu)}catch(s){if(r++,r>=Au){n.quiet||i.stop("Lost connection to iOS submit status"),de(`Could not fetch iOS submit status after ${r} attempts: ${s.message}`),process.exitCode=1;return}await $r(Math.min(2e3*r,15e3))}}async function Pu(e,t,n){let i;for(let r=1;r<=3;r++)try{await N.patch(`/submissions/${e}/${t}`,n);return}catch(o){if(i=o,r>=3||!Du(o))break;await $r(1e3*r)}Us.warn(ie.dim(`Could not report submission status: ${i?.message||i}`))}function Du(e){let t=e.response?.status;return!t||t===408||t===409||t===425||t===429||t>=500}function Ou(){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 Cu(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(`
|
|
1427
|
-
`):n||e.message||String(e)}function Bt(e,t){if(!e)return ot;let n=t?`?projectId=${encodeURIComponent(t)}`:"";return`${ot}/submissions/${e}${n}`}function It(e,t){if(!e.jsonOutput)return;let n=Pe.resolve(e.jsonOutput),i={...t,url:t.url||t.dashboardUrl||Bt(t.submitId,t.projectId),updatedAt:new Date().toISOString()};try{let r=Pe.dirname(n);r&&r!=="."&&oe.mkdirSync(r,{recursive:!0}),oe.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){Us.warn(ie.yellow(`Could not write submission metadata JSON: ${r.message}`))}}function ku(e,t){return t&&e.find(n=>n.credentialId===t||n.id===t||n.keyId===t||n.meta?.keyId===t)||null}function Tu(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 Nu(){return process.env.CI==="true"||process.env.CI==="1"||!process.stdin.isTTY}function $r(e){return new Promise(t=>setTimeout(t,e))}function xu(e){return/^[a-zA-Z0-9_./:=@-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function Lu(e,t){if(e.submit?.[t]?.android?.package)return e.submit[t].android.package;let n=vo(e,t);if(n)return n;let i=Pe.join(process.cwd(),"app.json");if(oe.existsSync(i))try{return JSON.parse(oe.readFileSync(i,"utf-8")).expo?.android?.package}catch{}let r=Pe.join(process.cwd(),"app.config.json");if(oe.existsSync(r))try{let o=JSON.parse(oe.readFileSync(r,"utf-8"));return o.expo?.android?.package||o.android?.package}catch{}}function Mu(e,t){let n=e.filter(o=>ii(o)===t);if(n.length>0)return n;let i=e.filter(o=>{let s=ii(o);return!s||s==="*"});return e.length>0&&e.length===i.length?i:[]}function Uu(e,t){return e.submit?.[t]?.ios?.bundleIdentifier?e.submit[t].ios.bundleIdentifier:e.submit?.[t]?.ios?.bundleId?e.submit[t].ios.bundleId:Ro(e,t)}function Fu(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 Bu(e,t,n){let i=n||e.submit?.[t]?.android?.releaseStatus||e.submit?.production?.android?.releaseStatus||"completed";return ju(i)}function ju(e){let t=Eu[String(e).trim().toLowerCase()];if(!t)throw new Error(`Invalid Android release status "${e}". Use completed, draft, halted, or inProgress.`);return t}function Hu(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 Gu(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 Vu(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 Ku(e,t,n,i){let r=n.buildId?"id":n.latest?"latest":null;if(!r){let s=await wr({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(Et(s))return _r("Operation cancelled"),null;r=s}if(r==="local"){let s=await _n({message:"Enter path to artifact (.ipa/.aab):",validate:l=>{if(!oe.existsSync(l))return"File not found";if(t==="ios"&&!l.endsWith(".ipa"))return"Must be an .ipa file";if(t==="android"&&!l.endsWith(".aab"))return"Must be an .aab file"}});return Et(s)?null:{filePath:s,source:"local"}}let o=wt();if(r==="latest"){let s=n.profile||n.buildProfile;o.start(`Fetching latest${s?` ${s}`:""} build...`);try{let l=await N.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(),u=w=>w.platform?.toLowerCase()===t.toLowerCase()&&w.status?.toLowerCase()==="success",c=w=>d?[w.buildProfile,w.profile,w.profileName,w.buildType].filter(Boolean).some(U=>String(U).toLowerCase()===d):!0,p=a.filter(w=>u(w)&&c(w)),f=p.find(w=>w.buildType?.toLowerCase()==="store"||w.distribution?.toLowerCase()==="store")||p[0],g=a.some(w=>w.platform?.toLowerCase()===t.toLowerCase()&&w.status?.toLowerCase()==="success");if(!f)return o.stop("No suitable build found"),de(s&&g?`No successful ${t} builds found for profile "${s}".`:"No successful builds found for this platform."),null;o.stop(`Found build: ${f.buildId}`);let y=f.artifacts||[];if(y.length===0||y.every(w=>!(w.url||w.downloadUrl)))try{let w=await N.get(`/builds/${e}/${f.buildId}/artifacts`);w.data.status==="success"&&w.data.artifacts?.length>0?(y=w.data.artifacts.map(U=>({...U,url:U.url||U.downloadUrl})),console.log(ie.cyan(` [RECOVERY] Fetched ${y.length} artifact(s) with download URLs.`))):console.log(ie.yellow(" [RECOVERY] /artifacts endpoint returned 0 artifacts."))}catch(w){console.log(ie.red(` [RECOVERY] /artifacts fetch failed: ${w.message}`))}let _=t==="ios",I=y.find(w=>{let U=(w.type||"").toLowerCase(),V=(w.name||"").toLowerCase();if(console.log(ie.dim(` - Checking: ${w.name} (Type: ${w.type}, HasLink: ${!!(w.url||w.downloadUrl)})`)),U)return U===(_?"ipa":"aab");let J=_?".ipa":".aab",A=(w.url||w.downloadUrl||"").toLowerCase();return V.endsWith(J)||A.includes(J)});if(!I||!(I.url||I.downloadUrl))return de("Build found but artifact URL is missing."),null;let T=I.url||I.downloadUrl;return{filePath:await Ar(T,_?"ios":"android"),buildId:f.buildId,artifactName:I.name,source:"latest"}}catch(l){return o.stop("Fetch failed"),de(`API Error: ${l.message}`),null}}if(r==="id"){let s=n.buildId||await _n({message:"Enter Build ID:",validate:a=>a.length<5?"Invalid ID":void 0});if(Et(s))return null;let l=String(s);o.start("Fetching build...");try{let a=null;try{let f=await N.get(`/builds/${e}/${l}`);f.data.status==="success"&&(a=f.data.build)}catch(f){f.response?.status!==404&&console.log(ie.dim(` [RECOVERY] Project build lookup skipped: ${f.message}`))}if(!a){let f=await N.get(`/build/${l}`);if(f.data.status!=="success")throw new Error(f.data.message);a=f.data.build}if(!a)throw new Error(`Build ${l} was not found.`);let d=t==="ios",u=ni(a.artifacts);zu(u)||(u=await Ns(e,l,u));let c=Ts(u,t);if(c||(u=await Ns(e,l,u),c=Ts(u,t)),!c)throw new Error(`No ${d?".ipa":".aab"} artifact found for build ${l}. The build exists, but its artifact list does not contain a downloadable submission artifact.`);let p=c.url||c.downloadUrl;if(!p)throw new Error(`Artifact ${c.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 Ar(p,d?"ios":"android"),buildId:a.buildId||l,artifactName:c.name,source:"id"}}catch(a){throw o.stop("Fetch failed"),a}}if(r==="url"){let s=await _n({message:"Enter Artifact URL:",validate:l=>l.startsWith("http")?void 0:"Must be a valid URL"});return Et(s)?null:{filePath:await Ar(s,t),source:"url"}}return null}function ni(e){return(e||[]).map(t=>({...t,url:t.url||t.downloadUrl}))}function zu(e){return e.some(t=>!!(t.url||t.downloadUrl))}function Ts(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 Wu(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 Ns(e,t,n){try{let i=await N.get(`/builds/${e}/${t}/artifacts`);if(i.data.status==="success"&&i.data.artifacts?.length>0){let r=ni(i.data.artifacts);return console.log(ie.cyan(` [RECOVERY] Fetched ${r.length} artifact(s) with download URLs.`)),r}}catch(i){console.log(ie.dim(` [RECOVERY] Project artifact lookup skipped: ${i.message}`))}try{let i=await N.get(`/public/builds/${t}`);if(i.data.status==="success"&&i.data.artifacts?.length>0){let r=ni(i.data.artifacts);return console.log(ie.cyan(` [RECOVERY] Fetched ${r.length} public artifact(s) with download URLs.`)),r}}catch(i){console.log(ie.dim(` [RECOVERY] Public artifact lookup skipped: ${i.message}`))}return ni(n)}async function Ar(e,t,n=3){let i=wt();i.start("Downloading artifact...");let r=oe.mkdtempSync(Pe.join(jt.tmpdir(),`${m.nameLower}-artifact-`)),o=`app.${t==="ios"?"ipa":"aab"}`,s=Pe.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=oe.createWriteStream(s),d=await Fs({url:e,method:"GET",responseType:"stream",timeout:6e4});return await new Promise((u,c)=>{d.data.pipe(a);let p=!1;d.data.on("error",f=>{p||(p=!0,a.close(),c(f))}),a.on("finish",()=>{p||u()}),a.on("error",f=>{p||(p=!0,c(f))})}),i.stop("Download complete"),s}catch(a){if(l===n)throw i.stop("Download failed"),a}throw new Error("Download failed after retries")}async function Ju(e,t,n,i,r){let o=wt();if(r&&Ae(`Bundle ID: ${ie.green(r)}`),!n||!i)throw de(`Missing credentials: issuerId=${n}, keyId=${i}. Check your Dashboard.`),new Error("Missing ASC API Key Metadata (IssuerID or KeyID)");let s=Hs(t,n,i),l=np();return o.start("Uploading to TestFlight (pilot)..."),new Promise((a,d)=>{let u=rp(),c=Su(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});c.stdout?.on("data",p=>u.append(p,process.stdout)),c.stderr?.on("data",p=>u.append(p,process.stderr)),c.on("close",p=>{if(u.flush(),p!==0){o.stop("Pilot failed");try{oe.unlinkSync(s)}catch{}d(op(p,u.lines()))}else{o.stop("IPA uploaded to TestFlight");try{oe.unlinkSync(s)}catch{}a({})}}),c.on("error",p=>{u.flush();try{oe.unlinkSync(s)}catch{}o.stop("Pilot execution error");let f=fp(p);f.logs=u.lines(),d(f)})})}async function Yu(e,t,n,i,r,o){let s=wt();if(r&&Ae(`Bundle ID: ${ie.green(r)}`),!n||!i)throw de(`Missing credentials: issuerId=${n}, keyId=${i}. Check your Dashboard.`),new Error("Missing ASC API Key Metadata (IssuerID or KeyID)");let l=Hs(t,n,i),a=`${o.sshUser}@${o.sshHost}`,d=qu(o),u=Xu(o),c="",p="";try{if(s.start(`Preparing remote iOS submit runner (${a})...`),c=Zu("ssh",[...d,"mktemp -d /tmp/mach-submit.XXXXXX"]).trim(),!c)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..."),Er("scp",[...u,e,`${a}:${c}/app.ipa`],"IPA upload to remote runner"),Er("scp",[...u,l,`${a}:${c}/api_key.json`],"ASC key upload to remote runner"),p=Pe.join(jt.tmpdir(),`${m.nameLower}-ios-submit-${Date.now()}.sh`),oe.writeFileSync(p,Qu(c)),Er("scp",[...u,p,`${a}:${c}/submit.sh`],"submit script upload to remote runner"),s.stop("Remote submit inputs uploaded"),s.start("Uploading to TestFlight on remote runner...");let f=`chmod +x ${$n(`${c}/submit.sh`)} && bash ${$n(`${c}/submit.sh`)}`,g=Ft("ssh",[...d,f],{stdio:"inherit"});if(g.error)throw Pr("ssh",g.error);if(g.status!==0)throw new Error(`Remote iOS submit failed with exit code ${g.status}.`);return s.stop("IPA uploaded to TestFlight"),{apiKeyJsonPath:null}}catch(f){throw s.stop("Remote iOS submit failed"),f}finally{try{oe.unlinkSync(l)}catch{}if(p)try{oe.unlinkSync(p)}catch{}if(c)try{Ft("ssh",[...d,`rm -rf ${$n(c)}`],{stdio:"ignore"})}catch{}}}function Hs(e,t,n){let i=oe.readFileSync(e,"utf8"),r;try{r=Rr.createPrivateKey(i).export({type:"pkcs8",format:"pem"})}catch{Ae("Key normalization failed, falling back to manual re-wrapping..."),r=`-----BEGIN PRIVATE KEY-----
|
|
1421
|
+
`),null)}function pu(e,t){let i=(pr("aapt",["dump","badging",e])||pr("aapt2",["dump","badging",e]))?.match(/package:\s+name='([^']+)'/);if(i?.[1])return i[1];let o=pr("apkanalyzer",["manifest","application-id",e])?.split(/\s+/).find(Boolean);return o||(x.appendFileSync(t,`[WARN] Could not determine Android application id from APK; post-run uninstall will be skipped.
|
|
1422
|
+
`),null)}function pr(e,t){for(let n of fu(e)){let i=qe(n,t,{encoding:"utf-8",env:process.env,maxBuffer:10485760});if(i.status===0&&i.stdout)return String(i.stdout).trim()}return null}function fu(e){let t=process.platform==="win32"&&!e.endsWith(".exe")?`${e}.exe`:e,n=[];if(e==="aapt"||e==="aapt2")for(let r of Ss()){let o=G.join(r,"build-tools");for(let s of bs(o))n.push(G.join(o,s,t))}if(e==="apkanalyzer")for(let r of Ss()){n.push(G.join(r,"cmdline-tools","latest","bin",t));let o=G.join(r,"cmdline-tools");for(let s of bs(o))n.push(G.join(o,s,"bin",t));n.push(G.join(r,"tools","bin",t))}let i=mu(e);return i&&n.unshift(i),n.push(t),[...new Set(n)]}function Ss(){let e=[process.env.ANDROID_HOME,process.env.ANDROID_SDK_ROOT];return process.platform==="darwin"?e.push(G.join(en.homedir(),"Library","Android","sdk")):process.platform==="linux"&&e.push(G.join(en.homedir(),"Android","Sdk"),G.join(en.homedir(),"Android","sdk"),"/opt/android-sdk","/usr/lib/android-sdk"),[...new Set(e.filter(t=>!!t))]}function bs(e){try{return x.readdirSync(e,{withFileTypes:!0}).filter(t=>t.isDirectory()).map(t=>t.name).sort((t,n)=>n.localeCompare(t,void 0,{numeric:!0}))}catch{return[]}}function mu(e){let t=process.platform==="win32"?"where":"/usr/bin/env",n=process.platform==="win32"?[e]:["which",e],i=qe(t,n,{encoding:"utf-8",env:process.env});return i.status!==0||!i.stdout?null:String(i.stdout).split(`
|
|
1423
|
+
`)[0]?.trim()||null}async function fr(e,t,n){if(!x.existsSync(e))return;let i=x.readFileSync(e),r;for(let o=1;o<=3;o+=1)try{await In.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,!$s(s)||o>=3)break;await br(2e3*o)}throw r}async function As(e,t,n,i){let r=G.join(n,"report.xml"),o=G.join(t,"artifacts.tar.gz");try{await fr(r,e.junitUploadUrl,"application/xml")}catch(s){x.appendFileSync(i,`[WARN] Failed to upload JUnit report: ${s.message||s}
|
|
1424
|
+
`)}try{await fr(i,e.logUploadUrl,"text/plain")}catch(s){x.appendFileSync(i,`[WARN] Failed to upload runner log: ${s.message||s}
|
|
1425
|
+
`)}try{yt("tar",["-czf",o,"-C",t,G.basename(n)],i),await fr(o,e.artifactsUploadUrl,"application/gzip")}catch(s){x.appendFileSync(i,`[WARN] Failed to upload Maestro artifacts: ${s.message||s}
|
|
1426
|
+
`)}}function gu(e){if(!e.endsWith(".apk"))return F.error(j.red("Local Android Maestro runs need an APK artifact.")),!1;F.info(j.dim("Installing APK on local Android device/emulator..."));let t=qe("adb",["install","-r",e],{stdio:"inherit",env:process.env});return t.error?(F.error(j.red(`adb failed to start: ${t.error.message}`)),!1):t.status!==0?(F.error(j.red(`adb install failed with exit code ${t.status??1}`)),!1):!0}function hu(e,t){if(e.endsWith(".ipa"))return F.error(j.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=G.join(t,"ios-app");x.mkdirSync(r,{recursive:!0}),new oi(e).extractAllTo(r,!0);let o=Ar(r);if(!o)return F.error(j.red("Could not find a .app bundle inside the downloaded zip.")),!1;n=o}if(!n.endsWith(".app"))return F.error(j.red("Local iOS Maestro runs need an iOS Simulator .app bundle or .app.zip artifact.")),!1;F.info(j.dim("Installing app on booted iOS Simulator..."));let i=qe("xcrun",["simctl","install","booted",n],{stdio:"inherit",env:process.env});return i.error?(F.error(j.red(`xcrun failed to start: ${i.error.message}`)),!1):i.status!==0?(F.error(j.red(`iOS Simulator install failed with exit code ${i.status??1}`)),!1):!0}function Ar(e){let t=x.readdirSync(e,{withFileTypes:!0});for(let n of t){let i=G.join(e,n.name);if(n.isDirectory()&&n.name.endsWith(".app"))return i;if(n.isDirectory()){let r=Ar(i);if(r)return r}}return null}function yu(e,t){let n=String(t||"").toLowerCase();return n==="android"?e.find(i=>Qt(i,".apk")):n==="ios"?e.find(i=>Qt(i,".app.zip"))||e.find(i=>Qt(i,".zip")):e.find(i=>Qt(i,".apk"))||e.find(i=>Qt(i,".app.zip"))||e.find(i=>Qt(i,".zip"))}function Qt(e,t){return String(e?.name||e?.downloadUrl||e?.url||"").toLowerCase().endsWith(t)}function Er(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 Cs(e){if(e)try{return G.basename(new URL(e).pathname)||void 0}catch{return G.basename(e)||void 0}}function Su(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 ks(e,t){if(!e.jsonOutput)return;let n=G.resolve(e.jsonOutput),i={...t,updatedAt:new Date().toISOString()};try{let r=G.dirname(n);r&&r!=="."&&x.mkdirSync(r,{recursive:!0}),x.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){F.warn(j.yellow(`Could not write Maestro metadata JSON: ${r.message}`))}}function bu(e,t){if(!e.jsonOutput)return;let n=G.resolve(e.jsonOutput),i={mode:"local",...t,updatedAt:new Date().toISOString()};try{let r=G.dirname(n);r&&r!=="."&&x.mkdirSync(r,{recursive:!0}),x.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){F.warn(j.yellow(`Could not write Maestro metadata JSON: ${r.message}`))}}import{spinner as vt,text as _n,select as Rr,isCancel as It,cancel as Pr,log as Hs}from"@clack/prompts";import ne from"chalk";import oe from"fs";import Pe from"path";import{spawn as vu,spawnSync as jt}from"child_process";import Gs from"axios";import Gt from"os";import Cr from"crypto";import Au from"crypto";import tn from"axios";import Ts from"fs";var $n=6e4,Eu=12e4,Ir=4,vn=e=>encodeURIComponent(e),Iu=e=>new Promise(t=>setTimeout(t,e));async function nn(e,t){let n;for(let i=1;i<=Ir;i++)try{return await t()}catch(r){if(n=r,i>=Ir||!wu(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}/${Ir}); retrying in ${Math.round(s/1e3)}s...`),await Iu(s)}throw n}function wu(e){let t=e.response?.status;return t?t===408||t===409||t===425||t===429||t>=500:!0}async function xs(e){let{packageName:t,serviceAccount:n,aabPath:i,track:r,releaseStatus:o,userFraction:s,changesNotSentForReview:l}=e,a;try{let u={Authorization:`Bearer ${await Ns(n)}`,Connection:"close"},c=vn(t);if(a=(await nn("create edit",()=>tn.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${c}/edits`,{},{headers:u,timeout:$n}))).data.id,!a)throw new Error("Google Play edit insert succeeded but did not return an edit id.");let f=vn(a),g=Ts.statSync(i),y=await nn("upload AAB",()=>tn.post(`https://androidpublisher.googleapis.com/upload/androidpublisher/v3/applications/${c}/edits/${f}/bundles`,Ts.createReadStream(i),{headers:{...u,"Content-Type":"application/octet-stream","Content-Length":g.size},maxBodyLength:1/0,maxContentLength:1/0,params:{uploadType:"media"},timeout:Eu})),h=Number(y.data.versionCode);if(!h)throw new Error("Google Play upload succeeded but did not return a versionCode.");let v={versionCodes:[String(h)],status:o};return(o==="inProgress"||o==="halted")&&typeof s=="number"&&(v.userFraction=s),await nn("update track",()=>tn.put(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${c}/edits/${f}/tracks/${vn(r)}`,{releases:[v]},{headers:u,timeout:$n})),await nn("commit edit",()=>tn.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${c}/edits/${f}:commit`,{},{headers:u,params:l?{changesNotSentForReview:!0}:void 0,timeout:$n})),{editId:a,versionCode:h,track:r,releaseStatus:o,userFraction:s}}catch(d){if(a)try{let c=await Ns(n);await nn("delete edit",()=>tn.delete(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${vn(t)}/edits/${vn(a)}`,{headers:{Authorization:`Bearer ${c}`,Connection:"close"},timeout:$n}))}catch{}let u=d.response?.data?.error?.message||d.message;throw new Error(`Google Play API Error: ${u}`)}}async function Ns(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=Au.createSign("RSA-SHA256");a.update(l);let d=a.sign(e.private_key,"base64url"),u=`${l}.${d}`;return(await nn("OAuth token exchange",()=>tn.post("https://oauth2.googleapis.com/token",{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:u},{headers:{Connection:"close"},timeout:$n}))).data.access_token}var $u=5e3,_u=12,Vs=100,wr=24,Ls=8e3,Ru={completed:"completed",draft:"draft",halted:"halted",inprogress:"inProgress","in-progress":"inProgress"},Pu=e=>e?.type==="google_service_account",ai=e=>e?.bundleId||e?.packageName||e?.meta?.packageName||e?.meta?.bundleId,Ks=e=>e.submitArgs||process.argv.slice(3).join(" ");async function li(e){let t=vt(),n=ke(),i=Du(e);if(!i){process.exitCode=1;return}let r=e.projectId||i.projectId,o=e.profile||e.buildProfile||"production";if(!r){ue(`${m.configFileName} is missing projectId. Pass --project-id in runner mode.`),process.exitCode=1;return}i.projectId=r,Ae(ne.dim(`Submit for project: ${i.name||r} | Profile: ${o}`));let s=e.platform;if(!s){let S=await Rr({message:"Select platform to submit:",options:[{value:"ios",label:"iOS (App Store Connect / TestFlight)"},{value:"android",label:"Android (Google Play Console)"}]});if(It(S)){Pr("Operation cancelled");return}s=S}if(s=String(s).toLowerCase(),s!=="ios"&&s!=="android"){ue(`Platform ${s} is not supported. Use 'ios' or 'android'.`),process.exitCode=1;return}let l=s==="ios"&&!e.local&&e.sshHost?Ku(i,o,e):null;if(s==="ios"&&!e.local&&!l){await Ou(i,o,e);return}let a=e.submitId,d=!!(e.local&&a),u=a||null,c=async(S,R={})=>{u&&await Nu(r,u,{status:S,...R})},p=s==="android"?e.packageName||e.androidPackage||Hu(i,o):void 0,f=s==="ios"?e.bundleId||e.iosBundleIdentifier||Vu(i,o):void 0,g,y,h,v=!1;try{s==="android"&&(g=e.track||i.submit?.[o]?.android?.track||i.submit?.production?.android?.track||"internal",y=zu(i,o,e.releaseStatus),h=Ju(i,o,e.rollout),v=Yu(i,o,e.changesNotSentForReview),qu(y,h))}catch(S){ue(S.message),process.exitCode=1;return}if(s==="android"&&!d&&(u=await Cu(i,r,s,o,e,{packageName:p,track:g,releaseStatus:y,rollout:h,changesNotSentForReview:v}),!u)){ue("Could not create submission tracking record. Submission was not started."),process.exitCode=1;return}await c("running",{platform:s,profile:o,packageName:p,track:g,releaseStatus:y,rollout:h,startTime:Date.now(),...d?Lu():{}});let I=null,N=null;try{N=await Xu(r,s,e,n?.token),I=N?.filePath||null}catch(S){await c("failed",{error:`Failed to resolve submission artifact: ${S.message}`,endTime:Date.now()}),ue(`Failed to resolve submission artifact: ${S.message}`),process.exitCode=1;return}if(!I){let S=Qu(s,e);await c("failed",{error:S,endTime:Date.now()}),ue(S),process.exitCode=1;return}await c("running",{buildId:N?.buildId,artifactName:N?.artifactName,artifactSource:N?.source}),Ae(`Using artifact: ${ne.green(Pe.basename(I))} `),t.start("Fetching submission credentials from Dashboard...");let w;try{let R=(await k.get(`/credentials/${r}`)).data.credentials||[];if(s==="android"&&!p){t.stop("Package name missing"),ue("Could not resolve Android package name. Set android.package in mach.config.json/app.json."),await c("failed",{error:"Could not resolve Android package name.",endTime:Date.now()}),process.exitCode=1;return}let M=R.filter(Pu),B=s==="ios"?R.filter(K=>K.type==="asc_api_key"):Gu(M,p);if(B.length===0){if(t.stop("Credentials missing"),ue(s==="android"?`No Google Play service credential found for package ${p}.`:`No Service Credentials found for ${s}.`),s==="android"){let K=M.map(ai).filter(Boolean).join(", ");K&&Ae(`Found Google Play service credential(s) for: ${K}`),Ae(`Use '${m.nameLower} credentials:service --platform android --package-name ${p}' or upload it under that package in the Dashboard.`)}else Ae(`Use '${m.nameLower} credentials:service --platform ${s}' or use the Dashboard to upload them.`);await c("failed",{error:`No submission credentials found for ${s}.`,endTime:Date.now()}),process.exitCode=1;return}if(w=Uu(B,e.credentialId),!w&&s==="ios"&&f&&(w=Fu(B,f)),w||B.length===1)w=w||B[0],t.stop(`Using: ${w.name}`),s==="android"&&ai(w)==="*"&&Ae(ne.yellow(`Using legacy wildcard Google Play credential for ${p}. Upload a package-scoped credential when possible.`));else{if(t.stop("Multiple credentials found"),Bu()){let z=B.map(Q=>`${Q.name||"credential"} (${Q.credentialId||Q.id||"no-id"})`).join(", ");ue(`Multiple ${s==="ios"?"App Store Connect":"Google Play"} credentials found. Use --credential-id in CI. Available: ${z}`),await c("failed",{error:"Multiple submission credentials found; --credential-id is required in CI.",endTime:Date.now()}),process.exitCode=1;return}let K=await Rr({message:`Choose a ${s==="ios"?"App Store Connect":"Google Play"} credential:`,options:B.map(z=>({value:z.credentialId,label:z.name,hint:`${z.keyId?`ID: ${z.keyId}`:""} ${z.issuerId?`(Issuer: ${z.issuerId.substring(0,8)}...)`:""}`}))});if(It(K)){Pr("Submission cancelled"),await c("failed",{error:"Submission cancelled while selecting credential.",endTime:Date.now()}),process.exitCode=1;return}w=B.find(z=>z.credentialId===K),Ae(`Using selected: ${ne.green(w.name)}`)}}catch(S){t.stop("Failed to fetch credentials"),ue(`API Error: ${S.message} `),await c("failed",{error:`Failed to fetch credentials: ${S.message}`,endTime:Date.now()}),process.exitCode=1;return}let U=oe.mkdtempSync(Pe.join(Gt.tmpdir(),`${m.nameLower}-submit-`)),V=w.keyId||w.meta?.keyId,J=w.issuerId||w.meta?.issuerId,A=w.type==="asc_api_key"?`AuthKey_${V}.p8`:"service-account.json",_=Pe.join(U,A);t.start("Downloading secure key...");try{let S=await k.get(`/credentials/${w.credentialId}/download`,{params:{projectId:r,format:"raw"}});if(S.data.status!=="success"||!S.data.downloadUrl)throw new Error("Failed to get secure download URL");let R=await Gs.get(S.data.downloadUrl,{responseType:"arraybuffer"});oe.writeFileSync(_,Buffer.from(R.data)),t.stop("Key downloaded to secure temp storage")}catch(S){t.stop("Download failed"),ue(`Failed to download key: ${S.message}`);try{oe.rmSync(U,{recursive:!0,force:!0})}catch{}await c("failed",{error:`Failed to download credential key: ${S.message}`,endTime:Date.now()}),process.exitCode=1;return}Ae(ne.blue(`Initiating ${s==="ios"?"TestFlight":"Google Play"} submission...`));let L=!1,P;try{if(s==="ios"){if(!V){let R=await _n({message:"Enter App Store Connect Key ID (e.g. 2X948D...):",validate:M=>M.length>0?void 0:"Key ID is required"});if(It(R)){await c("failed",{error:"Submission cancelled while entering ASC Key ID.",endTime:Date.now()}),process.exitCode=1;return}V=R}if(!J||J==="undefined"){let R=await _n({message:"Enter App Store Connect Issuer ID (Found on ASC Keys page):",validate:M=>M.length>0?void 0:"Issuer ID is required"});if(It(R)){await c("failed",{error:"Submission cancelled while entering ASC Issuer ID.",endTime:Date.now()}),process.exitCode=1;return}J=R}Ae(`Using ASC Key ID: ${V}`),Ae(`Using ASC Issuer ID: ${J}`);let S=l?await tp(I,_,J,V,f,l):await ep(I,_,J,V,f);Or(`${s==="ios"?"App Store":"Google Play"} submission successful!`),L=!0}else P=await sp(I,_,g||"internal",p,y||"completed",h,v,o),Or("Google Play submission successful!"),L=!0}catch(S){ue(`Submission failed: ${S.message}`),await c("failed",{error:S.message,endTime:Date.now()}),wt(e,{status:"failed",projectId:r,submitId:u,platform:s,profile:o,buildId:N?.buildId||e.buildId,artifactName:N?.artifactName,error:S.message,dashboardUrl:u?Ht(u,r):void 0}),process.exitCode=1}finally{L&&(await c("success",{endTime:Date.now(),versionCode:P?.versionCode,track:g,releaseStatus:y}),wt(e,{status:"success",projectId:r,submitId:u,platform:s,profile:o,buildId:N?.buildId||e.buildId,artifactName:N?.artifactName,versionCode:P?.versionCode,track:g,releaseStatus:y,dashboardUrl:u?Ht(u,r):void 0})),Ep(U),I&&I.includes(`${m.nameLower}-artifact-`)}}function Du(e){let t=`./${m.configFileName}`;if(oe.existsSync(t))try{return JSON.parse(oe.readFileSync(t,"utf-8"))}catch(n){return ue(`Failed to read ${m.configFileName}: ${n.message}`),null}return e.projectId?{projectId:e.projectId}:(ue(`No ${m.configFileName} found. Run \`${m.nameLower} init\` or \`${m.nameLower} link\` first.`),null)}async function Ou(e,t,n){let i=n.projectId||e.projectId;if(!i){ue(`${m.configFileName} is missing projectId.`),process.exitCode=1;return}let r=n.submitId||Cr.randomUUID(),o=!!n.latest||!n.buildId,s=ku({...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:Ks(n),runnerArgs:s,runnerCommand:[m.nameLower,"submit",...s].map(ju).join(" "),appName:e.name,startTime:Date.now()},a=vt();a.start("Queuing iOS submit on macOS runner...");try{let d=await k.post("/submissions",l),u=d.data?.submission||d.data?.submit||{},c=d.data?.dashboardUrl||Ht(r,i);a.stop("iOS submit queued"),Ae(`Submission ID: ${ne.cyan(r)}`),Ae(`Dashboard: ${ne.blue.underline(c)}`),wt(n,{status:"pending",projectId:i,submitId:r,platform:"ios",profile:t,latest:o,buildId:n.buildId,dashboardUrl:c}),await Tu(i,r,n)}catch(d){a.stop("Could not queue iOS submit"),ue(Mu(d)),process.exitCode=1}}async function Cu(e,t,n,i,r,o={}){let s=r.submitId||Cr.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:Ks(r),appName:e.name,startTime:Date.now(),...o};try{let d=await k.post("/submissions",a),u=d.data?.submission||d.data?.submit||{},c=d.data?.dashboardUrl||u.dashboardUrl||Ht(s,t);return Ae(`Submission ID: ${ne.cyan(s)}`),Ae(`Dashboard: ${ne.blue.underline(c)}`),wt(r,{status:"running",projectId:t,submitId:s,platform:n,profile:i,latest:l,buildId:r.buildId,dashboardUrl:c}),s}catch(d){let u=d.response?.data?.message||d.response?.data?.error||d.message;return Ae(ne.yellow(`Could not create submission tracking record: ${u}`)),null}}function ku(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 Tu(e,t,n){let i=vt(),r=0,o=0;for(n.quiet||i.start("Waiting for iOS submit runner...");;)try{let s=await k.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 u=o;u<d.length;u++){let c=d[u];c&&console.log(ne.dim(String(c)))}if(o=d.length,["success","completed","succeeded"].includes(a)){n.quiet||i.stop("iOS submit completed"),Or("App Store submission successful!"),wt(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||Ht(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.";ue(u),wt(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||Ht(t,e)}),process.exitCode=1;return}n.quiet||i.message(`iOS submit ${a}...`),await Dr($u)}catch(s){if(r++,r>=_u){n.quiet||i.stop("Lost connection to iOS submit status"),ue(`Could not fetch iOS submit status after ${r} attempts: ${s.message}`),process.exitCode=1;return}await Dr(Math.min(2e3*r,15e3))}}async function Nu(e,t,n){let i;for(let r=1;r<=3;r++)try{await k.patch(`/submissions/${e}/${t}`,n);return}catch(o){if(i=o,r>=3||!xu(o))break;await Dr(1e3*r)}Hs.warn(ne.dim(`Could not report submission status: ${i?.message||i}`))}function xu(e){let t=e.response?.status;return!t||t===408||t===409||t===425||t===429||t>=500}function Lu(){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 Mu(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(`
|
|
1427
|
+
`):n||e.message||String(e)}function Ht(e,t){if(!e)return ot;let n=t?`?projectId=${encodeURIComponent(t)}`:"";return`${ot}/submissions/${e}${n}`}function wt(e,t){if(!e.jsonOutput)return;let n=Pe.resolve(e.jsonOutput),i={...t,url:t.url||t.dashboardUrl||Ht(t.submitId,t.projectId),updatedAt:new Date().toISOString()};try{let r=Pe.dirname(n);r&&r!=="."&&oe.mkdirSync(r,{recursive:!0}),oe.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){Hs.warn(ne.yellow(`Could not write submission metadata JSON: ${r.message}`))}}function Uu(e,t){return t&&e.find(n=>n.credentialId===t||n.id===t||n.keyId===t||n.meta?.keyId===t)||null}function Fu(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 Bu(){return process.env.CI==="true"||process.env.CI==="1"||!process.stdin.isTTY}function Dr(e){return new Promise(t=>setTimeout(t,e))}function ju(e){return/^[a-zA-Z0-9_./:=@-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function Hu(e,t){if(e.submit?.[t]?.android?.package)return e.submit[t].android.package;let n=Zn(e,t);if(n)return n;let i=Pe.join(process.cwd(),"app.json");if(oe.existsSync(i))try{return JSON.parse(oe.readFileSync(i,"utf-8")).expo?.android?.package}catch{}let r=Pe.join(process.cwd(),"app.config.json");if(oe.existsSync(r))try{let o=JSON.parse(oe.readFileSync(r,"utf-8"));return o.expo?.android?.package||o.android?.package}catch{}}function Gu(e,t){let n=e.filter(o=>ai(o)===t);if(n.length>0)return n;let i=e.filter(o=>{let s=ai(o);return!s||s==="*"});return e.length>0&&e.length===i.length?i:[]}function Vu(e,t){return e.submit?.[t]?.ios?.bundleIdentifier?e.submit[t].ios.bundleIdentifier:e.submit?.[t]?.ios?.bundleId?e.submit[t].ios.bundleId:Qn(e,t)}function Ku(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 zu(e,t,n){let i=n||e.submit?.[t]?.android?.releaseStatus||e.submit?.production?.android?.releaseStatus||"completed";return Wu(i)}function Wu(e){let t=Ru[String(e).trim().toLowerCase()];if(!t)throw new Error(`Invalid Android release status "${e}". Use completed, draft, halted, or inProgress.`);return t}function Ju(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 Yu(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 qu(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 Xu(e,t,n,i){let r=n.buildId?"id":n.latest?"latest":null;if(!r){let s=await Rr({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 Pr("Operation cancelled"),null;r=s}if(r==="local"){let s=await _n({message:"Enter path to artifact (.ipa/.aab):",validate:l=>{if(!oe.existsSync(l))return"File not found";if(t==="ios"&&!l.endsWith(".ipa"))return"Must be an .ipa file";if(t==="android"&&!l.endsWith(".aab"))return"Must be an .aab file"}});return It(s)?null:{filePath:s,source:"local"}}let o=vt();if(r==="latest"){let s=n.profile||n.buildProfile;o.start(`Fetching latest${s?` ${s}`:""} build...`);try{let l=await k.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(),u=w=>w.platform?.toLowerCase()===t.toLowerCase()&&w.status?.toLowerCase()==="success",c=w=>d?[w.buildProfile,w.profile,w.profileName,w.buildType].filter(Boolean).some(U=>String(U).toLowerCase()===d):!0,p=a.filter(w=>u(w)&&c(w)),f=p.find(w=>w.buildType?.toLowerCase()==="store"||w.distribution?.toLowerCase()==="store")||p[0],g=a.some(w=>w.platform?.toLowerCase()===t.toLowerCase()&&w.status?.toLowerCase()==="success");if(!f)return o.stop("No suitable build found"),ue(s&&g?`No successful ${t} builds found for profile "${s}".`:"No successful builds found for this platform."),null;o.stop(`Found build: ${f.buildId}`);let y=f.artifacts||[];if(y.length===0||y.every(w=>!(w.url||w.downloadUrl)))try{let w=await k.get(`/builds/${e}/${f.buildId}/artifacts`);w.data.status==="success"&&w.data.artifacts?.length>0?(y=w.data.artifacts.map(U=>({...U,url:U.url||U.downloadUrl})),console.log(ne.cyan(` [RECOVERY] Fetched ${y.length} artifact(s) with download URLs.`))):console.log(ne.yellow(" [RECOVERY] /artifacts endpoint returned 0 artifacts."))}catch(w){console.log(ne.red(` [RECOVERY] /artifacts fetch failed: ${w.message}`))}let v=t==="ios",I=y.find(w=>{let U=(w.type||"").toLowerCase(),V=(w.name||"").toLowerCase();if(console.log(ne.dim(` - Checking: ${w.name} (Type: ${w.type}, HasLink: ${!!(w.url||w.downloadUrl)})`)),U)return U===(v?"ipa":"aab");let J=v?".ipa":".aab",A=(w.url||w.downloadUrl||"").toLowerCase();return V.endsWith(J)||A.includes(J)});if(!I||!(I.url||I.downloadUrl))return ue("Build found but artifact URL is missing."),null;let N=I.url||I.downloadUrl;return{filePath:await vr(N,v?"ios":"android"),buildId:f.buildId,artifactName:I.name,source:"latest"}}catch(l){return o.stop("Fetch failed"),ue(`API Error: ${l.message}`),null}}if(r==="id"){let s=n.buildId||await _n({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 f=await k.get(`/builds/${e}/${l}`);f.data.status==="success"&&(a=f.data.build)}catch(f){f.response?.status!==404&&console.log(ne.dim(` [RECOVERY] Project build lookup skipped: ${f.message}`))}if(!a){let f=await k.get(`/build/${l}`);if(f.data.status!=="success")throw new Error(f.data.message);a=f.data.build}if(!a)throw new Error(`Build ${l} was not found.`);let d=t==="ios",u=si(a.artifacts);Zu(u)||(u=await Us(e,l,u));let c=Ms(u,t);if(c||(u=await Us(e,l,u),c=Ms(u,t)),!c)throw new Error(`No ${d?".ipa":".aab"} artifact found for build ${l}. The build exists, but its artifact list does not contain a downloadable submission artifact.`);let p=c.url||c.downloadUrl;if(!p)throw new Error(`Artifact ${c.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 vr(p,d?"ios":"android"),buildId:a.buildId||l,artifactName:c.name,source:"id"}}catch(a){throw o.stop("Fetch failed"),a}}if(r==="url"){let s=await _n({message:"Enter Artifact URL:",validate:l=>l.startsWith("http")?void 0:"Must be a valid URL"});return It(s)?null:{filePath:await vr(s,t),source:"url"}}return null}function si(e){return(e||[]).map(t=>({...t,url:t.url||t.downloadUrl}))}function Zu(e){return e.some(t=>!!(t.url||t.downloadUrl))}function Ms(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 Qu(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 Us(e,t,n){try{let i=await k.get(`/builds/${e}/${t}/artifacts`);if(i.data.status==="success"&&i.data.artifacts?.length>0){let r=si(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 k.get(`/public/builds/${t}`);if(i.data.status==="success"&&i.data.artifacts?.length>0){let r=si(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 si(n)}async function vr(e,t,n=3){let i=vt();i.start("Downloading artifact...");let r=oe.mkdtempSync(Pe.join(Gt.tmpdir(),`${m.nameLower}-artifact-`)),o=`app.${t==="ios"?"ipa":"aab"}`,s=Pe.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=oe.createWriteStream(s),d=await Gs({url:e,method:"GET",responseType:"stream",timeout:6e4});return await new Promise((u,c)=>{d.data.pipe(a);let p=!1;d.data.on("error",f=>{p||(p=!0,a.close(),c(f))}),a.on("finish",()=>{p||u()}),a.on("error",f=>{p||(p=!0,c(f))})}),i.stop("Download complete"),s}catch(a){if(l===n)throw i.stop("Download failed"),a}throw new Error("Download failed after retries")}async function ep(e,t,n,i,r){let o=vt();if(r&&Ae(`Bundle ID: ${ne.green(r)}`),!n||!i)throw ue(`Missing credentials: issuerId=${n}, keyId=${i}. Check your Dashboard.`),new Error("Missing ASC API Key Metadata (IssuerID or KeyID)");let s=zs(t,n,i),l=lp();return o.start("Uploading to TestFlight (pilot)..."),new Promise((a,d)=>{let u=dp(),c=vu(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});c.stdout?.on("data",p=>u.append(p,process.stdout)),c.stderr?.on("data",p=>u.append(p,process.stderr)),c.on("close",p=>{if(u.flush(),p!==0){o.stop("Pilot failed");try{oe.unlinkSync(s)}catch{}d(up(p,u.lines()))}else{o.stop("IPA uploaded to TestFlight");try{oe.unlinkSync(s)}catch{}a({})}}),c.on("error",p=>{u.flush();try{oe.unlinkSync(s)}catch{}o.stop("Pilot execution error");let f=bp(p);f.logs=u.lines(),d(f)})})}async function tp(e,t,n,i,r,o){let s=vt();if(r&&Ae(`Bundle ID: ${ne.green(r)}`),!n||!i)throw ue(`Missing credentials: issuerId=${n}, keyId=${i}. Check your Dashboard.`),new Error("Missing ASC API Key Metadata (IssuerID or KeyID)");let l=zs(t,n,i),a=`${o.sshUser}@${o.sshHost}`,d=np(o),u=ip(o),c="",p="";try{if(s.start(`Preparing remote iOS submit runner (${a})...`),c=rp("ssh",[...d,"mktemp -d /tmp/mach-submit.XXXXXX"]).trim(),!c)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..."),$r("scp",[...u,e,`${a}:${c}/app.ipa`],"IPA upload to remote runner"),$r("scp",[...u,l,`${a}:${c}/api_key.json`],"ASC key upload to remote runner"),p=Pe.join(Gt.tmpdir(),`${m.nameLower}-ios-submit-${Date.now()}.sh`),oe.writeFileSync(p,op(c)),$r("scp",[...u,p,`${a}:${c}/submit.sh`],"submit script upload to remote runner"),s.stop("Remote submit inputs uploaded"),s.start("Uploading to TestFlight on remote runner...");let f=`chmod +x ${Rn(`${c}/submit.sh`)} && bash ${Rn(`${c}/submit.sh`)}`,g=jt("ssh",[...d,f],{stdio:"inherit"});if(g.error)throw kr("ssh",g.error);if(g.status!==0)throw new Error(`Remote iOS submit failed with exit code ${g.status}.`);return s.stop("IPA uploaded to TestFlight"),{apiKeyJsonPath:null}}catch(f){throw s.stop("Remote iOS submit failed"),f}finally{try{oe.unlinkSync(l)}catch{}if(p)try{oe.unlinkSync(p)}catch{}if(c)try{jt("ssh",[...d,`rm -rf ${Rn(c)}`],{stdio:"ignore"})}catch{}}}function zs(e,t,n){let i=oe.readFileSync(e,"utf8"),r;try{r=Cr.createPrivateKey(i).export({type:"pkcs8",format:"pem"})}catch{Ae("Key normalization failed, falling back to manual re-wrapping..."),r=`-----BEGIN PRIVATE KEY-----
|
|
1428
1428
|
${(i.replace(/-----BEGIN[^-]*-----/g,"").replace(/-----END[^-]*-----/g,"").replace(/\s+/g,"").match(/.{1,64}/g)||[]).join(`
|
|
1429
1429
|
`)}
|
|
1430
|
-
-----END PRIVATE KEY-----`}let o=Pe.join(
|
|
1430
|
+
-----END PRIVATE KEY-----`}let o=Pe.join(Gt.tmpdir(),`api_key_${n}_${Date.now()}.json`),s={key_id:n,issuer_id:t,key:r,in_house:!1};return oe.writeFileSync(o,JSON.stringify(s,null,2)),o}function np(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 ip(e){let t=["-o","StrictHostKeyChecking=no","-o","ServerAliveInterval=30"];return e.sshKey&&t.push("-i",e.sshKey),t}function rp(e,t){let n=jt(e,t,{encoding:"utf-8",stdio:["ignore","pipe","inherit"]});if(n.error)throw kr(e,n.error);if(n.status!==0)throw new Error(`${e} failed with exit code ${n.status}.`);return n.stdout||""}function $r(e,t,n){let i=jt(e,t,{stdio:"inherit"});if(i.error)throw kr(e,i.error);if(i.status!==0)throw new Error(`${n} failed with exit code ${i.status}.`)}function kr(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 Rn(e){return`'${e.replace(/'/g,"'\\''")}'`}function op(e){let t=Rn(`${e}/app.ipa`),n=Rn(`${e}/api_key.json`);return`#!/bin/bash
|
|
1431
1431
|
set -euo pipefail
|
|
1432
1432
|
|
|
1433
1433
|
export PATH="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:$HOME/.local/share/fastlane/3.4.0/bin:$PATH"
|
|
@@ -1455,39 +1455,39 @@ fastlane pilot upload \\
|
|
|
1455
1455
|
--api_key_path ${n} \\
|
|
1456
1456
|
--skip_submission true \\
|
|
1457
1457
|
--skip_waiting_for_build_processing true
|
|
1458
|
-
`}async function
|
|
1458
|
+
`}async function sp(e,t,n="internal",i,r="completed",o,s=!1,l="production"){let a=vt();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 u=JSON.parse(oe.readFileSync(t,"utf-8"));ap(u);let c=await xs({packageName:i,serviceAccount:u,aabPath:e,track:n,releaseStatus:r,userFraction:o,changesNotSentForReview:s});return a.stop(`AAB uploaded to ${n} track (versionCode ${c.versionCode})`),c}catch(u){throw a.stop("Google Play upload failed"),new Error(Ap(u,n,i,l))}}function ap(e){if(!e?.client_email||!e?.private_key)throw new Error("Invalid Google service account JSON: missing client_email or private_key.")}function _r(){let e=process.env.HOME||Gt.homedir(),t=process.env.FASTLANE_GEM_HOME||Pe.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",Pe.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 lp(){let e=_r(),t=Fs(e);if(t)return t;if(process.env.MACH_SKIP_FASTLANE_INSTALL!=="1"){cp(e);let n=Fs(_r());if(n)return n}return{command:"fastlane",env:_r()}}function Fs(e){let t=process.env.HOME||Gt.homedir(),n=[process.env.FASTLANE_BINARY,"/usr/local/bin/fastlane","/opt/homebrew/bin/fastlane","/usr/local/Cellar/fastlane/2.227.0/libexec/bin/fastlane",Pe.join(process.env.FASTLANE_GEM_HOME||Pe.join(t,".local/share/fastlane/3.4.0"),"bin/fastlane"),"fastlane"].filter(Boolean);for(let i of n){if(i.includes("/")&&!oe.existsSync(i))continue;if(!jt(i,["--version"],{env:e,stdio:"ignore"}).error)return{command:i,env:e}}return null}function cp(e){let t=jt("gem",["--version"],{env:e,stdio:"ignore"});if(t.error||t.status!==0)return;let n=process.env.HOME||Gt.homedir(),i=process.env.FASTLANE_GEM_HOME||Pe.join(n,".local/share/fastlane/3.4.0"),r=Pe.join(i,"bin");oe.mkdirSync(r,{recursive:!0}),Ae(ne.dim("fastlane not found. Installing fastlane into the local Mach runner cache..."));let o=jt("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)&&Ae(ne.yellow("Automatic fastlane install failed; Mach will try PATH resolution once more."))}function dp(e=Vs){let t=[],n="",i=r=>{let o=Js(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 up(e,t){let n=new Error(pp(e,t));return n.logs=Ws(t),n.exitCode=e,n}function pp(e,t){let n=`fastlane pilot failed with exit code ${e??"unknown"}.`,i=fp(t);return i.length===0?n:`${n}
|
|
1459
1459
|
|
|
1460
1460
|
Fastlane output:
|
|
1461
1461
|
${i.join(`
|
|
1462
|
-
`)}`}function
|
|
1463
|
-
`),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
|
|
1464
|
-
`))}function
|
|
1462
|
+
`)}`}function fp(e){let t=Ws(e);if(t.length===0)return[];let n=Bs(t.filter(gp)),i=mp(t);if(i)return[i,...js(n,wr-1,Ls)];let r=n.length>0?n:t.slice(-wr);return js(Bs(r),wr,Ls)}function mp(e){let t=e.join(`
|
|
1463
|
+
`),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 gp(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 Bs(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 js(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 Ws(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=Js(r);o&&t.push(o)}}return t.slice(-Vs)}function Js(e){return yp(hp(e).trimEnd()).trim()}function hp(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 yp(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(Sp(i),"g"),"[REDACTED]"));return t}function Sp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function bp(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(`
|
|
1464
|
+
`))}function Ap(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(`
|
|
1465
1465
|
`);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(`
|
|
1466
1466
|
`);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(`
|
|
1467
1467
|
`);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(`
|
|
1468
1468
|
`);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(`
|
|
1469
1469
|
`);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(`
|
|
1470
|
-
`);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 gp(e){try{oe.existsSync(e)&&oe.rmSync(e,{recursive:!0,force:!0})}catch{}}function de(e){console.log(ie.red(`\u274C ${e}`))}function Ae(e){console.log(ie.gray(`\u2022 ${e}`))}function vr(e){console.log(ie.green(`\u2713 ${e}`))}var Dr=8,Sp=6,qs=Number(process.env.MACH_ARTIFACT_UPLOAD_MAX_ATTEMPTS||2),Or=Number(process.env.MACH_ARTIFACT_UPLOAD_TIMEOUT_MS||12e4),Cr="ap-south-1",bp=`${m.envPrefix}S3_DEBUG`,Ap=()=>["1","true","yes","on"].includes(String(process.env[bp]||"").trim().toLowerCase()),Nr=(e,t)=>{if(Ap()&&t)try{let n=new URL(t);O.info(C.dim(`[S3_DEBUG] ${e} host=${n.hostname} expectedRegion=${Cr}`)),n.hostname.includes(Cr)||O.warn(C.yellow(`[S3_DEBUG] ${e} host ${n.hostname} does not include ${Cr}`))}catch(n){O.warn(C.yellow(`[S3_DEBUG] Could not parse ${e} presigned URL host: ${n.message}`))}},Xs=new Set([".git",".gradle",".idea",".mach-cache",".expo",".turbo",".yarn/cache","build","builds","coverage","dist","node_modules",`${m.nameLower}_cli`,`.${m.nameLower}_cli`]),Ep=new Set(["android/.gradle","android/.cxx","android/app/.cxx","android/app/build","android/build","ios/Pods","ios/build","ios/DerivedData"]),Ip=[{value:"production",label:"production",hint:"Store / release build"},{value:"staging",label:"staging",hint:"Internal testing build"},{value:"development",label:"development",hint:"Development build"}],da=e=>new Promise(t=>setTimeout(t,e)),ua=e=>e.split(Ee.sep).filter(Boolean).join("/"),wp=(e,t)=>{let n=ua(e),i=n.split("/")[0];return n?!!(Xs.has(n)||Xs.has(i)||Ep.has(n)||t==="ios"&&i==="android"||t==="android"&&i==="ios"):!1},_p=(e,t,n)=>{let i=0,r=new Set,o=(s,l)=>{let a=ua(l);if(wp(a,n)){r.add(a.split("/")[0]||a);return}let d=ue.lstatSync(s);if(!d.isSymbolicLink()){if(d.isDirectory()){for(let u of ue.readdirSync(s))o(Ee.join(s,u),Ee.join(l,u));return}if(d.isFile()){let u=Ee.dirname(a);e.addLocalFile(s,u==="."?void 0:u,Ee.basename(a)),i++}}};for(let s of ue.readdirSync(t))o(Ee.join(t,s),s);return{files:i,skipped:Array.from(r).sort()}},$p=e=>!e.yes&&!e.failOnly&&!e.buildId&&process.stdin.isTTY&&process.stdout.isTTY,vp=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},Rp=()=>{let e=ve(`./${m.configFileName}`),t=e?.build&&typeof e.build=="object"?e.build:{},n=Object.keys(t);return n.length===0?Ip:n.map(i=>({value:i,label:i,hint:vp(t[i])}))},Pp=async e=>{let t=$p(e);if(!e.platform&&t){let n=await Ks({message:"Select platform",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"}]});li(n)&&(Ws("Build cancelled."),process.exit(0)),e.platform=n}if(!e.buildProfile&&t){let n=Rp(),i=await Ks({message:"Select build profile",options:n,initialValue:n.find(r=>r.value==="production")?.value||n[0]?.value});li(i)&&(Ws("Build cancelled."),process.exit(0)),e.buildProfile=i}e.buildProfile||(e.buildProfile="production")},Zs=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},pa=(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,"")}},Dp=(e,t)=>!!e&&t.some(n=>new RegExp(`(?:^|\\s)${n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:\\s|$)`).test(e)),Op=e=>{let n=pa(e,["--platform"])||e?.split(/\s+/).find(i=>i==="ios"||i==="android");return n==="ios"||n==="android"?n:void 0},Cp=async e=>{if(!(!e.projectId||!e.buildId))try{let t=await N.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||Op(i);(r==="ios"||r==="android")&&(e.platform=r)}if(e.buildProfile||(e.buildProfile=n.buildProfile||n.profile||n.profileName||pa(i,["--profile","--build-profile","-p"])),e.simulator===void 0){let r=Zs(n.simulator??n.isSimulator);r!==void 0?e.simulator=r:Dp(i,["--simulator"])&&(e.simulator=!0)}if(e.developmentClient===void 0){let r=Zs(n.developmentClient??n.devClient);r!==void 0&&(e.developmentClient=r)}}catch(t){O.warn(C.yellow(`Could not load saved build options for runner: ${t.message}`))}},kp=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]}`},Tp=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},oi=async(e,t,n=Sp)=>{let i;for(let r=1;r<=n;r++)try{return await t()}catch(o){if(i=o,!Tp(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";O.warn(C.yellow(`${e} failed transiently (${l}). Retrying in ${Math.round(s/1e3)}s... (${r}/${n})`)),await da(s)}throw i},Np=async(e,t,n)=>{let i=Ee.basename(e),r=ue.statSync(e).size,o=Math.round(Or/1e3);Nr(`ARTIFACT_UPLOAD ${i}`,t);try{await oi(`Upload artifact ${i}`,async()=>{let s=new AbortController,l=ue.createReadStream(e),a=setTimeout(()=>{l.destroy(new Error(`Artifact upload timed out after ${o}s`)),s.abort()},Or);try{await ai.put(t,l,{headers:{"Content-Type":n,"Content-Length":r,Connection:"close"},maxBodyLength:1/0,maxContentLength:1/0,timeout:Or,timeoutErrorMessage:`Artifact upload timed out after ${o}s`,signal:s.signal})}finally{clearTimeout(a)}},qs)}catch(s){throw new Error(`${i} (${kp(r)}) failed after ${qs} upload attempt(s): ${s.message||s}`)}return r},xp=e=>{let t=e.response?.status;return t?t===408||t===429||t>=500:!0},Rn=e=>e.credentialId||e.id,Lp=async(e,t)=>{let n=Rn(e);if(!n)return e.downloadUrl;let i=await N.get(`/credentials/${n}/download`,{params:{projectId:t,format:"raw"}});return i.data?.status==="success"&&i.data?.downloadUrl?i.data.downloadUrl:e.downloadUrl},Mp=async(e,t)=>{let n=e.downloadUrl;for(let i=1;i<=Dr;i++)try{if((!n||i>1)&&(n=await Lp(e,t)),!n)throw new Error(`Credential ${e.name||Rn(e)||"unknown"} has no download URL.`);let r=await ai.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>=Dr||!xp(r))throw r;let o=Math.min(1500*i*i,15e3);O.warn(C.dim(` - Temporary network error downloading ${e.name}. Retrying... (${i}/${Dr})`)),await da(o)}throw new Error(`Failed to download credential ${e.name||Rn(e)||"unknown"}.`)},Up=(e,t)=>t?.ios?.buildNumber??t?.iosBuildNumber??e?.ios?.buildNumber??e?.expo?.ios?.buildNumber,Fp=(e,t)=>t?.android?.versionCode??t?.androidVersionCode??e?.android?.versionCode??e?.expo?.android?.versionCode,Qs=e=>{let t=parseInt(String(e||"0"),10);return Number.isFinite(t)&&t>0?t:0},ea=(e,t,n,i)=>e==="ios"?t.iosBundleIdentifier||n?.ios?.bundleIdentifier||n?.expo?.ios?.bundleIdentifier||i:t.androidPackage||n?.android?.package||n?.expo?.android?.package||n?.name||i,ta=async(e,t,n,i=0)=>{let r=await N.post(`/projects/${e}/next-build-number`,{platform:t,scope:n,startFrom:i});if(r.data.status!=="success"||!r.data.buildNumber)throw new Error(r.data.message||"Dashboard did not return a build number.");return String(r.data.buildNumber)},vn=e=>{let t={};return e.platform==="ios"&&e.resolvedBuildNumber&&(t.buildNumber=e.resolvedBuildNumber),e.platform==="android"&&e.resolvedVersionCode&&(t.versionCode=e.resolvedVersionCode),t},Bp=e=>typeof e=="string"&&e.trim().toLowerCase()==="auto",fa=(e,t,n=[])=>{if(!ue.existsSync(e))return n;let i;try{i=ue.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=Ee.join(e,r.name);r.isDirectory()?fa(o,t,n):r.name===t&&n.push(o)}return n},jp=(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},Hp=(e,t)=>{let n=Ee.resolve(process.cwd(),ue.existsSync("ios")?"ios":"."),i=fa(n,"project.pbxproj"),r=[];for(let o of i)try{let l=ue.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:jp(o,e,t)})).sort((o,s)=>s.score-o.score)[0]?.bundleId},si=e=>String(e||"").trim().toLowerCase().replace(/_/g,"-"),ci=(e,t)=>{let n=si(e);return t==="ios"&&(n==="internal"||n==="ad-hoc")?"adhoc":t==="android"&&["internal","adhoc","ad-hoc","development","dev","staging","stage"].includes(n)?"internal":n},na=(e,t,n)=>{let i=ci(e.distributionType||e.meta?.distributionType,n);return i?i===ci(t,n):!0},ia=(e,t,n)=>{let i=ci(e.distributionType||e.meta?.distributionType,n),r=ci(t,n);return i?i===r?3:n==="android"&&r!=="store"&&i!=="store"?2:0:1},Gp=e=>{let t=e.toLowerCase();return t==="development"||t==="dev"||t.startsWith("development-")||t.startsWith("dev-")||t.endsWith("-development")||t.endsWith("-dev")},Vp=e=>{let t=e.toLowerCase();return t.includes("staging")||t.includes("stage")||t.includes("preview")||t.includes("adhoc")||t.includes("ad-hoc")},Kp=(e,t)=>{let n=si(e.distribution),i=si(e.iosExportMethod),r=si(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":Gp(t)?"development":(Vp(t),"adhoc")},ma=e=>e.bundleId||e.bundleIdentifier||e.packageName||e.meta?.bundleId||e.meta?.bundleIdentifier||e.meta?.packageName,ra=(e,t)=>{if(!t)return!0;let n=ma(e);return!n||n==="*"||n===t},oa=(e,t)=>{let n=ma(e);return!t||!n?0:n===t?2:n==="*"?1:-1},ga=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}},zp=(e,t)=>{if(e===t||e==="*")return!0;if(e.endsWith(".*")){let n=e.slice(0,-2);return t.startsWith(`${n}.`)}return!1},Wp=(e,t)=>{if(!t)return!0;let n=ga(e);if(n)return zp(n,t);try{return Buffer.from(e,"base64").toString("latin1").includes(t)}catch{return!0}},di=async e=>{if(e.failOnly){(!e.projectId||!e.buildId)&&(O.error(C.red("--project-id and --build-id are required with --fail-only.")),process.exit(1));let l=e.error||"Build runner failed before it could report a final status.";try{await N.patch(`/builds/${e.projectId}/${e.buildId}`,{status:"failed",error:l,endTime:Date.now()}),O.info(C.yellow(`Marked build ${e.buildId} as failed.`));return}catch(a){O.error(C.red(`Could not mark build failed: ${a.message}`)),process.exit(1)}}await Cp(e),await Pp(e),e.platform!=="android"&&e.platform!=="ios"&&(O.error(`Platform ${e.platform} is not supported. Use 'android' or 'ios'.`),process.exit(1)),e.autoSubmit&&e.platform==="ios"&&e.simulator&&(O.error(C.red("--auto-submit cannot be used with --simulator because simulator builds are not App Store artifacts.")),process.exit(1)),e.autoSubmit&&e.dryRun&&O.warn(C.yellow("--auto-submit is ignored during --dry-run."));let t=Tr(),n=e.buildId||hp(),i=e.projectId,r=Date.now(),o=!!i,s=async l=>{if(i)try{await N.patch(`/builds/${i}/${n}`,{status:"failed",error:l,endTime:Date.now()})}catch{}};if(e.local&&e.buildId){e.quiet||t.start(`Preparing isolated workspace for build: ${e.buildId}`);try{let l=await N.get(`/builds/${i}/${e.buildId}/source-url`);if(l.data.status!=="success")throw new Error("Failed to get source download URL from API");Nr("SOURCE_DOWNLOAD",l.data.downloadUrl);let a=await ai.get(l.data.downloadUrl,{responseType:"stream"}),d=(i||e.projectId||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),u=Ee.join(yp.homedir(),m.workspacesDir,d);ue.mkdirSync(u,{recursive:!0});let c=new Set(["node_modules",`.${m.nameLower}-cache-meta`]),p=new Set(["Pods"]);if(ue.existsSync(u)){let _=ue.readdirSync(u);for(let I of _){if(c.has(I))continue;if(I==="ios"){let w=Ee.join(u,"ios");try{let U=ue.readdirSync(w);for(let V of U)if(!p.has(V))try{ue.rmSync(Ee.join(w,V),{recursive:!0,force:!0})}catch{}}catch{}continue}let T=Ee.join(u,I);try{ue.rmSync(T,{recursive:!0,force:!0})}catch{}}}let f=Ee.join(u,"source.zip"),g=a.data,y=ue.createWriteStream(f);await new Promise((_,I)=>{g.pipe(y),g.on("error",T=>I(T)),y.on("finish",()=>_())}),new Ys(f).extractAllTo(u,!0);try{ue.unlinkSync(f)}catch{}process.chdir(u),O.info(C.green(`\u2713 Persistent workspace ready: ${u}`)),O.info(C.dim(` \u{1F4E6} Cached dirs preserved: node_modules=${ue.existsSync(Ee.join(u,"node_modules"))?"\u2705":"\u274C"}, Pods=${ue.existsSync(Ee.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=Js("git config --get remote.origin.url").toString().trim()}catch{O.warn("Could not detect git repository URL.")}!l&&e.dryRun,l||(l="https://github.com/placeholder/repo.git"),O.info(`Build ID: ${C.cyan(n)}`);let a={},d={},u=null,c=ve(`./${m.configFileName}`);if(c||(O.error(C.red(`${m.configFileName} not found. Run \`${m.nameLower} init\` or \`${m.nameLower} link\` first.`)),process.exit(1)),c){u=c;let A=$o(c);e.framework=A,i=c.projectId;let v=e.buildProfile||"production",L=xe(c,v);!L&&e.buildProfile&&(O.error(`Build profile '${v}' not found in ${m.configFileName}`),process.exit(1));let P=L||{};process.env.MACH_DEBUG&&O.info(C.dim(`Framework: ${A} | Build profile: ${v} | Platform: ${e.platform} | Distribution: ${P.distribution||"store"} | Environment: ${P.environment||v}`)),P.env&&(d=P.env,O.info(C.blue(`Use Build Profile: ${v}`)));let S=e.platform,R=P[S]||{},M=["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=c.name,e.appName=c.name,e.androidPackage=c.android?.package,e.iosBundleIdentifier=c.ios?.bundleIdentifier,e.iosScheme=c.ios?.iosScheme,!e.nodeVersion&&c.nodeVersion&&(e.nodeVersion=c.nodeVersion);let B=Q=>Q==="androidPackage"?R.androidPackage??R.package??P.androidPackage??P.android?.package:Q==="iosBundleIdentifier"?R.iosBundleIdentifier??R.bundleIdentifier??P.iosBundleIdentifier??P.ios?.bundleIdentifier:R[Q]!==void 0?R[Q]:P[Q];for(let Q of M){let $=B(Q),pe=Q==="androidPackage"||Q==="iosBundleIdentifier";$!==void 0&&(e[Q]===void 0||pe)&&(e[Q]=$)}if(e.platform==="ios"&&!(R.iosBundleIdentifier??R.bundleIdentifier??P.iosBundleIdentifier??P.ios?.bundleIdentifier)){let $=Hp(e,v);$&&$!==e.iosBundleIdentifier&&(O.warn(C.yellow(`Detected native iOS bundle identifier ${$}; using it for credential lookup. Set build.${v}.ios.bundleIdentifier to make this explicit.`)),e.iosBundleIdentifier=$)}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),O.info(C.dim(`Resolved build config: framework=${A}, profile=${v}, platform=${e.platform}, simulator=${e.platform==="ios"?String(!!e.simulator):"n/a"}, developmentClient=${String(!!e.developmentClient)}, distribution=${e.distribution||P.distribution||"store"}, iosConfiguration=${e.platform==="ios"?e.iosConfiguration||"Release":"n/a"}`));let K=Q=>{if(!Q)return Q;if(Q.startsWith("scripts.")){let $=Q.split(".")[1],pe=c.scripts?.[$];if(pe)return pe;O.warn(`Script reference not found: ${Q}`)}return Q};e.buildCommand=K(e.buildCommand),e.preBuild=K(e.preBuild),e.postBuild=K(e.postBuild),!e.scheme&&c.scheme&&(e.scheme=c.scheme);let z={...Wt(c,m.envPrefix),...Wt(P,`${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&&P.ios?.appleTeamId&&(e.iosTeamId=P.ios.appleTeamId),!e.iosTeamId&&c.submit?.[v]?.ios?.appleTeamId&&(e.iosTeamId=c.submit[v].ios.appleTeamId),!e.iosTeamId&&c.submit?.production?.ios?.appleTeamId&&(O.warn(C.yellow(`Check: Using 'production' Team ID for '${v}' build.`)),e.iosTeamId=c.submit.production.ios.appleTeamId),e.iosTeamId?O.info(C.magenta(`\u2713 Injected iOS Team ID from config: ${e.iosTeamId}`)):e.simulator||O.warn(C.yellow("\u26A0\uFE0F No iOS Team ID found. Device or archive signing may fail unless managed iOS credentials provide the team automatically.")))}let p="unknown";try{p=Js("git rev-parse --abbrev-ref HEAD").toString().trim()}catch{O.warn("Failed to detect git branch.")}let f="1.0.0";try{ue.existsSync("./package.json")&&(f=JSON.parse(ue.readFileSync("./package.json","utf-8")).version||"1.0.0")}catch{}let g=e.buildProfile||"production",y=bn(c,{framework:e.framework,platform:e.platform}),h="Internal";e.developmentClient?h="DevelopmentClient":g.toLowerCase().includes("store")||g.toLowerCase()==="production"?h="Store":g.toLowerCase().includes("preview")||g.toLowerCase().includes("staging")?h="Staging":(g.toLowerCase().includes("development")||g.toLowerCase().includes("dev"))&&(h="Development");let _=e.platform==="ios"?"iOS":"Android",I=e.platform==="ios"&&e.simulator?" (Simulator)":"",T=`${_}${I} v${f} (${h})`;if(ui(e,{status:"created",projectId:i,buildId:n,platform:e.platform,profile:g,branch:p,version:f,runtimeVersion:y,...vn(e),buildType:h,developmentClient:!!e.developmentClient,summary:T}),i){try{let A=e.buildProfile||"production",v=e.environment||A;O.info(C.blue(`Fetching managed secrets for profile: ${A} (environment: ${v})...`));let P=(await N.get(`/projects/${i}/secrets/export?env=${v}`)).data;P.status==="success"&&P.secrets&&(a={...a,...P.secrets},Object.keys(P.secrets).length>0&&O.info(C.magenta(`\u2713 Injected ${Object.keys(P.secrets).length} secrets from Dashboard.`)))}catch(A){O.warn(`Failed to load managed secrets from Dashboard: ${A.message}`)}if(e.platform==="ios"&&e.simulator)O.info(C.dim("Skipping managed iOS signing credentials for simulator build."));else try{O.info(C.blue("Fetching managed credentials..."));let A=Kp(e,g),v=e.platform==="ios"?e.iosBundleIdentifier:e.androidPackage,L=e.platform==="ios"?"bundle":"package";O.info(C.dim(` Credential target: ${L} ${v||"not set"} (${A})`));let P=await N.get("/credentials/resolve",{params:{projectId:i,platform:e.platform,bundleId:v,distributionType:A,teamId:e.platform==="ios"?e.iosTeamId:void 0}});if(P.data.status==="success"&&P.data.credentials){let S=P.data.credentials;O.info(C.magenta(`\u2713 Found ${S.length} relevant credentials.`));let R=S.filter($=>e.platform==="ios"&&$.type==="ios_profile"?na($,A,e.platform)?ra($,v):!1:e.platform==="android"&&$.type==="android_keystore"?ra($,v):!!na($,A,e.platform)).sort(($,pe)=>{let te=oa(pe,v)*10+ia(pe,A,e.platform)-(oa($,v)*10+ia($,A,e.platform));return te!==0?te:(pe.createdAt||0)-($.createdAt||0)});O.info(C.dim(` Filtered to ${R.length} credentials for distributionType: ${A}`));let M=!1,B=!1,K=!1,z=[];for(let $ of R)if(!($.type==="ios_cert"&&M||$.type==="ios_profile"&&B||$.type==="android_keystore"&&K)&&["ios_cert","ios_profile","android_keystore"].includes($.type)&&($.downloadUrl||Rn($)))try{let te=await Mp($,i);if($.type==="ios_cert"&&!M)a.IOS_DIST_P12=te,$.password?(a.IOS_P12_PASSWORD=$.password,O.info(C.dim(` - Injected ${$.name} as IOS_DIST_P12 with password from credential record`))):O.info(C.dim(` - Injected ${$.name} as IOS_DIST_P12`)),M=!0;else if($.type==="ios_profile"&&!B){if(!Wp(te,v)){let ee=ga(te)||"unknown";throw new Error(`Provisioning profile ${$.name||Rn($)||"unknown"} is for a different bundle ID. Expected ${v}, found ${ee}. Upload a ${A} profile for ${v}.`)}a.IOS_PROVISIONING_PROFILE=te,O.info(C.dim(` - Injected ${$.name} as IOS_PROVISIONING_PROFILE`)),B=!0}else if($.type==="android_keystore"&&!K){a.ANDROID_KEYSTORE_BASE64=te;let ee=$.keystorePassword||$.password,X=$.keyPassword||$.keystorePassword||$.password,fe=$.alias||$.meta?.alias;if(ee)a.ANDROID_STORE_PASSWORD=ee,O.info(C.dim(" - Injected keystore password from credential record"));else{let be=["ANDROID_STORE_PASSWORD",...[A==="store"?"PRODUCTION":A==="internal"||A==="adhoc"?"STAGING":"DEVELOPMENT",A.toUpperCase(),"PRODUCTION","STORE","INTERNAL","STAGING","RELEASE","DEBUG"].map(me=>`KEYSTORE_PASSWORD_${me}`),"KEYSTORE_PASSWORD"].find(me=>!!a[me]);be&&a[be]&&(a.ANDROID_STORE_PASSWORD=a[be])}if(X?(a.ANDROID_KEY_PASSWORD=X,O.info(C.dim(" - Injected key password from credential record"))):a.ANDROID_KEY_PASSWORD=a.ANDROID_STORE_PASSWORD||"",fe)a.ANDROID_KEY_ALIAS=fe;else{let W=["ANDROID_KEY_ALIAS","KEYSTORE_ALIAS"].find(se=>!!a[se]);W&&(a.ANDROID_KEY_ALIAS=a[W])}O.info(C.dim(` - Injected ${$.name} as ANDROID_KEYSTORE_BASE64`)),K=!0}}catch(te){z.push(`${$.name||$.type}: ${te.message}`)}let Q=e.platform==="ios"?e.simulator||M&&B:K||!R.some($=>$.type==="android_keystore");if(z.length>0&&!Q)throw new Error(`Credential setup failed:
|
|
1470
|
+
`);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 Ep(e){try{oe.existsSync(e)&&oe.rmSync(e,{recursive:!0,force:!0})}catch{}}function ue(e){console.log(ne.red(`\u274C ${e}`))}function Ae(e){console.log(ne.gray(`\u2022 ${e}`))}function Or(e){console.log(ne.green(`\u2713 ${e}`))}var Tr=8,vp=6,ea=Number(process.env.MACH_ARTIFACT_UPLOAD_MAX_ATTEMPTS||2),Nr=Number(process.env.MACH_ARTIFACT_UPLOAD_TIMEOUT_MS||12e4),xr="ap-south-1",$p=`${m.envPrefix}S3_DEBUG`,_p=()=>["1","true","yes","on"].includes(String(process.env[$p]||"").trim().toLowerCase()),Ur=(e,t)=>{if(_p()&&t)try{let n=new URL(t);O.info(C.dim(`[S3_DEBUG] ${e} host=${n.hostname} expectedRegion=${xr}`)),n.hostname.includes(xr)||O.warn(C.yellow(`[S3_DEBUG] ${e} host ${n.hostname} does not include ${xr}`))}catch(n){O.warn(C.yellow(`[S3_DEBUG] Could not parse ${e} presigned URL host: ${n.message}`))}},ta=new Set([".git",".gradle",".idea",".mach-cache",".expo",".turbo",".yarn/cache","build","builds","coverage","dist","node_modules",`${m.nameLower}_cli`,`.${m.nameLower}_cli`]),Rp=new Set(["android/.gradle","android/.cxx","android/app/.cxx","android/app/build","android/build","ios/Pods","ios/build","ios/DerivedData"]),Pp=[{value:"production",label:"production",hint:"Store / release build"},{value:"staging",label:"staging",hint:"Internal testing build"},{value:"development",label:"development",hint:"Development build"}],fa=e=>new Promise(t=>setTimeout(t,e)),ma=e=>e.split(Ee.sep).filter(Boolean).join("/"),Dp=(e,t)=>{let n=ma(e),i=n.split("/")[0];return n?!!(ta.has(n)||ta.has(i)||Rp.has(n)||t==="ios"&&i==="android"||t==="android"&&i==="ios"):!1},Op=(e,t,n)=>{let i=0,r=new Set,o=(s,l)=>{let a=ma(l);if(Dp(a,n)){r.add(a.split("/")[0]||a);return}let d=pe.lstatSync(s);if(!d.isSymbolicLink()){if(d.isDirectory()){for(let u of pe.readdirSync(s))o(Ee.join(s,u),Ee.join(l,u));return}if(d.isFile()){let u=Ee.dirname(a);e.addLocalFile(s,u==="."?void 0:u,Ee.basename(a)),i++}}};for(let s of pe.readdirSync(t))o(Ee.join(t,s),s);return{files:i,skipped:Array.from(r).sort()}},Cp=e=>!e.yes&&!e.failOnly&&!e.buildId&&process.stdin.isTTY&&process.stdout.isTTY,kp=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},Tp=()=>{let e=ve(`./${m.configFileName}`),t=e?.build&&typeof e.build=="object"?e.build:{},n=Object.keys(t);return n.length===0?Pp:n.map(i=>({value:i,label:i,hint:kp(t[i])}))},Np=async e=>{let t=Cp(e);if(!e.platform&&t){let n=await Ys({message:"Select platform",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"}]});pi(n)&&(Xs("Build cancelled."),process.exit(0)),e.platform=n}if(!e.buildProfile&&t){let n=Tp(),i=await Ys({message:"Select build profile",options:n,initialValue:n.find(r=>r.value==="production")?.value||n[0]?.value});pi(i)&&(Xs("Build cancelled."),process.exit(0)),e.buildProfile=i}e.buildProfile||(e.buildProfile="production")},na=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},ga=(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,"")}},xp=(e,t)=>!!e&&t.some(n=>new RegExp(`(?:^|\\s)${n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:\\s|$)`).test(e)),Lp=e=>{let n=ga(e,["--platform"])||e?.split(/\s+/).find(i=>i==="ios"||i==="android");return n==="ios"||n==="android"?n:void 0},Mp=async e=>{if(!(!e.projectId||!e.buildId))try{let t=await k.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||Lp(i);(r==="ios"||r==="android")&&(e.platform=r)}if(e.buildProfile||(e.buildProfile=n.buildProfile||n.profile||n.profileName||ga(i,["--profile","--build-profile","-p"])),e.simulator===void 0){let r=na(n.simulator??n.isSimulator);r!==void 0?e.simulator=r:xp(i,["--simulator"])&&(e.simulator=!0)}if(e.developmentClient===void 0){let r=na(n.developmentClient??n.devClient);r!==void 0&&(e.developmentClient=r)}}catch(t){O.warn(C.yellow(`Could not load saved build options for runner: ${t.message}`))}},Up=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]}`},Fp=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},ci=async(e,t,n=vp)=>{let i;for(let r=1;r<=n;r++)try{return await t()}catch(o){if(i=o,!Fp(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";O.warn(C.yellow(`${e} failed transiently (${l}). Retrying in ${Math.round(s/1e3)}s... (${r}/${n})`)),await fa(s)}throw i},Bp=async(e,t,n)=>{let i=Ee.basename(e),r=pe.statSync(e).size,o=Math.round(Nr/1e3);Ur(`ARTIFACT_UPLOAD ${i}`,t);try{await ci(`Upload artifact ${i}`,async()=>{let s=new AbortController,l=pe.createReadStream(e),a=setTimeout(()=>{l.destroy(new Error(`Artifact upload timed out after ${o}s`)),s.abort()},Nr);try{await ui.put(t,l,{headers:{"Content-Type":n,"Content-Length":r,Connection:"close"},maxBodyLength:1/0,maxContentLength:1/0,timeout:Nr,timeoutErrorMessage:`Artifact upload timed out after ${o}s`,signal:s.signal})}finally{clearTimeout(a)}},ea)}catch(s){throw new Error(`${i} (${Up(r)}) failed after ${ea} upload attempt(s): ${s.message||s}`)}return r},jp=e=>{let t=e.response?.status;return t?t===408||t===429||t>=500:!0},Dn=e=>e.credentialId||e.id,Hp=async(e,t)=>{let n=Dn(e);if(!n)return e.downloadUrl;let i=await k.get(`/credentials/${n}/download`,{params:{projectId:t,format:"raw"}});return i.data?.status==="success"&&i.data?.downloadUrl?i.data.downloadUrl:e.downloadUrl},Gp=async(e,t)=>{let n=e.downloadUrl;for(let i=1;i<=Tr;i++)try{if((!n||i>1)&&(n=await Hp(e,t)),!n)throw new Error(`Credential ${e.name||Dn(e)||"unknown"} has no download URL.`);let r=await ui.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>=Tr||!jp(r))throw r;let o=Math.min(1500*i*i,15e3);O.warn(C.dim(` - Temporary network error downloading ${e.name}. Retrying... (${i}/${Tr})`)),await fa(o)}throw new Error(`Failed to download credential ${e.name||Dn(e)||"unknown"}.`)},Vp=(e,t)=>t?.ios?.buildNumber??t?.iosBuildNumber??e?.ios?.buildNumber??e?.expo?.ios?.buildNumber,Kp=(e,t)=>t?.android?.versionCode??t?.androidVersionCode??e?.android?.versionCode??e?.expo?.android?.versionCode,ia=(e,t,n,i)=>e==="ios"?t.iosBundleIdentifier||n?.ios?.bundleIdentifier||n?.expo?.ios?.bundleIdentifier||i:t.androidPackage||n?.android?.package||n?.expo?.android?.package||n?.name||i,ra=async(e,t,n)=>{let i=await k.post(`/projects/${e}/next-build-number`,{platform:t,scope:n});if(i.data.status!=="success"||!i.data.buildNumber)throw new Error(i.data.message||"Dashboard did not return a build number.");return String(i.data.buildNumber)},Pn=e=>{let t={};return e.platform==="ios"&&e.resolvedBuildNumber&&(t.buildNumber=e.resolvedBuildNumber),e.platform==="android"&&e.resolvedVersionCode&&(t.versionCode=e.resolvedVersionCode),t},zp=e=>typeof e=="string"&&e.trim().toLowerCase()==="auto",ha=(e,t,n=[])=>{if(!pe.existsSync(e))return n;let i;try{i=pe.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=Ee.join(e,r.name);r.isDirectory()?ha(o,t,n):r.name===t&&n.push(o)}return n},Wp=(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},Jp=(e,t)=>{let n=Ee.resolve(process.cwd(),pe.existsSync("ios")?"ios":"."),i=ha(n,"project.pbxproj"),r=[];for(let o of i)try{let l=pe.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:Wp(o,e,t)})).sort((o,s)=>s.score-o.score)[0]?.bundleId},di=e=>String(e||"").trim().toLowerCase().replace(/_/g,"-"),fi=(e,t)=>{let n=di(e);return t==="ios"&&(n==="internal"||n==="ad-hoc")?"adhoc":t==="android"&&["internal","adhoc","ad-hoc","development","dev","staging","stage"].includes(n)?"internal":n},oa=(e,t,n)=>{let i=fi(e.distributionType||e.meta?.distributionType,n);return i?i===fi(t,n):!0},sa=(e,t,n)=>{let i=fi(e.distributionType||e.meta?.distributionType,n),r=fi(t,n);return i?i===r?3:n==="android"&&r!=="store"&&i!=="store"?2:0:1},Yp=e=>{let t=e.toLowerCase();return t==="development"||t==="dev"||t.startsWith("development-")||t.startsWith("dev-")||t.endsWith("-development")||t.endsWith("-dev")},qp=e=>{let t=e.toLowerCase();return t.includes("staging")||t.includes("stage")||t.includes("preview")||t.includes("adhoc")||t.includes("ad-hoc")},Xp=(e,t)=>{let n=di(e.distribution),i=di(e.iosExportMethod),r=di(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":Yp(t)?"development":(qp(t),"adhoc")},ya=e=>e.bundleId||e.bundleIdentifier||e.packageName||e.meta?.bundleId||e.meta?.bundleIdentifier||e.meta?.packageName,aa=(e,t)=>{if(!t)return!0;let n=ya(e);return!n||n==="*"||n===t},la=(e,t)=>{let n=ya(e);return!t||!n?0:n===t?2:n==="*"?1:-1},Sa=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}},Zp=(e,t)=>{if(e===t||e==="*")return!0;if(e.endsWith(".*")){let n=e.slice(0,-2);return t.startsWith(`${n}.`)}return!1},Qp=(e,t)=>{if(!t)return!0;let n=Sa(e);if(n)return Zp(n,t);try{return Buffer.from(e,"base64").toString("latin1").includes(t)}catch{return!0}},mi=async e=>{if(e.failOnly){(!e.projectId||!e.buildId)&&(O.error(C.red("--project-id and --build-id are required with --fail-only.")),process.exit(1));let l=e.error||"Build runner failed before it could report a final status.";try{await k.patch(`/builds/${e.projectId}/${e.buildId}`,{status:"failed",error:l,endTime:Date.now()}),O.info(C.yellow(`Marked build ${e.buildId} as failed.`));return}catch(a){O.error(C.red(`Could not mark build failed: ${a.message}`)),process.exit(1)}}await Mp(e),await Np(e),e.platform!=="android"&&e.platform!=="ios"&&(O.error(`Platform ${e.platform} is not supported. Use 'android' or 'ios'.`),process.exit(1)),e.autoSubmit&&e.platform==="ios"&&e.simulator&&(O.error(C.red("--auto-submit cannot be used with --simulator because simulator builds are not App Store artifacts.")),process.exit(1)),e.autoSubmit&&e.dryRun&&O.warn(C.yellow("--auto-submit is ignored during --dry-run."));let t=Mr(),n=e.buildId||Ip(),i=e.projectId,r=Date.now(),o=!!i,s=async l=>{if(i)try{await k.patch(`/builds/${i}/${n}`,{status:"failed",error:l,endTime:Date.now()})}catch{}};if(e.local&&e.buildId){e.quiet||t.start(`Preparing isolated workspace for build: ${e.buildId}`);try{let l=await k.get(`/builds/${i}/${e.buildId}/source-url`);if(l.data.status!=="success")throw new Error("Failed to get source download URL from API");Ur("SOURCE_DOWNLOAD",l.data.downloadUrl);let a=await ui.get(l.data.downloadUrl,{responseType:"stream"}),d=(i||e.projectId||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),u=Ee.join(wp.homedir(),m.workspacesDir,d);pe.mkdirSync(u,{recursive:!0});let c=new Set(["node_modules",`.${m.nameLower}-cache-meta`]),p=new Set(["Pods"]);if(pe.existsSync(u)){let v=pe.readdirSync(u);for(let I of v){if(c.has(I))continue;if(I==="ios"){let w=Ee.join(u,"ios");try{let U=pe.readdirSync(w);for(let V of U)if(!p.has(V))try{pe.rmSync(Ee.join(w,V),{recursive:!0,force:!0})}catch{}}catch{}continue}let N=Ee.join(u,I);try{pe.rmSync(N,{recursive:!0,force:!0})}catch{}}}let f=Ee.join(u,"source.zip"),g=a.data,y=pe.createWriteStream(f);await new Promise((v,I)=>{g.pipe(y),g.on("error",N=>I(N)),y.on("finish",()=>v())}),new Qs(f).extractAllTo(u,!0);try{pe.unlinkSync(f)}catch{}process.chdir(u),O.info(C.green(`\u2713 Persistent workspace ready: ${u}`)),O.info(C.dim(` \u{1F4E6} Cached dirs preserved: node_modules=${pe.existsSync(Ee.join(u,"node_modules"))?"\u2705":"\u274C"}, Pods=${pe.existsSync(Ee.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=Zs("git config --get remote.origin.url").toString().trim()}catch{O.warn("Could not detect git repository URL.")}!l&&e.dryRun,l||(l="https://github.com/placeholder/repo.git"),O.info(`Build ID: ${C.cyan(n)}`);let a={},d={},u=null,c=ve(`./${m.configFileName}`);if(c||(O.error(C.red(`${m.configFileName} not found. Run \`${m.nameLower} init\` or \`${m.nameLower} link\` first.`)),process.exit(1)),c){u=c;let A=Co(c);e.framework=A,i=c.projectId;let _=e.buildProfile||"production",L=xe(c,_);!L&&e.buildProfile&&(O.error(`Build profile '${_}' not found in ${m.configFileName}`),process.exit(1));let P=L||{};process.env.MACH_DEBUG&&O.info(C.dim(`Framework: ${A} | Build profile: ${_} | Platform: ${e.platform} | Distribution: ${P.distribution||"store"} | Environment: ${P.environment||_}`)),P.env&&(d=P.env,O.info(C.blue(`Use Build Profile: ${_}`)));let S=e.platform,R=P[S]||{},M=["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=c.name,e.appName=c.name,e.androidPackage=c.android?.package,e.iosBundleIdentifier=c.ios?.bundleIdentifier,e.iosScheme=c.ios?.iosScheme,!e.nodeVersion&&c.nodeVersion&&(e.nodeVersion=c.nodeVersion);let B=Q=>Q==="androidPackage"?R.androidPackage??R.package??P.androidPackage??P.android?.package:Q==="iosBundleIdentifier"?R.iosBundleIdentifier??R.bundleIdentifier??P.iosBundleIdentifier??P.ios?.bundleIdentifier:R[Q]!==void 0?R[Q]:P[Q];for(let Q of M){let $=B(Q),ie=Q==="androidPackage"||Q==="iosBundleIdentifier";$!==void 0&&(e[Q]===void 0||ie)&&(e[Q]=$)}if(e.platform==="ios"&&!(R.iosBundleIdentifier??R.bundleIdentifier??P.iosBundleIdentifier??P.ios?.bundleIdentifier)){let $=Jp(e,_);$&&$!==e.iosBundleIdentifier&&(O.warn(C.yellow(`Detected native iOS bundle identifier ${$}; using it for credential lookup. Set build.${_}.ios.bundleIdentifier to make this explicit.`)),e.iosBundleIdentifier=$)}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),O.info(C.dim(`Resolved build config: framework=${A}, profile=${_}, platform=${e.platform}, simulator=${e.platform==="ios"?String(!!e.simulator):"n/a"}, developmentClient=${String(!!e.developmentClient)}, distribution=${e.distribution||P.distribution||"store"}, iosConfiguration=${e.platform==="ios"?e.iosConfiguration||"Release":"n/a"}`));let K=Q=>{if(!Q)return Q;if(Q.startsWith("scripts.")){let $=Q.split(".")[1],ie=c.scripts?.[$];if(ie)return ie;O.warn(`Script reference not found: ${Q}`)}return Q};e.buildCommand=K(e.buildCommand),e.preBuild=K(e.preBuild),e.postBuild=K(e.postBuild),!e.scheme&&c.scheme&&(e.scheme=c.scheme);let z={...Yt(c,m.envPrefix),...Yt(P,`${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&&P.ios?.appleTeamId&&(e.iosTeamId=P.ios.appleTeamId),!e.iosTeamId&&c.submit?.[_]?.ios?.appleTeamId&&(e.iosTeamId=c.submit[_].ios.appleTeamId),!e.iosTeamId&&c.submit?.production?.ios?.appleTeamId&&(O.warn(C.yellow(`Check: Using 'production' Team ID for '${_}' build.`)),e.iosTeamId=c.submit.production.ios.appleTeamId),e.iosTeamId?O.info(C.magenta(`\u2713 Injected iOS Team ID from config: ${e.iosTeamId}`)):e.simulator||O.warn(C.yellow("\u26A0\uFE0F No iOS Team ID found. Device or archive signing may fail unless managed iOS credentials provide the team automatically.")))}let p="unknown";try{p=Zs("git rev-parse --abbrev-ref HEAD").toString().trim()}catch{O.warn("Failed to detect git branch.")}let f="1.0.0";try{pe.existsSync("./package.json")&&(f=JSON.parse(pe.readFileSync("./package.json","utf-8")).version||"1.0.0")}catch{}let g=e.buildProfile||"production",y=En(c,{framework:e.framework,platform:e.platform}),h="Internal";e.developmentClient?h="DevelopmentClient":g.toLowerCase().includes("store")||g.toLowerCase()==="production"?h="Store":g.toLowerCase().includes("preview")||g.toLowerCase().includes("staging")?h="Staging":(g.toLowerCase().includes("development")||g.toLowerCase().includes("dev"))&&(h="Development");let v=e.platform==="ios"?"iOS":"Android",I=e.platform==="ios"&&e.simulator?" (Simulator)":"",N=`${v}${I} v${f} (${h})`;if(gi(e,{status:"created",projectId:i,buildId:n,platform:e.platform,profile:g,branch:p,version:f,runtimeVersion:y,...Pn(e),buildType:h,developmentClient:!!e.developmentClient,summary:N}),i){try{let A=e.buildProfile||"production",_=e.environment||A;O.info(C.blue(`Fetching managed secrets for profile: ${A} (environment: ${_})...`));let P=(await k.get(`/projects/${i}/secrets/export?env=${_}`)).data;P.status==="success"&&P.secrets&&(a={...a,...P.secrets},Object.keys(P.secrets).length>0&&O.info(C.magenta(`\u2713 Injected ${Object.keys(P.secrets).length} secrets from Dashboard.`)))}catch(A){O.warn(`Failed to load managed secrets from Dashboard: ${A.message}`)}if(e.platform==="ios"&&e.simulator)O.info(C.dim("Skipping managed iOS signing credentials for simulator build."));else try{O.info(C.blue("Fetching managed credentials..."));let A=Xp(e,g),_=e.platform==="ios"?e.iosBundleIdentifier:e.androidPackage,L=e.platform==="ios"?"bundle":"package";O.info(C.dim(` Credential target: ${L} ${_||"not set"} (${A})`));let P=await k.get("/credentials/resolve",{params:{projectId:i,platform:e.platform,bundleId:_,distributionType:A,teamId:e.platform==="ios"?e.iosTeamId:void 0}});if(P.data.status==="success"&&P.data.credentials){let S=P.data.credentials;O.info(C.magenta(`\u2713 Found ${S.length} relevant credentials.`));let R=S.filter($=>e.platform==="ios"&&$.type==="ios_profile"?oa($,A,e.platform)?aa($,_):!1:e.platform==="android"&&$.type==="android_keystore"?aa($,_):!!oa($,A,e.platform)).sort(($,ie)=>{let ge=la(ie,_)*10+sa(ie,A,e.platform)-(la($,_)*10+sa($,A,e.platform));return ge!==0?ge:(ie.createdAt||0)-($.createdAt||0)});O.info(C.dim(` Filtered to ${R.length} credentials for distributionType: ${A}`));let M=!1,B=!1,K=!1,z=[];for(let $ of R)if(!($.type==="ios_cert"&&M||$.type==="ios_profile"&&B||$.type==="android_keystore"&&K)&&["ios_cert","ios_profile","android_keystore"].includes($.type)&&($.downloadUrl||Dn($)))try{let ge=await Gp($,i);if($.type==="ios_cert"&&!M)a.IOS_DIST_P12=ge,$.password?(a.IOS_P12_PASSWORD=$.password,O.info(C.dim(` - Injected ${$.name} as IOS_DIST_P12 with password from credential record`))):O.info(C.dim(` - Injected ${$.name} as IOS_DIST_P12`)),M=!0;else if($.type==="ios_profile"&&!B){if(!Qp(ge,_)){let ee=Sa(ge)||"unknown";throw new Error(`Provisioning profile ${$.name||Dn($)||"unknown"} is for a different bundle ID. Expected ${_}, found ${ee}. Upload a ${A} profile for ${_}.`)}a.IOS_PROVISIONING_PROFILE=ge,O.info(C.dim(` - Injected ${$.name} as IOS_PROVISIONING_PROFILE`)),B=!0}else if($.type==="android_keystore"&&!K){a.ANDROID_KEYSTORE_BASE64=ge;let ee=$.keystorePassword||$.password,X=$.keyPassword||$.keystorePassword||$.password,fe=$.alias||$.meta?.alias;if(ee)a.ANDROID_STORE_PASSWORD=ee,O.info(C.dim(" - Injected keystore password from credential record"));else{let be=["ANDROID_STORE_PASSWORD",...[A==="store"?"PRODUCTION":A==="internal"||A==="adhoc"?"STAGING":"DEVELOPMENT",A.toUpperCase(),"PRODUCTION","STORE","INTERNAL","STAGING","RELEASE","DEBUG"].map(me=>`KEYSTORE_PASSWORD_${me}`),"KEYSTORE_PASSWORD"].find(me=>!!a[me]);be&&a[be]&&(a.ANDROID_STORE_PASSWORD=a[be])}if(X?(a.ANDROID_KEY_PASSWORD=X,O.info(C.dim(" - Injected key password from credential record"))):a.ANDROID_KEY_PASSWORD=a.ANDROID_STORE_PASSWORD||"",fe)a.ANDROID_KEY_ALIAS=fe;else{let W=["ANDROID_KEY_ALIAS","KEYSTORE_ALIAS"].find(ae=>!!a[ae]);W&&(a.ANDROID_KEY_ALIAS=a[W])}O.info(C.dim(` - Injected ${$.name} as ANDROID_KEYSTORE_BASE64`)),K=!0}}catch(ge){z.push(`${$.name||$.type}: ${ge.message}`)}let Q=e.platform==="ios"?e.simulator||M&&B:K||!R.some($=>$.type==="android_keystore");if(z.length>0&&!Q)throw new Error(`Credential setup failed:
|
|
1471
1471
|
${z.map($=>`- ${$}`).join(`
|
|
1472
|
-
`)}`);z.length>0&&O.warn(C.dim(` Skipped ${z.length} stale or unusable credential(s).`))}if(e.platform==="ios"&&!e.simulator){let S=e.buildProfile||"production",R=xe(c,S)||{},M=
|
|
1473
|
-
\u{1F517} Download Links:`));for(let S of P)O.info(C.dim(` - ${S.name}: `)+C.blue.underline(S.url));await
|
|
1474
|
-
\u2713 Build completed and reported to dashboard.`)),e.maestro&&!w&&await
|
|
1475
|
-
${R}`)),await
|
|
1476
|
-
\u{1F3BC} Queuing managed Maestro test...`)),await
|
|
1477
|
-
Auto-submit: submitting the successful build...`));try{let r=await
|
|
1478
|
-
\u2717 Build failed: ${a.error||"Unknown error"}`)),process.exit(1);else if(r==="completed"||r==="success"){n.quiet||i.stop("Build successful!"),
|
|
1472
|
+
`)}`);z.length>0&&O.warn(C.dim(` Skipped ${z.length} stale or unusable credential(s).`))}if(e.platform==="ios"&&!e.simulator){let S=e.buildProfile||"production",R=xe(c,S)||{},M=Vp(c,R),B=zp(M),K=e.distribution!==void 0?e.distribution==="store":h==="Store",z=M===void 0&&K;if(e.autoVersion||B||z){t.start("Assigning iOS buildNumber from Mach counter...");try{let $=ia("ios",e,c,S),ie=await ra(i,"ios",$);a.BUILD_NUMBER=ie,a.CURRENT_PROJECT_VERSION=ie,a.MACH_IOS_BUILD_NUMBER_LOCKED="1",e.resolvedBuildNumber=ie,t.stop(`\u2713 Assigned iOS buildNumber ${C.green(ie)} (${$})`)}catch($){throw t.stop("iOS buildNumber assignment failed"),new Error(`Auto-versioning failed: ${$.response?.data?.message||$.message}`)}}}if(e.platform==="android"){let S=e.buildProfile||"production",R=xe(c,S)||{},M=Kp(c,R),B=M==="auto",K=e.distribution!==void 0?e.distribution==="store":h==="Store",z=M===void 0&&K;if(e.autoVersion||B||z){t.start("Assigning Android versionCode from Mach counter...");try{let $=ia("android",e,c,S),ie=await ra(i,"android",$);a.ANDROID_VERSION_CODE=ie,e.resolvedVersionCode=ie,t.stop(`\u2713 Assigned Android versionCode ${C.green(ie)} (${$})`)}catch($){throw t.stop("Android versionCode assignment failed"),new Error(`Auto-versioning failed: ${$.response?.data?.message||$.message}`)}}}if(y=En(c,{framework:e.framework,platform:e.platform,iosBuildNumber:e.resolvedBuildNumber||a.BUILD_NUMBER,androidVersionCode:e.resolvedVersionCode||a.ANDROID_VERSION_CODE}),e.platform==="ios"&&!e.simulator){let S=!!a.IOS_DIST_P12,R=!!a.IOS_PROVISIONING_PROFILE;if(!S||!R){let M=[...S?[]:["Distribution Certificate"],...R?[]:["Provisioning Profile"]].join(" and ");if(e.local&&e.buildId)throw new Error(`Missing iOS credentials: ${M}. Expected ${A} credentials for ${_||"the selected bundle ID"}. Run \`${m.nameLower} credentials --platform ios --profile ${g}\` and select ${_||"the correct bundle ID"}.`);O.error(C.red(`Missing iOS credentials: ${M}`)),e.quiet&&process.exit(1);let B=e.yes||await qs({message:"Would you like to generate these credentials now?",initialValue:!0});if(B&&!pi(B))return await hn({platform:"ios",profile:g}),e.quiet||O.info(C.green("\u2713 Credentials setup complete! Restarting build phase...")),mi(e);e.quiet||O.info(C.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)){O.error(C.red("Missing Android credentials: Signing Keystore")),e.quiet&&process.exit(1);let R=e.yes||await qs({message:"Would you like to automatically create and upload an Android Keystore for this profile now?",initialValue:!0});if(R&&!pi(R))return await hn({platform:"android",profile:g}),e.quiet||O.info(C.green("\u2713 Android Keystore setup complete! Restarting build phase...")),mi(e);e.quiet||O.info(C.yellow(`Run \`${m.nameLower} credentials --platform android\` to set up a signing keystore manually.`)),process.exit(1)}}catch(A){(String(A.message||"").startsWith("Credential download failed")||String(A.message||"").startsWith("Credential setup failed")||String(A.message||"").startsWith("Missing iOS credentials")||String(A.message||"").startsWith("Auto-versioning failed"))&&(O.error(C.red(A.message)),process.exit(1)),e.platform==="ios"&&e.local&&e.buildId&&(O.error(C.red(`Failed to resolve iOS credentials: ${A.message}`)),process.exit(1)),O.warn(`Failed to resolve credentials: ${A.message}`)}}let w=!!(e.local&&e.buildId),U=!!(e.local||e.sshHost),V=!U&&!w;if(w){O.info(C.magenta("\u{1F3D7}\uFE0F Runner Mode: Executing isolated build task..."));let A=await ar({...e,interactive:!1},n,a,i,{branch:p,version:f,runtimeVersion:y,summary:N,buildType:h});await J(A),process.exit(0)}async function J(A){let _=async L=>{if(i)try{await ci("Report failed build status",()=>k.patch(`/builds/${i}/${n}`,{status:"failed",error:L,endTime:Date.now()}),3)}catch(P){O.warn(C.yellow(`Could not report failed build status: ${P.message}`))}};if(i&&A.length>0){let L=Mr(),P=[];e.quiet||L.start("Uploading artifacts to Dashboard...");try{for(let S of A){let R=Ee.basename(S),M=pe.statSync(S).size,B=Ee.extname(R).toLowerCase(),K="application/octet-stream",z=await ci(`Create artifact upload URL for ${R}`,()=>k.post(`/builds/${i}/${n}/artifact-upload-url`,{fileName:R,fileType:K}));if(z.data.status!=="success")throw new Error(`Failed to get upload URL for ${R}`);await Bp(S,z.data.uploadUrl,K),P.push({name:R,url:z.data.downloadUrl,size:M,type:B.substring(1)})}e.quiet||L.stop("Artifacts uploaded.")}catch(S){e.quiet||L.stop("Failed to upload artifacts.");let R=`Artifact upload failed: ${S.message}`;throw O.error(C.red(R)),await _(R),new Error(R)}if(i&&P.length>0)try{O.info(C.cyan(`
|
|
1473
|
+
\u{1F517} Download Links:`));for(let S of P)O.info(C.dim(` - ${S.name}: `)+C.blue.underline(S.url));await ci("Finalize build in dashboard",()=>k.patch(`/builds/${i}/${n}`,{status:"success",artifacts:P,endTime:Date.now(),runtimeVersion:y,...Pn(e)})),gi(e,{status:"success",projectId:i,buildId:n,platform:e.platform,profile:g,branch:p,version:f,runtimeVersion:y,...Pn(e),buildType:h,developmentClient:!!e.developmentClient,summary:N,artifacts:P}),O.success(C.green(`
|
|
1474
|
+
\u2713 Build completed and reported to dashboard.`)),e.maestro&&!w&&await ca(i,n,e,g),e.autoSubmit&&!w&&await Lr(i,n,e,g)}catch(S){let R=`Build artifact uploaded but dashboard finalization failed: ${S.message}`;throw O.error(C.red(`
|
|
1475
|
+
${R}`)),await _(R),new Error(R)}}else if(i){let L="Build completed but produced no uploadable artifacts.";throw O.error(C.red(L)),await _(L),new Error(L)}}if(U){if(O.info(C.cyan(`\u{1F680} Direct Build Mode: Executing on ${e.sshHost||"local"}...`)),i&&!o){let A=process.argv.slice(3).join(" ");await k.post("/builds",{projectId:i,buildId:n,platform:e.platform,status:"building",branch:p,version:f,runtimeVersion:y,...Pn(e),summary:N,startTime:r,buildType:h,buildProfile:g,buildArgs:A,framework:e.framework,simulator:!!e.simulator,developmentClient:!!e.developmentClient,...da(e,n,g,u)}),ua(e)}if(e.sshHost&&e.platform==="ios")await Jo(e,n,a,i),e.autoSubmit&&await Lr(i,n,e,g);else{let A=await ar({...e,interactive:!!e.local},n,a,i,{branch:p,version:f,runtimeVersion:y,summary:N,buildType:h});await J(A)}return}if(V&&(O.info(C.blue("\u{1F6F0}\uFE0F Cloud Initiator Mode: Preparing orchestration...")),!e.dryRun)){e.quiet||t.start("Zipping and uploading local source...");let A=await k.post("/builds/source-upload-url",{projectId:i,buildId:n});if(A.data.status!=="success")throw t.stop("Failed to get upload URL."),new Error("Failed to get source upload URL from API");Ur("SOURCE_UPLOAD",A.data.uploadUrl);let _=new Qs,L=Op(_,process.cwd(),e.platform),P=_.toBuffer();if(!e.quiet){let R=L.skipped.length>0?` Skipped: ${L.skipped.join(", ")}.`:"";t.message(`Prepared source (${L.files} files).${R}`)}e.quiet||t.message(`Uploading source (${(P.length/1024/1024).toFixed(1)} MB)...`);let S=!1;for(let R=1;R<=3;R++)try{await ui.put(A.data.uploadUrl,P,{headers:{"Content-Type":"application/zip"},maxBodyLength:1/0,maxContentLength:1/0,timeout:12e4}),S=!0;break}catch(M){if(R<3)t.message(`Upload attempt ${R} failed (${M.code||M.message}), retrying...`),await new Promise(B=>setTimeout(B,2e3*R));else throw M}if(e.quiet||t.stop("Source uploaded"),i){let R=process.argv.slice(3).join(" ");await k.post("/builds",{projectId:i,buildId:n,platform:e.platform,status:"pending",branch:p,version:f,runtimeVersion:y,...Pn(e),summary:N,startTime:r,buildType:h,buildProfile:g,buildArgs:R,framework:e.framework,simulator:!!e.simulator,developmentClient:!!e.developmentClient,...da(e,n,g,u)}),O.info(C.green("\u2713 Cloud build registered.")),ua(e)}e.platform==="android"&&await Ko(e,n,a,i,e.preBuild),e.quiet||O.info(C.cyan("\u{1F4E1} Connecting to build stream...")),await nf(i,n,e),e.maestro&&await ca(i,n,e,g),e.autoSubmit&&await Lr(i,n,e,g);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&&await s(a),O.error(C.red(`\u2717 Build failed: ${a}`)),process.exit(1)}};async function ca(e,t,n,i){O.info(C.cyan(`
|
|
1476
|
+
\u{1F3BC} Queuing managed Maestro test...`)),await Sr({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 Lr(e,t,n,i){if(!e){O.error(C.red("Auto-submit requires a linked Mach project. Run `mach link` or pass --project-id.")),process.exitCode=1;return}O.info(C.cyan(`
|
|
1477
|
+
Auto-submit: submitting the successful build...`));try{let r=await ef(e,t);if(r?.autoSubmit){let o=r.submissionId?`${ot}/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?(O.info(C.green(`Auto-submit is already queued by Mach backend: ${r.submissionId}`)),O.info(C.dim(`Dashboard: ${o}`))):r.autoSubmitStatus==="failed"?O.warn(C.yellow(`Backend auto-submit failed: ${r.autoSubmitError||"Unknown error"}`)):a&&O.info(C.green("Auto-submit is registered with Mach backend; skipping local duplicate submit.")),a){wt(n,{status:r.autoSubmitStatus||"pending",projectId:e,submitId:r.submissionId,platform:n.platform,profile:i,buildId:t,dashboardUrl:o});return}}await li({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:ba(n,t,i)})}catch(r){O.error(C.red(`Auto-submit failed: ${r.message||r}`)),process.exitCode=1}}function ba(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 ef(e,t){try{let i=(await k.get(`/builds/${e}/${t}`)).data?.build;if(i?.autoSubmit)return i}catch(n){O.warn(C.dim(`Could not check backend auto-submit status: ${n.message}`))}return null}function Aa(e){for(let t of Object.keys(e))e[t]===void 0&&delete e[t];return e}function tf(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 Aa({track:o,releaseStatus:s,rollout:l,changesNotSentForReview:a===void 0?!1:a===!0||a==="true"||a==="1"})}function da(e,t,n,i){if(!e.autoSubmit||e.dryRun)return{};let r=e.platform==="android"?tf(e,n,i):{};return{autoSubmit:!0,autoSubmitStatus:"pending",autoSubmitOptions:Aa({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:ba(e,t,n)})}}function ua(e){!e.autoSubmit||e.dryRun||e.quiet||(O.info(C.green("\u2713 Auto-submit has been registered with the build.")),O.info(C.dim(" You can close this terminal; submission will start after build success.")))}function pa(e){return`${ot}/build/${e}`}function gi(e,t){if(!e.jsonOutput)return;let n=Ee.resolve(e.jsonOutput),i={...t,url:t.url||pa(t.buildId),dashboardUrl:t.dashboardUrl||pa(t.buildId),updatedAt:new Date().toISOString()};try{let r=Ee.dirname(n);r&&r!=="."&&pe.mkdirSync(r,{recursive:!0}),pe.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){O.warn(C.yellow(`Could not write build metadata JSON: ${r.message}`))}}async function nf(e,t,n){let i=Mr(),r="pending",o=0,s=0;for(n.quiet||i.start("Connecting to build stream...");;){try{let a=(await k.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."),gi(n,{status:"failed",projectId:e,buildId:t,platform:n.platform,profile:a.buildProfile,buildType:a.buildType,developmentClient:!!a.developmentClient,version:a.version,runtimeVersion:a.runtimeVersion,buildNumber:a.buildNumber,versionCode:a.versionCode,summary:a.summary,error:a.error||"Unknown error",artifacts:a.artifacts||[]}),O.error(C.red(`
|
|
1478
|
+
\u2717 Build failed: ${a.error||"Unknown error"}`)),process.exit(1);else if(r==="completed"||r==="success"){n.quiet||i.stop("Build successful!"),gi(n,{status:r,projectId:e,buildId:t,platform:n.platform,profile:a.buildProfile,buildType:a.buildType,developmentClient:!!a.developmentClient,version:a.version,runtimeVersion:a.runtimeVersion,buildNumber:a.buildNumber,versionCode:a.versionCode,summary:a.summary,artifacts:a.artifacts||[]}),O.success(C.green(`
|
|
1479
1479
|
\u2713 Build completed successfully!`));try{n.quiet||(O.info(C.magenta(`
|
|
1480
|
-
\u{1F4F1} Installation Hub:`)),O.info(C.dim(" - View & Install Build: ")+C.white.underline(`${ot}/build/${t}`)))}catch{}return}else if(r!=="pending"){n.quiet||i.stop(`Build status: ${r}`);return}}try{let u=(await
|
|
1480
|
+
\u{1F4F1} Installation Hub:`)),O.info(C.dim(" - View & Install Build: ")+C.white.underline(`${ot}/build/${t}`)))}catch{}return}else if(r!=="pending"){n.quiet||i.stop(`Build status: ${r}`);return}}try{let u=(await k.get(`/builds/${e}/${t}/logs`)).data;if(u&&typeof u=="string"&&!n.quiet){let c=u.split(`
|
|
1481
1481
|
`);if(c.length>o){for(let p=o;p<c.length;p++)c[p].trim()&&console.log(C.dim(` ${c[p]}`));o=c.length}}}catch{}s=0}catch{s++,s>10&&(i.stop("Connection lost."),O.error(C.red(`
|
|
1482
|
-
\u2717 Lost connection to Dashboard API.`)),process.exit(1))}await new Promise(l=>setTimeout(l,3e3))}}import*as
|
|
1482
|
+
\u2717 Lost connection to Dashboard API.`)),process.exit(1))}await new Promise(l=>setTimeout(l,3e3))}}import*as Ei from"http";import*as Ra from"net";import{execFile as rf,execFileSync as Rt,execSync as Si,spawn as Ea}from"child_process";import he from"chalk";import{log as Z}from"@clack/prompts";import of from"axios";import le from"fs";import Xe from"os";import q from"path";var St=7070,Cn=`http://127.0.0.1:${St}`,on="com.radhya.mach.agent",rn="Mach Agent",sn=`${on}.service`,sf=5e3,af=3e3,hi=null,yi=null,Ze=()=>q.join(Xe.homedir(),m.configDir),Pa=()=>q.join(Xe.homedir(),"Library","LaunchAgents"),bi=()=>q.join(Pa(),`${on}.plist`),Da=()=>q.join(Xe.homedir(),".config","systemd","user"),Br=()=>q.join(Da(),sn),jr=()=>q.join(Ze(),"agent.cmd");function Hr(){return`gui/${process.getuid?.()||Number(Si("id -u").toString().trim())}`}function Oa(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function On(e){return`<string>${Oa(e)}</string>`}function Gr(){let e=process.argv[1]?le.realpathSync(process.argv[1]):"";if(!e||!le.existsSync(e))throw new Error("Could not resolve the current Mach CLI entrypoint.");return[process.execPath,e,"agent","run"]}function Vr(){let e=Ca(),t=process.platform==="win32"?[process.env.SystemRoot?q.join(process.env.SystemRoot,"System32"):void 0,process.env.SystemRoot]:["/opt/homebrew/bin","/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"],n={HOME:Xe.homedir(),PATH:[process.env.PATH,...e.flatMap(i=>[q.join(i,"platform-tools"),q.join(i,"emulator"),q.join(i,"cmdline-tools","latest","bin"),q.join(i,"tools","bin")]),...t].filter(Boolean).join(q.delimiter)};for(let i of["ANDROID_HOME","ANDROID_SDK_ROOT","JAVA_HOME","SHELL"])process.env[i]&&(n[i]=process.env[i]);return n}function Ca(){let e=[process.env.ANDROID_HOME,process.env.ANDROID_SDK_ROOT];if(process.platform==="darwin")e.push(q.join(Xe.homedir(),"Library","Android","sdk"));else if(process.platform==="linux")e.push(q.join(Xe.homedir(),"Android","Sdk"),q.join(Xe.homedir(),"Android","sdk"),"/opt/android-sdk","/usr/lib/android-sdk");else if(process.platform==="win32"){let t=process.env.LOCALAPPDATA,n=process.env.USERPROFILE||Xe.homedir();e.push(t?q.join(t,"Android","Sdk"):void 0,q.join(n,"AppData","Local","Android","Sdk"))}return Array.from(new Set(e.filter(t=>!!t)))}function lf(e){return process.platform==="win32"&&!e.toLowerCase().endsWith(".exe")?`${e}.exe`:e}function ka(e,t){let n=lf(e);for(let i of Ca()){let r=q.join(i,t,n);if(le.existsSync(r))return r}return n}function Ta(){return ka("adb","platform-tools")}function Na(){return ka("emulator","emulator")}function Fr(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}"`}function cf(){if(process.platform!=="linux")throw new Error("Linux service install requires Linux.");le.mkdirSync(Ze(),{recursive:!0}),le.mkdirSync(Da(),{recursive:!0});let e=Gr(),t=Vr(),n=Object.entries(t).map(([r,o])=>`Environment=${Fr(`${r}=${o}`)}`).join(`
|
|
1483
1483
|
`),i=`[Unit]
|
|
1484
1484
|
Description=Mach local device agent
|
|
1485
1485
|
After=default.target
|
|
1486
1486
|
|
|
1487
1487
|
[Service]
|
|
1488
1488
|
Type=simple
|
|
1489
|
-
ExecStart=${e.map(
|
|
1490
|
-
WorkingDirectory=${
|
|
1489
|
+
ExecStart=${e.map(Fr).join(" ")}
|
|
1490
|
+
WorkingDirectory=${Fr(Xe.homedir())}
|
|
1491
1491
|
${n}
|
|
1492
1492
|
Restart=on-failure
|
|
1493
1493
|
RestartSec=5
|
|
@@ -1496,20 +1496,20 @@ StandardError=append:%h/${m.configDir}/agent.error.log
|
|
|
1496
1496
|
|
|
1497
1497
|
[Install]
|
|
1498
1498
|
WantedBy=default.target
|
|
1499
|
-
`;return
|
|
1499
|
+
`;return le.writeFileSync(Br(),i),Br()}function _t(e,t={}){try{return Rt("systemctl",["--user",...e],{stdio:t.ignoreError?"ignore":"pipe"}),!0}catch(n){if(t.ignoreError)return!1;throw n}}function df(){if(process.platform!=="win32")throw new Error("Windows agent script requires Windows.");le.mkdirSync(Ze(),{recursive:!0});let e=Vr(),[t,n,...i]=Gr(),r=q.join(Ze(),"agent.log"),o=q.join(Ze(),"agent.error.log"),s=Object.entries(e).map(([d,u])=>`set "${d}=${u}"`).join(`\r
|
|
1500
1500
|
`),l=i.map(d=>`"${d.replace(/"/g,'\\"')}"`).join(" "),a=`@echo off\r
|
|
1501
1501
|
${s}\r
|
|
1502
1502
|
cd /d "${Xe.homedir()}"\r
|
|
1503
1503
|
"${t}" "${n}" ${l} >> "${r}" 2>> "${o}"\r
|
|
1504
|
-
`;return
|
|
1505
|
-
${
|
|
1506
|
-
`),o=e.map(l=>` ${
|
|
1504
|
+
`;return le.writeFileSync(jr(),a),jr()}function kn(e,t={}){try{return Rt("schtasks.exe",e,{stdio:t.ignoreError?"ignore":"pipe"}),!0}catch(n){if(t.ignoreError)return!1;throw n}}function uf(){if(process.platform!=="darwin")throw new Error("Background agent install currently supports macOS only.");le.mkdirSync(Ze(),{recursive:!0}),le.mkdirSync(Pa(),{recursive:!0});let e=Gr(),t=Vr(),n=q.join(Ze(),"agent.log"),i=q.join(Ze(),"agent.error.log"),r=Object.entries(t).map(([l,a])=>` <key>${Oa(l)}</key>
|
|
1505
|
+
${On(a)}`).join(`
|
|
1506
|
+
`),o=e.map(l=>` ${On(l)}`).join(`
|
|
1507
1507
|
`),s=`<?xml version="1.0" encoding="UTF-8"?>
|
|
1508
1508
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
1509
1509
|
<plist version="1.0">
|
|
1510
1510
|
<dict>
|
|
1511
1511
|
<key>Label</key>
|
|
1512
|
-
${
|
|
1512
|
+
${On(on)}
|
|
1513
1513
|
<key>ProgramArguments</key>
|
|
1514
1514
|
<array>
|
|
1515
1515
|
${o}
|
|
@@ -1521,26 +1521,26 @@ ${r}
|
|
|
1521
1521
|
<key>RunAtLoad</key>
|
|
1522
1522
|
<true/>
|
|
1523
1523
|
<key>StandardOutPath</key>
|
|
1524
|
-
${
|
|
1524
|
+
${On(n)}
|
|
1525
1525
|
<key>StandardErrorPath</key>
|
|
1526
|
-
${
|
|
1526
|
+
${On(i)}
|
|
1527
1527
|
</dict>
|
|
1528
1528
|
</plist>
|
|
1529
|
-
`;return
|
|
1530
|
-
`).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
|
|
1531
|
-
`).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 La(){if(process.platform!=="darwin")return[];try{let e=await hi("/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 Sf(){if(process.platform!=="darwin")return[];try{let e=await hi("/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 bf(e){let t=await La(),n=t.find(r=>r.id===e);if(n)return n;let i=t.filter(r=>r.status==="online");return i.length===1?i[0]:null}async function Af(){let[e,t,n]=await Promise.all([yf(),La(),Sf()]);return[...e,...t,...n]}async function Ef(){let e=Date.now();return pi&&e-pi.updatedAt<ef?pi.targets:(fi||(fi=Af().then(t=>(pi={targets:t,updatedAt:Date.now()},t)).finally(()=>{fi=null})),fi)}async function Ea(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 If(e,t){let n=await Zp({method:"GET",url:e,responseType:"stream",timeout:12e4}),i=ae.createWriteStream(t);n.data.pipe(i),await new Promise((r,o)=>{i.on("finish",r),i.on("error",o)})}function Ia(e,t){let n=e?.stderr?.toString?.().trim();if(n)return n;let i=e?.stdout?.toString?.().trim();return i||e?.message||t}function wf(e,t){return vt("/usr/libexec/PlistBuddy",["-c",`Print :${t}`,e],{encoding:"utf-8"}).trim()}function _f(e){let t=Y.join(e,"Info.plist");if(!ae.existsSync(t))throw new Error(`Could not validate iOS app executable: ${t} not found.`);let n=wf(t,"CFBundleExecutable"),i=Y.join(e,n);if(!ae.existsSync(i))throw new Error(`Could not validate iOS app executable: ${i} not found.`);return i}function $f(){return process.arch==="arm64"?"arm64":"x86_64"}function vf(e){return ae.existsSync(e)?ae.readdirSync(e).map(t=>Y.join(e,t)).filter(t=>t.endsWith(".app")&&ae.statSync(t).isDirectory()):[]}function wa(e,t){let n=vf(e);if(n.length===1)return n[0];if(n.length>1)throw new Error(`Multiple .app bundles found in ${t}: ${n.map(i=>Y.basename(i)).join(", ")}. Mach cannot safely choose which app to install.`);return""}function Rf(e){let t=_f(e),n=$f(),i="",r="";try{i=vt("lipo",["-info",t],{encoding:"utf-8"}).trim()}catch(o){throw new Error(`Could not inspect iOS simulator app architecture for ${Y.basename(e)}: ${o.message}`)}if(!new RegExp(`\\b${n}\\b`).test(i))throw new Error(`This iOS simulator artifact cannot be installed because ${Y.basename(e)} does not include the ${n} simulator architecture. lipo output: ${i}. Rebuild the app with the latest Mach CLI and make sure the profile is a simulator build.`);try{r=vt("/usr/bin/xcrun",["vtool","-show-build",t],{encoding:"utf-8"}).trim()}catch(o){throw new Error(`Could not inspect iOS simulator app platform for ${Y.basename(e)}: ${o.message}`)}if(!/\bplatform\s+IOSSIMULATOR\b/i.test(r))throw new Error(`This iOS simulator artifact cannot be installed because ${Y.basename(e)} was built for the wrong Apple platform. A simulator artifact must contain platform IOSSIMULATOR. vtool output: ${r}. Rebuild the app with the latest Mach CLI.`)}async function Pf(e,t,n){let i=n||(t.toLowerCase().includes(".apk")?"android":"ios"),r=t.toLowerCase().includes(".ipa"),o=ae.mkdtempSync(Y.join(Xe.tmpdir(),`${St}-install-`)),s=Y.join(o,i==="android"?"install.apk":r?"install.ipa":"install.zip");try{if(await If(t,s),i==="android"){vt(Oa(),["-s",e,"install","-r",s],{stdio:"pipe"});return}if(process.platform!=="darwin")throw new Error("iOS local install requires macOS.");mi(`unzip -o ${JSON.stringify(s)} -d ${JSON.stringify(o)}`,{stdio:"pipe"});let l=Y.join(o,"Payload"),a=ae.existsSync(l),d=r||a,u="";if(d?u=wa(l,"Payload"):u=wa(o,"the simulator artifact"),!u)throw new Error(`No .app bundle found inside the ${r?"IPA":"archive"}.`);let c=d?null:await bf(e);if(c){try{Rf(u),vt("/usr/bin/xcrun",["simctl","install",c.id,u],{stdio:"pipe"})}catch(p){throw new Error(Ia(p,"iOS Simulator install failed."))}return}if(!d)throw new Error("Selected iOS Simulator was not found. Refresh Install Hub devices or boot one simulator and try again.");try{mi(`/usr/bin/xcrun devicectl device install app --device ${JSON.stringify(e)} ${JSON.stringify(u)}`,{stdio:"pipe"})}catch(p){throw new Error(Ia(p,"iOS device install failed."))}}finally{ae.rmSync(o,{recursive:!0,force:!0})}}function Df(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 mi(`/usr/bin/xcrun simctl boot ${JSON.stringify(e)}`,{stdio:"pipe"}),Sa("open",["-a","Simulator"],{detached:!0,stdio:"ignore"}).unref(),"Simulator booting..."}if(t==="android")return Sa(Ca(),["-avd",e],{detached:!0,stdio:"ignore",windowsHide:!0}).unref(),"Emulator booting in background...";throw new Error("Invalid platform.")}async function Of(){process.platform!=="darwin"&&Z.warn("Running on non-macOS \u2014 iOS discovery unavailable, Android only.");let e=yi.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:${St}`);if(i.method==="GET"&&o.pathname==="/local/devices"){Ef().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:St,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 Ea(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 Pf(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 Ea(i),l=Df(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(St,"127.0.0.1",()=>{Z.success(he.green(`Local device agent running on http://localhost:${St}`)),Z.info(he.dim("Keep this running while using the Install Hub on the dashboard.")),Z.info(he.dim("Press Ctrl+C to stop."))}),e.on("error",i=>{i.code==="EADDRINUSE"?Z.error(`Port ${St} is already in use \u2014 agent may already be running.`):Z.error(`Agent error: ${i.message}`),process.exit(1)}),await new Promise(()=>{})}async function Ma(e="start"){let t=String(e||"start").toLowerCase();if(t==="start"||t==="run"){await Of();return}if(t==="install"){await ba();return}if(t==="status"){await hf();return}if(t==="stop"){await Aa();return}if(t==="uninstall"){await gf();return}if(t==="restart"){await Aa(),await ba();return}Z.error(`Unknown agent action: ${e}`),Z.info(he.dim(`Use: ${m.nameLower} agent start | install | status | restart | stop | uninstall`)),process.exit(1)}import{createRequire as qg}from"module";import{text as kf,password as Tf,spinner as Nf,isCancel as Ba}from"@clack/prompts";import Kr from"chalk";import Cn from"fs";import Ua from"path";import Cf from"os";var Hr=Ua.join(Cf.homedir(),m.configDir),Gr=Ua.join(Hr,"config.json");function Vr(){if(!Cn.existsSync(Gr))return{};try{return JSON.parse(Cn.readFileSync(Gr,"utf-8"))}catch{return{}}}function Fa(e){Cn.existsSync(Hr)||Cn.mkdirSync(Hr,{recursive:!0});let n={...Vr(),...e};Cn.writeFileSync(Gr,JSON.stringify(n,null,2))}async function ja(){let e=Vr(),t=await kf({message:"Enter your email:",placeholder:"user@example.com",initialValue:e.lastLoginEmail,validate(r){if(r.length===0)return"Email is required!"}});if(Ba(t))return;let n=await Tf({message:"Enter your password:",validate(r){if(r.length===0)return"Password is required!"}});if(Ba(n))return;let i=Nf();i.start("Authenticating...");try{let o=await(await fetch(`${dt}/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:t,password:n})})).json();o.status==="success"&&o.user.token?(wo({id:o.user.id,email:t,token:o.user.token,refreshToken:o.user.refreshToken}),Fa({lastLoginEmail:t}),i.stop(Kr.green("Login successful!"))):i.stop(Kr.red("Login failed: "+(o.message||"Unknown error")))}catch(r){i.stop(Kr.red("Network error: "+r.message))}}import{log as Si,outro as xf}from"@clack/prompts";import kn from"chalk";async function Ha(){let e=_o(),t=`${m.envPrefix}TOKEN`;e?Si.success(kn.green(`Logged out. Removed saved credentials from ~/${m.configDir}/credentials.json.`)):Si.warn(kn.yellow(`No saved ${m.name} credentials found.`)),process.env[t]&&(Si.warn(kn.yellow(`${t} is still set in this shell. Commands will continue to authenticate with that token until you unset it.`)),Si.info(kn.dim(`Run: unset ${t}`))),xf(kn.blue("---"))}import{outro as Lf,select as Mf,spinner as Uf,isCancel as Ff}from"@clack/prompts";import bi from"chalk";import zr from"fs";import Bf from"path";var Ga=e=>e==="1234567890"||e==="ABC123DEFG"||e==="XXXXXXXXXX"?"":typeof e=="string"?e:"",jf=()=>process.versions.node.split(".")[0]||"24";async function Va(){if(!Ne()){console.log(bi.red(`You are not logged in. Run \`${m.nameLower} login\` first.`));return}let t=Uf();t.start("Fetching projects...");try{let{data:n}=await N.get("/projects");if(t.stop("Projects loaded."),n.status!=="success"||!n.projects||n.projects.length===0){console.log(bi.yellow(`No projects found. Run \`${m.nameLower} init\` to create one.`));return}let i=n.projects.map(g=>({value:g.projectId,label:`${g.name} (${g.slug})`})),r=await Mf({message:"Select a project to link:",options:i});if(Ff(r))return;let o=Bf.join(process.cwd(),m.configFileName),s={};if(zr.existsSync(o))try{s=JSON.parse(zr.readFileSync(o,"utf-8"))}catch{}let l=n.projects.find(g=>g.projectId===r),a=s.android?.package||ht("android"),d=s.ios?.bundleIdentifier||ht("ios"),u=s.android||{},c=s.submit?.production?.android||{},p=s.submit?.production?.ios||{},f={projectId:r,framework:He(s.framework)||zt,name:l?.name,slug:l?.slug,nodeVersion:s.nodeVersion||jf(),scheme:l?.slug?.toLowerCase()||"app",android:{...u,package:a||"",versionCode:u.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:{...c,track:c.track||"internal",releaseStatus:c.releaseStatus||"completed"},ios:{ascAppId:Ga(p.ascAppId),appleTeamId:Ga(p.appleTeamId)}}}};zr.writeFileSync(o,JSON.stringify(f,null,2)),Lf(bi.green(`Linked to project ${f.name} (${f.slug})`))}catch(n){t.stop(bi.red("Error fetching projects: "+n.message))}}import{outro as Hf,text as Ai,select as Gf,spinner as Vf,isCancel as Tn}from"@clack/prompts";import Nn from"chalk";import Kf from"fs";import zf from"path";import{randomUUID as Wf}from"crypto";var Jf=()=>process.versions.node.split(".")[0]||"24";async function Ka(){if(!Ne()){console.log(Nn.red(`You are not logged in. Run \`${m.nameLower} login\` first.`));return}let t=await Ai({message:"Project Name:",placeholder:"My Awesome App",validate(l){if(l.length===0)return"Name is required!"}});if(Tn(t))return;let n=await Ai({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(Tn(n))return;let i=await Gf({message:"Platform:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"},{value:"web",label:"Web"},{value:"all",label:"All Platforms"}]});if(Tn(i))return;let r="";if(i==="android"||i==="all"){let l=ht("android");if(r=await Ai({message:"Android Package Name:",initialValue:l||"",placeholder:"com.example.app",validate(a){if(a.length===0)return"Package name is required for Android!"}}),Tn(r))return}let o="";if(i==="ios"||i==="all"){let l=ht("ios");if(o=await Ai({message:"iOS Bundle Identifier:",initialValue:l||"",placeholder:"com.example.app",validate(a){if(a.length===0)return"Bundle ID is required for iOS!"}}),Tn(o))return}let s=Vf();s.start("Creating project...");try{let l=Wf(),d={projectId:l,name:t,slug:n,storageType:"managed",platforms:i==="all"?["android","ios","web"]:[i]},{data:u}=await N.post("/projects",d);if(u.status==="success"){s.stop(Nn.green("Project created successfully!"));let c=zf.join(process.cwd(),m.configFileName);Kf.writeFileSync(c,JSON.stringify({projectId:l,framework:zt,name:t,slug:n,nodeVersion:Jf(),...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)),Hf(Nn.green(`Initialized project ${t} and linked locally!`))}else s.stop(Nn.red("creation failed: "+u.message))}catch(l){s.stop(Nn.red("Network error: "+l.message))}}import{spinner as Wr,log as Te}from"@clack/prompts";import xn from"chalk";import Ei from"fs";import za from"path";function Jr(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 Yf(e){let t=String(e??"");return t===""?'""':/^[A-Za-z0-9_./:@%+-]+$/.test(t)?t:JSON.stringify(t)}function qf(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}=${Yf(e[i])}`)].join(`
|
|
1529
|
+
`;return le.writeFileSync(bi(),s),bi()}function $t(e,t={}){try{return Rt("launchctl",e,{stdio:t.ignoreError?"ignore":"pipe"}),!0}catch(n){if(t.ignoreError)return!1;throw n}}function pf(e){return new Promise(t=>setTimeout(t,e))}function Ai(e,t,n=sf){return new Promise((i,r)=>{rf(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 xa(){if(typeof fetch=="function"){let e=new AbortController,t=setTimeout(()=>e.abort(),3e3);try{return(await fetch(`${Cn}/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=Ei.get(`${Cn}/health`,r=>{r.resume(),n(r.statusCode===200)});i.setTimeout(3e3,()=>{i.destroy(),n(!1)}),i.on("error",()=>n(!1))})}async function ff(e=8e3){let t=Date.now()+e;for(;Date.now()<t;){if(await xa())return!0;await pf(250)}return!1}async function La(){return new Promise(e=>{let t=!1,n=Ra.createConnection({host:"127.0.0.1",port:St}),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 Kr(){if(await ff()){Z.success(he.green("Mach agent installed and started."));return}if(await La()){Z.warn(`Mach agent service is installed, but port ${St} is held by a process that is not answering /health.`),Z.info(he.dim(`Run \`${m.nameLower} agent stop\`, close any foreground \`${m.nameLower} agent\` terminal, then run \`${m.nameLower} agent install\` again.`));return}Z.warn(`Mach agent service is installed, but it did not start listening on ${Cn}.`)}async function mf(){let e=uf(),t=Hr();$t(["bootout",t,e],{ignoreError:!0}),$t(["bootstrap",t,e],{ignoreError:!0})||$t(["load","-w",e]),$t(["enable",`${t}/${on}`],{ignoreError:!0}),$t(["kickstart","-k",`${t}/${on}`],{ignoreError:!0}),await Kr(),Z.info(he.dim(`It will start automatically when you log in. Plist: ${e}`)),Z.info(he.dim(`Logs: ${q.join(Ze(),"agent.log")}`))}async function Ma(){let e=bi(),t=Hr();$t(["bootout",t,e],{ignoreError:!0})||$t(["unload","-w",e],{ignoreError:!0})?Z.success(he.green("Mach agent service stopped.")):Z.warn("Mach agent service was not loaded.")}async function gf(){await Ma();let e=bi();le.existsSync(e)&&le.unlinkSync(e),Z.success(he.green("Mach agent service uninstalled."))}async function hf(){let e=cf();_t(["daemon-reload"]),_t(["enable","--now",sn]),await Kr(),Z.info(he.dim(`It will start automatically when you log in. Service: ${e}`)),Z.info(he.dim(`Logs: ${q.join(Ze(),"agent.log")}`))}async function yf(){_t(["stop",sn],{ignoreError:!0})?Z.success(he.green("Mach agent service stopped.")):Z.warn("Mach agent service was not running.")}async function Sf(){_t(["disable","--now",sn],{ignoreError:!0}),_t(["daemon-reload"],{ignoreError:!0});let e=Br();le.existsSync(e)&&le.unlinkSync(e),_t(["daemon-reload"],{ignoreError:!0}),Z.success(he.green("Mach agent service uninstalled."))}async function bf(){let e=df();kn(["/Create","/TN",rn,"/SC","ONLOGON","/TR",`"${e}"`,"/RL","LIMITED","/F"]),kn(["/Run","/TN",rn],{ignoreError:!0}),await Kr(),Z.info(he.dim(`It will start automatically when you log in. Task: ${rn}`)),Z.info(he.dim(`Logs: ${q.join(Ze(),"agent.log")}`))}async function Ua(){kn(["/End","/TN",rn],{ignoreError:!0})?Z.success(he.green("Mach agent task stopped.")):Z.warn("Mach agent task was not running.")}async function Af(){await Ua(),kn(["/Delete","/TN",rn,"/F"],{ignoreError:!0});let e=jr();le.existsSync(e)&&le.unlinkSync(e),Z.success(he.green("Mach agent task uninstalled."))}async function Ia(){if(process.platform==="darwin")return mf();if(process.platform==="linux")return hf();if(process.platform==="win32")return bf();throw new Error(`Background agent install is not supported on ${process.platform}.`)}async function wa(){if(process.platform==="darwin")return Ma();if(process.platform==="linux")return yf();if(process.platform==="win32")return Ua();Z.warn(`Background agent service control is not supported on ${process.platform}.`)}async function Ef(){if(process.platform==="darwin")return gf();if(process.platform==="linux")return Sf();if(process.platform==="win32")return Af();Z.warn(`Background agent uninstall is not supported on ${process.platform}.`)}async function If(){let e=await xa(),t=e?!0:await La();if(e?Z.success(he.green(`Mach agent is online at ${Cn}`)):t?Z.warn(`Mach agent port is open, but /health did not respond. Run \`${m.nameLower} agent restart\` if the dashboard still shows offline.`):Z.warn(`Mach agent is not responding at ${Cn}`),process.platform==="darwin"){let n=$t(["print",`${Hr()}/${on}`],{ignoreError:!0});Z.info(he.dim(`Login service: ${n?"installed/loaded":"not loaded"}`))}else if(process.platform==="linux"){let n=_t(["is-enabled",sn],{ignoreError:!0}),i=_t(["is-active",sn],{ignoreError:!0});Z.info(he.dim(`Login service: ${n?"enabled":"not enabled"} / ${i?"active":"inactive"}`))}else if(process.platform==="win32"){let n=kn(["/Query","/TN",rn],{ignoreError:!0});Z.info(he.dim(`Login task: ${n?"installed":"not installed"}`))}}async function wf(){let e=[];try{(await Ai(Ta(),["devices","-l"])).split(`
|
|
1530
|
+
`).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 Ai(Na(),["-list-avds"])).split(`
|
|
1531
|
+
`).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 Fa(){if(process.platform!=="darwin")return[];try{let e=await Ai("/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 vf(){if(process.platform!=="darwin")return[];try{let e=await Ai("/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 $f(e){let t=await Fa(),n=t.find(r=>r.id===e);if(n)return n;let i=t.filter(r=>r.status==="online");return i.length===1?i[0]:null}async function _f(){let[e,t,n]=await Promise.all([wf(),Fa(),vf()]);return[...e,...t,...n]}async function Rf(){let e=Date.now();return hi&&e-hi.updatedAt<af?hi.targets:(yi||(yi=_f().then(t=>(hi={targets:t,updatedAt:Date.now()},t)).finally(()=>{yi=null})),yi)}async function va(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 Pf(e,t){let n=await of({method:"GET",url:e,responseType:"stream",timeout:12e4}),i=le.createWriteStream(t);n.data.pipe(i),await new Promise((r,o)=>{i.on("finish",r),i.on("error",o)})}function $a(e,t){let n=e?.stderr?.toString?.().trim();if(n)return n;let i=e?.stdout?.toString?.().trim();return i||e?.message||t}function Df(e,t){return Rt("/usr/libexec/PlistBuddy",["-c",`Print :${t}`,e],{encoding:"utf-8"}).trim()}function Of(e){let t=q.join(e,"Info.plist");if(!le.existsSync(t))throw new Error(`Could not validate iOS app executable: ${t} not found.`);let n=Df(t,"CFBundleExecutable"),i=q.join(e,n);if(!le.existsSync(i))throw new Error(`Could not validate iOS app executable: ${i} not found.`);return i}function Cf(){return process.arch==="arm64"?"arm64":"x86_64"}function kf(e){return le.existsSync(e)?le.readdirSync(e).map(t=>q.join(e,t)).filter(t=>t.endsWith(".app")&&le.statSync(t).isDirectory()):[]}function _a(e,t){let n=kf(e);if(n.length===1)return n[0];if(n.length>1)throw new Error(`Multiple .app bundles found in ${t}: ${n.map(i=>q.basename(i)).join(", ")}. Mach cannot safely choose which app to install.`);return""}function Tf(e){let t=Of(e),n=Cf(),i="",r="";try{i=Rt("lipo",["-info",t],{encoding:"utf-8"}).trim()}catch(o){throw new Error(`Could not inspect iOS simulator app architecture for ${q.basename(e)}: ${o.message}`)}if(!new RegExp(`\\b${n}\\b`).test(i))throw new Error(`This iOS simulator artifact cannot be installed because ${q.basename(e)} does not include the ${n} simulator architecture. lipo output: ${i}. Rebuild the app with the latest Mach CLI and make sure the profile is a simulator build.`);try{r=Rt("/usr/bin/xcrun",["vtool","-show-build",t],{encoding:"utf-8"}).trim()}catch(o){throw new Error(`Could not inspect iOS simulator app platform for ${q.basename(e)}: ${o.message}`)}if(!/\bplatform\s+IOSSIMULATOR\b/i.test(r))throw new Error(`This iOS simulator artifact cannot be installed because ${q.basename(e)} was built for the wrong Apple platform. A simulator artifact must contain platform IOSSIMULATOR. vtool output: ${r}. Rebuild the app with the latest Mach CLI.`)}async function Nf(e,t,n){let i=n||(t.toLowerCase().includes(".apk")?"android":"ios"),r=t.toLowerCase().includes(".ipa"),o=le.mkdtempSync(q.join(Xe.tmpdir(),`${St}-install-`)),s=q.join(o,i==="android"?"install.apk":r?"install.ipa":"install.zip");try{if(await Pf(t,s),i==="android"){Rt(Ta(),["-s",e,"install","-r",s],{stdio:"pipe"});return}if(process.platform!=="darwin")throw new Error("iOS local install requires macOS.");Si(`unzip -o ${JSON.stringify(s)} -d ${JSON.stringify(o)}`,{stdio:"pipe"});let l=q.join(o,"Payload"),a=le.existsSync(l),d=r||a,u="";if(d?u=_a(l,"Payload"):u=_a(o,"the simulator artifact"),!u)throw new Error(`No .app bundle found inside the ${r?"IPA":"archive"}.`);let c=d?null:await $f(e);if(c){try{Tf(u),Rt("/usr/bin/xcrun",["simctl","install",c.id,u],{stdio:"pipe"})}catch(p){throw new Error($a(p,"iOS Simulator install failed."))}return}if(!d)throw new Error("Selected iOS Simulator was not found. Refresh Install Hub devices or boot one simulator and try again.");try{Si(`/usr/bin/xcrun devicectl device install app --device ${JSON.stringify(e)} ${JSON.stringify(u)}`,{stdio:"pipe"})}catch(p){throw new Error($a(p,"iOS device install failed."))}}finally{le.rmSync(o,{recursive:!0,force:!0})}}function xf(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 Si(`/usr/bin/xcrun simctl boot ${JSON.stringify(e)}`,{stdio:"pipe"}),Ea("open",["-a","Simulator"],{detached:!0,stdio:"ignore"}).unref(),"Simulator booting..."}if(t==="android")return Ea(Na(),["-avd",e],{detached:!0,stdio:"ignore",windowsHide:!0}).unref(),"Emulator booting in background...";throw new Error("Invalid platform.")}async function Lf(){process.platform!=="darwin"&&Z.warn("Running on non-macOS \u2014 iOS discovery unavailable, Android only.");let e=Ei.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:${St}`);if(i.method==="GET"&&o.pathname==="/local/devices"){Rf().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:St,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 va(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 Nf(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 va(i),l=xf(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(St,"127.0.0.1",()=>{Z.success(he.green(`Local device agent running on http://localhost:${St}`)),Z.info(he.dim("Keep this running while using the Install Hub on the dashboard.")),Z.info(he.dim("Press Ctrl+C to stop."))}),e.on("error",i=>{i.code==="EADDRINUSE"?Z.error(`Port ${St} is already in use \u2014 agent may already be running.`):Z.error(`Agent error: ${i.message}`),process.exit(1)}),await new Promise(()=>{})}async function Ba(e="start"){let t=String(e||"start").toLowerCase();if(t==="start"||t==="run"){await Lf();return}if(t==="install"){await Ia();return}if(t==="status"){await If();return}if(t==="stop"){await wa();return}if(t==="uninstall"){await Ef();return}if(t==="restart"){await wa(),await Ia();return}Z.error(`Unknown agent action: ${e}`),Z.info(he.dim(`Use: ${m.nameLower} agent start | install | status | restart | stop | uninstall`)),process.exit(1)}import{createRequire as sh}from"module";import{text as Uf,password as Ff,spinner as Bf,isCancel as Ga}from"@clack/prompts";import Yr from"chalk";import Tn from"fs";import ja from"path";import Mf from"os";var zr=ja.join(Mf.homedir(),m.configDir),Wr=ja.join(zr,"config.json");function Jr(){if(!Tn.existsSync(Wr))return{};try{return JSON.parse(Tn.readFileSync(Wr,"utf-8"))}catch{return{}}}function Ha(e){Tn.existsSync(zr)||Tn.mkdirSync(zr,{recursive:!0});let n={...Jr(),...e};Tn.writeFileSync(Wr,JSON.stringify(n,null,2))}async function Va(){let e=Jr(),t=await Uf({message:"Enter your email:",placeholder:"user@example.com",initialValue:e.lastLoginEmail,validate(r){if(r.length===0)return"Email is required!"}});if(Ga(t))return;let n=await Ff({message:"Enter your password:",validate(r){if(r.length===0)return"Password is required!"}});if(Ga(n))return;let i=Bf();i.start("Authenticating...");try{let o=await(await fetch(`${dt}/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:t,password:n})})).json();o.status==="success"&&o.user.token?(Do({id:o.user.id,email:t,token:o.user.token,refreshToken:o.user.refreshToken}),Ha({lastLoginEmail:t}),i.stop(Yr.green("Login successful!"))):i.stop(Yr.red("Login failed: "+(o.message||"Unknown error")))}catch(r){i.stop(Yr.red("Network error: "+r.message))}}import{log as Ii,outro as jf}from"@clack/prompts";import Nn from"chalk";async function Ka(){let e=Oo(),t=`${m.envPrefix}TOKEN`;e?Ii.success(Nn.green(`Logged out. Removed saved credentials from ~/${m.configDir}/credentials.json.`)):Ii.warn(Nn.yellow(`No saved ${m.name} credentials found.`)),process.env[t]&&(Ii.warn(Nn.yellow(`${t} is still set in this shell. Commands will continue to authenticate with that token until you unset it.`)),Ii.info(Nn.dim(`Run: unset ${t}`))),jf(Nn.blue("---"))}import{outro as Hf,select as Gf,spinner as Vf,isCancel as Kf}from"@clack/prompts";import wi from"chalk";import qr from"fs";import zf from"path";var za=e=>e==="1234567890"||e==="ABC123DEFG"||e==="XXXXXXXXXX"?"":typeof e=="string"?e:"",Wf=()=>process.versions.node.split(".")[0]||"24";async function Wa(){if(!ke()){console.log(wi.red(`You are not logged in. Run \`${m.nameLower} login\` first.`));return}let t=Vf();t.start("Fetching projects...");try{let{data:n}=await k.get("/projects");if(t.stop("Projects loaded."),n.status!=="success"||!n.projects||n.projects.length===0){console.log(wi.yellow(`No projects found. Run \`${m.nameLower} init\` to create one.`));return}let i=n.projects.map(g=>({value:g.projectId,label:`${g.name} (${g.slug})`})),r=await Gf({message:"Select a project to link:",options:i});if(Kf(r))return;let o=zf.join(process.cwd(),m.configFileName),s={};if(qr.existsSync(o))try{s=JSON.parse(qr.readFileSync(o,"utf-8"))}catch{}let l=n.projects.find(g=>g.projectId===r),a=s.android?.package||ht("android"),d=s.ios?.bundleIdentifier||ht("ios"),u=s.android||{},c=s.submit?.production?.android||{},p=s.submit?.production?.ios||{},f={projectId:r,framework:He(s.framework)||Jt,name:l?.name,slug:l?.slug,nodeVersion:s.nodeVersion||Wf(),scheme:l?.slug?.toLowerCase()||"app",android:{...u,package:a||"",versionCode:u.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:{...c,track:c.track||"internal",releaseStatus:c.releaseStatus||"completed"},ios:{ascAppId:za(p.ascAppId),appleTeamId:za(p.appleTeamId)}}}};qr.writeFileSync(o,JSON.stringify(f,null,2)),Hf(wi.green(`Linked to project ${f.name} (${f.slug})`))}catch(n){t.stop(wi.red("Error fetching projects: "+n.message))}}import{outro as Jf,text as vi,select as Yf,spinner as qf,isCancel as xn}from"@clack/prompts";import Ln from"chalk";import Xf from"fs";import Zf from"path";import{randomUUID as Qf}from"crypto";var em=()=>process.versions.node.split(".")[0]||"24";async function Ja(){if(!ke()){console.log(Ln.red(`You are not logged in. Run \`${m.nameLower} login\` first.`));return}let t=await vi({message:"Project Name:",placeholder:"My Awesome App",validate(l){if(l.length===0)return"Name is required!"}});if(xn(t))return;let n=await vi({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(xn(n))return;let i=await Yf({message:"Platform:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"},{value:"web",label:"Web"},{value:"all",label:"All Platforms"}]});if(xn(i))return;let r="";if(i==="android"||i==="all"){let l=ht("android");if(r=await vi({message:"Android Package Name:",initialValue:l||"",placeholder:"com.example.app",validate(a){if(a.length===0)return"Package name is required for Android!"}}),xn(r))return}let o="";if(i==="ios"||i==="all"){let l=ht("ios");if(o=await vi({message:"iOS Bundle Identifier:",initialValue:l||"",placeholder:"com.example.app",validate(a){if(a.length===0)return"Bundle ID is required for iOS!"}}),xn(o))return}let s=qf();s.start("Creating project...");try{let l=Qf(),d={projectId:l,name:t,slug:n,storageType:"managed",platforms:i==="all"?["android","ios","web"]:[i]},{data:u}=await k.post("/projects",d);if(u.status==="success"){s.stop(Ln.green("Project created successfully!"));let c=Zf.join(process.cwd(),m.configFileName);Xf.writeFileSync(c,JSON.stringify({projectId:l,framework:Jt,name:t,slug:n,nodeVersion:em(),...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)),Jf(Ln.green(`Initialized project ${t} and linked locally!`))}else s.stop(Ln.red("creation failed: "+u.message))}catch(l){s.stop(Ln.red("Network error: "+l.message))}}import{spinner as Xr,log as Ne}from"@clack/prompts";import Mn from"chalk";import $i from"fs";import Ya from"path";function Zr(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 tm(e){let t=String(e??"");return t===""?'""':/^[A-Za-z0-9_./:@%+-]+$/.test(t)?t:JSON.stringify(t)}function nm(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}=${tm(e[i])}`)].join(`
|
|
1532
1532
|
`)}
|
|
1533
|
-
`}async function
|
|
1534
|
-
`)}function
|
|
1533
|
+
`}async function qa(e,t,n={}){let i=ke();if(!i){Ne.error(`You are not logged in. Run \`${m.nameLower} login\` first.`);return}let r=Ya.join(process.cwd(),m.configFileName);if(!$i.existsSync(r)){Ne.error(`No ${m.configFileName} found. Run \`${m.nameLower} init\` or \`${m.nameLower} link\` first.`);return}let o;try{o=JSON.parse($i.readFileSync(r,"utf-8"))}catch{Ne.error(`Failed to parse ${m.configFileName}`);return}let{projectId:s}=o;if(!s){Ne.error(`${m.configFileName} is missing projectId.`);return}e==="set"?await im(s,t,i):e==="list"?await rm(s,i):e==="pull"||e==="download"||e==="export"?await om(s,n):Ne.error(`Unknown env action: ${e}. Use 'set', 'list', or 'pull'.`)}async function im(e,t,n){if(t.length===0){Ne.error(`Usage: ${m.nameLower} env set KEY=VALUE [KEY2=VALUE2 ...]`);return}let i=Xr();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){Ne.warn(`Invalid format for argument: ${s}. Expected KEY=VALUE.`),o++;continue}try{let u={key:l.trim(),value:d,type:"env",environment:"global",visibility:"secret"},{data:c}=await k.post(`/projects/${e}/secrets`,u);c.status==="success"?r++:(Ne.error(`Failed to set ${l}: ${c.message}`),o++)}catch(u){Ne.error(Zr(u,e,"set",l)),o++}}i.stop(`Set ${r} variable(s). ${o>0?`${o} failed.`:""}`)}async function rm(e,t){let n=Xr();n.start("Fetching environment variables...");try{let{data:i}=await k.get(`/projects/${e}/secrets`);if(i.status==="success"){n.stop("Fetched variables.");let r=i.secrets||[];r.length===0?Ne.info("No environment variables found for this project."):(Ne.info(Mn.bold("Environment Variables (Global & Scoped):")),r.forEach(o=>{let s=o.visibility==="plain"?o.value:"********";console.log(` ${Mn.cyan(o.key)} = ${s} ${Mn.gray(`[${o.environment}]`)}`)}))}else n.stop(Mn.red(`Failed to fetch variables: ${i.message}`))}catch(i){n.stop("Failed to fetch variables."),Ne.error(Zr(i,e,"list"))}}async function om(e,t){let n=(t.environment||"development").trim(),i=t.out||".env.local",r=Ya.resolve(process.cwd(),i);if($i.existsSync(r)&&!t.overwrite){Ne.error(`${i} already exists. Re-run with \`--overwrite\` to replace it.`);return}let o=Xr();o.start(`Downloading ${n} environment variables...`);try{let{data:s}=await k.get(`/projects/${e}/secrets/export?env=${encodeURIComponent(n)}`);if(s.status!=="success"){o.stop(Mn.red(`Failed to download variables: ${s.message||"Unknown API error"}`));return}let l=s.secrets||{},a=nm(l,n);$i.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."),Ne.error(Zr(s,e,"pull"))}}import{cancel as sm,confirm as am,isCancel as Qr,log as at,note as lm,outro as an,select as cm,spinner as dm,text as um}from"@clack/prompts";import Qe from"chalk";import ce from"fs";import Se from"path";import{spawnSync as tl}from"child_process";import nl from"crypto";import pm from"axios";var Te=`${m.npmScope}/mach/expo-plugin`,il=()=>process.stdin.isTTY&&process.stdout.isTTY,eo=()=>{sm("Operation cancelled."),process.exit(0)},Pt=e=>{if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0};function _i(e){if(!ce.existsSync(e))return null;try{return JSON.parse(ce.readFileSync(e,"utf-8"))}catch{return null}}function rl(e,t){ce.writeFileSync(e,`${JSON.stringify(t,null,2)}
|
|
1534
|
+
`)}function Un(){let e=ve();return e?.projectId||(at.error(`No ${m.configFileName} found or missing projectId. Run \`${m.nameLower} link\` first.`),process.exit(1)),e}function fm(e){rl(Se.join(process.cwd(),m.configFileName),e)}function to(e){let t=He(e.framework);if(t)return t;let n=_i(Se.join(process.cwd(),"package.json"))||{},i={...n.dependencies||{},...n.devDependencies||{}};return i.expo?"expo":(i["react-native"],"react-native")}function no(e,t){let n=String(e||"").trim().toLowerCase();return n==="expo"||n==="expo-updates"?"expo-updates":n==="react-native"||n==="mach-react-native"||n==="rn"?"mach-react-native":t==="expo"?"expo-updates":"mach-react-native"}function mm(e){let t=String(e||"all").trim().toLowerCase();if(t==="ios")return["ios"];if(t==="android")return["android"];if(t==="all"||t==="both")return["ios","android"];throw new Error("Platform must be ios, android, or all.")}function gm(e){return ce.existsSync(Se.join(e,"pnpm-lock.yaml"))?{command:"pnpm",args:["add","-D",`${m.npmScope}/mach@latest`],label:`pnpm add -D ${m.npmScope}/mach@latest`}:ce.existsSync(Se.join(e,"yarn.lock"))?{command:"yarn",args:["add","-D",`${m.npmScope}/mach@latest`],label:`yarn add -D ${m.npmScope}/mach@latest`}:ce.existsSync(Se.join(e,"bun.lockb"))||ce.existsSync(Se.join(e,"bun.lock"))?{command:"bun",args:["add","-d",`${m.npmScope}/mach@latest`],label:`bun add -d ${m.npmScope}/mach@latest`}:{command:"npm",args:["install","--save-dev",`${m.npmScope}/mach@latest`],label:`npm install --save-dev ${m.npmScope}/mach@latest`}}function io(e){let t=_i(Se.join(e,"package.json"))||{};return!!(t.dependencies?.[`${m.npmScope}/mach`]||t.devDependencies?.[`${m.npmScope}/mach`])}function hm(e){let t=gm(e),n=tl(t.command,t.args,{cwd:e,stdio:"inherit",env:{...process.env}});return n.error?{ok:!1,label:t.label,error:n.error.message}:n.status!==0?{ok:!1,label:t.label,error:`${t.command} exited with code ${n.status}`}:{ok:io(e),label:t.label}}function Xa(e){if(typeof e=="string")return e;if(Array.isArray(e)&&typeof e[0]=="string")return e[0]}function ym(e){let t=["app.config.json","app.json"].find(s=>ce.existsSync(Se.join(e,s)));if(!t)return null;let n=Se.join(e,t),i=_i(n);if(!i)return null;let r=i.expo&&typeof i.expo=="object"?i.expo:i,o=Array.isArray(r.plugins)?r.plugins:[];return o.some(s=>Xa(s)===Te)||(r.plugins=[...o.filter(s=>{let l=Xa(s);return l!=="./plugins/withMachDeepLinks"&&l!=="plugins/withMachDeepLinks"}),Te],rl(n,i)),t}function Sm(e){let t=["app.config.ts","app.config.js"].find(f=>ce.existsSync(Se.join(e,f)));if(!t)return"missing";let n=Se.join(e,t),i=ce.readFileSync(n,"utf-8");if(i.includes(Te))return"already";let r=/(['"`])(?:\.\/)?plugins\/withMachDeepLinks\1/g;if(r.test(i))return ce.writeFileSync(n,i.replace(r,(f,g)=>`${g}${Te}${g}`)),"inserted";let o=/(^[ \t]*)plugins\s*:\s*\[([\s\S]*?)\]/m.exec(i);if(!o||o.index===void 0)return"manual";let s=i.includes(`\r
|
|
1535
1535
|
`)?`\r
|
|
1536
1536
|
`:`
|
|
1537
|
-
`,l=o[1]||"",a=o[2]||"",u=a.match(/\r?\n([ \t]+)\S/)?.[1]||`${l} `,c=a.trim().length===0?`${s}${u}'${
|
|
1538
|
-
`)||a.includes("\r")?`${s}${u}'${
|
|
1539
|
-
`),"OTA setup"),await
|
|
1540
|
-
`))}else
|
|
1537
|
+
`,l=o[1]||"",a=o[2]||"",u=a.match(/\r?\n([ \t]+)\S/)?.[1]||`${l} `,c=a.trim().length===0?`${s}${u}'${Te}',${s}${l}`:a.includes(`
|
|
1538
|
+
`)||a.includes("\r")?`${s}${u}'${Te}',${a}`:`${s}${u}'${Te}',${s}${u}${a.trim()}${s}${l}`,p=`${o[0].slice(0,o[0].indexOf("[")+1)}${c}]`;return ce.writeFileSync(n,`${i.slice(0,o.index)}${p}${i.slice(o.index+o[0].length)}`),"inserted"}async function bm(e,t){let n=[];if(!io(e)){let r=!!(t.installPlugin||t.yes);if(!r&&!t.skipInstall&&il()){let o=await am({message:`Install ${m.npmScope}/mach locally so Expo can use ${Te}?`,initialValue:!0});Qr(o)&&eo(),r=!!o}if(r&&!t.skipInstall){let o=hm(e);o.ok?n.push(`Installed ${m.npmScope}/mach with ${o.label}.`):n.push(`Could not install ${m.npmScope}/mach with ${o.label}: ${o.error||"unknown error"}.`)}else n.push(`Install ${m.npmScope}/mach in this app so Expo can resolve ${Te}.`)}let i=Sm(e);if(i==="already"&&n.push(`Expo config already includes ${Te}.`),i==="inserted"&&n.push(`Expo config updated to include ${Te}.`),i==="manual"&&n.push(`Add "${Te}" to the plugins array in app.config.ts/app.config.js.`),i==="missing"){let r=ym(e);r?n.push(`${r} updated to include ${Te}.`):n.push(`Add "${Te}" to your Expo config plugins array.`)}return n}async function Za(e,t,n,i,r){if(t)return t;if(r||!il()){if(i)throw new Error(`${e.replace(/:$/,"")} is required.`);return}let o=await um({message:e,placeholder:n,validate(s){if(i&&s.trim().length===0)return"Required."}});return Qr(o)&&eo(),Pt(o)}function Am(e,t,n){return En(e,{runtimeVersion:t.runtimeVersion,framework:He(t.framework)||He(e.framework),platform:n})}function Em(e){return nl.createHash("sha256").update(ce.readFileSync(e)).digest("hex")}function Im(e){let t=Se.extname(e).toLowerCase();return t===".json"?"application/json":t===".js"||t===".bundle"||t===".hbc"?"application/javascript":t===".map"?"application/json":t===".png"?"image/png":t===".jpg"||t===".jpeg"?"image/jpeg":t===".webp"?"image/webp":t===".gif"?"image/gif":t===".svg"?"image/svg+xml":t===".ttf"?"font/ttf":t===".otf"?"font/otf":t===".woff"?"font/woff":t===".woff2"?"font/woff2":"application/octet-stream"}function ol(e){let t=[];if(!ce.existsSync(e))return t;for(let n of ce.readdirSync(e)){let i=Se.join(e,n),r=ce.statSync(i);r.isDirectory()?t.push(...ol(i)):r.isFile()&&t.push(i)}return t}function wm(e,t){let n=e.filter(i=>{let r=i.toLowerCase();return r.endsWith(".map")?!1:r.endsWith(".js")||r.endsWith(".bundle")||r.endsWith(".hbc")});return n.find(i=>i.toLowerCase().includes(t))||n.sort((i,r)=>ce.statSync(r).size-ce.statSync(i).size)[0]}async function Qa(e){let t=await k.post("/ota/upload-url",{projectId:e.projectId,updateId:e.updateId,platform:e.platform,fileName:e.fileName,contentType:e.contentType});if(t.data.status!=="success")throw new Error(t.data.message||`Could not create upload URL for ${e.fileName}`);let n=ce.statSync(e.filePath).size;return await pm.put(t.data.uploadUrl,ce.createReadStream(e.filePath),{headers:{"Content-Type":e.contentType,"Content-Length":n},maxBodyLength:1/0,maxContentLength:1/0}),{key:t.data.key,url:t.data.publicUrl,contentType:e.contentType,hash:Em(e.filePath),size:n}}function sl(e,t,n){let i=tl(e,t,{cwd:n,stdio:"inherit",env:{...process.env,CI:process.env.CI||"1",EXPO_NO_TELEMETRY:"1"}});if(i.error)throw new Error(i.error.message);if(i.status!==0)throw new Error(`${e} ${t.join(" ")} exited with code ${i.status}`)}function vm(e,t){sl("npx",["expo","export","--platform",e,"--output-dir",t],process.cwd())}function $m(e,t){let n=e==="ios"?"main.jsbundle":"index.android.bundle",r=["index.js","index.ts","index.tsx"].find(s=>ce.existsSync(Se.join(process.cwd(),s)))||"index.js",o=Se.join(t,"assets");ce.mkdirSync(o,{recursive:!0}),sl("npx",["react-native","bundle","--platform",e,"--dev","false","--entry-file",r,"--bundle-output",Se.join(t,n),"--assets-dest",o],process.cwd())}async function _m(e){let t=e.config.projectId,n=`ota_${Date.now()}_${e.platform}_${nl.randomUUID().slice(0,8)}`,i=Se.join(process.cwd(),".mach","ota",n,e.platform);ce.rmSync(i,{recursive:!0,force:!0}),ce.mkdirSync(i,{recursive:!0}),e.engine==="expo-updates"?vm(e.platform,i):$m(e.platform,i);let r=ol(i),o=wm(r,e.platform);if(!o)throw new Error(`Could not find a ${e.platform} JS bundle in ${i}.`);let s=[];for(let f of r){let g=Se.relative(i,f).replace(/\\/g,"/");s.push({filePath:f,relative:g,uploaded:await Qa({projectId:t,updateId:n,platform:e.platform,filePath:f,fileName:g,contentType:Im(f)})})}let l=s.find(f=>f.filePath===o),a=s.filter(f=>f.filePath!==o&&!f.relative.endsWith(".map")).map(f=>({key:f.relative,url:f.uploaded.url,contentType:f.uploaded.contentType,hash:f.uploaded.hash,size:f.uploaded.size})),d={id:n,createdAt:new Date().toISOString(),runtimeVersion:e.runtimeVersion,platform:e.platform,launchAsset:{key:Se.basename(l.relative),url:l.uploaded.url,contentType:l.uploaded.contentType,hash:l.uploaded.hash,size:l.uploaded.size},assets:a,metadata:{projectId:t,channel:e.channel,message:e.message||null,engine:e.engine},extra:{mach:{projectId:t,updateId:n,channel:e.channel,platform:e.platform}}},u=Se.join(i,"mach-manifest.json");ce.writeFileSync(u,JSON.stringify(d,null,2));let c=await Qa({projectId:t,updateId:n,platform:e.platform,filePath:u,fileName:"manifest.json",contentType:"application/json"}),p=await k.post("/ota/publish",{projectId:t,updateId:n,channelName:e.channel,runtimeVersion:e.runtimeVersion,platform:e.platform,manifestKey:c.key,message:e.message,launchAsset:d.launchAsset,assets:a});if(p.data.status!=="success")throw new Error(p.data.message||`Failed to publish ${e.platform} OTA update.`);return p.data.update}async function Rm(e){let t=Un(),n=He(e.framework)||to(t),i=no(e.engine||t.ota?.engine,n),r=!!e.yes,o=await Za("OTA channel:",Pt(e.channel||e.branch||t.ota?.channel)||"production","production",!0,r),s=`${dt.replace(/\/$/,"")}/api/ota/${i==="expo-updates"?"expo":"react-native"}/${t.projectId}`,l=await Za("Mach OTA update URL:",Pt(e.url||t.ota?.url)||s,s,!0,r);t.framework=n,t.ota={...t.ota||{},enabled:!0,engine:i,channel:o,url:l,deploymentUrl:l,statsUrl:`${dt.replace(/\/$/,"")}/api/ota/events`,runtimeVersionPolicy:t.ota?.runtimeVersionPolicy||"appVersion"},delete t.update,fm(t);let a=[`${m.configFileName} updated.`];n==="expo"?a.push(...await bm(process.cwd(),e)):a.push("Vanilla React Native native OTA client setup is planned; this command wrote Mach config only for now."),lm(a.map(d=>`- ${d}`).join(`
|
|
1539
|
+
`),"OTA setup"),await al({...e,action:"verify"})}async function Pm(e){Wt();let t=Un(),n=He(e.framework)||to(t),i=no(e.engine||t.ota?.engine,n),r=Pt(e.channel||e.branch||t.ota?.channel)||"production",o=mm(e.platform||"all"),s=dm();s.start(`Publishing OTA update (${o.join("+")}, ${r})`);try{let l=[];for(let a of o){let d=Am(t,e,a);s.message(`Exporting and uploading ${a} OTA bundle for runtime ${d}...`),l.push(await _m({config:t,engine:i,platform:a,channel:r,runtimeVersion:d,message:e.message}))}if(s.stop("OTA update published."),e.json)at.info(JSON.stringify({status:"success",updates:l},null,2));else{let a=Array.from(new Set(l.map(d=>d.runtimeVersion).filter(Boolean)));an(Qe.green(`\u2713 OTA update live on "${r}" for runtime ${a.join(", ")||"unknown"}.`));for(let d of l)at.info(Qe.dim(`${d.platform}: ${d.updateId}`))}}catch(l){s.stop("OTA publish failed."),at.error(l.response?.data?.message||l.message),process.exit(1)}}async function al(e){let t=Un(),n=He(e.framework)||to(t),i=no(e.engine||t.ota?.engine,n),r=[],o=t.ota;if(r.push(o?.enabled?{level:"pass",message:"mach.config.json has ota.enabled."}:{level:"fail",message:"mach.config.json is missing ota.enabled. Run `mach ota setup`."}),r.push(o?.url?{level:"pass",message:`OTA URL configured: ${o.url}`}:{level:"fail",message:"OTA URL is missing. Run `mach ota setup`."}),r.push(o?.channel?{level:"pass",message:`Default channel: ${o.channel}`}:{level:"warn",message:"No default OTA channel configured; publish will use production."}),r.push(o?.runtimeVersionPolicy||o?.runtimeVersion?{level:"pass",message:"Runtime version policy configured."}:{level:"warn",message:"No explicit runtime policy configured; Mach will use Expo runtimeVersion or package.json version."}),i==="expo-updates"){let l=_i(Se.join(process.cwd(),"package.json"))||{},a={...l.dependencies||{},...l.devDependencies||{}};r.push(a["expo-updates"]?{level:"pass",message:"expo-updates is installed."}:{level:"warn",message:"Install expo-updates before making native builds that consume Mach OTA."}),r.push(io(process.cwd())?{level:"pass",message:`${m.npmScope}/mach is installed locally for the Expo plugin.`}:{level:"warn",message:`${m.npmScope}/mach is not installed locally; Expo may not resolve ${Te}.`});let d=dr(process.cwd());if(d){let u=Pt(d.updates?.url),c=Pt(o?.channel)||"production",p=Pt(d.updates?.requestHeaders?.["expo-channel-name"]);r.push(u===o?.url?{level:"pass",message:"Expo Updates URL resolves to Mach."}:{level:"warn",message:`Expo Updates URL resolves to ${u||"none"} instead of ${o?.url||"the Mach OTA URL"}.`}),r.push(p===c?{level:"pass",message:`Expo update channel header resolves to ${c}.`}:{level:"warn",message:`Expo update channel header is ${p||"not set"}; install the latest ${m.npmScope}/mach package and rebuild.`})}else r.push({level:"warn",message:"Could not resolve Expo config to confirm update URL/channel header."})}else r.push({level:"warn",message:"Vanilla React Native OTA native client is not fully automated yet. Publish can upload bundles, but apps need the Mach RN OTA client before consuming them."});for(let l of r){let a=l.level==="pass"?Qe.green("PASS"):l.level==="warn"?Qe.yellow("WARN"):Qe.red("FAIL");at.info(`${a} ${l.message}`)}let s=r.filter(l=>l.level==="fail").length;s>0&&(an(Qe.red(`OTA verification failed with ${s} issue(s).`)),process.exit(1)),an(Qe.green("OTA verification passed."))}async function Dm(e){Wt();let t=Un(),n=await k.get(`/ota/${t.projectId}/updates`),i=n.data.updates||[];if(e.json){at.info(JSON.stringify(n.data,null,2));return}if(i.length===0){an("No OTA updates found.");return}for(let r of i){let o=r.stats?.total||{};at.info(`${Qe.bold(r.updateId)} ${Qe.dim(`${r.platform} ${r.channelName} runtime ${r.runtimeVersion}`)} ${r.status||"active"}`),at.info(Qe.dim(` downloads ios=${o.iosDownloaded||0} android=${o.androidDownloaded||0} applied ios=${o.iosApplied||0} android=${o.androidApplied||0}`))}an(`Found ${i.length} OTA update(s).`)}async function el(e,t){Wt();let n=Un(),i=Pt(t.updateId);i||(at.error(`Missing update id. Use \`${m.nameLower} ota ${e} --update-id <id>\`.`),process.exit(1));let r=await k.post(`/ota/${n.projectId}/updates/${encodeURIComponent(i)}/${e}`);t.json?at.info(JSON.stringify(r.data,null,2)):an(Qe.green(`\u2713 OTA update ${e==="rollback"?"rolled back":"promoted"}: ${i}`))}async function Dt(e,t={}){let n=e||t.action||"publish";if(n==="setup")return Rm({...t,action:n});if(n==="publish")return Pm({...t,action:n});if(n==="verify")return al({...t,action:n});if(n==="list")return Dm({...t,action:n});if(n==="rollback")return el("rollback",{...t,action:n});if(n==="promote")return el("promote",{...t,action:n});let i=await cm({message:"What do you want to do?",options:[{value:"setup",label:"Setup OTA"},{value:"publish",label:"Publish OTA update"},{value:"verify",label:"Verify OTA setup"},{value:"list",label:"List OTA updates"}]});return Qr(i)&&eo(),Dt(i,t)}import{intro as Om,outro as ll,log as ln}from"@clack/prompts";import lt from"chalk";async function cl(){Om(lt.blue(`${m.name} CLI - User Profile`));let e=ke();if(!e){ln.warn(lt.yellow("You are not logged in.")),ln.info(`Run \`${m.nameLower} login\` to authenticate.`),ll();return}ln.info(`${lt.bold("Logged in as:")} ${lt.green(e.email)}`);try{await k.get("/projects");let n=ke().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);ln.info(`${lt.bold("Token status:")} Valid (Expires in ~${a}h / ${l}m)`)}else ln.warn(`${lt.bold("Token status:")} ${lt.red("Expired")} (Auto-refresh failed)`)}}}catch{ln.warn(`${lt.bold("Token status:")} ${lt.red("Unreachable")} (Session might be truly expired)${dt}`)}ll(lt.blue("---"))}import{spawn as Tm}from"child_process";import{log as Ot}from"@clack/prompts";import Ve from"chalk";import Nm from"fs";import Cm from"net";async function km(e){return new Promise(t=>{let n=Cm.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 dl(e,t=20){let n=e;for(;n<e+t;){if(!await km(n))return n;n++}throw new Error(`Could not find an available port after ${t} attempts starting from ${e}.`)}var ul=async e=>{Ot.info(Ve.blue(`Starting ${m.name} Dev Orchestrator...`));let t=ve(),n=e.buildProfile||"development",i=t?xe(t,n):null,r={...process.env};if(t?.projectId)try{Ot.info(Ve.dim(`Fetching managed secrets for profile: ${n}...`));let c=await k.get(`/projects/${t.projectId}/secrets/export?env=${n}`);c.data?.status==="success"&&c.data.secrets&&(Object.assign(r,c.data.secrets),Ot.info(Ve.magenta(`\u2713 Injected secrets from ${m.name} Dashboard.`)))}catch{Ot.warn("Could not fetch managed secrets. Running with local env only.")}t&&Object.assign(r,Yt(t,m.envPrefix)),i&&(Object.assign(r,Yt(i,`${m.envPrefix}PROFILE_`)),i.env&&Object.assign(r,i.env));let o=!1;try{let c=JSON.parse(Nm.readFileSync("package.json","utf-8"));o=!!(c.dependencies?.expo||c.devDependencies?.expo)}catch{Ot.warn("Could not parse package.json. Defaulting to Bare React Native mode.")}let s=Number(e.port||i?.port||8081),l=await dl(s);l!==s&&Ot.info(Ve.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 c=[`${Ve.cyan("i")} open iOS simulator`,`${Ve.cyan("a")} open Android emulator/device`,`${Ve.cyan("w")} open web`,`${Ve.cyan("r")} reload app`];Ot.info([Ve.bold("Launch controls"),...c.map(p=>` ${p}`),"",Ve.dim("Direct launch: mach start --ios | --android | --web"),Ve.dim(`Metro URL: http://localhost:${l}`)].join(`
|
|
1540
|
+
`))}else Ot.info(Ve.dim(`Metro URL: http://localhost:${l}`));let u=Tm(a,d,{stdio:"inherit",env:r});return new Promise((c,p)=>{u.on("exit",f=>{f===0?c():p(new Error(`Dev server exited with code ${f}`))}),u.on("error",f=>{p(f)})})};import{log as Fe}from"@clack/prompts";import et from"chalk";var pl=async e=>{let t=ve();t||(Fe.error(et.red(`No ${m.configFileName} found in the current directory.`)),process.exit(1));let n=e.profile||"development",i=xe(t,n);if(e.json){console.log(JSON.stringify({project:t,resolved:i},null,2));return}Fe.info(et.bgBlue.white(` Resolved ${m.name} Config [${n}] `)),Fe.info(et.dim("----------------------------------------")),Fe.info(`${et.blue("Project ID:")} ${t.projectId}`),Fe.info(`${et.blue("Name:")} ${t.name}`),Fe.info(`${et.blue("Scheme:")} ${t.scheme}`),i?(Fe.info(et.dim(`
|
|
1541
1541
|
Profile Settings:`)),Fe.info(`${et.cyan("Distribution:")} ${i.distribution||"none"}`),Fe.info(`${et.cyan("Development Client:")} ${i.developmentClient||"false"}`),i.env&&Object.keys(i.env).length>0&&(Fe.info(et.dim(`
|
|
1542
|
-
Environment Variables:`)),Object.entries(i.env).forEach(([r,o])=>{Fe.info(` ${r}=${o}`)}))):Fe.warn(`Profile '${n}' not found.`),Fe.info(et.dim("----------------------------------------"))};import{cancel as
|
|
1543
|
-
`),n}import
|
|
1542
|
+
Environment Variables:`)),Object.entries(i.env).forEach(([r,o])=>{Fe.info(` ${r}=${o}`)}))):Fe.warn(`Profile '${n}' not found.`),Fe.info(et.dim("----------------------------------------"))};import{cancel as tg,confirm as Ol,isCancel as Hn,log as Li,note as ng,outro as Mi,select as ig,text as Cl}from"@clack/prompts";import nt from"chalk";import rg from"fs";import Pl from"path";import Vt from"fs";import cn from"path";var dn="./plugins/withMachDeepLinks",ro="mach.deep-links.json",ml=["/*"],oo=e=>{if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0},Pi=e=>{let t=new Set,n=[];for(let i of e){let r=oo(i);!r||t.has(r)||(t.add(r),n.push(r))}return n},tt=(...e)=>{for(let t of e){let n=oo(t);if(n)return n}},fl=(e,t)=>e.length!==t.length?!1:e.every((n,i)=>n===t[i]);function gl(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();if(t==="ios"||t==="android"||t==="all")return t}function Fn(e){let t=e.includes("://")?e:`https://${e}`,n=new URL(t),i=n.pathname==="/"?"":n.pathname.replace(/\/+$/,"");return`${n.protocol}//${n.host}${i}`}function Ri(e){return new URL(Fn(e)).hostname}function Di(e){return e.trim().toLowerCase().replace(/[^a-z0-9+.-]/g,"-").replace(/^-+|-+$/g,"")||"app"}function hl(e=process.cwd()){let t=cn.join(e,"package.json"),n=["app.json","app.config.json","app.config.js","app.config.ts"].some(r=>Vt.existsSync(cn.join(e,r))),i=!1;if(Vt.existsSync(t))try{let r=JSON.parse(Vt.readFileSync(t,"utf-8"));i=!!(r.dependencies?.expo||r.devDependencies?.expo)}catch{i=!1}return n&&i?"expo":Vt.existsSync(cn.join(e,"ios"))||Vt.existsSync(cn.join(e,"android"))?"react-native":Jt}function yl(e,t,n){if(t)return t;let i=!!(e.ios?.bundleIdentifier||n?.ios?.bundleIdentifier||e.deepLinks?.ios?.bundleIdentifier),r=!!(e.android?.package||n?.android?.package||n?.android?.applicationId||e.deepLinks?.android?.package);return i&&!r?"ios":r&&!i?"android":"all"}function Oi(e=process.cwd(),t){let n=t?.deepLinks?.web?.outputDir;return n||(Vt.existsSync(cn.join(e,"public"))?"public":"deep-links")}function Sl(e,t){let n=e.deepLinks,i=Fn(t.baseUrl||n?.baseUrl||(t.domain?`https://${t.domain}`:"")),r=oo(t.domain)||(t.baseUrl?Ri(i):n?.domain)||Ri(i),o=t.profile||n?.profile||"production",s=xe(e,o)||{},l=s.ios||{},a=s.android||{},d=e.submit?.[o]?.ios||{},u=e.submit?.[o]?.android||{},c=Di(t.scheme||n?.scheme||l.scheme||e.scheme||e.slug||e.name||"app"),p=xt(e,o),f=Pi([...t.androidFingerprint||[],...n?.android?.sha256CertFingerprints||[],...a.sha256CertFingerprints||[],...e.android?.sha256CertFingerprints||[]]);return{baseUrl:i,domain:r,scheme:c,profile:o!=="production"?o:void 0,paths:n?.paths?.length?n.paths:["/*"],ios:{appStoreId:tt(t.appStoreId,n?.ios?.appStoreId,l.ascAppId,d.ascAppId,e.ios?.ascAppId),appleTeamId:tt(t.appleTeamId,n?.ios?.appleTeamId,l.appleTeamId,l.developerTeamId,d.appleTeamId,d.developerTeamId,e.ios?.appleTeamId,e.ios?.developerTeamId,p.teamId),bundleIdentifier:tt(t.iosBundleId,n?.ios?.bundleIdentifier,l.bundleIdentifier,l.bundleId,e.ios?.bundleIdentifier,e.ios?.bundleId,e.expo?.ios?.bundleIdentifier),webCredentials:!!n?.ios?.webCredentials,activityContinuation:!!n?.ios?.activityContinuation},android:{package:tt(t.androidPackage,n?.android?.package,a.package,a.applicationId,e.android?.package,e.expo?.android?.package,u.packageName,u.package),sha256CertFingerprints:f},web:{smartAppBanner:n?.web?.smartAppBanner??!0,outputDir:t.output||n?.web?.outputDir||Oi(process.cwd(),e)}}}function Ci(e,t={}){let n=e.deepLinks,i=t.profile||n?.profile||"production",r=t.expoHints||null,o=tt(n?.baseUrl,r?.domain?`https://${r.domain}`:void 0);if(!o)return null;let s=Fn(o),l=xe(e,i)||{},a=l.ios||{},d=l.android||{},u=e.submit?.[i]?.ios||{},c=e.submit?.[i]?.android||{},p=xt(e,i),f=tt(n?.domain,r?.domain)||Ri(s),g=Di(tt(n?.scheme,a.scheme,e.scheme,r?.scheme,e.slug,e.name,"app")||"app"),y=n?.paths?.length?n.paths:[...ml];return{baseUrl:s,domain:f,scheme:g,profile:i!=="production"?i:void 0,paths:y,ios:{appStoreId:tt(n?.ios?.appStoreId,a.ascAppId,u.ascAppId,e.ios?.ascAppId),appleTeamId:tt(n?.ios?.appleTeamId,a.appleTeamId,a.developerTeamId,u.appleTeamId,u.developerTeamId,e.ios?.appleTeamId,e.ios?.developerTeamId,p.teamId),bundleIdentifier:tt(n?.ios?.bundleIdentifier,a.bundleIdentifier,a.bundleId,e.ios?.bundleIdentifier,e.ios?.bundleId,e.expo?.ios?.bundleIdentifier,r?.iosBundleIdentifier),webCredentials:!!n?.ios?.webCredentials,activityContinuation:!!n?.ios?.activityContinuation},android:{package:tt(n?.android?.package,d.package,d.applicationId,e.android?.package,e.expo?.android?.package,c.packageName,c.package,r?.androidPackage),sha256CertFingerprints:Pi([...n?.android?.sha256CertFingerprints||[],...d.sha256CertFingerprints||[],...e.android?.sha256CertFingerprints||[]])},web:{smartAppBanner:n?.web?.smartAppBanner??!0,outputDir:n?.web?.outputDir||Oi(t.cwd||process.cwd(),e)}}}function ki(e,t,n="production",i=process.cwd()){return t?.domain?Ci({...e,deepLinks:{baseUrl:`https://${t.domain}`,domain:t.domain,scheme:t.scheme}},{profile:n,cwd:i,expoHints:t}):null}function xm(e,t,n=t.profile||"production"){let i=Ci({...e,deepLinks:{baseUrl:t.baseUrl}},{profile:n}),r={baseUrl:t.baseUrl};n!=="production"&&(r.profile=n),t.domain&&t.domain!==Ri(t.baseUrl)&&(r.domain=t.domain),t.scheme&&t.scheme!==i?.scheme&&(r.scheme=t.scheme),t.paths?.length&&!fl(t.paths,ml)&&(r.paths=t.paths);let o={};t.ios?.bundleIdentifier&&t.ios.bundleIdentifier!==i?.ios?.bundleIdentifier&&(o.bundleIdentifier=t.ios.bundleIdentifier),t.ios?.appleTeamId&&t.ios.appleTeamId!==i?.ios?.appleTeamId&&(o.appleTeamId=t.ios.appleTeamId),t.ios?.appStoreId&&t.ios.appStoreId!==i?.ios?.appStoreId&&(o.appStoreId=t.ios.appStoreId),t.ios?.webCredentials&&(o.webCredentials=!0),t.ios?.activityContinuation&&(o.activityContinuation=!0),Object.keys(o).length>0&&(r.ios=o);let s={};t.android?.package&&t.android.package!==i?.android?.package&&(s.package=t.android.package);let l=t.android?.sha256CertFingerprints||[],a=i?.android?.sha256CertFingerprints||[];l.length>0&&!fl(l,a)&&(s.sha256CertFingerprints=l),Object.keys(s).length>0&&(r.android=s);let d={outputDir:t.web?.outputDir||"deep-links"};return t.web?.smartAppBanner===!1&&(d.smartAppBanner=!1),r.web=d,r}function bl(e,t,n,i=n.profile||"production"){let r={...e,framework:t,scheme:e.scheme||n.scheme};return{...r,deepLinks:xm(r,n,i)}}function Al(e,t=process.cwd()){let n=cn.join(t,"mach.config.json");return Vt.writeFileSync(n,`${JSON.stringify(e,null,2)}
|
|
1543
|
+
`),n}import $e from"fs";import De from"path";import{spawnSync as El}from"child_process";var Bn="@radhya/mach/expo-plugin",Lm=`const fs = require('fs')
|
|
1544
1544
|
const path = require('path')
|
|
1545
1545
|
|
|
1546
1546
|
const unique = values => Array.from(new Set(values.filter(Boolean)))
|
|
@@ -1660,24 +1660,24 @@ module.exports = function withMachDeepLinks(config) {
|
|
|
1660
1660
|
config.android.intentFilters = intentFilters
|
|
1661
1661
|
return config
|
|
1662
1662
|
}
|
|
1663
|
-
`,
|
|
1663
|
+
`,jn=e=>{if(typeof e=="string"){if(e===Bn)return Bn;if(e===dn||e===dn.replace(/^\.\//,""))return dn}},ao=e=>Array.isArray(e)?ao(e[0]):jn(e),Il=e=>!!ao(e),Mm=(e,t)=>{let n=jn(t)||t;return ao(e)===n},Um=(e,t)=>Array.isArray(e)?[t,...e.slice(1)]:t,Fm=(e,t)=>{let n=Array.isArray(e.plugins)?e.plugins:[];if(n.findIndex(o=>Mm(o,t))>=0)return e.plugins=n,"already";let r=n.findIndex(Il);return r>=0?(n[r]=Um(n[r],t),e.plugins=n,"updated"):(n.push(t),e.plugins=n,"inserted")},so=/(['"`])((?:\.\/)?plugins\/withMachDeepLinks|@radhya\/mach\/expo-plugin)\1/g;function Ti(e){let t=De.join(e,"package.json");if(!$e.existsSync(t))return!1;try{let n=JSON.parse($e.readFileSync(t,"utf-8"));return!!(n.dependencies?.["@radhya/mach"]||n.devDependencies?.["@radhya/mach"])}catch{return!1}}function Bm(e){return $e.existsSync(De.join(e,"pnpm-lock.yaml"))?{command:"pnpm",args:["add","-D","@radhya/mach@latest"],label:"pnpm add -D @radhya/mach@latest"}:$e.existsSync(De.join(e,"yarn.lock"))?{command:"yarn",args:["add","-D","@radhya/mach@latest"],label:"yarn add -D @radhya/mach@latest"}:$e.existsSync(De.join(e,"bun.lockb"))||$e.existsSync(De.join(e,"bun.lock"))?{command:"bun",args:["add","-d","@radhya/mach@latest"],label:"bun add -d @radhya/mach@latest"}:{command:"npm",args:["install","--save-dev","@radhya/mach@latest"],label:"npm install --save-dev @radhya/mach@latest"}}function jm(e){let t=Bm(e),n=El(t.command,t.args,{cwd:e,stdio:"inherit",env:{...process.env}});return n.error?{ok:!1,label:t.label,error:n.error.message}:n.status!==0?{ok:!1,label:t.label,error:`${t.command} exited with code ${n.status}`}:{ok:Ti(e),label:t.label}}function Hm(e,t){let n=$e.readFileSync(e,"utf-8"),i=Array.from(n.matchAll(so));if(i.length>0){let p=jn(t)||t,f=i.some(h=>jn(h[2])===p),g=i.some(h=>jn(h[2])!==p);if(f&&!g)return"already";let y=n.replace(so,(h,v)=>`${v}${t}${v}`);return $e.writeFileSync(e,y),"updated"}let r=/(^[ \t]*)plugins\s*:\s*\[([\s\S]*?)\]/m.exec(n);if(!r||r.index===void 0)return"unsupported";let o=n.includes(`\r
|
|
1664
1664
|
`)?`\r
|
|
1665
1665
|
`:`
|
|
1666
1666
|
`,s=r[1]||"",l=r[2]||"",d=l.match(/\r?\n([ \t]+)\S/)?.[1]||`${s} `,u=l.trim().length===0?`${o}${d}'${t}',${o}${s}`:l.includes(`
|
|
1667
|
-
`)||l.includes("\r")?`${o}${d}'${t}',${l}`:`${o}${d}'${t}',${o}${d}${l.trim()}${o}${s}`,c=`${r[0].slice(0,r[0].indexOf("[")+1)}${u}]`;return
|
|
1668
|
-
`),i.push(d),f==="updated"&&o.push(`${d} updated to use ${l}.`)}catch(c){r.push(`Expo config plugin insertion failed: ${c.message}`)}return{written:i,skipped:r,notes:o}}function
|
|
1669
|
-
`)};var
|
|
1670
|
-
${i}`)),!0):!1}function wl(e,t){let n=[],i=[],r=[],o=t.web?.outputDir||"deep-links",s=Be.join(e,o),l=oo(t);if(l){let c=_i([Be.join(s,".well-known/apple-app-site-association"),Be.join(s,".well-known/apple-app-site-association.json"),Be.join(s,"apple-app-site-association"),Be.join(s,"apple-app-site-association.json")]);for(let p of c)Il(p,l),n.push(Be.relative(e,p))}else i.push("Apple AASA files: missing ios.appleTeamId or ios.bundleIdentifier");let a=Bm(t);if(a){let c=Be.join(s,".well-known/assetlinks.json");Il(c,a),n.push(Be.relative(e,c)),t.android?.sha256CertFingerprints?.length||r.push("assetlinks.json was generated without SHA256 fingerprints. Add them before Android App Links can verify.")}else i.push("Android assetlinks.json: missing android.package");let d=Be.join(e,eo);ct.existsSync(d)&&(ct.unlinkSync(d),r.push(`Removed legacy ${eo}; mach.config.json is now the source of truth.`));let u=Be.join(s,"index.html");return t.web?.smartAppBanner&&jm(u,t)?n.push(Be.relative(e,u)):t.web?.smartAppBanner&&t.ios?.appStoreId?r.push(`Smart App Banner skipped because ${Be.relative(e,u)} was not found.`):t.web?.smartAppBanner&&r.push("Smart App Banner skipped because ios.appStoreId is not configured."),o!=="public"&&r.push(`Host ${o}/.well-known files at https://${t.domain}/.well-known/.`),{written:n,skipped:i,notes:r}}function so(e){if(!ct.existsSync(e))return null;try{return JSON.parse(ct.readFileSync(e,"utf-8"))}catch{return null}}import Ot from"fs";import Ct from"path";import{spawnSync as Hm}from"child_process";var H=(e,t)=>({level:e,message:t}),_l=(e,t)=>Ct.join(e,t.web?.outputDir||"deep-links");function Gm(e,t,n="fail"){let i=[],r=_l(e,t),o=Ct.join(r,".well-known/apple-app-site-association");if(!oo(t))return i.push(H("warn","Skipping AASA verification because ios.appleTeamId or ios.bundleIdentifier is missing.")),i;if(!Ot.existsSync(o))return i.push(H(n,`${Ct.relative(e,o)} is missing.`)),i;Ot.statSync(o).size>128*1024?i.push(H("fail","Apple AASA file is larger than 128 KB.")):i.push(H("pass","Apple AASA file is under 128 KB."));let a=so(o);if(!a)return i.push(H("fail","Apple AASA file is not valid JSON.")),i;let d=`${t.ios?.appleTeamId}.${t.ios?.bundleIdentifier}`,u=a.applinks?.details||[],c=Array.isArray(u)&&u.some(p=>p.appID===d||p.appIDs?.includes(d));return i.push(c?H("pass",`AASA contains ${d}.`):H("fail",`AASA does not contain ${d}.`)),i}function Vm(e,t,n="fail"){let i=[],r=_l(e,t),o=Ct.join(r,".well-known/assetlinks.json");if(!t.android?.package)return i.push(H("warn","Skipping Android Asset Links verification because android.package is missing.")),i;if(!Ot.existsSync(o))return i.push(H(n,`${Ct.relative(e,o)} is missing.`)),i;let s=so(o);if(!s||!Array.isArray(s))return i.push(H("fail","assetlinks.json is not a valid JSON array.")),i;let l=s.find(d=>d?.target?.package_name===t.android?.package);i.push(l?H("pass",`assetlinks.json contains ${t.android.package}.`):H("fail",`assetlinks.json does not contain ${t.android.package}.`));let a=l?.target?.sha256_cert_fingerprints;return i.push(Array.isArray(a)&&a.length>0?H("pass","assetlinks.json has at least one SHA256 fingerprint."):H("warn","assetlinks.json has no SHA256 fingerprints.")),i}function Km(e,t,n,i){if(t.framework!=="expo")return[];let r=[],o=ro(e),l=(Array.isArray(o?.ios?.associatedDomains)?o.ios.associatedDomains:[]).includes(`applinks:${n.domain}`);r.push(l?H("pass",`Expo iOS config contains applinks:${n.domain}.`):H(i?"warn":"fail",`Expo iOS config does not contain applinks:${n.domain}.`));let d=(Array.isArray(o?.android?.intentFilters)?o.android.intentFilters:[]).flatMap(c=>Array.isArray(c?.data)?c.data:[]).some(c=>c?.scheme==="https"&&c.host===n.domain);if(r.push(d?H("pass",`Expo Android config contains App Link host ${n.domain}.`):H(i?"warn":"fail",`Expo Android config does not contain App Link host ${n.domain}.`)),i)return r.push(H("warn","mach.config.json is missing deepLinks; values were inferred from Expo config. Run `mach deeplink setup` to persist Mach metadata and generate hosted files.")),r;let u=El(e);return u==="wired"?r.push(H("pass","Expo deep link plugin is wired into Expo config and derives values from mach.config.json.")):u==="manual"&&l&&d?r.push(H("pass","Expo resolved config contains the deep-link settings from the dynamic config.")):u==="manual"?r.push(H("warn","Expo deep link plugin exists, but dynamic or missing Expo config means manual plugin insertion must be confirmed.")):l&&d?r.push(H("warn","Expo plugin is not wired, but resolved Expo config already contains the deep-link settings.")):r.push(H("fail","Expo deep link plugin is missing or not wired into Expo config.")),r}function zm(e,t,n){if(t.framework!=="react-native")return[];let i=[],r=Ct.join(e,"android/app/src/main/AndroidManifest.xml");if(Ot.existsSync(r)){let s=Ot.readFileSync(r,"utf-8");i.push(s.includes(`android:host="${n.domain}"`)?H("pass","AndroidManifest.xml contains the App Links host."):H("warn","AndroidManifest.xml does not contain the App Links host. Native patching is planned for a later phase."))}let o=Ct.join(e,"ios");if(Ot.existsSync(o)){let l=Ot.readdirSync(o,{recursive:!0}).filter(a=>typeof a=="string"&&a.endsWith(".entitlements")).some(a=>Ot.readFileSync(Ct.join(o,a),"utf-8").includes(`applinks:${n.domain}`));i.push(l?H("pass","iOS entitlements contain the associated domain."):H("warn","iOS entitlements do not contain the associated domain. Native patching is planned for a later phase."))}return i}async function ao(e,t){let n=[];try{let i=await fetch(e,{redirect:"manual"});if(i.status>=300&&i.status<400&&!t)return n.push(H("fail",`${e} redirects. Apple AASA endpoints must not redirect.`)),n;n.push(i.status===200?H("pass",`${e} returned HTTP 200.`):H("fail",`${e} returned HTTP ${i.status}.`));let r=i.headers.get("content-type")||"";!r.includes("application/json")&&!r.includes("text/json")&&n.push(H("warn",`${e} content-type is "${r||"missing"}"; application/json is recommended.`)),JSON.parse(await i.text()),n.push(H("pass",`${e} contains valid JSON.`))}catch(i){n.push(H("fail",`${e} check failed: ${i.message}`))}return n}async function Wm(e){let t=e.domain;return(await Promise.all([ao(`https://${t}/.well-known/apple-app-site-association`,!1),ao(`https://${t}/apple-app-site-association`,!1),ao(`https://${t}/.well-known/assetlinks.json`,!0)])).flat()}function Jm(e){let t=e.android?.package;if(!t)return[H("warn","Cannot print Android device verification commands because android.package is missing.")];let i=Hm("adb",["version"],{encoding:"utf-8"}).status===0?"Run":"Install Android platform-tools, then run";return[H("info",`${i}: adb shell pm set-app-links --package ${t} 0 all`),H("info",`${i}: adb shell pm verify-app-links --re-verify ${t}`),H("info",`${i}: adb shell pm get-app-links ${t}`)]}async function lo(e,t,n){let i=n.profile||t.deepLinks?.profile||"production",r=t.framework==="expo"?Oi(e):null,o=t.framework==="expo"?Pi(t,r,i,e):null,s=!t.deepLinks&&!!o,l=t.deepLinks?Ri(t,{profile:i,cwd:e,expoHints:r}):o,a=[];if(!l)return[H("fail","mach.config.json is missing deepLinks and Mach could not infer existing deep-link settings. Run `mach deeplink setup`.")];a.push(l.baseUrl?H("pass","deepLinks.baseUrl is configured."):H("fail","deepLinks.baseUrl is missing.")),a.push(l.domain?H("pass","deepLinks.domain is configured."):H("fail","deepLinks.domain is missing.")),a.push(l.scheme?H("pass","deepLinks.scheme is configured."):H("fail","deepLinks.scheme is missing."));let d=s?"warn":"fail";return a.push(...Gm(e,l,d)),a.push(...Vm(e,l,d)),a.push(...Km(e,t,l,s)),a.push(...zm(e,t,l)),n.live&&a.push(...await Wm(l)),n.androidDevice&&a.push(...Jm(l)),a}var jn=()=>process.stdin.isTTY&&process.stdout.isTTY,vl=`${m.npmScope}/mach`,Hn=()=>{Ym("Operation cancelled."),process.exit(0)},po=e=>{if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0},bt=(...e)=>{for(let t of e){let n=po(t);if(n)return n}},Gt=async(e,t,n,i,r)=>{if(t)return t;if(r||!jn()){if(i)throw new Error(`${e.replace(/:$/,"")} is required. Pass it as an option or run interactively.`);return}let o=await Pl({message:e,initialValue:t||"",placeholder:n,validate(s){if(i&&s.trim().length===0)return"Required."}});return Bn(o)&&Hn(),po(o)};async function Qm(e,t,n){let i=He(e.framework),r=He(t);if(r)return r;if(i)return i;let o=fl();if(n||!jn())return o;let s=await Xm({message:`Which framework should ${m.name} configure?`,initialValue:o,options:[{value:"expo",label:"Expo"},{value:"react-native",label:"React Native"},{value:"flutter",label:"Flutter (not supported yet)"}]});return Bn(s)&&Hn(),s}var Ci=e=>e==="ios"||e==="all",co=e=>e==="android"||e==="all";async function eg(e,t,n){if(t!=="expo"||Di(e)||n.installPlugin===!1)return!1;if(n.installPlugin===!0||n.yes)return!0;if(!jn())return!1;let i=await Rl({message:`Install ${vl} locally so Expo can use ${vl}/expo-plugin?`,initialValue:!0});return Bn(i)&&Hn(),!!i}async function tg(e,t){let n=!!t.yes,i=t.profile||e.deepLinks?.profile||"production",r=xe(e,i)||{},o=r.ios||{},s=r.android||{},l=e.submit?.[i]?.ios||{},a=e.submit?.[i]?.android||{},d=Tt(e,i),u=await Qm(e,t.framework,n);if(u==="flutter")throw new Error("Flutter deep-link automation is planned but not supported yet.");let c=ml(e,pl(t.platform),r),p=e.deepLinks,g=u==="expo"&&(!bt(t.baseUrl,p?.baseUrl,t.domain?`https://${t.domain}`:void 0)||!bt(t.scheme,p?.scheme,o.scheme,e.scheme,e.slug,e.name)||Ci(c)&&!bt(t.iosBundleId,p?.ios?.bundleIdentifier,o.bundleIdentifier,o.bundleId,e.ios?.bundleIdentifier)||co(c)&&!bt(t.androidPackage,p?.android?.package,s.package,s.applicationId,e.android?.package,a.packageName,a.package))?Pi(e,Oi(process.cwd()),i,process.cwd()):null,y=t.output||p?.web?.outputDir||vi(process.cwd(),e),h=await Gt("Deep link base URL:",t.baseUrl||p?.baseUrl||(t.domain?`https://${t.domain}`:void 0)||g?.baseUrl,"https://app.example.com",!0,n),_=Mn(h),I=t.baseUrl?new URL(_).hostname:void 0,T=await Gt("Associated domain:",t.domain||I||p?.domain||g?.domain||new URL(_).hostname,"app.example.com",!0,n),w=$i(await Gt("URI scheme:",bt(t.scheme,p?.scheme,o.scheme,e.scheme,g?.scheme,e.slug,e.name,"app"),"myapp",!0,n)||"app"),U=Ci(c)?await Gt("iOS bundle identifier:",bt(t.iosBundleId,p?.ios?.bundleIdentifier,o.bundleIdentifier,o.bundleId,e.ios?.bundleIdentifier,g?.ios?.bundleIdentifier),"com.example.app",!0,n):p?.ios?.bundleIdentifier||e.ios?.bundleIdentifier,V=Ci(c)?await Gt("Apple Team ID:",bt(t.appleTeamId,p?.ios?.appleTeamId,o.appleTeamId,o.developerTeamId,l.appleTeamId,l.developerTeamId,e.ios?.appleTeamId,e.ios?.developerTeamId,d.teamId),"ABCDE12345",!0,n):p?.ios?.appleTeamId||e.ios?.appleTeamId,J=Ci(c)?await Gt("App Store ID (optional, for Smart App Banner):",bt(t.appStoreId,p?.ios?.appStoreId,o.ascAppId,l.ascAppId,e.ios?.ascAppId),"1234567890",!1,n):p?.ios?.appStoreId,A=co(c)?await Gt("Android package name:",bt(t.androidPackage,p?.android?.package,s.package,s.applicationId,e.android?.package,a.packageName,a.package,g?.android?.package),"com.example.app",!0,n):p?.android?.package||e.android?.package,v=p?.android?.sha256CertFingerprints||[],L=t.androidFingerprint||[],P=e.android?.sha256CertFingerprints||[],S=s.sha256CertFingerprints||[],R=[...L,...v,...S,...P].filter(Boolean);if(co(c)&&R.length===0&&!n&&jn()){let B=await Pl({message:"Android SHA256 fingerprint (optional now, required for verified App Links):",placeholder:"AA:BB:CC:..."});Bn(B)&&Hn(),po(B)&&R.push(B)}let M=gl(e,{...t,baseUrl:_,domain:T,scheme:w,output:y,appleTeamId:V,appStoreId:J,androidFingerprint:R});return M.ios={...M.ios||{},bundleIdentifier:U,appleTeamId:V,appStoreId:J},M.android={...M.android||{},package:A,sha256CertFingerprints:Array.from(new Set(R))},{framework:u,platform:c,deepLinks:M}}var uo=(e,t)=>{t.length!==0&&qm(t.map(n=>`- ${n}`).join(`
|
|
1671
|
-
`),e)},
|
|
1667
|
+
`)||l.includes("\r")?`${o}${d}'${t}',${l}`:`${o}${d}'${t}',${o}${d}${l.trim()}${o}${s}`,c=`${r[0].slice(0,r[0].indexOf("[")+1)}${u}]`;return $e.writeFileSync(e,`${n.slice(0,r.index)}${c}${n.slice(r.index+r[0].length)}`),"inserted"}function wl(e,t,n={}){let i=[],r=[],o=[],s=Ti(e);if(!s&&n.installPackage){o.push("Installing @radhya/mach locally so Expo can use @radhya/mach/expo-plugin.");let c=jm(e);c.ok?(s=!0,o.push(`Installed @radhya/mach with ${c.label}.`)):o.push(`Could not install @radhya/mach with ${c.label}: ${c.error||"unknown error"}. Falling back to local plugin.`)}let l=s?Bn:dn;if(s)o.push(`Using packaged Expo plugin ${Bn}.`);else{let c=De.join(e,"plugins/withMachDeepLinks.js");$e.mkdirSync(De.dirname(c),{recursive:!0}),$e.writeFileSync(c,Lm),i.push(De.relative(e,c)),o.push(`Using local Expo plugin fallback ${dn}. Install @radhya/mach in this app to use ${Bn}.`)}let a=["app.config.ts","app.config.js"].find(c=>$e.existsSync(De.join(e,c)));if(a){let c=De.join(e,a),p=Hm(c,l);return p==="inserted"?i.push(a):p==="updated"?(i.push(a),o.push(`${a} updated to use ${l}.`)):p==="already"?o.push(`${a} already includes the Mach Expo plugin.`):o.push(`Add "${l}" to the plugins array in ${a}. Mach could not safely auto-edit this dynamic config.`),{written:i,skipped:r,notes:o}}let d=["app.config.json","app.json"].find(c=>$e.existsSync(De.join(e,c)));if(!d)return r.push("Expo config plugin insertion: no app.json or app.config.json found."),{written:i,skipped:r,notes:o};let u=De.join(e,d);try{let c=JSON.parse($e.readFileSync(u,"utf-8")),p=c.expo&&typeof c.expo=="object"?c.expo:c,f=Fm(p,l);$e.writeFileSync(u,`${JSON.stringify(c,null,2)}
|
|
1668
|
+
`),i.push(d),f==="updated"&&o.push(`${d} updated to use ${l}.`)}catch(c){r.push(`Expo config plugin insertion failed: ${c.message}`)}return{written:i,skipped:r,notes:o}}function vl(e){let t=["app.config.ts","app.config.js"].find(i=>$e.existsSync(De.join(e,i)));if(t){let i=$e.readFileSync(De.join(e,t),"utf-8");return so.test(i)?"manual":"missing"}let n=["app.config.json","app.json"].find(i=>$e.existsSync(De.join(e,i)));if(!n)return"missing";try{let i=JSON.parse($e.readFileSync(De.join(e,n),"utf-8")),r=i.expo&&typeof i.expo=="object"?i.expo:i;return Array.isArray(r.plugins)&&r.plugins.some(Il)?"wired":"missing"}catch{return"missing"}}function lo(e){let t=El("npx",["--no-install","expo","config","--type","public","--json"],{cwd:e,encoding:"utf-8",timeout:8e3,env:{...process.env,CI:"1",EXPO_NO_TELEMETRY:"1"}});if(t.error||t.status!==0||!t.stdout)return null;let n=t.stdout.trim(),i=n.indexOf("{");if(i<0)return null;try{return JSON.parse(n.slice(i))}catch{return null}}function Gm(e){if(!e||typeof e!="object")return null;let n=(Array.isArray(e.ios?.associatedDomains)?e.ios.associatedDomains:[]).map(s=>typeof s=="string"?s.match(/^applinks:(.+)$/)?.[1]:void 0).find(Boolean),r=(Array.isArray(e.android?.intentFilters)?e.android.intentFilters:[]).flatMap(s=>Array.isArray(s?.data)?s.data:[]).find(s=>s?.scheme==="https"&&typeof s.host=="string")?.host,o=n||r;return!o&&!e.scheme&&!e.ios?.bundleIdentifier&&!e.android?.package?null:{domain:o,scheme:typeof e.scheme=="string"?e.scheme:void 0,iosBundleIdentifier:typeof e.ios?.bundleIdentifier=="string"?e.ios.bundleIdentifier:void 0,androidPackage:typeof e.android?.package=="string"?e.android.package:void 0}}function Ni(e){return Gm(lo(e))}import ct from"fs";import Be from"path";var Vm=e=>{ct.mkdirSync(Be.dirname(e),{recursive:!0})},$l=(e,t)=>{Vm(e),ct.writeFileSync(e,`${JSON.stringify(t,null,2)}
|
|
1669
|
+
`)};var Km=e=>{let t=e.ios?.appleTeamId,n=e.ios?.bundleIdentifier;return!t||!n?null:`${t}.${n}`};function co(e){let t=Km(e);if(!t)return null;let n=e.paths?.length?e.paths:["/*"],i=n.map(s=>s==="/*"?"*":s),r=n.map(s=>({"/":s,comment:s==="/*"?"Matches all URLs":`Matches ${s}`})),o={applinks:{apps:[],details:[{appIDs:[t],components:r,appID:t,paths:i}]}};return e.ios?.webCredentials&&(o.webcredentials={apps:[t]}),e.ios?.activityContinuation&&(o.activitycontinuation={apps:[t]}),o}function zm(e){let t=e.android?.package;return t?[{relation:["delegate_permission/common.handle_all_urls"],target:{namespace:"android_app",package_name:t,sha256_cert_fingerprints:e.android?.sha256CertFingerprints||[]}}]:null}function Wm(e,t){let n=t.ios?.appStoreId;if(!n||!ct.existsSync(e))return!1;let i=`<meta name="apple-itunes-app" content="app-id=${n}, app-argument=${t.baseUrl}" />`,r=ct.readFileSync(e,"utf-8");if(/name=["']apple-itunes-app["']/i.test(r)){let o=r.replace(/<meta[^>]+name=["']apple-itunes-app["'][^>]*>/i,i);return ct.writeFileSync(e,o),!0}return/<head[^>]*>/i.test(r)?(ct.writeFileSync(e,r.replace(/<head([^>]*)>/i,`<head$1>
|
|
1670
|
+
${i}`)),!0):!1}function _l(e,t){let n=[],i=[],r=[],o=t.web?.outputDir||"deep-links",s=Be.join(e,o),l=co(t);if(l){let c=Pi([Be.join(s,".well-known/apple-app-site-association"),Be.join(s,".well-known/apple-app-site-association.json"),Be.join(s,"apple-app-site-association"),Be.join(s,"apple-app-site-association.json")]);for(let p of c)$l(p,l),n.push(Be.relative(e,p))}else i.push("Apple AASA files: missing ios.appleTeamId or ios.bundleIdentifier");let a=zm(t);if(a){let c=Be.join(s,".well-known/assetlinks.json");$l(c,a),n.push(Be.relative(e,c)),t.android?.sha256CertFingerprints?.length||r.push("assetlinks.json was generated without SHA256 fingerprints. Add them before Android App Links can verify.")}else i.push("Android assetlinks.json: missing android.package");let d=Be.join(e,ro);ct.existsSync(d)&&(ct.unlinkSync(d),r.push(`Removed legacy ${ro}; mach.config.json is now the source of truth.`));let u=Be.join(s,"index.html");return t.web?.smartAppBanner&&Wm(u,t)?n.push(Be.relative(e,u)):t.web?.smartAppBanner&&t.ios?.appStoreId?r.push(`Smart App Banner skipped because ${Be.relative(e,u)} was not found.`):t.web?.smartAppBanner&&r.push("Smart App Banner skipped because ios.appStoreId is not configured."),o!=="public"&&r.push(`Host ${o}/.well-known files at https://${t.domain}/.well-known/.`),{written:n,skipped:i,notes:r}}function uo(e){if(!ct.existsSync(e))return null;try{return JSON.parse(ct.readFileSync(e,"utf-8"))}catch{return null}}import Ct from"fs";import kt from"path";import{spawnSync as Jm}from"child_process";var H=(e,t)=>({level:e,message:t}),Rl=(e,t)=>kt.join(e,t.web?.outputDir||"deep-links");function Ym(e,t,n="fail"){let i=[],r=Rl(e,t),o=kt.join(r,".well-known/apple-app-site-association");if(!co(t))return i.push(H("warn","Skipping AASA verification because ios.appleTeamId or ios.bundleIdentifier is missing.")),i;if(!Ct.existsSync(o))return i.push(H(n,`${kt.relative(e,o)} is missing.`)),i;Ct.statSync(o).size>128*1024?i.push(H("fail","Apple AASA file is larger than 128 KB.")):i.push(H("pass","Apple AASA file is under 128 KB."));let a=uo(o);if(!a)return i.push(H("fail","Apple AASA file is not valid JSON.")),i;let d=`${t.ios?.appleTeamId}.${t.ios?.bundleIdentifier}`,u=a.applinks?.details||[],c=Array.isArray(u)&&u.some(p=>p.appID===d||p.appIDs?.includes(d));return i.push(c?H("pass",`AASA contains ${d}.`):H("fail",`AASA does not contain ${d}.`)),i}function qm(e,t,n="fail"){let i=[],r=Rl(e,t),o=kt.join(r,".well-known/assetlinks.json");if(!t.android?.package)return i.push(H("warn","Skipping Android Asset Links verification because android.package is missing.")),i;if(!Ct.existsSync(o))return i.push(H(n,`${kt.relative(e,o)} is missing.`)),i;let s=uo(o);if(!s||!Array.isArray(s))return i.push(H("fail","assetlinks.json is not a valid JSON array.")),i;let l=s.find(d=>d?.target?.package_name===t.android?.package);i.push(l?H("pass",`assetlinks.json contains ${t.android.package}.`):H("fail",`assetlinks.json does not contain ${t.android.package}.`));let a=l?.target?.sha256_cert_fingerprints;return i.push(Array.isArray(a)&&a.length>0?H("pass","assetlinks.json has at least one SHA256 fingerprint."):H("warn","assetlinks.json has no SHA256 fingerprints.")),i}function Xm(e,t,n,i){if(t.framework!=="expo")return[];let r=[],o=lo(e),l=(Array.isArray(o?.ios?.associatedDomains)?o.ios.associatedDomains:[]).includes(`applinks:${n.domain}`);r.push(l?H("pass",`Expo iOS config contains applinks:${n.domain}.`):H(i?"warn":"fail",`Expo iOS config does not contain applinks:${n.domain}.`));let d=(Array.isArray(o?.android?.intentFilters)?o.android.intentFilters:[]).flatMap(c=>Array.isArray(c?.data)?c.data:[]).some(c=>c?.scheme==="https"&&c.host===n.domain);if(r.push(d?H("pass",`Expo Android config contains App Link host ${n.domain}.`):H(i?"warn":"fail",`Expo Android config does not contain App Link host ${n.domain}.`)),i)return r.push(H("warn","mach.config.json is missing deepLinks; values were inferred from Expo config. Run `mach deeplink setup` to persist Mach metadata and generate hosted files.")),r;let u=vl(e);return u==="wired"?r.push(H("pass","Expo deep link plugin is wired into Expo config and derives values from mach.config.json.")):u==="manual"&&l&&d?r.push(H("pass","Expo resolved config contains the deep-link settings from the dynamic config.")):u==="manual"?r.push(H("warn","Expo deep link plugin exists, but dynamic or missing Expo config means manual plugin insertion must be confirmed.")):l&&d?r.push(H("warn","Expo plugin is not wired, but resolved Expo config already contains the deep-link settings.")):r.push(H("fail","Expo deep link plugin is missing or not wired into Expo config.")),r}function Zm(e,t,n){if(t.framework!=="react-native")return[];let i=[],r=kt.join(e,"android/app/src/main/AndroidManifest.xml");if(Ct.existsSync(r)){let s=Ct.readFileSync(r,"utf-8");i.push(s.includes(`android:host="${n.domain}"`)?H("pass","AndroidManifest.xml contains the App Links host."):H("warn","AndroidManifest.xml does not contain the App Links host. Native patching is planned for a later phase."))}let o=kt.join(e,"ios");if(Ct.existsSync(o)){let l=Ct.readdirSync(o,{recursive:!0}).filter(a=>typeof a=="string"&&a.endsWith(".entitlements")).some(a=>Ct.readFileSync(kt.join(o,a),"utf-8").includes(`applinks:${n.domain}`));i.push(l?H("pass","iOS entitlements contain the associated domain."):H("warn","iOS entitlements do not contain the associated domain. Native patching is planned for a later phase."))}return i}async function po(e,t){let n=[];try{let i=await fetch(e,{redirect:"manual"});if(i.status>=300&&i.status<400&&!t)return n.push(H("fail",`${e} redirects. Apple AASA endpoints must not redirect.`)),n;n.push(i.status===200?H("pass",`${e} returned HTTP 200.`):H("fail",`${e} returned HTTP ${i.status}.`));let r=i.headers.get("content-type")||"";!r.includes("application/json")&&!r.includes("text/json")&&n.push(H("warn",`${e} content-type is "${r||"missing"}"; application/json is recommended.`)),JSON.parse(await i.text()),n.push(H("pass",`${e} contains valid JSON.`))}catch(i){n.push(H("fail",`${e} check failed: ${i.message}`))}return n}async function Qm(e){let t=e.domain;return(await Promise.all([po(`https://${t}/.well-known/apple-app-site-association`,!1),po(`https://${t}/apple-app-site-association`,!1),po(`https://${t}/.well-known/assetlinks.json`,!0)])).flat()}function eg(e){let t=e.android?.package;if(!t)return[H("warn","Cannot print Android device verification commands because android.package is missing.")];let i=Jm("adb",["version"],{encoding:"utf-8"}).status===0?"Run":"Install Android platform-tools, then run";return[H("info",`${i}: adb shell pm set-app-links --package ${t} 0 all`),H("info",`${i}: adb shell pm verify-app-links --re-verify ${t}`),H("info",`${i}: adb shell pm get-app-links ${t}`)]}async function fo(e,t,n){let i=n.profile||t.deepLinks?.profile||"production",r=t.framework==="expo"?Ni(e):null,o=t.framework==="expo"?ki(t,r,i,e):null,s=!t.deepLinks&&!!o,l=t.deepLinks?Ci(t,{profile:i,cwd:e,expoHints:r}):o,a=[];if(!l)return[H("fail","mach.config.json is missing deepLinks and Mach could not infer existing deep-link settings. Run `mach deeplink setup`.")];a.push(l.baseUrl?H("pass","deepLinks.baseUrl is configured."):H("fail","deepLinks.baseUrl is missing.")),a.push(l.domain?H("pass","deepLinks.domain is configured."):H("fail","deepLinks.domain is missing.")),a.push(l.scheme?H("pass","deepLinks.scheme is configured."):H("fail","deepLinks.scheme is missing."));let d=s?"warn":"fail";return a.push(...Ym(e,l,d)),a.push(...qm(e,l,d)),a.push(...Xm(e,t,l,s)),a.push(...Zm(e,t,l)),n.live&&a.push(...await Qm(l)),n.androidDevice&&a.push(...eg(l)),a}var Gn=()=>process.stdin.isTTY&&process.stdout.isTTY,Dl=`${m.npmScope}/mach`,Vn=()=>{tg("Operation cancelled."),process.exit(0)},ho=e=>{if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0},bt=(...e)=>{for(let t of e){let n=ho(t);if(n)return n}},Kt=async(e,t,n,i,r)=>{if(t)return t;if(r||!Gn()){if(i)throw new Error(`${e.replace(/:$/,"")} is required. Pass it as an option or run interactively.`);return}let o=await Cl({message:e,initialValue:t||"",placeholder:n,validate(s){if(i&&s.trim().length===0)return"Required."}});return Hn(o)&&Vn(),ho(o)};async function og(e,t,n){let i=He(e.framework),r=He(t);if(r)return r;if(i)return i;let o=hl();if(n||!Gn())return o;let s=await ig({message:`Which framework should ${m.name} configure?`,initialValue:o,options:[{value:"expo",label:"Expo"},{value:"react-native",label:"React Native"},{value:"flutter",label:"Flutter (not supported yet)"}]});return Hn(s)&&Vn(),s}var xi=e=>e==="ios"||e==="all",mo=e=>e==="android"||e==="all";async function sg(e,t,n){if(t!=="expo"||Ti(e)||n.installPlugin===!1)return!1;if(n.installPlugin===!0||n.yes)return!0;if(!Gn())return!1;let i=await Ol({message:`Install ${Dl} locally so Expo can use ${Dl}/expo-plugin?`,initialValue:!0});return Hn(i)&&Vn(),!!i}async function ag(e,t){let n=!!t.yes,i=t.profile||e.deepLinks?.profile||"production",r=xe(e,i)||{},o=r.ios||{},s=r.android||{},l=e.submit?.[i]?.ios||{},a=e.submit?.[i]?.android||{},d=xt(e,i),u=await og(e,t.framework,n);if(u==="flutter")throw new Error("Flutter deep-link automation is planned but not supported yet.");let c=yl(e,gl(t.platform),r),p=e.deepLinks,g=u==="expo"&&(!bt(t.baseUrl,p?.baseUrl,t.domain?`https://${t.domain}`:void 0)||!bt(t.scheme,p?.scheme,o.scheme,e.scheme,e.slug,e.name)||xi(c)&&!bt(t.iosBundleId,p?.ios?.bundleIdentifier,o.bundleIdentifier,o.bundleId,e.ios?.bundleIdentifier)||mo(c)&&!bt(t.androidPackage,p?.android?.package,s.package,s.applicationId,e.android?.package,a.packageName,a.package))?ki(e,Ni(process.cwd()),i,process.cwd()):null,y=t.output||p?.web?.outputDir||Oi(process.cwd(),e),h=await Kt("Deep link base URL:",t.baseUrl||p?.baseUrl||(t.domain?`https://${t.domain}`:void 0)||g?.baseUrl,"https://app.example.com",!0,n),v=Fn(h),I=t.baseUrl?new URL(v).hostname:void 0,N=await Kt("Associated domain:",t.domain||I||p?.domain||g?.domain||new URL(v).hostname,"app.example.com",!0,n),w=Di(await Kt("URI scheme:",bt(t.scheme,p?.scheme,o.scheme,e.scheme,g?.scheme,e.slug,e.name,"app"),"myapp",!0,n)||"app"),U=xi(c)?await Kt("iOS bundle identifier:",bt(t.iosBundleId,p?.ios?.bundleIdentifier,o.bundleIdentifier,o.bundleId,e.ios?.bundleIdentifier,g?.ios?.bundleIdentifier),"com.example.app",!0,n):p?.ios?.bundleIdentifier||e.ios?.bundleIdentifier,V=xi(c)?await Kt("Apple Team ID:",bt(t.appleTeamId,p?.ios?.appleTeamId,o.appleTeamId,o.developerTeamId,l.appleTeamId,l.developerTeamId,e.ios?.appleTeamId,e.ios?.developerTeamId,d.teamId),"ABCDE12345",!0,n):p?.ios?.appleTeamId||e.ios?.appleTeamId,J=xi(c)?await Kt("App Store ID (optional, for Smart App Banner):",bt(t.appStoreId,p?.ios?.appStoreId,o.ascAppId,l.ascAppId,e.ios?.ascAppId),"1234567890",!1,n):p?.ios?.appStoreId,A=mo(c)?await Kt("Android package name:",bt(t.androidPackage,p?.android?.package,s.package,s.applicationId,e.android?.package,a.packageName,a.package,g?.android?.package),"com.example.app",!0,n):p?.android?.package||e.android?.package,_=p?.android?.sha256CertFingerprints||[],L=t.androidFingerprint||[],P=e.android?.sha256CertFingerprints||[],S=s.sha256CertFingerprints||[],R=[...L,..._,...S,...P].filter(Boolean);if(mo(c)&&R.length===0&&!n&&Gn()){let B=await Cl({message:"Android SHA256 fingerprint (optional now, required for verified App Links):",placeholder:"AA:BB:CC:..."});Hn(B)&&Vn(),ho(B)&&R.push(B)}let M=Sl(e,{...t,baseUrl:v,domain:N,scheme:w,output:y,appleTeamId:V,appStoreId:J,androidFingerprint:R});return M.ios={...M.ios||{},bundleIdentifier:U,appleTeamId:V,appStoreId:J},M.android={...M.android||{},package:A,sha256CertFingerprints:Array.from(new Set(R))},{framework:u,platform:c,deepLinks:M}}var go=(e,t)=>{t.length!==0&&ng(t.map(n=>`- ${n}`).join(`
|
|
1671
|
+
`),e)},kl=e=>e.filter(t=>t.level==="fail").length;function Tl(e){for(let t of e){let n=t.level==="pass"?nt.green("PASS"):t.level==="warn"?nt.yellow("WARN"):t.level==="info"?nt.cyan("INFO"):nt.red("FAIL");Li.info(`${n} ${t.message}`)}}async function Nl(e){try{let t=process.cwd(),n=Pl.join(t,m.configFileName),i=ve()||{};if(!rg.existsSync(n)){let v=e.yes||!Gn()?!0:await Ol({message:`${m.configFileName} was not found. Create one with deep link settings?`,initialValue:!0});if(Hn(v)&&Vn(),!v)return}let{framework:r,deepLinks:o}=await ag(i,e),s=e.profile||i.deepLinks?.profile||"production",l=bl(i,r,o,s),a=Al(l,t),d=_l(t,o),u=await sg(t,r,e),c=r==="expo"?wl(t,o,{installPackage:u}):{written:[],skipped:[],notes:r==="react-native"?["React Native native patching is planned for a later phase. Hosted files were generated now."]:[]},p=[Pl.relative(t,a),...d.written,...c.written],f=[...d.skipped,...c.skipped],g=[...d.notes,...c.notes];go("Written",p),go("Skipped",f),go("Notes",g);let y=await fo(t,l,{});Tl(y);let h=kl(y);if(h>0){Mi(nt.yellow(`Deep link setup finished with ${h} verification issue(s).`));return}Mi(nt.green("Deep link setup complete."))}catch(t){Li.error(nt.red(t.message||"Deep link setup failed.")),process.exit(1)}}async function xl(e){try{let t=ve();t||(Li.error(nt.red(`No ${m.configFileName} found in the current directory.`)),process.exit(1));let n=await fo(process.cwd(),t,e);Tl(n);let i=kl(n);i>0&&(Mi(nt.red(`Deep link verification failed with ${i} issue(s).`)),process.exit(1)),Mi(nt.green("Deep link verification passed."))}catch(t){Li.error(nt.red(t.message||"Deep link verification failed.")),process.exit(1)}}import{log as At,spinner as Ll}from"@clack/prompts";import Tt from"chalk";var lg=e=>{let t=String(e||"").trim().toLowerCase();if(t==="ios"||t==="android")return t;throw new Error("Pass --platform ios or --platform android.")},cg=e=>{let t=Number(e);if(!Number.isFinite(t))throw new Error("Counter value must be a non-negative integer.");let n=Math.floor(t);if(n<0)throw new Error("Counter value must be a non-negative integer.");return n},dg=(e,t,n)=>{let i=String(n.scope||"").trim();if(i)return i;let r=n.profile||"production",o=e==="android"?n.package||n.androidPackage:n.bundleId||n.iosBundleIdentifier;if(o)return String(o).trim();let s=e==="android"?Zn(t,r):Qn(t,r);if(s)return s;throw new Error(e==="android"?`Could not resolve Android package. Set android.package in ${m.configFileName}, or pass --package/--scope.`:`Could not resolve iOS bundle identifier. Set ios.bundleIdentifier in ${m.configFileName}, or pass --bundle-id/--scope.`)},ug=()=>{let e=ve();if(!e)throw new Error(`No ${m.configFileName} found in the current directory. Run \`${m.nameLower} init\` or \`${m.nameLower} link\` first.`);if(!e.projectId)throw new Error(`${m.configFileName} is missing projectId.`);return e},yo=e=>{At.info(Tt.bgBlue.white(" Native Version Counter ")),At.info(`${Tt.blue("Platform:")} ${e.platform}`),At.info(`${Tt.blue("Scope:")} ${e.scope}`),At.info(`${Tt.blue("Current DB value:")} ${e.current}`),At.info(`${Tt.blue("Next build will use:")} ${e.next}`),e.seeded||At.warn(Tt.yellow("This counter has not been seeded yet. Existing store apps should run `mach version seed` once before auto-version builds."))};async function So(e,t={}){if(!ke()){At.error(`You are not logged in. Run \`${m.nameLower} login\` first.`);return}try{let i=ug(),r=lg(t.platform),o=dg(r,i,t),s=String(i.projectId);if(e==="show"){let u=Ll();t.json||u.start("Fetching native version counter...");let{data:c}=await k.get(`/projects/${s}/version-counters`,{params:{platform:r,scope:o}});if(c.status!=="success")throw new Error(c.message||"Failed to fetch version counter.");t.json?console.log(JSON.stringify(c.counter,null,2)):(u.stop("Fetched native version counter."),yo(c.counter));return}let l=cg(t.value),a=Ll();t.json||a.start("Seeding native version counter...");let{data:d}=await k.post(`/projects/${s}/version-counters/seed`,{platform:r,scope:o,value:l,force:!!t.force});if(d.status!=="success")throw new Error(d.message||"Failed to seed version counter.");t.json?console.log(JSON.stringify(d.counter,null,2)):(a.stop(`Seeded ${r} counter for ${o}.`),yo(d.counter))}catch(i){let r=i?.response?.data?.message||i?.message||"Version command failed.";if(i?.response?.data?.counter&&!t.json){At.error(Tt.red(r)),yo(i.response.data.counter);return}t.json?console.log(JSON.stringify({status:"error",message:r},null,2)):At.error(Tt.red(r))}}import{log as Ke,spinner as Wn,text as Ml,select as Ul,confirm as pg,isCancel as Kn,cancel as zn,outro as Jn,note as fg}from"@clack/prompts";import re from"chalk";import{execSync as mg}from"child_process";async function gg(){try{let e=mg("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 Fl=e=>e?.trim().toUpperCase()||void 0;function Bl(e){let t=ve(),n=t?xt(t):{},i=Fl(e.teamId),r=i||n.teamId;return{...n,teamId:r,developerTeamId:i||n.developerTeamId||r}}async function hg(e){let t=e.udid,n=e.name,i=Bl(e),r=i.teamId;if(!t){let s=Wn();s.start("Scanning for connected iOS devices...");let l=await gg();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,Ke.info(`Detected: ${re.bold(n)} (${re.dim(t.substring(0,12)+"...")})`);else if(l.length>1){let a=await Ul({message:"Select a device to register:",options:l.map(u=>({value:u.udid,label:`${u.name} (${u.model})`,hint:u.udid.substring(0,12)+"..."}))});if(Kn(a)){zn("Cancelled");return}t=a;let d=l.find(u=>u.udid===t);n=n||d.name}else{Ke.info(re.dim("No connected devices found. Enter UDID manually."));let a=await Ml({message:"Device UDID:",placeholder:"00008101-XXXXXXXXXXXX",validate(d){if(d.length<10)return"UDID seems too short"}});if(Kn(a)){zn("Cancelled");return}t=a}}if(!n){let s=await Ml({message:"Device name:",placeholder:"Nitesh's iPhone",validate(l){if(l.length===0)return"Name is required"}});if(Kn(s)){zn("Cancelled");return}n=s}let o=Wn();o.start("Registering device...");try{await k.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!")),Ke.info(` ${re.bold("Name:")} ${n}`),Ke.info(` ${re.bold("UDID:")} ${re.dim(t)}`),r&&Ke.info(` ${re.bold("Team:")} ${re.dim(r)}`)}catch(s){o.stop(re.red("Failed to register device")),Ke.error(s.response?.data?.message||s.message)}Jn(re.blue("---"))}async function yg(e={}){let t=Fl(e.teamId),n=Wn();n.start("Fetching registered devices...");try{let r=(await k.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){Ke.info(re.dim(`No devices registered yet. Run \`${m.nameLower} device register\` to add one.`)),Jn(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)}`});fg(` ${re.bold("Name".padEnd(24))} ${"UDID".padEnd(28)} ${"Team".padEnd(12)} ${"Via".padEnd(10)} Date
|
|
1672
1672
|
`+o.join(`
|
|
1673
|
-
`),"Registered Devices")}catch(i){n.stop(re.red("Failed to fetch devices")),Ke.error(i.response?.data?.message||i.message)}
|
|
1674
|
-
`),d=
|
|
1675
|
-
`),u=
|
|
1676
|
-
`),u=
|
|
1677
|
-
`),u=
|
|
1678
|
-
`);/__DEV__/.test(g)||n.push({id:`DBG-${String(i++).padStart(3,"0")}`,title:"Sensitive data in console log",description:"Console log may expose sensitive data (token, password, etc.) in production",severity:"medium",category:"debug",file:u,line:c+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
|
|
1679
|
-
Running expo prebuild for deeper analysis...`));try{
|
|
1680
|
-
Skipping manifest/plist checks \u2014 no android/ios dirs. Use --prebuild to generate them.`)),o;for(let d of r){let u=
|
|
1673
|
+
`),"Registered Devices")}catch(i){n.stop(re.red("Failed to fetch devices")),Ke.error(i.response?.data?.message||i.message)}Jn(re.blue("---"))}async function Sg(e){let t=e.udid,n=Bl(e).teamId;if(!t){let o=Wn();o.start("Fetching registered devices...");try{let l=(await k.get("/devices",n?{params:{teamId:n}}:void 0)).data.devices||[];if(o.stop(`${l.length} device(s) found`),l.length===0){Ke.info(re.dim("No devices to remove.")),Jn(re.blue("---"));return}let a=await Ul({message:"Select device to remove:",options:l.map(u=>({value:u.deviceKey||u.udid,label:u.name,hint:`${u.udid.substring(0,12)}...${u.teamId?` \xB7 ${u.teamId}`:""}`}))});if(Kn(a)){zn("Cancelled");return}let d=l.find(u=>(u.deviceKey||u.udid)===a);t=d?.udid||a,n=d?.teamId||n}catch(s){o.stop(re.red("Failed to fetch devices")),Ke.error(s.response?.data?.message||s.message);return}}let i=await pg({message:`Remove device ${re.dim(t.substring(0,12)+"...")}?`});if(Kn(i)||!i){zn("Cancelled");return}let r=Wn();r.start("Removing device...");try{await k.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")),Ke.error(o.response?.data?.message||o.message)}Jn(re.blue("---"))}async function Ui(e,t){switch(e){case"register":await hg(t);break;case"list":await yg(t);break;case"remove":await Sg(t);break;default:Ke.error(`Unknown action: ${e}`)}}import{log as We,spinner as gc}from"@clack/prompts";import rt from"chalk";import Ji from"path";import Xn from"fs";import Zg from"os";import Qg from"axios";var ze=(o=>(o.CRITICAL="critical",o.HIGH="high",o.MEDIUM="medium",o.LOW="low",o.INFO="info",o))(ze||{}),it=(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))(it||{});import{spinner as oc,log as qn}from"@clack/prompts";import je from"chalk";import{execSync as Hg}from"child_process";import sc from"fs";import ac from"path";import Nt from"fs";import Yn from"path";import{execSync as bg}from"child_process";var jl={"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"}},Ag={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 Eg(e){try{let n=bg("npx expo config --type introspect --json 2>/dev/null",{cwd:e,encoding:"utf-8",timeout:3e4});return JSON.parse(n)}catch{}let t=Yn.join(e,"app.json");if(Nt.existsSync(t))try{let n=JSON.parse(Nt.readFileSync(t,"utf-8"));return n.expo||n}catch{}return null}function Ig(e){let t=[],n=Yn.join(e,"node_modules");if(!Nt.existsSync(n))return t;let i=/<uses-permission\s+android:name="([^"]+)"/g;function r(o,s){let l=Yn.join(o,"android","src","main","AndroidManifest.xml");if(!Nt.existsSync(l))return;let a=Nt.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 Nt.readdirSync(n)){if(o.startsWith("."))continue;let s=Yn.join(n,o);if(o.startsWith("@")){if(!Nt.statSync(s).isDirectory())continue;for(let l of Nt.readdirSync(s))r(Yn.join(s,l),`${o}/${l}`)}else r(s,o)}return t}async function Hl(e,t){let n=[],i=1,r=Eg(e),o=r?.android?.permissions||[],s=r?.android?.blockedPermissions||[];for(let d of o){let u=jl[d];u&&n.push({id:`PERM-${String(i++).padStart(3,"0")}`,title:`${d.split(".").pop()} declared`,description:u.description,severity:u.severity,category:"permissions",file:"app.config.ts",recommendation:"Remove from permissions if not needed, or add justification."})}let l=Ig(e);for(let{pkg:d,permission:u}of l){let c=jl[u];c&&(s.includes(u)||o.includes(u)||n.push({id:`PERM-${String(i++).padStart(3,"0")}`,title:`${u.split(".").pop()} injected by ${d}`,description:`${c.description}. Auto-injected via ${d} AndroidManifest.xml`,severity:c.severity,category:"permissions",file:`node_modules/${d}/android/src/main/AndroidManifest.xml`,recommendation:`Add "${u}" to blockedPermissions if not needed.`,autoFixable:!0}))}let a=r?.ios?.infoPlist||{};for(let[d,u]of Object.entries(Ag))d in a&&n.push({id:`PERM-${String(i++).padStart(3,"0")}`,title:`iOS: ${d} declared`,description:u.description,severity:u.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 bo from"fs";import Fi from"path";var wg=[{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"}],vg=new Set([".ts",".tsx",".js",".jsx"]),$g=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function Gl(e){let t=[],n=bo.readdirSync(e,{withFileTypes:!0});for(let i of n){if($g.has(i.name))continue;let r=Fi.join(e,i.name);i.isDirectory()?t.push(...Gl(r)):vg.has(Fi.extname(i.name))&&t.push(r)}return t}function _g(e){let t=e.trim();return t.startsWith("//")||t.startsWith("*")||t.startsWith("/*")}function Rg(e){return/process\.env\./i.test(e)||/import\.meta\.env/i.test(e)}async function Vl(e,t){let n=[],i=Fi.join(e,"src"),r=bo.existsSync(i)?i:e,o=Gl(r);for(let s of o){let a=bo.readFileSync(s,"utf-8").split(`
|
|
1674
|
+
`),d=Fi.relative(e,s);for(let u=0;u<a.length;u++){let c=a[u];if(!_g(c)&&!Rg(c))for(let{id:p,pattern:f,severity:g,label:y}of wg)f.lastIndex=0,f.test(c)&&n.push({id:p,title:y,description:`Potential ${y.toLowerCase()} found in source code`,severity:g,category:"secrets",file:d,line:u+1,recommendation:`Move to environment variables or a secrets manager. Use \`${m.nameLower} env set\` for managed secrets.`})}}return{category:"secrets",label:"Secrets Detection",findings:n,durationMs:0}}import{execSync as Pg}from"child_process";var Dg={critical:"critical",high:"high",moderate:"medium",low:"low",info:"info"};async function Kl(e,t){let n=[],i=1,r;try{r=Pg("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=Dg[a.severity]||"info",u=Array.isArray(a.via)?a.via.map(c=>typeof c=="string"?c:c.title||c.name).join(", "):String(a.via);n.push({id:`DEP-${String(i++).padStart(3,"0")}`,title:`${l} \u2014 ${a.severity}`,description:`Via: ${u}. Range: ${a.range||"unknown"}`,severity: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 Bi from"fs";import ji from"path";var Og=/(?:token|password|credential|secret|apiKey|api_key|session|auth|jwt|refresh_token|access_token|private_key|pin|otp)/i,zl=/AsyncStorage\s*\.\s*(?:setItem|mergeItem)\s*\(\s*['"`]([^'"`]+)['"`]/g,Cg=/from\s+['"]@react-native-async-storage\/async-storage['"]|from\s+['"]react-native['"].*AsyncStorage/,kg=new Set([".ts",".tsx",".js",".jsx"]),Tg=new Set(["node_modules",".expo",".git","android","ios","dist","build"]);function Wl(e){let t=[];if(!Bi.existsSync(e))return t;let n=Bi.readdirSync(e,{withFileTypes:!0});for(let i of n){if(Tg.has(i.name))continue;let r=ji.join(e,i.name);i.isDirectory()?t.push(...Wl(r)):kg.has(ji.extname(i.name))&&t.push(r)}return t}async function Jl(e,t){let n=[],i=1,r=ji.join(e,"src"),o=Bi.existsSync(r)?r:e,s=Wl(o);for(let l of s){let a=Bi.readFileSync(l,"utf-8");if(!Cg.test(a))continue;let d=a.split(`
|
|
1675
|
+
`),u=ji.relative(e,l);for(let c=0;c<d.length;c++){let p=d[c];zl.lastIndex=0;let f;for(;(f=zl.exec(p))!==null;){let g=f[1];Og.test(g)&&n.push({id:`STOR-${String(i++).padStart(3,"0")}`,title:`AsyncStorage used for "${g}"`,description:`Sensitive data key "${g}" stored in AsyncStorage (unencrypted).`,severity:"high",category:"storage",file:u,line:c+1,recommendation:"Use expo-secure-store (SecureStore) for sensitive data instead of AsyncStorage."})}}}return{category:"storage",label:"Insecure Storage",findings:n,durationMs:0}}import Hi from"fs";import Gi from"path";var Yl=/['"`](http:\/\/(?!localhost|127\.0\.0\.1|10\.|192\.168\.|0\.0\.0\.0|172\.(?:1[6-9]|2\d|3[01])\.)[^'"`\s]+)['"`]/g,Ng=/\/api\/|\/v[0-9]+\/|\/graphql|\/rest\//i,xg=new Set([".ts",".tsx",".js",".jsx"]),Lg=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function ql(e){let t=[];if(!Hi.existsSync(e))return t;let n=Hi.readdirSync(e,{withFileTypes:!0});for(let i of n){if(Lg.has(i.name))continue;let r=Gi.join(e,i.name);i.isDirectory()?t.push(...ql(r)):xg.has(Gi.extname(i.name))&&t.push(r)}return t}async function Xl(e,t){let n=[],i=1,r=Gi.join(e,"src"),o=Hi.existsSync(r)?r:e,s=ql(o);for(let l of s){let d=Hi.readFileSync(l,"utf-8").split(`
|
|
1676
|
+
`),u=Gi.relative(e,l);for(let c=0;c<d.length;c++){let p=d[c],f=p.trim();if(f.startsWith("//")||f.startsWith("*"))continue;Yl.lastIndex=0;let g;for(;(g=Yl.exec(p))!==null;){let y=g[1],h=Ng.test(y);n.push({id:`NET-${String(i++).padStart(3,"0")}`,title:`Insecure HTTP URL${h?" (API endpoint)":""}`,description:`Plain HTTP URL found: ${y}`,severity:h?"high":"medium",category:"network",file:u,line:c+1,recommendation:"Use HTTPS instead of HTTP for all network requests."})}}}return{category:"network",label:"HTTP URLs",findings:n,durationMs:0}}import Vi from"fs";import Ki from"path";var Zl=/(?:debug|debugMode|devMode|enableDebug)\s*[:=]\s*true/gi,Ql=/console\.(?:log|warn|info|debug)\s*\([^)]*(?:token|password|secret|credential|key|auth)/gi,Mg=new Set([".ts",".tsx",".js",".jsx"]),Ug=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function ec(e){let t=[];if(!Vi.existsSync(e))return t;let n=Vi.readdirSync(e,{withFileTypes:!0});for(let i of n){if(Ug.has(i.name))continue;let r=Ki.join(e,i.name);i.isDirectory()?t.push(...ec(r)):Mg.has(Ki.extname(i.name))&&t.push(r)}return t}async function tc(e,t){let n=[],i=1,r=Ki.join(e,"src"),o=Vi.existsSync(r)?r:e,s=ec(o);for(let l of s){let d=Vi.readFileSync(l,"utf-8").split(`
|
|
1677
|
+
`),u=Ki.relative(e,l);for(let c=0;c<d.length;c++){let p=d[c],f=p.trim();if(!(f.startsWith("//")||f.startsWith("*"))&&(Zl.lastIndex=0,Zl.test(p)&&n.push({id:`DBG-${String(i++).padStart(3,"0")}`,title:"Hardcoded debug flag",description:"Debug/dev mode enabled in source code",severity:"medium",category:"debug",file:u,line:c+1,recommendation:"Use __DEV__ or environment variables instead of hardcoded debug flags."}),Ql.lastIndex=0,Ql.test(p))){let g=d.slice(Math.max(0,c-3),c).join(`
|
|
1678
|
+
`);/__DEV__/.test(g)||n.push({id:`DBG-${String(i++).padStart(3,"0")}`,title:"Sensitive data in console log",description:"Console log may expose sensitive data (token, password, etc.) in production",severity:"medium",category:"debug",file:u,line:c+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 nc from"fs";import Ao from"path";var Fg=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 Bg(e){let t=[Ao.join(e,"android","app","src","main","AndroidManifest.xml"),Ao.join(e,"android","AndroidManifest.xml")];for(let n of t)if(nc.existsSync(n))return n;return null}async function ic(e,t){let n=[],i=1,r=Bg(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=nc.readFileSync(r,"utf-8"),s=Ao.relative(e,r),l=/<(activity|service|receiver|provider)\s+([^>]*?)(?:\/>|>)/gs,a;for(;(a=l.exec(o))!==null;){let d=a[1],u=a[2],p=u.match(/android:name="([^"]+)"/)?.[1]||"unknown";if(Fg.has(p))continue;let f=/android:exported="true"/.test(u),g=/android:permission="/.test(u);f&&!g&&n.push({id:`MAN-${String(i++).padStart(3,"0")}`,title:`Exported ${d}: ${p.split(".").pop()}`,description:`${p} is exported=true without android:permission protection`,severity:"medium",category:"manifest",file:s,recommendation:'Set android:exported="false" or add an android:permission attribute.'})}return/android:allowBackup="true"/.test(o)&&n.push({id:`MAN-${String(i++).padStart(3,"0")}`,title:"allowBackup is enabled",description:'android:allowBackup="true" allows data extraction via ADB backup',severity:"medium",category:"manifest",file:s,recommendation:'Set android:allowBackup="false" via expo-build-properties plugin.',autoFixable:!0}),/android:debuggable="true"/.test(o)&&n.push({id:`MAN-${String(i++).padStart(3,"0")}`,title:"App is debuggable",description:'android:debuggable="true" allows attaching a debugger in production',severity:"critical",category:"manifest",file:s,recommendation:"Ensure debuggable is false for production builds. This is usually set automatically for release builds."}),{category:"manifest",label:"Android Manifest",findings:n,durationMs:0}}import zi from"fs";import Eo from"path";function jg(e){let t=Eo.join(e,"ios");if(!zi.existsSync(t))return null;let n=zi.readdirSync(t,{withFileTypes:!0});for(let i of n){if(!i.isDirectory()||i.name==="Pods"||i.name.startsWith("."))continue;let r=Eo.join(t,i.name,"Info.plist");if(zi.existsSync(r))return r}return null}async function rc(e,t){let n=[],i=1,r=jg(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=zi.readFileSync(r,"utf-8"),s=Eo.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 u=d[1].match(/<key>([^<]+)<\/key>/g);if(u)for(let c of u){let p=c.replace(/<\/?key>/g,"");p!=="NSExceptionDomains"&&n.push({id:`ATS-${String(i++).padStart(3,"0")}`,title:`ATS exception: ${p}`,description:`ATS exception configured for ${p}`,severity:"low",category:"ats",file:s,recommendation:`Verify that the ATS exception for ${p} is necessary. Use HTTPS where possible.`})}}}return{category:"ats",label:"iOS ATS Config",findings:n,durationMs:0}}var Gg=[{category:"permissions",label:"Permission Audit",fn:Hl,requiresPrebuild:!1},{category:"secrets",label:"Secrets Detection",fn:Vl,requiresPrebuild:!1},{category:"dependencies",label:"Dependency CVEs",fn:Kl,requiresPrebuild:!1},{category:"storage",label:"Insecure Storage",fn:Jl,requiresPrebuild:!1},{category:"network",label:"HTTP URLs",fn:Xl,requiresPrebuild:!1},{category:"debug",label:"Debug/Dev Flags",fn:tc,requiresPrebuild:!1},{category:"manifest",label:"Android Manifest",fn:ic,requiresPrebuild:!0},{category:"ats",label:"iOS ATS Config",fn:rc,requiresPrebuild:!0}];async function lc(e,t){let n=Gg;t.category&&(n=n.filter(s=>s.category===t.category),n.length===0&&(qn.error(je.red(`Unknown category: ${t.category}`)),qn.info(je.dim(`Available: ${Object.values(it).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=oc();l.start(je.dim(`Running ${s.label}...`));try{let a=Date.now(),d=await s.fn(e,t);d.durationMs=Date.now()-a,o.push(d);let u=d.findings.length;l.stop(u>0?je.yellow(`${s.label} \u2014 ${u} finding(s)`):je.green(`${s.label} \u2014 clean`))}catch(a){l.stop(je.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=ac.join(e,"android"),l=ac.join(e,"ios"),a=sc.existsSync(s)||sc.existsSync(l);if(!a&&t.prebuild){t.json||qn.info(je.dim(`
|
|
1679
|
+
Running expo prebuild for deeper analysis...`));try{Hg("npx expo prebuild --no-install",{cwd:e,stdio:"pipe"})}catch{return qn.warn(je.yellow("Prebuild failed \u2014 skipping manifest/plist checks.")),o}}else if(!a)return t.json||qn.info(je.dim(`
|
|
1680
|
+
Skipping manifest/plist checks \u2014 no android/ios dirs. Use --prebuild to generate them.`)),o;for(let d of r){let u=oc();u.start(je.dim(`Running ${d.label}...`));try{let c=Date.now(),p=await d.fn(e,t);p.durationMs=Date.now()-c,o.push(p);let f=p.findings.length;u.stop(f>0?je.yellow(`${d.label} \u2014 ${f} finding(s)`):je.green(`${d.label} \u2014 clean`))}catch(c){u.stop(je.red(`${d.label} \u2014 error`)),o.push({category:d.category,label:d.label,findings:[],durationMs:0,error:c.message})}}}return o}import _e from"chalk";import{log as Ie}from"@clack/prompts";var un={critical:_e.bgRed.white.bold,high:_e.red.bold,medium:_e.yellow.bold,low:_e.blue,info:_e.dim},Wi={critical:0,high:1,medium:2,low:3,info:4};function Vg(e,t){if(!t)return!0;let n=Wi[t];return n===void 0?!0:Wi[e]<=n}function cc(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=>Vg(d.severity,t));if(l.length===0&&!s.error)continue;if(Ie.info(""),Ie.info(_e.bold(` ${s.label}`)+_e.dim(` ${l.length} finding(s)`)),Ie.info(_e.dim(" "+"\u2500".repeat(60))),s.error){Ie.error(_e.red(` Error: ${s.error}`));continue}let a=[...l].sort((d,u)=>Wi[d.severity]-Wi[u.severity]);for(let d of a){let u=un[d.severity](` ${d.severity.toUpperCase()} `);Ie.info(` ${u} ${_e.bold(d.id)} ${d.title}`),Ie.info(_e.dim(` ${d.description}`)),d.file&&Ie.info(_e.dim(` File: ${d.file}${d.line?`:${d.line}`:""}`)),Ie.info(_e.cyan(` Fix: ${d.recommendation}`)),Ie.info(""),i[d.severity]++,n++}}Ie.info(""),Ie.info(_e.bold(" Summary")),Ie.info(_e.dim(" "+"\u2500".repeat(60))),Ie.info(` Total: ${_e.bold(String(n))} finding(s)`),Ie.info(` ${un.critical(` ${i.critical} Critical `)} ${un.high(` ${i.high} High `)} ${un.medium(` ${i.medium} Medium `)} ${un.low(` ${i.low} Low `)} ${un.info(` ${i.info} Info `)}`);let r=i.critical>0,o=i.high>0;r||o?(Ie.info(""),Ie.error(_e.red.bold(` FAIL \u2014 ${i.critical} critical, ${i.high} high issue(s) found`))):n>0?(Ie.info(""),Ie.warn(_e.yellow(" PASS (with warnings) \u2014 no critical or high issues"))):(Ie.info(""),Ie.success(_e.green.bold(" PASS \u2014 no issues found")))}function dc(e,t){let n=e.flatMap(r=>r.findings),i={};for(let r of Object.values(ze))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 we,spinner as Kg}from"@clack/prompts";import ye from"chalk";import Et from"fs";import zg from"os";import pn from"path";import{execSync as Wg}from"child_process";var uc=16384,Jg=1,Yg=Buffer.from([127,69,76,70]);async function pc(e){we.info(ye.bold.underline("16KB Page Alignment Check")),console.log("");let t=pn.resolve(e);if(!Et.existsSync(t))return we.error(ye.red(`APK file not found: ${t}`)),!1;if(!t.endsWith(".apk"))return we.error(ye.red("The provided file is not an APK file.")),!1;let n=Kg();n.start("Extracting and analyzing native libraries...");let i=Et.mkdtempSync(pn.join(zg.tmpdir(),"mach-16kb-"));try{try{Wg(`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=fc(pn.join(i,"lib"));if(r.length===0)return n.stop("Analysis complete."),we.info(ye.yellow("No arm64-v8a or x86_64 native libraries found in the APK.")),we.info(ye.dim("16KB alignment check only applies to arm64-v8a and x86_64 architectures.")),!0;let o=[];for(let a of r){let d=pn.relative(i,a),u=Xg(d),c=pn.basename(a),p=qg(a);p!==null&&o.push({name:c,filePath:d,arch:u,align:p,compatible:p>=uc})}if(n.stop("Analysis complete."),o.length===0)return we.info(ye.yellow("No valid ELF shared libraries found.")),!0;let s=o.filter(a=>!a.compatible),l=o.filter(a=>a.compatible);if(we.info(ye.dim(`Checked ${o.length} native librar${o.length===1?"y":"ies"}
|
|
1681
1681
|
`)),s.length>0){we.info(ye.red.bold(`Incompatible libraries:
|
|
1682
|
-
`));for(let a of s)we.error(ye.red(`${ye.bold(a.name)} ${ye.dim(`(${a.arch})`)}`)),we.info(ye.dim(` PT_LOAD alignment: 2**${Math.log2(a.align)} (${a.align} bytes, needs 2**14 = ${ac})`))}return l.length>0&&(console.log(""),we.success(ye.green(`${l.length} librar${l.length===1?"y":"ies"} correctly aligned (2**14 or higher).`))),console.log(""),s.length===0?(we.success(ye.green.bold("ELF Verification Successful. APK is 16KB compatible.")),!0):(we.error(ye.red.bold(`Found ${s.length} unaligned lib${s.length===1?"":"s"} (arm64-v8a/x86_64 libs need to be aligned).`)),console.log(""),we.info(ye.yellow("To fix this:")),we.info(ye.dim(" 1. Rebuild with NDK r28+ which defaults to 16KB page alignment")),we.info(ye.dim(" 2. Or set -DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON in CMake")),we.info(ye.dim(" 3. Update third-party libraries that ship prebuilt .so files")),we.info(ye.dim(" 4. After rebuilding: zipalign -p -f -v 16 input.apk output.apk")),console.log(""),we.info(ye.dim("Reference: https://developer.android.com/guide/practices/page-sizes")),!1)}catch(r){return n.stop("Analysis failed."),we.error(ye.red(`Failed to analyze APK: ${r.message}`)),!1}finally{try{At.rmSync(i,{recursive:!0,force:!0})}catch{}}}function Bg(e){let t=At.openSync(e,"r");try{let n=Buffer.alloc(64);if(At.readSync(t,n,0,64,0),!n.subarray(0,4).equals(Fg))return null;let i=n[4]===2,r=n[5]===1,o=(p,f)=>r?p.readUInt16LE(f):p.readUInt16BE(f),s=(p,f)=>r?p.readUInt32LE(f):p.readUInt32BE(f),l=(p,f)=>Number(r?p.readBigUInt64LE(f):p.readBigUInt64BE(f)),a,d,u;i?(a=l(n,32),d=o(n,54),u=o(n,56)):(a=s(n,28),d=o(n,42),u=o(n,44));let c=null;for(let p=0;p<u;p++){let f=Buffer.alloc(d);if(At.readSync(t,f,0,d,a+p*d),s(f,0)!==Ug)continue;let y;i?y=l(f,48):y=s(f,28),y>0&&(c===null||y<c)&&(c=y)}return c??0}catch{return null}finally{At.closeSync(t)}}function cc(e){let t=[];if(!At.existsSync(e))return t;let n=At.readdirSync(e,{withFileTypes:!0});for(let i of n){let r=dn.join(e,i.name);i.isDirectory()?t.push(...cc(r)):i.name.endsWith(".so")&&t.push(r)}return t}function jg(e){return e.includes("arm64-v8a")?"arm64-v8a":e.includes("x86_64")?"x86_64":"unknown"}var pc=async e=>{if(Ne()||(We.error(rt.red(`You are not logged in. Run \`${m.nameLower} login\` first.`)),process.exit(1)),e.apk){await Vg(e);return}let n=process.cwd(),i=Vi.join(n,"package.json");Yn.existsSync(i)||(We.error(rt.red("No package.json found. Run this command from a project root.")),process.exit(1));let r=JSON.parse(Yn.readFileSync(i,"utf-8")),o=!!(r.dependencies?.expo||r.devDependencies?.expo);e.json||(We.info(rt.dim(`Project: ${r.name||"unknown"} v${r.version||"0.0.0"}`)),We.info(rt.dim(`Type: ${o?"Expo":"Bare React Native"}`)),We.info(""));let s={json:e.json,fix:e.fix,category:e.category,severity:e.severity,prebuild:e.prebuild},l=await rc(n,s);e.json?console.log(JSON.stringify(sc(l,r),null,2)):oc(l,e.severity);let a=l.some(u=>u.findings.some(c=>c.severity==="critical")),d=l.some(u=>u.findings.some(c=>c.severity==="high"));(a||d)&&process.exit(1)},dc=["16kb"];async function Vg(e){let t=e.category?.toLowerCase();t&&!dc.includes(t)&&(We.error(rt.red(`Unknown APK check category: "${t}"`)),We.info(rt.dim(`Available APK checks: ${dc.join(", ")}`)),process.exit(1));let n=await Kg(e.apk);n||process.exit(1);let i=!t,r=!1;(i||t==="16kb")&&(await lc(n)||(r=!0)),r&&process.exit(1)}async function Kg(e){if(e.startsWith("build:")){let n=e.slice(6);return await zg(n)}if(e.startsWith("http://")||e.startsWith("https://"))return await fc(e);let t=Vi.resolve(e);return Yn.existsSync(t)?t:(We.error(rt.red(`APK file not found: ${t}`)),null)}async function zg(e){let t=uc();t.start(`Fetching APK from build ${e}...`);try{let n=await N.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"),We.error(rt.red("This build does not have an APK artifact.")),We.info(rt.dim("Make sure the build produced an APK (not just an AAB).")),null):(t.stop(`Found build: ${i.buildId||e}`),await fc(r.url))}catch(n){return t.stop("Failed to fetch build"),We.error(rt.red(n.message)),null}}async function fc(e){let t=uc();t.start("Downloading APK...");try{let n=Yn.mkdtempSync(Vi.join(Hg.tmpdir(),`${m.nameLower}-audit-`)),i=Vi.join(n,"app.apk"),r=await Gg.get(e,{responseType:"arraybuffer"});Yn.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"),We.error(rt.red(`Failed to download APK: ${n.message}`)),null}}var Yg=console.log;console.log=()=>{};Jg();console.log=Yg;ge(ce.bgCyan.black(m.cliTag("Production Build Orchestrator")));var Xg=qg(import.meta.url),Zg=Xg("../package.json"),ho=(e,t=[])=>t.concat(e),q=new Wg;q.name(m.nameLower).description(`${m.name} CLI: Powerful Cloud Infrastructure Tools`).version(Zg.version).option("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1);q.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 Ma(e)});q.command("host").description("Setup AWS S3 static hosting and CloudFront").action(async()=>{ge(ce.bgCyan.black(m.cliTag("Hosting"))),await Oo()});q.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=>{ge(ce.bgCyan.black(m.cliTag("Sitemap Generator"))),await No(e)});q.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 Je("--build-id <id>","Internal build ID").hideHelp()).addOption(new Je("--project-id <id>","Internal project ID").hideHelp()).addOption(new Je("--fail-only","Internal: mark an existing build failed").hideHelp()).addOption(new Je("--error <message>","Internal failure message").hideHelp()).option("--local","Run build on local machine").option("--auto-version","Assign the next Android versionCode or iOS buildNumber from Mach").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",ho,[]).option("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1).action(async(e,t)=>{let n=q.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||ge(ce.bgCyan.black(m.cliTag("Cloud Build"))),await di(t)});q.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",ho,[]).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 Je("--local-runner","Internal: execute a managed Maestro run on this machine").hideHelp()).addOption(new Je("--test-run-id <id>","Internal test run ID").hideHelp()).addOption(new Je("--project-id <id>","Internal project ID").hideHelp()).addOption(new Je("--runner-token <token>","Internal runner token").hideHelp()).action(async e=>{ge(ce.bgCyan.black(m.cliTag("Maestro Testing"))),await bs(e)});var un=e=>e.option("--platform <os>","Target platform: ios, android, or all","all").option("--channel <name>","OTA channel (for example: production, staging)").option("--branch <name>","Alias for --channel").option("--runtime-version <version>","Runtime version override").option("--message <text>","Release note/message for this OTA update").option("--framework <name>","Framework override: expo or react-native").option("--engine <name>","OTA engine override: expo-updates or mach-react-native").option("--url <url>","Mach OTA update URL override").option("--install-plugin","Install @radhya/mach locally for the Expo config plugin").option("--skip-install","Do not install local Expo plugin dependency").option("--update-id <id>","OTA update id for rollback/promote").option("--json","Print JSON output"),pn=q.command("ota").description("Setup, publish, verify, and manage Mach OTA updates");un(pn.command("setup").description("Configure OTA for this project")).action(async e=>{let t=q.opts();ge(ce.bgCyan.black(m.cliTag("OTA Setup"))),await Pt("setup",{...e,yes:e.yes||t.yes})});un(pn.command("publish").description("Publish an OTA update")).action(async e=>{let t=q.opts();ge(ce.bgCyan.black(m.cliTag("OTA Publish"))),await Pt("publish",{...e,yes:e.yes||t.yes})});un(pn.command("verify").description("Verify OTA configuration")).action(async e=>{let t=q.opts();ge(ce.bgCyan.black(m.cliTag("OTA Verify"))),await Pt("verify",{...e,yes:e.yes||t.yes})});un(pn.command("list").description("List OTA updates for the linked project")).action(async e=>{let t=q.opts();ge(ce.bgCyan.black(m.cliTag("OTA Updates"))),await Pt("list",{...e,yes:e.yes||t.yes})});un(pn.command("rollback").description("Roll back an OTA update")).action(async e=>{let t=q.opts();ge(ce.bgCyan.black(m.cliTag("OTA Rollback"))),await Pt("rollback",{...e,yes:e.yes||t.yes})});un(pn.command("promote").description("Promote an OTA update")).action(async e=>{let t=q.opts();ge(ce.bgCyan.black(m.cliTag("OTA Promote"))),await Pt("promote",{...e,yes:e.yes||t.yes})});q.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 Je("--submit-id <id>","Internal submission ID").hideHelp()).addOption(new Je("--project-id <id>","Internal project ID").hideHelp()).addOption(new Je("--package-name <name>","Internal Android package name").hideHelp()).addOption(new Je("--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=q.opts();e.quiet=e.quiet||t.quiet,e.yes=e.yes||t.yes,ge(ce.bgCyan.black(m.cliTag("Store Submission"))),await ri(e)});q.command("login").description(`Login to ${m.name} Dashboard`).action(async()=>{ge(ce.bgCyan.black(m.cliTag("Login"))),await ja()});q.command("logout").description(`Logout from ${m.name} on this machine`).action(async()=>{ge(ce.bgCyan.black(m.cliTag("Logout"))),await Ha()});q.command("link").description(`Link local directory to a ${m.name} Project`).action(async()=>{ge(ce.bgCyan.black(m.cliTag("Link Project"))),await Va()});q.command("me").description("Display currently logged in user details").action(async()=>{await sl()});q.command("init").description(`Create a new ${m.name} Project`).action(async()=>{ge(ce.bgCyan.black(m.cliTag("Init Project"))),await Ka()});q.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)=>{ge(ce.bgCyan.black(m.cliTag("Env Manager"))),await Wa(e,t,n)});q.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=>{ge(ce.bgCyan.black(m.cliTag("Dev Server"))),await ll(e)});q.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 cl(e)});var gc=q.command("deeplink").description("Configure and verify app links, universal links, and URI schemes");gc.command("setup").description("Generate deep link config, hosted association files, and Expo plugin support").option("--domain <domain>","Associated domain, e.g. app.example.com").option("--base-url <url>","Base URL, e.g. https://app.example.com").option("-p, --profile <name>","Profile used for build/submit overrides").option("--platform <platform>","ios, android, or all").option("--framework <framework>","expo or react-native").option("--scheme <scheme>","URI scheme, e.g. myapp").option("--ios-bundle-id <id>","iOS bundle identifier").option("--android-package <name>","Android package name").option("--apple-team-id <id>","Apple Developer Team ID").option("--app-store-id <id>","App Store app ID for Smart App Banner").option("--android-fingerprint <sha256>","Android SHA256 signing certificate fingerprint; repeatable",ho,[]).option("--output <dir>","Directory for hosted files, e.g. public or deep-links").option("--install-plugin","Install @radhya/mach locally so Expo can use the packaged config plugin").option("--no-install-plugin","Do not install @radhya/mach for Expo projects; use the local plugin fallback if the package is missing").option("-y, --yes","Automatically answer yes to prompts",!1).action(async e=>{let t=q.opts();e.yes=e.yes||t.yes,ge(ce.bgCyan.black(m.cliTag("Deep Links"))),await Cl(e)});gc.command("verify").description("Verify local and optionally live deep link configuration").option("-p, --profile <name>","Profile used for build/submit overrides").option("--live","Check hosted files over HTTPS").option("--android-device","Print Android device verification commands").action(async e=>{ge(ce.bgCyan.black(m.cliTag("Deep Link Verify"))),await kl(e)});q.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-STB7QAPB.js");await t(e)});q.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=>{ge(ce.bgCyan.black(m.cliTag("Credentials Setup"))),await mn(e),mc(ce.green("Done!"))});q.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=>{ge(ce.bgCyan.black(m.cliTag("Service Credentials"))),await Po(e),mc(ce.green("Done!"))});var yo=q.command("device").description("Manage registered iOS test devices");yo.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 Ni("register",e)});yo.command("list").description("List all registered devices").option("--team-id <id>","Filter by Apple Developer Team ID").action(async e=>{await Ni("list",e)});yo.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 Ni("remove",e)});q.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=>{ge(ce.bgCyan.black(m.cliTag(e.apk?"APK Audit":"Security Audit"))),await pc(e)});var Qg=new Set(["login","logout","agent"]);q.hook("preAction",(e,t)=>{let n=t.name(),i=t.opts?.()||{};n==="maestro"&&(i.local||i.localRunner)||t.parent?.name()!=="deeplink"&&(Qg.has(n)||Kt())});q.on("command:*",()=>{console.error(`Invalid command: %s
|
|
1683
|
-
See --help for a list of available commands.`,
|
|
1682
|
+
`));for(let a of s)we.error(ye.red(`${ye.bold(a.name)} ${ye.dim(`(${a.arch})`)}`)),we.info(ye.dim(` PT_LOAD alignment: 2**${Math.log2(a.align)} (${a.align} bytes, needs 2**14 = ${uc})`))}return l.length>0&&(console.log(""),we.success(ye.green(`${l.length} librar${l.length===1?"y":"ies"} correctly aligned (2**14 or higher).`))),console.log(""),s.length===0?(we.success(ye.green.bold("ELF Verification Successful. APK is 16KB compatible.")),!0):(we.error(ye.red.bold(`Found ${s.length} unaligned lib${s.length===1?"":"s"} (arm64-v8a/x86_64 libs need to be aligned).`)),console.log(""),we.info(ye.yellow("To fix this:")),we.info(ye.dim(" 1. Rebuild with NDK r28+ which defaults to 16KB page alignment")),we.info(ye.dim(" 2. Or set -DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON in CMake")),we.info(ye.dim(" 3. Update third-party libraries that ship prebuilt .so files")),we.info(ye.dim(" 4. After rebuilding: zipalign -p -f -v 16 input.apk output.apk")),console.log(""),we.info(ye.dim("Reference: https://developer.android.com/guide/practices/page-sizes")),!1)}catch(r){return n.stop("Analysis failed."),we.error(ye.red(`Failed to analyze APK: ${r.message}`)),!1}finally{try{Et.rmSync(i,{recursive:!0,force:!0})}catch{}}}function qg(e){let t=Et.openSync(e,"r");try{let n=Buffer.alloc(64);if(Et.readSync(t,n,0,64,0),!n.subarray(0,4).equals(Yg))return null;let i=n[4]===2,r=n[5]===1,o=(p,f)=>r?p.readUInt16LE(f):p.readUInt16BE(f),s=(p,f)=>r?p.readUInt32LE(f):p.readUInt32BE(f),l=(p,f)=>Number(r?p.readBigUInt64LE(f):p.readBigUInt64BE(f)),a,d,u;i?(a=l(n,32),d=o(n,54),u=o(n,56)):(a=s(n,28),d=o(n,42),u=o(n,44));let c=null;for(let p=0;p<u;p++){let f=Buffer.alloc(d);if(Et.readSync(t,f,0,d,a+p*d),s(f,0)!==Jg)continue;let y;i?y=l(f,48):y=s(f,28),y>0&&(c===null||y<c)&&(c=y)}return c??0}catch{return null}finally{Et.closeSync(t)}}function fc(e){let t=[];if(!Et.existsSync(e))return t;let n=Et.readdirSync(e,{withFileTypes:!0});for(let i of n){let r=pn.join(e,i.name);i.isDirectory()?t.push(...fc(r)):i.name.endsWith(".so")&&t.push(r)}return t}function Xg(e){return e.includes("arm64-v8a")?"arm64-v8a":e.includes("x86_64")?"x86_64":"unknown"}var hc=async e=>{if(ke()||(We.error(rt.red(`You are not logged in. Run \`${m.nameLower} login\` first.`)),process.exit(1)),e.apk){await eh(e);return}let n=process.cwd(),i=Ji.join(n,"package.json");Xn.existsSync(i)||(We.error(rt.red("No package.json found. Run this command from a project root.")),process.exit(1));let r=JSON.parse(Xn.readFileSync(i,"utf-8")),o=!!(r.dependencies?.expo||r.devDependencies?.expo);e.json||(We.info(rt.dim(`Project: ${r.name||"unknown"} v${r.version||"0.0.0"}`)),We.info(rt.dim(`Type: ${o?"Expo":"Bare React Native"}`)),We.info(""));let s={json:e.json,fix:e.fix,category:e.category,severity:e.severity,prebuild:e.prebuild},l=await lc(n,s);e.json?console.log(JSON.stringify(dc(l,r),null,2)):cc(l,e.severity);let a=l.some(u=>u.findings.some(c=>c.severity==="critical")),d=l.some(u=>u.findings.some(c=>c.severity==="high"));(a||d)&&process.exit(1)},mc=["16kb"];async function eh(e){let t=e.category?.toLowerCase();t&&!mc.includes(t)&&(We.error(rt.red(`Unknown APK check category: "${t}"`)),We.info(rt.dim(`Available APK checks: ${mc.join(", ")}`)),process.exit(1));let n=await th(e.apk);n||process.exit(1);let i=!t,r=!1;(i||t==="16kb")&&(await pc(n)||(r=!0)),r&&process.exit(1)}async function th(e){if(e.startsWith("build:")){let n=e.slice(6);return await nh(n)}if(e.startsWith("http://")||e.startsWith("https://"))return await yc(e);let t=Ji.resolve(e);return Xn.existsSync(t)?t:(We.error(rt.red(`APK file not found: ${t}`)),null)}async function nh(e){let t=gc();t.start(`Fetching APK from build ${e}...`);try{let n=await k.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"),We.error(rt.red("This build does not have an APK artifact.")),We.info(rt.dim("Make sure the build produced an APK (not just an AAB).")),null):(t.stop(`Found build: ${i.buildId||e}`),await yc(r.url))}catch(n){return t.stop("Failed to fetch build"),We.error(rt.red(n.message)),null}}async function yc(e){let t=gc();t.start("Downloading APK...");try{let n=Xn.mkdtempSync(Ji.join(Zg.tmpdir(),`${m.nameLower}-audit-`)),i=Ji.join(n,"app.apk"),r=await Qg.get(e,{responseType:"arraybuffer"});Xn.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"),We.error(rt.red(`Failed to download APK: ${n.message}`)),null}}var oh=console.log;console.log=()=>{};rh();console.log=oh;de(se.bgCyan.black(m.cliTag("Production Build Orchestrator")));var ah=sh(import.meta.url),lh=ah("../package.json"),Io=(e,t=[])=>t.concat(e),Y=new ih;Y.name(m.nameLower).description(`${m.name} CLI: Powerful Cloud Infrastructure Tools`).version(lh.version).option("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1);Y.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 Ba(e)});Y.command("host").description("Setup AWS S3 static hosting and CloudFront").action(async()=>{de(se.bgCyan.black(m.cliTag("Hosting"))),await No()});Y.command("sitemap").description("Generate sitemap.xml from Expo Router app structure").option("-o, --output <path>","Output path for sitemap.xml","./public/sitemap.xml").action(async e=>{de(se.bgCyan.black(m.cliTag("Sitemap Generator"))),await Uo(e)});Y.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 Je("--build-id <id>","Internal build ID").hideHelp()).addOption(new Je("--project-id <id>","Internal project ID").hideHelp()).addOption(new Je("--fail-only","Internal: mark an existing build failed").hideHelp()).addOption(new Je("--error <message>","Internal failure message").hideHelp()).option("--local","Run build on local machine").option("--auto-version","Assign the next Android versionCode or iOS buildNumber from Mach").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",Io,[]).option("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1).action(async(e,t)=>{let n=Y.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||de(se.bgCyan.black(m.cliTag("Cloud Build"))),await mi(t)});Y.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",Io,[]).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 Je("--local-runner","Internal: execute a managed Maestro run on this machine").hideHelp()).addOption(new Je("--test-run-id <id>","Internal test run ID").hideHelp()).addOption(new Je("--project-id <id>","Internal project ID").hideHelp()).addOption(new Je("--runner-token <token>","Internal runner token").hideHelp()).action(async e=>{de(se.bgCyan.black(m.cliTag("Maestro Testing"))),await ws(e)});var fn=e=>e.option("--platform <os>","Target platform: ios, android, or all","all").option("--channel <name>","OTA channel (for example: production, staging)").option("--branch <name>","Alias for --channel").option("--runtime-version <version>","Runtime version override").option("--message <text>","Release note/message for this OTA update").option("--framework <name>","Framework override: expo or react-native").option("--engine <name>","OTA engine override: expo-updates or mach-react-native").option("--url <url>","Mach OTA update URL override").option("--install-plugin","Install @radhya/mach locally for the Expo config plugin").option("--skip-install","Do not install local Expo plugin dependency").option("--update-id <id>","OTA update id for rollback/promote").option("--json","Print JSON output"),mn=Y.command("ota").description("Setup, publish, verify, and manage Mach OTA updates");fn(mn.command("setup").description("Configure OTA for this project")).action(async e=>{let t=Y.opts();de(se.bgCyan.black(m.cliTag("OTA Setup"))),await Dt("setup",{...e,yes:e.yes||t.yes})});fn(mn.command("publish").description("Publish an OTA update")).action(async e=>{let t=Y.opts();de(se.bgCyan.black(m.cliTag("OTA Publish"))),await Dt("publish",{...e,yes:e.yes||t.yes})});fn(mn.command("verify").description("Verify OTA configuration")).action(async e=>{let t=Y.opts();de(se.bgCyan.black(m.cliTag("OTA Verify"))),await Dt("verify",{...e,yes:e.yes||t.yes})});fn(mn.command("list").description("List OTA updates for the linked project")).action(async e=>{let t=Y.opts();de(se.bgCyan.black(m.cliTag("OTA Updates"))),await Dt("list",{...e,yes:e.yes||t.yes})});fn(mn.command("rollback").description("Roll back an OTA update")).action(async e=>{let t=Y.opts();de(se.bgCyan.black(m.cliTag("OTA Rollback"))),await Dt("rollback",{...e,yes:e.yes||t.yes})});fn(mn.command("promote").description("Promote an OTA update")).action(async e=>{let t=Y.opts();de(se.bgCyan.black(m.cliTag("OTA Promote"))),await Dt("promote",{...e,yes:e.yes||t.yes})});Y.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 Je("--submit-id <id>","Internal submission ID").hideHelp()).addOption(new Je("--project-id <id>","Internal project ID").hideHelp()).addOption(new Je("--package-name <name>","Internal Android package name").hideHelp()).addOption(new Je("--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=Y.opts();e.quiet=e.quiet||t.quiet,e.yes=e.yes||t.yes,de(se.bgCyan.black(m.cliTag("Store Submission"))),await li(e)});Y.command("login").description(`Login to ${m.name} Dashboard`).action(async()=>{de(se.bgCyan.black(m.cliTag("Login"))),await Va()});Y.command("logout").description(`Logout from ${m.name} on this machine`).action(async()=>{de(se.bgCyan.black(m.cliTag("Logout"))),await Ka()});Y.command("link").description(`Link local directory to a ${m.name} Project`).action(async()=>{de(se.bgCyan.black(m.cliTag("Link Project"))),await Wa()});Y.command("me").description("Display currently logged in user details").action(async()=>{await cl()});Y.command("init").description(`Create a new ${m.name} Project`).action(async()=>{de(se.bgCyan.black(m.cliTag("Init Project"))),await Ja()});Y.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)=>{de(se.bgCyan.black(m.cliTag("Env Manager"))),await qa(e,t,n)});Y.command("start").description("Start the development server (Metro)").option("-p, --build-profile <name>","Build profile (e.g. development, staging)","development").option("--tunnel","Use ngrok tunnel").option("--lan","Use LAN IP").option("--localhost","Use localhost").option("-c, --clear","Clear Metro cache").option("--port <number>","Port to listen on").option("--ios","Start on iOS").option("--android","Start on Android").option("--web","Start on Web").action(async e=>{de(se.bgCyan.black(m.cliTag("Dev Server"))),await ul(e)});Y.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 pl(e)});var bc=Y.command("version").description("Show or seed DB-owned native version counters"),Ac=e=>e.requiredOption("--platform <os>","Target platform: ios or android").option("-p, --profile <name>","Build profile used to resolve package/bundle scope","production").option("--scope <value>","Counter scope override, usually package name or bundle identifier").option("--package <name>","Android package override").option("--bundle-id <id>","iOS bundle identifier override").option("--json","Print JSON output");Ac(bc.command("show").description("Show the current native version counter")).action(async e=>{de(se.bgCyan.black(m.cliTag("Version Counter"))),await So("show",e)});Ac(bc.command("seed").description("Seed the native version counter for an existing app").argument("[value]","Latest already-used value; the next build uses value + 1").option("--value <number>","Latest already-used value; the next build uses value + 1").option("--force","Allow lowering an existing counter")).action(async(e,t)=>{de(se.bgCyan.black(m.cliTag("Version Counter"))),await So("seed",{...t,value:t.value??e})});var Ec=Y.command("deeplink").description("Configure and verify app links, universal links, and URI schemes");Ec.command("setup").description("Generate deep link config, hosted association files, and Expo plugin support").option("--domain <domain>","Associated domain, e.g. app.example.com").option("--base-url <url>","Base URL, e.g. https://app.example.com").option("-p, --profile <name>","Profile used for build/submit overrides").option("--platform <platform>","ios, android, or all").option("--framework <framework>","expo or react-native").option("--scheme <scheme>","URI scheme, e.g. myapp").option("--ios-bundle-id <id>","iOS bundle identifier").option("--android-package <name>","Android package name").option("--apple-team-id <id>","Apple Developer Team ID").option("--app-store-id <id>","App Store app ID for Smart App Banner").option("--android-fingerprint <sha256>","Android SHA256 signing certificate fingerprint; repeatable",Io,[]).option("--output <dir>","Directory for hosted files, e.g. public or deep-links").option("--install-plugin","Install @radhya/mach locally so Expo can use the packaged config plugin").option("--no-install-plugin","Do not install @radhya/mach for Expo projects; use the local plugin fallback if the package is missing").option("-y, --yes","Automatically answer yes to prompts",!1).action(async e=>{let t=Y.opts();e.yes=e.yes||t.yes,de(se.bgCyan.black(m.cliTag("Deep Links"))),await Nl(e)});Ec.command("verify").description("Verify local and optionally live deep link configuration").option("-p, --profile <name>","Profile used for build/submit overrides").option("--live","Check hosted files over HTTPS").option("--android-device","Print Android device verification commands").action(async e=>{de(se.bgCyan.black(m.cliTag("Deep Link Verify"))),await xl(e)});Y.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-STB7QAPB.js");await t(e)});Y.command("credentials:setup").description("Automated credential provisioning (iOS/Android) [Legacy]").requiredOption("--platform <os>","Platform: ios or android").option("--profile <name>","Build profile (production, staging, development)").option("--bundle-id <id>","Bundle ID / Package Name (optional, auto-detected)").option("--team-id <id>","Apple Team ID (iOS only)").option("--key-alias <alias>","Android keystore alias (optional, auto-generated)").option("--aws-profile <name>","AWS Credentials Profile (for S3 storage)").option("--force","Force recreate certificates (nuke existing on Apple Portal)",!1).action(async e=>{de(se.bgCyan.black(m.cliTag("Credentials Setup"))),await hn(e),Sc(se.green("Done!"))});Y.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=>{de(se.bgCyan.black(m.cliTag("Service Credentials"))),await ko(e),Sc(se.green("Done!"))});var wo=Y.command("device").description("Manage registered iOS test devices");wo.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 Ui("register",e)});wo.command("list").description("List all registered devices").option("--team-id <id>","Filter by Apple Developer Team ID").action(async e=>{await Ui("list",e)});wo.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 Ui("remove",e)});Y.command("audit").description("Run automated security audit on the project or APK").option("--apk <path>","Path to APK file (runs APK diagnostics like 16KB alignment)").option("--json","Output results as JSON (for CI/CD)").option("--fix","Auto-apply fixes where possible").option("--category <name>","Run only a specific check category (e.g. 16kb, permissions, secrets)").option("--severity <level>","Minimum severity to display (critical, high, medium, low, info)").option("--prebuild","Run expo prebuild for deeper manifest/plist analysis").action(async e=>{de(se.bgCyan.black(m.cliTag(e.apk?"APK Audit":"Security Audit"))),await hc(e)});var ch=new Set(["login","logout","agent"]);Y.hook("preAction",(e,t)=>{let n=t.name(),i=t.opts?.()||{};n==="maestro"&&(i.local||i.localRunner)||t.parent?.name()!=="deeplink"&&(ch.has(n)||Wt())});Y.on("command:*",()=>{console.error(`Invalid command: %s
|
|
1683
|
+
See --help for a list of available commands.`,Y.args.join(" ")),process.exit(1)});process.argv.slice(2).length||Y.help();Y.parse(process.argv);
|