@radhya/mach 1.8.4 → 1.8.12
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 +109 -55
- package/dist/index.js +214 -101
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as
|
|
3
|
-
`;
|
|
4
|
-
`,
|
|
5
|
-
|
|
6
|
-
CloudFront ID: ${
|
|
7
|
-
CloudFront URL: ${
|
|
8
|
-
${
|
|
9
|
-
`)}`,"Sitemap Summary"),
|
|
2
|
+
import{a as Te,b as Je,c as Mi,d as Hi,e as rt,f as Fi,h as gt}from"./chunk-NIGYNUTS.js";import{a as f,b as Li,c as he,d as Ui,e as xt,f as Ge,g as v}from"./chunk-YBL2LBMW.js";import{Command as Wa,Option as ri}from"commander";import{configDotenv as Ya}from"dotenv";import{intro as pe,outro as Dr}from"@clack/prompts";import de from"chalk";import{text as Bi,confirm as Rr,spinner as vr,isCancel as si,cancel as ht,note as Or,outro as Cr}from"@clack/prompts";import yt from"chalk";async function Gi(){try{let e=await Bi({message:"Enter Bucket Name:",placeholder:"e.g. my-app-dev",validate(r){if(r.length===0)return"Bucket name is required"}});si(e)&&(ht("Operation cancelled."),process.exit(0));let t=await Bi({message:"Enter Region:",initialValue:"ap-south-1"});si(t)&&(ht("Operation cancelled."),process.exit(0));let i=await Rr({message:"Do you want to create a CloudFront Distribution for this bucket?",initialValue:!0});si(i)&&(ht("Operation cancelled."),process.exit(0));let n=vr();n.start("Setting up hosting infrastructure...");try{let r=await v.post("/hosting/setup",{bucketName:e,region:t,createCloudFront:i});if(r.data.status!=="success")throw new Error(r.data.message||"Hosting setup failed");n.stop("Hosting setup complete!");let o=r.data,s=`Bucket Name: ${yt.cyan(o.bucketName)}
|
|
3
|
+
`;s+=`Region: ${yt.cyan(o.region)}
|
|
4
|
+
`,s+=`S3 Website URL: ${yt.blue(o.s3WebsiteUrl)}`,o.cloudFrontId&&(s+=`
|
|
5
|
+
|
|
6
|
+
CloudFront ID: ${yt.cyan(o.cloudFrontId)}`,s+=`
|
|
7
|
+
CloudFront URL: ${yt.blue(o.cloudFrontUrl)}`),Or(s,"Setup Complete!"),Cr("You are all set!")}catch(r){n.stop("Setup failed"),ht(`Error: ${r.response?.data?.message||r.message}`)}}catch(e){ht(`An unexpected error occurred: ${e.message}`)}}import{readdir as Nr,writeFile as Tr,access as kr,mkdir as xr}from"fs/promises";import{join as ji}from"path";import{spinner as Lr,text as Ki,isCancel as Vi,cancel as ai,note as Ur,outro as Mr}from"@clack/prompts";import Hr from"chalk";async function Fr(){let e=["./app","./src/app"];for(let t of e)try{return await kr(t),t}catch{}return null}async function zi(e){try{let i=await Fr()||"./app",n=await Ki({message:"Enter path to your app directory:",placeholder:i,initialValue:i,validate(d){if(d.length===0)return"Path is required"}});Vi(n)&&(ai("Operation cancelled."),process.exit(0));let r=await Ki({message:"Enter your website base URL:",placeholder:"https://example.com",validate(d){if(d.length===0)return"Base URL is required";if(!d.startsWith("http"))return"URL must start with http:// or https://"}});Vi(r)&&(ai("Operation cancelled."),process.exit(0));let o=Lr();o.start("Scanning app directory for routes...");let s=await Wi(n);o.stop(`Found ${s.length} routes`);let l=Br(s,r),a=e.output||"./public/sitemap.xml";o.start(`Writing sitemap to ${a}...`);let c=a.substring(0,a.lastIndexOf("/"));if(c)try{await xr(c,{recursive:!0})}catch{}await Tr(a,l,"utf-8"),o.stop("Sitemap generated successfully!"),Ur(`Routes included:
|
|
8
|
+
${s.map(d=>` \u2022 ${d.path}`).join(`
|
|
9
|
+
`)}`,"Sitemap Summary"),Mr(`Sitemap saved to ${Hr.cyan(a)}`)}catch(t){ai(`An error occurred: ${t.message}`)}}async function Wi(e,t=""){let i=[];try{let n=await Nr(e,{withFileTypes:!0});for(let r of n){let o=ji(e,r.name);if(!(r.name.startsWith("_")||r.name.startsWith("."))){if(r.isDirectory()){let s=await Wi(o,ji(t,r.name));i.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}`;i.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,"/");i.push({path:l,file:o})}}}}}catch(n){throw new Error(`Failed to scan directory ${e}: ${n.message}`)}return i}function Br(e,t){let i=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
|
-
${e.map(
|
|
12
|
-
<loc>${t}${
|
|
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
|
+
<loc>${t}${o}</loc>
|
|
13
13
|
<lastmod>${i}</lastmod>
|
|
14
14
|
<changefreq>weekly</changefreq>
|
|
15
15
|
<priority>0.8</priority>
|
|
16
16
|
</url>`}).join(`
|
|
17
17
|
`)}
|
|
18
|
-
</urlset>`}import{randomUUID as
|
|
18
|
+
</urlset>`}import{randomUUID as Po}from"crypto";import Ee from"path";import Et from"axios";import $o from"os";import{spinner as fi,confirm as yn,isCancel as Sn,log as C}from"@clack/prompts";import T from"chalk";import le from"fs";import{execSync as En}from"child_process";import bn from"adm-zip";import{spinner as Wr,log as Lt}from"@clack/prompts";import Ji from"chalk";import qi from"fs";import Xi from"path";var Yi=`#!/bin/bash
|
|
19
19
|
# --- Mach Cloud Build Script (Android) ---
|
|
20
20
|
# All S3 operations use presigned URLs via curl \u2014 zero AWS credentials on instance.
|
|
21
21
|
BUILD_ID="{{BUILD_ID}}"
|
|
@@ -28,6 +28,8 @@ echo "Starting build setup..."
|
|
|
28
28
|
|
|
29
29
|
# Forward environment variables (includes PRESIGNED_* URLs + project secrets)
|
|
30
30
|
{{ENV_VARS}}
|
|
31
|
+
export EXPO_NO_DOTENV=1
|
|
32
|
+
echo "[ENV] EXPO_NO_DOTENV=$EXPO_NO_DOTENV"
|
|
31
33
|
export HUSKY=0
|
|
32
34
|
export CI=true
|
|
33
35
|
export npm_config_engine_strict=false
|
|
@@ -196,6 +198,21 @@ if [ -f /tmp/android-cache.tar.gz ]; then
|
|
|
196
198
|
tar $TAR_COMPRESS -xf /tmp/android-cache.tar.gz -C /home/ubuntu/build && rm -f /tmp/android-cache.tar.gz && echo "android/ cache restored."
|
|
197
199
|
fi
|
|
198
200
|
|
|
201
|
+
# Older android/ caches may include Gradle outputs and pre-bundled JS from a
|
|
202
|
+
# different build profile. Keep the native project, but force fresh outputs.
|
|
203
|
+
if [ -d "/home/ubuntu/build/android" ]; then
|
|
204
|
+
echo "[CACHE] Pruning restored android build outputs..."
|
|
205
|
+
find /home/ubuntu/build/android -type d \\( -name build -o -name .cxx \\) -prune -exec rm -rf {} + 2>/dev/null || true
|
|
206
|
+
fi
|
|
207
|
+
|
|
208
|
+
clear_js_transform_caches() {
|
|
209
|
+
# Metro/Hermes can cache transformed modules with inlined EXPO_PUBLIC_* values.
|
|
210
|
+
# Clear after dependency restore/install so restored node_modules cannot reintroduce stale transforms.
|
|
211
|
+
echo "[CACHE] Clearing Metro/Hermes JS transform caches..."
|
|
212
|
+
rm -rf /tmp/metro-* /tmp/haste-map-* /tmp/react-native-packager-cache-* 2>/dev/null || true
|
|
213
|
+
rm -rf /root/.cache/metro /root/.cache/react-native-packager /home/ubuntu/.cache/metro .expo node_modules/.cache/metro 2>/dev/null || true
|
|
214
|
+
}
|
|
215
|
+
|
|
199
216
|
echo "Cache restore complete."
|
|
200
217
|
|
|
201
218
|
# CodeArtifact Logic \u2014 use env var if already set (pass as project secret)
|
|
@@ -237,6 +254,7 @@ if [ -f "yarn.lock" ]; then
|
|
|
237
254
|
else
|
|
238
255
|
npm install --no-audit --no-fund --prefer-offline
|
|
239
256
|
fi
|
|
257
|
+
clear_js_transform_caches
|
|
240
258
|
|
|
241
259
|
# --- Injected Version Code (Auto-versioning) ---
|
|
242
260
|
# Apply before Expo prebuild so generated Gradle files receive the new versionCode.
|
|
@@ -246,12 +264,20 @@ if [ ! -z "$ANDROID_VERSION_CODE" ]; then
|
|
|
246
264
|
fi
|
|
247
265
|
|
|
248
266
|
# --- Prebuild (expo only) ---
|
|
249
|
-
# Compute a hash of native-affecting files
|
|
250
|
-
#
|
|
267
|
+
# Compute a hash of native-affecting files and the Mach-injected app env to
|
|
268
|
+
# decide if android/ cache is still valid. Env names are project-defined, so the
|
|
269
|
+
# CLI precomputes MACH_ENV_FINGERPRINT from all relevant managed values.
|
|
251
270
|
if grep -q '"expo"' package.json 2>/dev/null; then
|
|
252
271
|
if [ -f "app.json" ] || [ -f "app.config.ts" ] || [ -f "app.config.js" ]; then
|
|
253
272
|
PREBUILD_HASH_FILE="/home/ubuntu/build/.mach-prebuild-hash"
|
|
254
|
-
|
|
273
|
+
PREBUILD_ENV_HASH="\${MACH_ENV_FINGERPRINT:-missing-env-fingerprint}"
|
|
274
|
+
PREBUILD_CURRENT_HASH=$(
|
|
275
|
+
{
|
|
276
|
+
cat app.json app.config.ts app.config.js 2>/dev/null
|
|
277
|
+
node -e "try{const p=require('./package.json');const keys=Object.keys({...p.dependencies,...p.devDependencies}).filter(k=>k.startsWith('expo-')||k.startsWith('@expo/')||k.startsWith('@react-native'));console.log(keys.join(','))}catch(e){}" 2>/dev/null
|
|
278
|
+
printf '%s\\n' "$PREBUILD_ENV_HASH"
|
|
279
|
+
} | md5sum | cut -d' ' -f1
|
|
280
|
+
)
|
|
255
281
|
|
|
256
282
|
ANDROID_CACHE_VALID=false
|
|
257
283
|
if [ -f "$PREBUILD_HASH_FILE" ] && [ -d "android" ] && [ -f "android/gradlew" ]; then
|
|
@@ -276,6 +302,7 @@ fi
|
|
|
276
302
|
|
|
277
303
|
# Build
|
|
278
304
|
step_marker build
|
|
305
|
+
clear_js_transform_caches
|
|
279
306
|
if [ -f "android/gradlew" ]; then
|
|
280
307
|
cd android
|
|
281
308
|
GRADLEW="./gradlew"
|
|
@@ -468,7 +495,7 @@ if [ -d "/home/ubuntu/build/node_modules" ] && [ ! -z "$PRESIGNED_CACHE_NODE_MOD
|
|
|
468
495
|
fi
|
|
469
496
|
|
|
470
497
|
if [ -d "/home/ubuntu/build/android" ] && [ ! -z "$PRESIGNED_CACHE_ANDROID_UPLOAD" ]; then
|
|
471
|
-
(tar $TAR_COMPRESS -cf /tmp/android-cache.tar.gz -C /home/ubuntu/build
|
|
498
|
+
(find /home/ubuntu/build/android -type d \\( -name build -o -name .cxx \\) -prune -exec rm -rf {} + 2>/dev/null || true; tar $TAR_COMPRESS -cf /tmp/android-cache.tar.gz -C /home/ubuntu/build --exclude='android/.gradle' --exclude='android/**/build' --exclude='android/**/.cxx' android && curl -X PUT -T /tmp/android-cache.tar.gz "$PRESIGNED_CACHE_ANDROID_UPLOAD" --silent && rm -f /tmp/android-cache.tar.gz && echo "android/ cache saved.") &
|
|
472
499
|
cache_pids+=($!)
|
|
473
500
|
fi
|
|
474
501
|
|
|
@@ -487,12 +514,14 @@ for pid in "\${cache_pids[@]}"; do wait "$pid" || true; done
|
|
|
487
514
|
echo "Build orchestrator finished. Auto-terminating instance in 5 seconds..."
|
|
488
515
|
sleep 5
|
|
489
516
|
sudo shutdown -h now
|
|
490
|
-
`;var
|
|
491
|
-
`):"",p;if(
|
|
492
|
-
export MACH_APP_NAME="${
|
|
493
|
-
export MACH_BUILD_PROFILE="${
|
|
517
|
+
`;import Gr from"crypto";var jr="mach-env-v2-js-bundle-cache",Kr=new Set(["BUILD_ID","BUILD_NUMBER","ANDROID_VERSION_CODE","MACH_TOKEN","MACH_DEBUG","MACH_ENV_FINGERPRINT","CODEARTIFACT_AUTH_TOKEN","EXPO_ZQRN_BB_REPO_TOKEN","SENTRY_AUTH_TOKEN","IOS_DIST_P12","IOS_PROVISIONING_PROFILE","IOS_P12_PASSWORD","MATCH_ENCRYPTION_PASSPHRASE","MATCH_PASSWORD","MATCH_KEYCHAIN_NAME","MATCH_KEYCHAIN_PASSWORD","APPLE_TEAM_ID","FASTLANE_TEAM_ID","ANDROID_KEYSTORE","ANDROID_KEYSTORE_BASE64","ANDROID_STORE_PASSWORD","ANDROID_KEY_PASSWORD","ANDROID_KEY_ALIAS","KEYSTORE_PASSWORD","KEYSTORE_ALIAS","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","AWS_SECURITY_TOKEN","GITHUB_TOKEN","NPM_TOKEN"]),Vr=["PRESIGNED_","KEYSTORE_PASSWORD_"],zr=e=>!e||Kr.has(e)?!1:!Vr.some(t=>e.startsWith(t)),qe=(e,t,i)=>({...e,EXPO_NO_DOTENV:"1",MACH_BUILD_PROFILE:t,MACH_APP_NAME:i.appName||i.name||"App"}),ot=e=>{let t=Object.entries(e).filter(([i])=>zr(i)).sort(([i],[n])=>i.localeCompare(n));return Gr.createHash("sha256").update(JSON.stringify({version:jr,entries:t})).digest("hex")};var Zi=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`"),Qi=async(e,t,i={},n,r)=>{let o=Wr(),s=e.buildProfile||"production",l=s==="production",a=e.apk===!0,c=e.developmentClient?"assembleDebug":l?"bundleRelease":"assembleRelease",d=e.buildCommand||(a?"assembleRelease":c),u=e.nodeVersion?[`echo "[NODE] Switching to Node ${e.nodeVersion}..."`,`CURRENT_MAJOR=$(node -e "process.stdout.write(process.version.split('.')[0].replace('v',''))" 2>/dev/null || echo "0")`,`if [ "$CURRENT_MAJOR" != "${e.nodeVersion}" ]; then`,` curl -fsSL https://deb.nodesource.com/setup_${e.nodeVersion}.x | bash - 2>&1`," apt-get install -y nodejs 2>&1",' echo "[NODE] Installed Node $(node -v)"',"else",' echo "[NODE] Already on Node $(node -v) \u2014 no switch needed"',"fi"].join(`
|
|
518
|
+
`):"",p;if(r){let A=Xi.isAbsolute(r)?r:Xi.resolve(process.cwd(),r);qi.existsSync(A)?(p=qi.readFileSync(A,"utf-8"),Lt.info(Ji.magenta(`\u2713 Loaded preBuild hook: ${r}`))):Lt.warn(`preBuild script not found at ${A} \u2014 skipping`)}let m=qe(i,s,e),S=ot(m),D=Yi.replace(/\{\{BUILD_ID\}\}/g,t).replace(/\{\{BUILD_COMMAND\}\}/g,d).replace("{{NODE_VERSION_SETUP}}",u).replace("{{ENV_VARS}}",`
|
|
519
|
+
export MACH_APP_NAME="${Zi(m.MACH_APP_NAME)}"
|
|
520
|
+
export MACH_BUILD_PROFILE="${Zi(s)}"
|
|
521
|
+
export MACH_ENV_FINGERPRINT="${S}"
|
|
522
|
+
export EXPO_NO_DOTENV=1
|
|
494
523
|
{{ENV_VARS}}
|
|
495
|
-
`);if(e.dryRun){
|
|
524
|
+
`);if(e.dryRun){Lt.info("User Data Script (dry run):"),console.log(D);return}o.start("Requesting cloud build instance...");try{let A=await v.post("/builds/launch-android",{projectId:n,buildId:t,platform:e.platform,buildProfile:e.buildProfile,buildCommand:d,instanceType:e.instanceType,ami:e.ami,keepInstance:e.keepInstance,region:e.region,subnet:e.subnet,securityGroup:e.securityGroup,projectSecrets:i,dryRun:e.dryRun,userDataScript:D,preBuildScriptContent:p});if(A.data.status!=="success")throw new Error(A.data.message||"Failed to launch build instance");let H=A.data.instanceId;return o.stop("Build Started"),Lt.success(Ji.green(`Build initiated on cloud instance (${H}).`)),{instanceId:H}}catch(A){o.stop("Android Build Failed");let H=A.response?.data?.message||A.message;throw new Error(`Failed to launch Android build: ${H}`)}};import{spinner as Yr,log as st}from"@clack/prompts";import je from"chalk";import Jr from"fs";import{execSync as St}from"child_process";var en=`#!/bin/bash
|
|
496
525
|
# --- Mach Cloud Build Script (iOS) ---
|
|
497
526
|
# All S3 operations use presigned URLs via curl \u2014 zero AWS credentials on Mac.
|
|
498
527
|
|
|
@@ -519,8 +548,12 @@ set -e
|
|
|
519
548
|
|
|
520
549
|
# 4. Forward environment variables (includes PRESIGNED_* URLs + project secrets)
|
|
521
550
|
{{ENV_VARS}}
|
|
551
|
+
export EXPO_NO_DOTENV=1
|
|
552
|
+
echo "[ENV] EXPO_NO_DOTENV=$EXPO_NO_DOTENV"
|
|
522
553
|
|
|
523
554
|
BUILD_ID="{{BUILD_ID}}"
|
|
555
|
+
BUILD_ENV_HASH="\${MACH_ENV_FINGERPRINT:-missing-env-fingerprint}"
|
|
556
|
+
echo "[CACHE] Build environment hash: \${BUILD_ENV_HASH:0:12}"
|
|
524
557
|
|
|
525
558
|
# Start log uploader (every 15s via presigned URL, only if changed)
|
|
526
559
|
(
|
|
@@ -576,6 +609,34 @@ else
|
|
|
576
609
|
echo "DerivedData found locally. Skipping download (Persistent Worker Optimization)."
|
|
577
610
|
fi
|
|
578
611
|
|
|
612
|
+
# DerivedData can contain the app bundle and React Native JS generated by a
|
|
613
|
+
# previous profile. Keep compiler/module caches for speed, but drop build
|
|
614
|
+
# products whenever the env fingerprint changes (or old caches have no stamp).
|
|
615
|
+
DD_ENV_HASH_FILE="$DERIVED_DATA_PATH/.mach-env-hash"
|
|
616
|
+
DD_PREVIOUS_ENV_HASH=""
|
|
617
|
+
if [ -f "$DD_ENV_HASH_FILE" ]; then
|
|
618
|
+
DD_PREVIOUS_ENV_HASH=$(cat "$DD_ENV_HASH_FILE" 2>/dev/null || true)
|
|
619
|
+
fi
|
|
620
|
+
if [ -d "$DERIVED_DATA_PATH/Build" ]; then
|
|
621
|
+
if [ -z "$DD_PREVIOUS_ENV_HASH" ]; then
|
|
622
|
+
echo "[CACHE] DerivedData has no env stamp. Pruning iOS build products..."
|
|
623
|
+
elif [ "$DD_PREVIOUS_ENV_HASH" != "$BUILD_ENV_HASH" ]; then
|
|
624
|
+
echo "[CACHE] Build env changed. Pruning iOS build products..."
|
|
625
|
+
else
|
|
626
|
+
echo "[CACHE] Pruning iOS build products to force a fresh JS bundle."
|
|
627
|
+
fi
|
|
628
|
+
rm -rf "$DERIVED_DATA_PATH/Build"
|
|
629
|
+
fi
|
|
630
|
+
echo "$BUILD_ENV_HASH" > "$DD_ENV_HASH_FILE"
|
|
631
|
+
|
|
632
|
+
clear_js_transform_caches() {
|
|
633
|
+
# Metro/Hermes can cache transformed modules with inlined EXPO_PUBLIC_* values.
|
|
634
|
+
# Clear after dependency restore/install so restored node_modules cannot reintroduce stale transforms.
|
|
635
|
+
echo "[CACHE] Clearing Metro/Hermes JS transform caches..."
|
|
636
|
+
rm -rf "\${TMPDIR:-/tmp}"/metro-* "\${TMPDIR:-/tmp}"/haste-map-* "\${TMPDIR:-/tmp}"/react-native-packager-cache-* 2>/dev/null || true
|
|
637
|
+
rm -rf "$HOME/Library/Caches/metro" "$HOME/Library/Caches/react-native-packager" "$HOME/.cache/metro" .expo node_modules/.cache/metro 2>/dev/null || true
|
|
638
|
+
}
|
|
639
|
+
|
|
579
640
|
# 1. Node Modules Cache \u2014 download via presigned URL
|
|
580
641
|
if [ ! -d "node_modules" ] || [ -z "$(ls -A node_modules 2>/dev/null)" ]; then
|
|
581
642
|
echo "Checking node_modules cache..."
|
|
@@ -603,6 +664,8 @@ else
|
|
|
603
664
|
yarn install || npm install || exit 1
|
|
604
665
|
fi
|
|
605
666
|
|
|
667
|
+
clear_js_transform_caches
|
|
668
|
+
|
|
606
669
|
# Save node_modules cache via presigned URL
|
|
607
670
|
if [ ! -z "$PRESIGNED_CACHE_NODE_UPLOAD" ]; then
|
|
608
671
|
echo "Uploading node_modules cache..."
|
|
@@ -686,6 +749,10 @@ if [ -f "ios/Podfile" ]; then
|
|
|
686
749
|
cd ..
|
|
687
750
|
fi
|
|
688
751
|
|
|
752
|
+
# Remove stale artifacts from persistent workspaces before archiving.
|
|
753
|
+
# Keep ios/build because React Native Codegen writes generated podspecs there.
|
|
754
|
+
rm -rf build.xcarchive build.ipa build.app.zip export
|
|
755
|
+
|
|
689
756
|
# 6. EAS-Style Automatic Signing (Temporary Keychain)
|
|
690
757
|
echo "[STEP_START:signing] $(date +%s)"
|
|
691
758
|
|
|
@@ -762,6 +829,7 @@ security unlock-keychain -p "\${TEMP_KEYCHAIN_PASSWORD}" "\${TEMP_KEYCHAIN_PATH}
|
|
|
762
829
|
|
|
763
830
|
# Build IPA
|
|
764
831
|
echo "[STEP_START:build] $(date +%s)"
|
|
832
|
+
clear_js_transform_caches
|
|
765
833
|
if [ -f "Fastfile" ] || [ -d "fastlane" ]; then
|
|
766
834
|
bundle exec fastlane ios build
|
|
767
835
|
elif [ -d "ios" ]; then
|
|
@@ -803,8 +871,11 @@ elif [ -d "ios" ]; then
|
|
|
803
871
|
if [ "$IS_SIMULATOR" == "true" ]; then
|
|
804
872
|
xcodebuild build -workspace "$WORKSPACE" -scheme "$SCHEME" -configuration "$USER_CONFIG" -sdk "$SDK" -derivedDataPath "$DERIVED_DATA_PATH" $EXTRA_ARGS -parallelizeTargets || exit 1
|
|
805
873
|
else
|
|
806
|
-
ARCHIVE_SIGN_ARGS="CODE_SIGN_STYLE=Manual
|
|
807
|
-
|
|
874
|
+
ARCHIVE_SIGN_ARGS=("CODE_SIGN_STYLE=Manual")
|
|
875
|
+
[ -n "$TEAM_ID" ] && ARCHIVE_SIGN_ARGS+=("DEVELOPMENT_TEAM=$TEAM_ID")
|
|
876
|
+
[ -n "$PROFILE_UUID" ] && ARCHIVE_SIGN_ARGS+=("PROVISIONING_PROFILE=$PROFILE_UUID")
|
|
877
|
+
[ -n "$PROFILE_NAME" ] && ARCHIVE_SIGN_ARGS+=("PROVISIONING_PROFILE_SPECIFIER=$PROFILE_NAME")
|
|
878
|
+
xcodebuild archive -workspace "$WORKSPACE" -scheme "$SCHEME" -archivePath "../build.xcarchive" -configuration "$USER_CONFIG" -sdk "$SDK" -derivedDataPath "$DERIVED_DATA_PATH" \${AUTH_PARAMS:+-allowProvisioningUpdates $AUTH_PARAMS} "\${ARCHIVE_SIGN_ARGS[@]}" -parallelizeTargets -allowConcurrentBuilds || exit 1
|
|
808
879
|
fi
|
|
809
880
|
elif [ ! -z "$PROJECT" ]; then
|
|
810
881
|
if [ -z "$USER_SCHEME" ]; then
|
|
@@ -822,8 +893,11 @@ elif [ -d "ios" ]; then
|
|
|
822
893
|
if [ "$IS_SIMULATOR" == "true" ]; then
|
|
823
894
|
xcodebuild build -project "$PROJECT" -scheme "$SCHEME" -configuration "$USER_CONFIG" -sdk "$SDK" -derivedDataPath "$DERIVED_DATA_PATH" $EXTRA_ARGS -parallelizeTargets || exit 1
|
|
824
895
|
else
|
|
825
|
-
ARCHIVE_SIGN_ARGS="CODE_SIGN_STYLE=Manual
|
|
826
|
-
|
|
896
|
+
ARCHIVE_SIGN_ARGS=("CODE_SIGN_STYLE=Manual")
|
|
897
|
+
[ -n "$TEAM_ID" ] && ARCHIVE_SIGN_ARGS+=("DEVELOPMENT_TEAM=$TEAM_ID")
|
|
898
|
+
[ -n "$PROFILE_UUID" ] && ARCHIVE_SIGN_ARGS+=("PROVISIONING_PROFILE=$PROFILE_UUID")
|
|
899
|
+
[ -n "$PROFILE_NAME" ] && ARCHIVE_SIGN_ARGS+=("PROVISIONING_PROFILE_SPECIFIER=$PROFILE_NAME")
|
|
900
|
+
xcodebuild archive -project "$PROJECT" -scheme "$SCHEME" -archivePath "../build.xcarchive" -configuration "$USER_CONFIG" -sdk "$SDK" -derivedDataPath "$DERIVED_DATA_PATH" \${AUTH_PARAMS:+-allowProvisioningUpdates $AUTH_PARAMS} "\${ARCHIVE_SIGN_ARGS[@]}" -parallelizeTargets -allowConcurrentBuilds || exit 1
|
|
827
901
|
fi
|
|
828
902
|
else
|
|
829
903
|
echo "Error: Neither workspace nor project found for building."
|
|
@@ -905,6 +979,7 @@ echo "[STEP_START:upload] $(date +%s)"
|
|
|
905
979
|
|
|
906
980
|
# Upload DerivedData Cache via presigned URL
|
|
907
981
|
echo "Uploading DerivedData cache..."
|
|
982
|
+
echo "$BUILD_ENV_HASH" > "$DD_ENV_HASH_FILE"
|
|
908
983
|
tar -czf derived_data.tar.gz -C "$DERIVED_DATA_PATH" .
|
|
909
984
|
if [ ! -z "$PRESIGNED_CACHE_DD_UPLOAD" ]; then
|
|
910
985
|
curl -X PUT -T derived_data.tar.gz "$PRESIGNED_CACHE_DD_UPLOAD" --silent || true
|
|
@@ -930,52 +1005,57 @@ touch done
|
|
|
930
1005
|
if [ ! -z "$PRESIGNED_DONE_MARKER" ]; then
|
|
931
1006
|
curl -X PUT -T done "$PRESIGNED_DONE_MARKER" --silent
|
|
932
1007
|
fi
|
|
933
|
-
`;var
|
|
934
|
-
`:
|
|
935
|
-
`);
|
|
936
|
-
`:"";if(i)for(let[
|
|
937
|
-
`}let
|
|
938
|
-
`),
|
|
939
|
-
`):"",
|
|
940
|
-
${
|
|
941
|
-
${
|
|
942
|
-
${
|
|
943
|
-
`)
|
|
944
|
-
`)),o(
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
`)
|
|
949
|
-
`))
|
|
950
|
-
`)
|
|
951
|
-
`),
|
|
952
|
-
|
|
953
|
-
`),
|
|
1008
|
+
`;var tn=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`"),nn=async(e,t,i={},n)=>{let r=Yr();e.sshHost||(e.sshHost="localhost",st.message(je.yellow("No SSH host provided, defaulting to localhost."))),r.start(`Connecting to remote Mac at ${je.cyan(e.sshHost)}...`);let o=e.sshUser||process.env.USER||"ubuntu",s=e.sshKey,l=`${o}@${e.sshHost}`,a=`ssh ${s?`-i ${s}`:""} -o StrictHostKeyChecking=no ${l}`,c=`scp ${s?`-i ${s}`:""} -o StrictHostKeyChecking=no`;try{let d=o==="ubuntu"?"/home/ubuntu":`/Users/${o}`,u=(i.PROJECT_ID||"default_project").replace(/[^a-zA-Z0-9-_]/g,"_"),p=`${d}/${f.remoteWorkspacesDir}/${u}`;r.message(`Preparing stable workspace: ${p}...`),St(`${a} "mkdir -p ${p}"`,{stdio:"inherit"}),r.message("Transferring source code...");let m=`/tmp/${f.nameLower}-source-${t}.zip`;St(`${c} ${m} ${l}:${p}/source.zip`,{stdio:"inherit"});let S=e.iosApiKeyPath?`${p}/api_key.p8`:"",D="";e.iosApiKeyPath&&(r.message("Uploading App Store Connect API key..."),St(`${c} ${e.iosApiKeyPath} ${l}:${S}`),e.iosApiKeyId&&e.iosApiKeyIssuer&&(D=`-authenticationKeyID ${e.iosApiKeyId} -authenticationKeyIssuerID ${e.iosApiKeyIssuer} -authenticationKeyPath ${S}`));let A={};if(n)try{let U=await v.post(`/builds/${n}/${t}/build-urls`,{platform:"ios"});U.data.status==="success"&&(A=U.data.urls)}catch(U){st.warn(je.yellow(`Could not fetch build URLs: ${U.message}`))}let H="";if(A.credentials&&A.credentials.length>0)for(let U of A.credentials)U.type==="p12"?H+=`curl -sf -o "$CERT_DIR/${U.name}" "${U.downloadUrl}" || true
|
|
1009
|
+
`:U.type==="mobileprovision"&&(H+=`curl -sf -o "$PROV_TEMP/${U.name}" "${U.downloadUrl}" || true
|
|
1010
|
+
`);r.message("Generating macOS build script...");let F=process.env.CODEARTIFACT_AUTH_TOKEN?`export CODEARTIFACT_AUTH_TOKEN="${process.env.CODEARTIFACT_AUTH_TOKEN}"
|
|
1011
|
+
`:"";if(i)for(let[U,P]of Object.entries(i)){let k=P.replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");F+=`export ${U}="${k}"
|
|
1012
|
+
`}let z=e.buildProfile||"production",b=qe(i,z,e),G=ot(b),_=[F,A.logUpload?`export PRESIGNED_LOG_UPLOAD="${A.logUpload}"`:"",A.doneMarker?`export PRESIGNED_DONE_MARKER="${A.doneMarker}"`:"",A.cacheDerivedDataDownload?`export PRESIGNED_CACHE_DD_DOWNLOAD="${A.cacheDerivedDataDownload}"`:"",A.cacheDerivedDataUpload?`export PRESIGNED_CACHE_DD_UPLOAD="${A.cacheDerivedDataUpload}"`:"",A.cacheNodeModulesDownload?`export PRESIGNED_CACHE_NODE_DOWNLOAD="${A.cacheNodeModulesDownload}"`:"",A.cacheNodeModulesUpload?`export PRESIGNED_CACHE_NODE_UPLOAD="${A.cacheNodeModulesUpload}"`:"",A.cachePodsDownload?`export PRESIGNED_CACHE_PODS_DOWNLOAD="${A.cachePodsDownload}"`:"",A.cachePodsUpload?`export PRESIGNED_CACHE_PODS_UPLOAD="${A.cachePodsUpload}"`:"",A.artifactIpaUpload?`export PRESIGNED_ARTIFACT_IPA_UPLOAD="${A.artifactIpaUpload}"`:"",A.artifactAppZipUpload?`export PRESIGNED_ARTIFACT_APP_ZIP_UPLOAD="${A.artifactAppZipUpload}"`:"",`export BUILD_ID="${t}"`,`export MACH_BUILD_PROFILE="${tn(z)}"`,`export MACH_APP_NAME="${tn(b.MACH_APP_NAME)}"`,`export MACH_ENV_FINGERPRINT="${G}"`,"export EXPO_NO_DOTENV=1",`export ${f.envPrefix}PROJECT_ID="${u}"`,i.MATCH_ENCRYPTION_PASSPHRASE?`export MATCH_PASSWORD="${i.MATCH_ENCRYPTION_PASSPHRASE}"`:"",i.APPLE_TEAM_ID?`export FASTLANE_TEAM_ID="${i.APPLE_TEAM_ID}"`:"",`export MATCH_KEYCHAIN_NAME="${f.credentialsKeychain}"`,`export MATCH_KEYCHAIN_PASSWORD="${f.keychainPassword}"`].filter(Boolean).join(`
|
|
1013
|
+
`),h=e.nodeVersion?[`echo "[NODE] Switching to Node ${e.nodeVersion}..."`,'export NVM_DIR="$HOME/.nvm"','[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" --no-use',`nvm install ${e.nodeVersion} 2>/dev/null || true`,`nvm use ${e.nodeVersion} --silent`,`export PATH="$NVM_DIR/versions/node/$(nvm version ${e.nodeVersion})/bin:$PATH"`,'echo "[NODE] Now using: $(node -v) at $(which node)"'].join(`
|
|
1014
|
+
`):"",w=en,R={"{{REMOTE_DIR}}":p,"{{ENV_VARS}}":_,"{{CREDENTIAL_DOWNLOADS}}":H,"{{IOS_SCHEME}}":e.iosScheme||"","{{IOS_CONFIG}}":e.iosConfiguration||"Release","{{TEAM_ID}}":e.iosTeamId||"","{{AUTH_PARAMS}}":D,"{{IS_SIMULATOR}}":e.simulator?"true":"false","{{BUILD_ID}}":t,"{{EXPORT_METHOD}}":e.iosExportMethod||"ad-hoc","{{NODE_VERSION_SETUP}}":h};Object.entries(R).forEach(([U,P])=>{w=w.split(U).join(P)});let L=`/tmp/${f.nameLower}-mac-build-${t}.sh`;if(Jr.writeFileSync(L,w),St(`${c} ${L} ${l}:${p}/build.sh`),r.stop("Remote script uploaded."),st.info(je.cyan("Executing remote build. This might take a while...")),St(`${a} "bash ${p}/build.sh"`,{stdio:"inherit"}),r.stop("Remote build finished!"),n){r.start("Fetching artifact links...");try{let P=(await v.get(`/builds/${n}/${t}/artifacts`)).data.artifacts||[],k=e.simulator===!0;if(P.length===0&&!k)throw r.stop("Build Failed!"),new Error("Build completed but no artifacts were generated. Check build logs for errors.");if(r.stop("Build Successful!"),P.length>0){st.success("Build Artifacts Ready:");for(let I of P)console.log(`
|
|
1015
|
+
${je.yellow(I.name)}:
|
|
1016
|
+
${je.cyan(I.downloadUrl)}`);console.log(`
|
|
1017
|
+
${je.dim("Note: Links are valid for 7 days.")}`)}else k&&st.warn("Simulator build completed. No artifacts uploaded.")}catch(U){r.stop("Could not fetch artifacts"),st.warn(je.yellow(`Artifact listing failed: ${U.message}`))}}}catch(d){throw r.stop("iOS Build Failed"),d}};import qr from"crypto";import $e from"axios";import rn from"fs";var ke=6e4,Xr=12e4,li=4,Me=e=>encodeURIComponent(e),Zr=e=>new Promise(t=>setTimeout(t,e));async function we(e,t){let i;for(let n=1;n<=li;n++)try{return await t()}catch(r){if(i=r,n>=li||!Qr(r))throw r;let o=Number(r.response?.headers?.["retry-after"]),s=Number.isFinite(o)&&o>0?o*1e3:Math.min(2e3*n*n,15e3);console.log(`[Google Play] ${e} failed (attempt ${n}/${li}); retrying in ${Math.round(s/1e3)}s...`),await Zr(s)}throw i}function Qr(e){let t=e.response?.status;return t?t===408||t===409||t===425||t===429||t>=500:!0}async function on(e,t){let i;try{let n=await Ut(t),r=Me(e);if(i=(await we("create edit",()=>$e.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits`,{},{headers:{Authorization:`Bearer ${n}`,Connection:"close"},timeout:ke}))).data.id,!i)throw new Error("Google Play edit insert succeeded but did not return an edit id.");let s=Me(i),l=0,c=(await we("list tracks",()=>$e.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits/${s}/tracks`,{headers:{Authorization:`Bearer ${n}`,Connection:"close"},timeout:ke}))).data.tracks||[];for(let d of c)if(d.releases){for(let u of d.releases)if(u.versionCodes)for(let p of u.versionCodes){let m=parseInt(p,10);m>l&&(l=m)}}try{let u=(await we("list bundles",()=>$e.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits/${s}/bundles`,{headers:{Authorization:`Bearer ${n}`,Connection:"close"},timeout:ke}))).data.bundles||[];for(let p of u)p.versionCode&&p.versionCode>l&&(l=p.versionCode)}catch{}try{let u=(await we("list APKs",()=>$e.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits/${s}/apks`,{headers:{Authorization:`Bearer ${n}`,Connection:"close"},timeout:ke}))).data.apks||[];for(let p of u)p.versionCode&&p.versionCode>l&&(l=p.versionCode)}catch{}return l}catch(n){let r=n.response?.data?.error?.message||n.message;throw new Error(`Google Play API Error: ${r}`)}finally{if(i)try{let n=await Ut(t);await we("delete edit",()=>$e.delete(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${Me(e)}/edits/${Me(i)}`,{headers:{Authorization:`Bearer ${n}`,Connection:"close"},timeout:ke}))}catch{}}}async function sn(e){let{packageName:t,serviceAccount:i,aabPath:n,track:r,releaseStatus:o,userFraction:s,changesNotSentForReview:l}=e,a;try{let d={Authorization:`Bearer ${await Ut(i)}`,Connection:"close"},u=Me(t);if(a=(await we("create edit",()=>$e.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${u}/edits`,{},{headers:d,timeout:ke}))).data.id,!a)throw new Error("Google Play edit insert succeeded but did not return an edit id.");let m=Me(a),S=rn.statSync(n),D=await we("upload AAB",()=>$e.post(`https://androidpublisher.googleapis.com/upload/androidpublisher/v3/applications/${u}/edits/${m}/bundles`,rn.createReadStream(n),{headers:{...d,"Content-Type":"application/octet-stream","Content-Length":S.size},maxBodyLength:1/0,maxContentLength:1/0,params:{uploadType:"media"},timeout:Xr})),A=Number(D.data.versionCode);if(!A)throw new Error("Google Play upload succeeded but did not return a versionCode.");let H={versionCodes:[String(A)],status:o};return(o==="inProgress"||o==="halted")&&typeof s=="number"&&(H.userFraction=s),await we("update track",()=>$e.put(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${u}/edits/${m}/tracks/${Me(r)}`,{releases:[H]},{headers:d,timeout:ke})),await we("commit edit",()=>$e.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${u}/edits/${m}:commit`,{},{headers:d,params:l?{changesNotSentForReview:!0}:void 0,timeout:ke})),{editId:a,versionCode:A,track:r,releaseStatus:o,userFraction:s}}catch(c){if(a)try{let u=await Ut(i);await we("delete edit",()=>$e.delete(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${Me(t)}/edits/${Me(a)}`,{headers:{Authorization:`Bearer ${u}`,Connection:"close"},timeout:ke}))}catch{}let d=c.response?.data?.error?.message||c.message;throw new Error(`Google Play API Error: ${d}`)}}async function Ut(e){let t=Math.floor(Date.now()/1e3),i=t+3600,n={alg:"RS256",typ:"JWT"},r={iss:e.client_email,sub:e.client_email,aud:"https://oauth2.googleapis.com/token",iat:t,exp:i,scope:"https://www.googleapis.com/auth/androidpublisher"},o=Buffer.from(JSON.stringify(n)).toString("base64url"),s=Buffer.from(JSON.stringify(r)).toString("base64url"),l=`${o}.${s}`,a=qr.createSign("RSA-SHA256");a.update(l);let c=a.sign(e.private_key,"base64url"),d=`${l}.${c}`;return(await we("OAuth token exchange",()=>$e.post("https://oauth2.googleapis.com/token",{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:d},{headers:{Connection:"close"},timeout:ke}))).data.access_token}import{spinner as Mt,log as E,isCancel as Ht,confirm as eo,select as ci}from"@clack/prompts";import y from"chalk";import g from"fs";import $ from"path";import{execSync as K,spawn as dn}from"child_process";import ue from"os";import to from"crypto";var un=(e,t)=>t.filter(i=>g.existsSync($.join(e,i))).reduce((i,n)=>i.update(g.readFileSync($.join(e,n))),to.createHash("sha256")).digest("hex").slice(0,16),io=e=>un(e,["package.json","yarn.lock","package-lock.json","bun.lockb"]),no=e=>un(e,["Podfile","Podfile.lock"]),ro=e=>{let t=$.join(e,"fingerprint.json");try{return JSON.parse(g.readFileSync(t,"utf-8"))}catch{return{}}},an=(e,t)=>{g.mkdirSync(e,{recursive:!0}),g.writeFileSync($.join(e,"fingerprint.json"),JSON.stringify(t,null,2))},oo=7200*1e3,so=(e,t)=>{g.mkdirSync(e,{recursive:!0});let i=$.join(e,"build.lock");if(g.existsSync(i))try{let n=JSON.parse(g.readFileSync(i,"utf-8")),r=Date.now()-(n.timestamp||0);if(r<oo)throw new Error(`Another build is already running for this project (build ${n.buildId}, started ${Math.round(r/6e4)}m ago). Cancel it from the dashboard first, or wait for it to complete.`)}catch(n){if(n.message.includes("Another build"))throw n}g.writeFileSync(i,JSON.stringify({buildId:t,pid:process.pid,timestamp:Date.now()}))},ao=(e,t)=>{let i=$.join(e,"build.lock");try{g.existsSync(i)&&JSON.parse(g.readFileSync(i,"utf-8")).buildId===t&&g.unlinkSync(i)}catch{}},ln=2e5,cn=(e,t)=>{let i=e+t;return i.length>ln?i.slice(-ln):i},lo=e=>e.replace(/\u001b\[[0-9;]*m/g,""),co=(e,t,i,n)=>{let r=lo(n).replace(/\r/g,`
|
|
1018
|
+
`).split(`
|
|
1019
|
+
`).map(a=>a.trimEnd()).filter(Boolean),o=r.filter(a=>/\berror:|fatal error:|xcodebuild: error|The following build commands failed|Command PhaseScriptExecution failed|CodeSign|Provisioning profile|No profiles|requires a provisioning profile|Undefined symbols|ld:|clang: error|SwiftCompile|CompileC/i.test(a)),s=o.length>0?o.slice(-40):r.slice(-80),l=o.length>0?"Key failure output":"Last command output";return[`Command failed with code ${i}: ${e} ${t.join(" ")}`,s.length>0?`
|
|
1020
|
+
${l}:
|
|
1021
|
+
${s.join(`
|
|
1022
|
+
`)}`:""].join("")},Xe=e=>{try{g.existsSync(e)&&g.rmSync(e,{recursive:!0,force:!0})}catch{}},uo=(e,t)=>{try{if(!g.existsSync(e))return;for(let i of g.readdirSync(e))t(i)&&Xe($.join(e,i))}catch{}},pn=e=>{E.info(y.dim("Clearing Metro/Hermes JS transform caches..."));let t=ue.tmpdir();uo(t,i=>i==="metro-cache"||i.startsWith("metro-")||i.startsWith("haste-map-")||i.startsWith("react-native-packager-cache-")),Xe($.join(e,".expo")),Xe($.join(e,"node_modules/.cache/metro")),Xe($.join(ue.homedir(),".cache/metro")),Xe($.join(ue.homedir(),".cache/react-native-packager")),Xe($.join(ue.homedir(),"Library/Caches/metro")),Xe($.join(ue.homedir(),"Library/Caches/react-native-packager"))},xe=(e,t,i=process.cwd(),n={},r,o)=>new Promise((s,l)=>{let a="",c=["/opt/homebrew/bin","/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin",$.join(ue.homedir(),".npm-global/bin")],u=[...(process.env.PATH||"").split(":"),...c].filter((D,A,H)=>D&&H.indexOf(D)===A).join(":");process.env[`${f.envPrefix}DEBUG`]&&console.log(y.magenta(`[${f.nameUpper}_DEBUG] Execution PATH: ${u}`));let p={...process.env,...n,PATH:u,LANG:"en_US.UTF-8",LC_ALL:"en_US.UTF-8"};r&&process.env[`${f.envPrefix}DEBUG`]&&(r(y.magenta(`[ENVIRONMENT] node: ${process.execPath}
|
|
1023
|
+
`)),r(y.magenta(`[ENVIRONMENT] PATH: ${u}
|
|
1024
|
+
`)),r(y.magenta(`[ENVIRONMENT] command: ${e} ${t.join(" ")}
|
|
1025
|
+
`)));let m=e;if(["node","npm","npx","pod"].includes(e)){let D=$.dirname(process.execPath),A=$.join(D,e);g.existsSync(A)&&(m=A,r&&r(y.dim(`[EXEC] Using absolute path: ${m}
|
|
1026
|
+
`)))}let S=dn(m,t,{stdio:"pipe",cwd:i,shell:!0,env:p,detached:process.platform!=="win32"});if(o){if(o.aborted){if(S.pid)try{process.kill(-S.pid,"SIGTERM")}catch{S.kill()}return l(new Error("Command aborted"))}o.addEventListener("abort",()=>{if(S.pid)try{process.kill(-S.pid,"SIGTERM")}catch{S.kill()}l(new Error("Command aborted"))})}S.stdout.on("data",D=>{let A=D.toString();a=cn(a,A),process.stdout.write(A),r&&r(A)}),S.stderr.on("data",D=>{let A=D.toString();a=cn(a,A),process.stderr.write(A),r&&r(A)}),S.on("close",D=>{D===0?s(D):l(new Error(co(e,t,D,a)))}),S.on("error",D=>l(D))}),po=e=>{let t=Math.floor(e/1e3%60),i=Math.floor(e/(1e3*60)%60),n=Math.floor(e/(1e3*60*60)%24),r=[];return n>0&&r.push(`${n}h`),i>0&&r.push(`${i}m`),(t>0||r.length===0)&&r.push(`${t}s`),r.join(" ")},at=(e,t)=>{let i=[];try{if(!g.existsSync(e))return i;let n=g.readdirSync(e);for(let r of n){let o=$.join(e,r);try{let s=g.statSync(o);if(t.some(a=>r.endsWith(a))){i.push($.resolve(o));continue}s.isDirectory()&&(i=i.concat(at(o,t)))}catch{}}}catch{}return i},di=async(e,t,i={},n,r={})=>{let o=Mt(),s=Date.now(),l=e.platform,a=e.buildProfile||"production",c=()=>qe(i,a,e),d=async(h,w={})=>{if(n)for(let R=1;R<=3;R++)try{await v.patch(`/builds/${n}/${t}`,{status:h,...w});return}catch(L){let U=L?.response?.data?.message||L?.message||String(L);console.error(`[reportStatus] attempt ${R}/3 failed (status=${h}): ${U}`),R<3&&await new Promise(P=>setTimeout(P,2e3))}},u=new AbortController,{signal:p}=u,m=null;n&&(m=setInterval(async()=>{try{(await v.get(`/builds/${n}/${t}`)).data.status==="cancelled"&&(E.warn(y.yellow(`
|
|
1027
|
+
\u{1F6D1} Build cancelled from dashboard. Terminating...`)),u.abort(),m&&clearInterval(m))}catch{}},5e3));let S=$.join(process.cwd(),".mach-cache"),D="setup",A="",H=null,F=async()=>{if(!A||!n)return;let h=A;A="";try{let w=h;Object.values(i).forEach(R=>{if(R&&R.length>5){let L=R.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");w=w.replace(new RegExp(L,"g"),"[SECRET]")}}),await v.post(`/builds/${n}/${t}/logs`,{log:w,step:D})}catch{}},z=async()=>{H&&(clearTimeout(H),H=null),await F(),ao(S,t),m&&(clearInterval(m),m=null);try{let h=$.join(ue.tmpdir(),`${f.buildPrefix}-${t}.keychain-db`);g.existsSync(h)&&(K(`security delete-keychain "${h}"`,{stdio:"ignore"}),E.info(y.dim("\u{1F511} Build keychain deleted.")))}catch{}try{let h=$.join(ue.homedir(),"Library/MobileDevice/Provisioning Profiles");if(g.existsSync(h)){let w=g.readdirSync(h).filter(R=>R.includes(t)||R.startsWith(`${f.nameLower}-temp-${t}`));for(let R of w)g.unlinkSync($.join(h,R))}}catch{}},b=async h=>{n&&(A+=h,A.length>=8192?(H&&(clearTimeout(H),H=null),await F()):H||(H=setTimeout(()=>{H=null,F()},2e3)))},G=async h=>{D=h,await b(`[STEP_START:${h}] ${Math.floor(Date.now()/1e3)}
|
|
1028
|
+
`)},_=async(h,w,R,L)=>await xe(h,w,R,L,U=>{b(U)},p);E.info(y.blue(`\u{1F680} Starting local build for ${l} (${a})...`));try{so(S,t)}catch(h){throw await d("failed",{error:h.message}),h}if(await d("building"),await G("setup"),n&&l==="ios"&&!e.simulator)try{let h=parseInt(i.BUILD_NUMBER||"0",10),w=await v.post(`/projects/${n}/next-build-number`,{platform:"ios",startFrom:h});w.data.status==="success"&&(i.BUILD_NUMBER=String(w.data.buildNumber),E.info(y.dim(`Auto build number: ${i.BUILD_NUMBER}`)),await b(`[BUILD_NUMBER] ${i.BUILD_NUMBER}
|
|
1029
|
+
`))}catch(h){E.warn(y.yellow(`Could not fetch auto build number: ${h.message}`))}await G("lock"),e.developmentClient?(E.info(y.blue("\u2139\uFE0F Configuring build to INCLUDE expo-dev-client (Development Client mode)...")),delete process.env.EXPO_NO_DEV_CLIENT,delete process.env.EXPO_AUTOLINKING_EXCLUDE):(E.info(y.blue("\u2139\uFE0F Configuring build to EXCLUDE expo-dev-client (Production/Staging mode)...")),process.env.EXPO_NO_DEV_CLIENT="1",process.env.EXPO_AUTOLINKING_EXCLUDE="expo-dev-client");try{await G("clone"),E.info(y.dim("Preparing source...")),await G("read_config");let h=$.join(process.cwd(),f.configFileName);if(g.existsSync(h)){let O=JSON.parse(g.readFileSync(h,"utf-8"))?.build?.[a]||{};await b(`[CONFIG] Profile: ${a}, distribution: ${O.distribution||"not set"}, simulator: ${O.simulator||!1}
|
|
1030
|
+
`)}if(await G("read_package"),e.nodeVersion){let x=process.env.NVM_DIR||$.join(ue.homedir(),".nvm"),O=$.join(x,"versions","node"),V;if(g.existsSync(O)){let M=g.readdirSync(O).sort().reverse(),ie=e.nodeVersion.startsWith("v")?e.nodeVersion:`v${e.nodeVersion}`,Q=M.find(ee=>ee===ie||ee.startsWith(ie+".")||ee.startsWith(`v${e.nodeVersion}.`));Q&&(V=$.join(O,Q,"bin"))}if(V&&g.existsSync(V)){let M=process.env.PATH||"";process.env.PATH=`${V}:${M}`,await b(`[NODE] Switched to Node ${e.nodeVersion} \u2014 using ${V}
|
|
1031
|
+
`),E.info(y.green(`\u2713 Node switched to ${e.nodeVersion} (${V})`))}else await b(`[NODE] Warning: Node ${e.nodeVersion} not found in nvm. Run: nvm install ${e.nodeVersion} on the build machine.
|
|
1032
|
+
`),E.warn(y.yellow(`Node ${e.nodeVersion} not found in nvm \u2014 using system default`))}await G("deps"),o.start("Checking dependencies...");let w=ro(S),R=io(process.cwd()),L=g.existsSync("node_modules"),U=g.existsSync("yarn.lock"),P=g.existsSync("bun.lockb");L&&w.node&&w.node!==R&&(o.stop("Dependency fingerprint changed \u2014 clearing node_modules for clean install..."),await b(`[CACHE] package.json/lockfile changed \u2014 wiping node_modules
|
|
1033
|
+
`),g.rmSync($.join(process.cwd(),"node_modules"),{recursive:!0,force:!0}),L=!1);let k="npm",I=["install","--prefer-offline"];U?(k="yarn",I=["install","--prefer-offline"]):P&&(k="bun",I=["install"]),L?o.stop("Cached node_modules found. Syncing dependencies..."):o.stop("No cached dependencies. Running fresh install..."),e.preBuild&&(E.info(y.blue("Running pre-install hook...")),E.info(y.dim(`> ${e.preBuild}`)),await G("prebuild"),await _("bash",[e.preBuild],process.cwd(),c())),E.info(y.dim(`Running ${k} ${I.join(" ")}...`)),await _(k,I,process.cwd(),c()),w.node=R,an(S,w);let N=JSON.parse(g.readFileSync("package.json","utf-8")),B=N.dependencies?.expo||N.devDependencies?.expo,j=e.iosBundleIdentifier||"",se=e.name||"";if(B){o.start(`Enforcing ${f.name} configuration...`);let x=$.join(process.cwd(),"app.json"),O=null;if(g.existsSync(x)){O=g.readFileSync(x,"utf-8");let M=JSON.parse(O);M.expo=M.expo||{},se||(se=M.expo.name||""),l==="ios"&&!j&&(j=M.expo?.ios?.bundleIdentifier||""),e.name&&(M.expo.name=e.name),e.scheme&&(M.expo.scheme=e.scheme),l==="ios"&&e.iosBundleIdentifier?(M.expo.ios=M.expo.ios||{},M.expo.ios.bundleIdentifier=e.iosBundleIdentifier):l==="android"&&e.androidPackage&&(M.expo.android=M.expo.android||{},M.expo.android.package=e.androidPackage),g.writeFileSync(x,JSON.stringify(M,null,2))}let V=["exec","--","expo","prebuild","--platform",l,"--no-install"];try{if(await G("prebuild"),await _("npm",V,process.cwd(),c()),l==="ios"&&g.existsSync("ios")){await G("pods"),E.info(y.blue("Running pod install..."));try{let M=$.resolve("ios"),ie=$.join(M,"Podfile");if(!g.existsSync(ie))throw new Error("ios/Podfile not found. Skipping pod install.");let Q=g.readFileSync(ie,"utf-8"),ee=e.iosDeploymentTarget||"13.4";if(!e.developmentClient&&(E.info(y.blue("\u2139\uFE0F Patching Podfile to EXCLUDE expo-dev-client...")),Q.includes("use_expo_modules!")&&!Q.includes("exclude:"))){let Ye=/use_expo_modules!(\s*)$/m;Ye.test(Q)?Q=Q.replace(Ye,'use_expo_modules!(exclude: ["expo-dev-client"])$1'):Q=Q.replace("use_expo_modules!",'use_expo_modules!(exclude: ["expo-dev-client"])')}let fe=`
|
|
954
1034
|
installer.generated_projects.each do |project|
|
|
955
1035
|
project.targets.each do |target|
|
|
956
1036
|
target.build_configurations.each do |config|
|
|
957
|
-
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '${
|
|
1037
|
+
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '${ee}'
|
|
958
1038
|
end
|
|
959
1039
|
end
|
|
960
1040
|
end
|
|
961
1041
|
installer.pods_project.targets.each do |target|
|
|
962
1042
|
target.build_configurations.each do |config|
|
|
963
|
-
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '${
|
|
1043
|
+
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '${ee}'
|
|
964
1044
|
end
|
|
965
1045
|
end
|
|
966
|
-
`,
|
|
967
|
-
${
|
|
1046
|
+
`,Ue=/post_install\s+do\s+\|installer\|/;if(Ue.test(Q))E.info(y.dim(`Injecting deployment target (${ee}) into existing post_install hook...`)),Q=Q.replace(Ue,`post_install do |installer|
|
|
1047
|
+
${fe}`),g.writeFileSync(ie,Q);else{E.info(y.dim(`Appending new post_install hook for deployment target (${ee})...`));let Ye=`
|
|
968
1048
|
post_install do |installer|
|
|
969
|
-
${
|
|
1049
|
+
${fe}
|
|
970
1050
|
end
|
|
971
|
-
`;
|
|
972
|
-
`),
|
|
973
|
-
\u2713 Local build completed successfully in ${
|
|
974
|
-
\u{1F4E6} Generated Artifacts:`)),
|
|
975
|
-
\u274C Build aborted.`)),await
|
|
976
|
-
\u2717 Local build failed: ${
|
|
977
|
-
`)[0]||"unknown"}`))}if(!
|
|
978
|
-
`).map(
|
|
1051
|
+
`;g.appendFileSync(ie,Ye)}let it="/opt/homebrew/bin/pod",mt=g.existsSync(it)?it:"pod",nt=no(M);g.existsSync($.join(M,"Pods"))&&w.pods&&w.pods!==nt&&(await b(`[CACHE] Podfile/Podfile.lock changed \u2014 wiping ios/Pods
|
|
1052
|
+
`),E.info(y.dim("Podfile fingerprint changed \u2014 clearing Pods for clean install...")),g.rmSync($.join(M,"Pods"),{recursive:!0,force:!0})),E.info(y.dim(`Using pod command: ${mt} in ${M}`)),await _(mt,["install"],M,c()),w.pods=nt,an(S,w)}catch(M){let ie=M.message||"Unknown error";E.warn(y.yellow(`Native "pod" command failed: ${ie}`)),E.info(y.dim("Falling back to npm exec pod-install...")),E.info(y.magenta(`${f.nameUpper}_DEBUG: Executing pod-install override via npx --yes pod-install@latest`)),await _("npx",["--yes","pod-install@latest","ios"],process.cwd(),c())}if(g.existsSync("ios/Pods")){E.info(y.dim("Disabling signing for Pod targets to prevent conflicts..."));try{K(`find ios/Pods -name "project.pbxproj" -exec sed -i '' 's/buildSettings = {/buildSettings = { CODE_SIGNING_ALLOWED = NO; CODE_SIGNING_REQUIRED = NO; PROVISIONING_PROFILE_SPECIFIER = ""; EXPANDED_CODE_SIGN_IDENTITY = "";/g' {} +`,{stdio:"ignore"})}catch{}}}}finally{O&&g.writeFileSync(x,O)}o.stop(`Expo prebuild complete (${f.name} config enforced).`)}let Z=[];if(l==="android")await G("build"),Z=await fo(e,a,i,x=>b(x),p);else if(l==="ios"){await G("signing"),E.info(y.dim("Preparing credentials..."));let x=r?.distributionType;Z=await mo(e,t,a,i,n,O=>b(O),p,x,O=>G(O))}e.postBuild&&(E.info(y.blue("Running post-build hook...")),E.info(y.dim(`> ${e.postBuild}`)),await _(e.postBuild,[],process.cwd(),c()));let Pe=po(Date.now()-s);if(E.success(y.green(`
|
|
1053
|
+
\u2713 Local build completed successfully in ${Pe}`)),await d("building",{...j&&{bundleId:j},...se&&{appName:se}}),Z.length>0&&(E.info(y.cyan(`
|
|
1054
|
+
\u{1F4E6} Generated Artifacts:`)),Z.forEach(x=>{let O=$.resolve(x);E.info(y.dim(` - ${x}`)),E.info(y.gray(` Path: ${O}`))}),e.interactive)){let x=await eo({message:"Install on connected device?"});if(!Ht(x)&&x){if(l==="android"){let O=Z.find(V=>V.endsWith(".apk"))||Z[0];await ho(O,V=>b(V))}else if(l==="ios"){let O=Z.find(M=>M.endsWith(".ipa"))||Z.find(M=>M.endsWith(".app"))||Z[0],V=He("ios");e.simulator?await yo(O,V||"",M=>b(M)):await So(O,V||"",M=>b(M))}}}await G("upload");let ge=[];for(let x of Z)try{let O=$.join(ue.tmpdir(),`${t}-${$.basename(x)}`);g.copyFileSync(x,O),ge.push(O),E.info(y.dim(` \u{1F4CB} Preserved artifact: ${$.basename(x)}`))}catch{E.warn(y.yellow(` Failed to preserve artifact: ${$.basename(x)}`))}Z=ge,E.info(y.dim("\u{1F9F9} Cleaning workspace (preserving dependency cache)..."));try{let x=process.cwd(),O=new Set(["node_modules"]),V=g.readdirSync(x),M=0;for(let ie of V)if(!O.has(ie)){if(ie==="ios"){let Q=$.join(x,"ios"),ee=g.readdirSync(Q);for(let fe of ee)if(fe!=="Pods")try{g.rmSync($.join(Q,fe),{recursive:!0,force:!0}),M++}catch{}continue}try{g.rmSync($.join(x,ie),{recursive:!0,force:!0}),M++}catch{}}E.info(y.dim(` Cleaned ${M} items. Cached: node_modules${g.existsSync($.join(x,"ios","Pods"))?", ios/Pods":""}`)),E.info(y.green("\u{1F512} Security: No source code retained on build server. Only public dependencies cached."))}catch{E.warn(y.yellow("Post-build cleanup encountered errors (non-fatal)."))}try{let O=$.join(ue.homedir(),f.workspacesDir),V=K(`df -k "${O}" | tail -1 | awk '{print $4}'`,{encoding:"utf8"}).trim(),M=parseInt(V,10)*1024;if(M<53687091200&&g.existsSync(O)){E.info(y.dim(` \u26A0\uFE0F Low disk space (${(M/1024/1024/1024).toFixed(0)} GB free). Running cache eviction...`));let ie=$.basename(process.cwd()),Q=g.readdirSync(O).filter(ee=>ee!==ie).map(ee=>{let fe=$.join(O,ee);try{let Ue=g.statSync(fe);return Ue.isDirectory()?{name:ee,dir:fe,mtime:Ue.mtimeMs}:null}catch{return null}}).filter(Boolean);Q.sort((ee,fe)=>ee.mtime-fe.mtime);for(let ee of Q){if(M>=53687091200)break;try{g.rmSync(ee.dir,{recursive:!0,force:!0}),E.info(y.dim(` \u{1F5D1}\uFE0F Evicted stale workspace: ${ee.name}`));let fe=K(`df -k "${O}" | tail -1 | awk '{print $4}'`,{encoding:"utf8"}).trim();if(parseInt(fe,10)*1024>=53687091200)break}catch{}}}}catch{}return await z(),Z}catch(h){throw await z(),h.message==="Command aborted"?(E.warn(y.yellow(`
|
|
1055
|
+
\u274C Build aborted.`)),await d("failed",{error:"Aborted by user"}),h):(E.error(y.red(`
|
|
1056
|
+
\u2717 Local build failed: ${h.message}`)),await d("failed",{error:h.message}),h)}},fo=async(e,t,i={},n,r)=>{let o=g.existsSync("android/gradlew")?"android/gradlew":g.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;E.info(y.blue(`Running Android build: ${l}...`));let a=o.includes("android/")?"android":".",c=(o.includes("android/"),"./gradlew"),d=[l],u={...i,EXPO_NO_DOTENV:"1",MACH_BUILD_PROFILE:t,MACH_APP_NAME:e.appName||e.name||"App"};if(i.ANDROID_VERSION_CODE){let m=$.join(a,"app/build.gradle");if(g.existsSync(m)){let S=i.ANDROID_VERSION_CODE,D=g.readFileSync(m,"utf-8");D=D.replace(/versionCode\s+\d+/,`versionCode ${S}`),g.writeFileSync(m,D),E.info(y.green(`\u2713 Applied Android versionCode ${S}`))}d.push(`-Pandroid.injected.version.code=${i.ANDROID_VERSION_CODE}`)}for(let m of["app/build","build",".cxx"]){let S=$.join(a,m);g.existsSync(S)&&g.rmSync(S,{recursive:!0,force:!0})}pn(process.cwd()),await xe(c,d,a,u,n,r);let p=$.join(a,"app/build/outputs");return at(p,[".apk",".aab"])},mo=async(e,t,i,n={},r,o,s,l,a)=>{if(process.platform!=="darwin")throw new Error("iOS builds can only be run on macOS.");let c=$.resolve(process.cwd(),g.existsSync("ios")?"ios":"."),d=g.readdirSync(c),u=d.find(h=>h.endsWith(".xcworkspace")),p=d.find(h=>h.endsWith(".xcodeproj")),m=qe(n,i,e);if(!u&&!p)throw new Error("Could not find Xcode workspace or project in ios/ directory.");try{let h=K("xcode-select -p").toString().trim();E.info(y.dim(`Using Xcode at: ${h}`))}catch{E.warn(y.dim("Could not detect Xcode path."))}E.info(y.blue("Running iOS build via xcodebuild..."));let S=u?u.replace(".xcworkspace",""):p?.replace(".xcodeproj",""),D=e.iosScheme||S||e.scheme,A=e.developmentClient?"Debug":e.iosConfiguration||"Release",H=(r||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),F=$.join(ue.homedir(),`Library/Developer/Xcode/DerivedData/${f.nameLower}`,H);g.mkdirSync(F,{recursive:!0});let z=ot(m),b=$.join(F,".mach-env-hash"),G=$.join(F,"Build"),_=g.existsSync(b)?g.readFileSync(b,"utf-8").trim():"";if(g.existsSync(G)){let h=_&&_!==z?"Build environment changed \u2014 clearing iOS DerivedData build products.":_?"Clearing iOS DerivedData build products to force a fresh JS bundle.":"DerivedData has no environment stamp \u2014 clearing iOS build products.";E.info(y.dim(h)),g.rmSync(G,{recursive:!0,force:!0})}if(g.writeFileSync(b,z),pn(process.cwd()),e.simulator){E.info(y.dim(`Building for simulator (Scheme: ${D}, Config: ${A})...`)),await xe("xcodebuild",[u?"-workspace":"-project",u||p,"-scheme",D,"-configuration",A,"-sdk","iphonesimulator","-derivedDataPath",F,"CODE_SIGNING_ALLOWED=NO","CODE_SIGNING_REQUIRED=NO"],c,m,o,s);let h=$.join(F,"Build/Products",`${A}-iphonesimulator`),w=at(h,[".app"]);if(w.length>0){let R=w[0],L=$.basename(R,".app"),U=$.join(h,`${L}_simulator.zip`);return E.info(y.dim(`Creating simulator artifact: ${U}...`)),K(`cd "${h}" && zip -r "${U}" "${$.basename(R)}"`),[U]}return[]}else{E.info(y.dim(`Archiving (Scheme: ${D}, Config: ${A})...`));let h=$.join(c,"build.xcarchive"),w=$.join(c,"export");g.rmSync(h,{recursive:!0,force:!0}),g.rmSync(w,{recursive:!0,force:!0});let R=n.IOS_DIST_P12,L=n.IOS_PROVISIONING_PROFILE,U=n.IOS_P12_PASSWORD||"",P=[],k,I,N={isAppStore:!1,isDevelopment:!1};if(R&&L){E.info(y.blue("\u{1F510} CI/CD Signing: Importing certificates..."));try{let x=`${f.buildPrefix}-${t}.keychain-db`,O=$.join(ue.tmpdir(),x),V=f.keychainPassword;K(`security create-keychain -p "${V}" "${O}" 2>/dev/null || true`),K(`security set-keychain-settings -t 3600 -l "${O}"`),K(`security unlock-keychain -p "${V}" "${O}"`);let M=$.join(ue.tmpdir(),`cert-${t}.p12`),ie=Buffer.from(R,"base64");g.writeFileSync(M,ie),E.info(y.dim(`P12 data size: ${ie.length} bytes, first bytes: ${ie.slice(0,4).toString("hex")}`)),(ie.length<100||ie[0]!==48)&&(E.warn(y.yellow("\u26A0\uFE0F P12 data looks corrupted or was not decrypted correctly.")),E.warn(y.yellow(" This usually means MACH_ENCRYPTION_KEY on the Remote API differs from when credentials were uploaded.")));let Q=[U,"",f.keychainPassword],ee=!1;for(let me of Q)try{K(`security import "${M}" -k "${O}" -P "${me}" -A -T /usr/bin/codesign -T /usr/bin/security`,{stdio:"pipe"}),ee=!0,E.info(y.dim(`\u2713 P12 imported successfully with password: ${me?"[set]":"[empty]"}`));break}catch(Ne){E.info(y.dim(` P12 import attempt with password ${me?`"${me.substring(0,3)}..."`:"[empty]"} failed: ${Ne.message?.split(`
|
|
1057
|
+
`)[0]||"unknown"}`))}if(!ee)throw new Error("Failed to import P12.");g.unlinkSync(M),K(`security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "${V}" "${O}"`);let fe=K("security list-keychains -d user",{encoding:"utf-8"}).split(`
|
|
1058
|
+
`).map(me=>me.trim().replace(/^"|"$/g,"")).filter(me=>me.length>0),Ue=[O,...fe].map(me=>`"${me}"`).join(" ");K(`security list-keychains -d user -s ${Ue}`),K(`security default-keychain -s "${O}"`);let it=$.join(ue.homedir(),"Library/MobileDevice/Provisioning Profiles");g.mkdirSync(it,{recursive:!0});let mt=Buffer.from(L,"base64"),nt=$.join(it,`${f.nameLower}-temp-${t}.mobileprovision`);g.writeFileSync(nt,mt);let kt=mt.toString("utf-8"),Ye=/<key>get-task-allow<\/key>\s*<true\/>/.test(kt);N={isAppStore:!kt.includes("<key>ProvisionedDevices</key>")&&!Ye,isDevelopment:Ye};try{let Ne=K(`security cms -D -i "${nt}"`,{encoding:"utf-8"}).match(/<key>UUID<\/key>\s*<string>([^<]+)<\/string>/);I=Ne?Ne[1]:void 0}catch{let Ne=kt.match(/<key>UUID<\/key>\s*<string>([^<]+)<\/string>/);I=Ne?Ne[1]:void 0}I||(E.warn("Could not extract UUID from provisioning profile. Using fallback."),I=`${f.nameLower}-${t}`);let oi=$.join(it,`${I}.mobileprovision`);g.existsSync(oi)&&g.unlinkSync(oi),g.renameSync(nt,oi);try{let Ne=K(`security find-identity -v -p codesigning "${O}"`,{encoding:"utf-8"}).match(/"((?:Apple|iPhone) (?:Distribution|Developer|Development)[^"]*)"/);Ne&&(k=Ne[1],E.info(y.blue(`Identity auto-detected from keychain: "${k}"`)))}catch{}k||(k=N.isDevelopment?"Apple Development":"Apple Distribution",E.info(y.blue(`Identity fallback (profile heuristic): "${k}"`))),E.info(y.dim(`Profile type: ${N.isDevelopment?"Development":N.isAppStore?"App Store":"Ad-Hoc"}`)),E.info(y.dim(`Identity Detection: get-task-allow=${N.isDevelopment}, Selected Identity="${k}"`)),P.push("CODE_SIGN_STYLE=Manual"),P.push(`CODE_SIGN_IDENTITY="${k}"`),P.push(`PROVISIONING_PROFILE_SPECIFIER=${I}`),e.iosTeamId&&P.push(`DEVELOPMENT_TEAM=${e.iosTeamId}`)}catch(x){throw E.error(`Signing setup failed: ${x.message}`),x}}else P.push("-allowProvisioningUpdates"),e.iosTeamId&&P.push(`DEVELOPMENT_TEAM=${e.iosTeamId}`);a&&await a("archive"),E.info(y.blue(`Archive detected Identity: "${k}"`)),E.info(y.blue(`Archive detected UUID: "${I}"`)),await xe("xcodebuild",["archive",u?"-workspace":"-project",u||p,"-scheme",D,"-configuration",A,"-archivePath",h,"-derivedDataPath",F,...P],c,m,o,s);let B;I?(N.isAppStore?B="app-store":N.isDevelopment?B="development":B="ad-hoc",E.info(y.blue(`Export method from profile: "${B}"`))):(B=e.distribution==="store"?"app-store":e.distribution==="internal"?"ad-hoc":"development",E.warn(y.yellow(`No profile UUID detected. Export method from distribution flag: "${B}"`)));let j=e.iosExportMethod||B,se=He("ios"),Z=$.join(c,"ExportOptions.plist"),Pe=`<?xml version="1.0" encoding="UTF-8"?>
|
|
979
1059
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
980
1060
|
<plist version="1.0">
|
|
981
1061
|
<dict>
|
|
@@ -988,55 +1068,88 @@ end
|
|
|
988
1068
|
<key>thinning</key>
|
|
989
1069
|
<string><none></string>
|
|
990
1070
|
${e.iosTeamId?`<key>teamID</key><string>${e.iosTeamId}</string>`:""}
|
|
991
|
-
${
|
|
1071
|
+
${se&&I?`
|
|
992
1072
|
<key>provisioningProfiles</key>
|
|
993
1073
|
<dict>
|
|
994
|
-
<key>${
|
|
1074
|
+
<key>${se}</key>
|
|
995
1075
|
<string>${I}</string>
|
|
996
1076
|
</dict>`:""}
|
|
997
1077
|
</dict>
|
|
998
|
-
</plist>`;if(
|
|
999
|
-
${
|
|
1078
|
+
</plist>`;if(g.writeFileSync(Z,Pe),process.env[`${f.envPrefix}DEBUG`]&&E.info(y.magenta(`[${f.nameUpper}_DEBUG] ExportOptions.plist:
|
|
1079
|
+
${Pe}`)),a&&await a("export"),E.info(y.blue(`Exporting with Bundle ID: "${se}"`)),E.info(y.blue(`Exporting with Method: "${j}"`)),o){o(y.magenta(`
|
|
1000
1080
|
[DIAGNOSTIC] Checking available signing identities...
|
|
1001
|
-
`));try{let
|
|
1002
|
-
`))}catch(
|
|
1003
|
-
`))}}await
|
|
1004
|
-
`)}catch{let
|
|
1005
|
-
`),new Error(
|
|
1006
|
-
`).slice(1).map(
|
|
1007
|
-
`).filter(
|
|
1008
|
-
`).find(s=>s.includes("android.intent.action.MAIN")&&s.includes("android.intent.category.LAUNCHER"))?G(`adb shell monkey -p ${r} -c android.intent.category.LAUNCHER 1`,{stdio:"ignore"}):G(`adb shell monkey -p ${r} -c android.intent.category.LAUNCHER 1`,{stdio:"ignore"})}catch{A.warn("Could not auto-launch app. You may need to open it manually.")}}}catch(n){i.stop("Installation failed."),A.error(y.red(`Failed to install APK: ${n.message}`))}},vo=async(e,t,i)=>{let n=It();try{if(!G("xcrun simctl list devices booted").toString().includes("(Booted)")){A.warn(y.yellow("No iOS Simulator is currently booted."));let r=G("xcrun simctl list devices --json").toString(),l=JSON.parse(r).devices,a=[];Object.keys(l).forEach(u=>{l[u].forEach(p=>{p.isAvailable&&a.push({...p,runtime:u})})});let s=await jt({message:"Select a simulator to launch:",options:a.map(u=>({value:u.udid,label:`${u.name} (${u.runtime.split(".").pop()})`}))});if(_t(s))return;n.start(`Booting ${s}...`),G(`xcrun simctl boot ${s}`),G(`open -a Simulator --args -CurrentDeviceUDID ${s}`);let c=0,d=!1;for(;c<30;){try{if(G("xcrun simctl list devices booted").toString().includes(s)){d=!0;break}}catch{}await new Promise(u=>setTimeout(u,2e3)),c++}if(!d)throw n.stop("Simulator boot timed out."),new Error("Simulator boot timed out.");n.stop("Simulator booted.")}n.start("Installing on iOS Simulator..."),await Oe("xcrun",["simctl","install","booted",e],process.cwd(),{},i),n.stop("Installation complete."),A.info(y.blue(`\u{1F680} Launching ${t}...`)),await Oe("xcrun",["simctl","launch","booted",t],process.cwd(),{},i)}catch(o){n.stop("Installation failed."),A.error(y.red(`Failed to install on Simulator: ${o.message}`))}},Oo=async(e,t,i)=>{let n=It();n.start("Scanning for connected iOS devices...");try{let o=G("xcrun devicectl list devices --json-output -").toString(),l=(JSON.parse(o).result?.devices||[]).filter(s=>s.connectionProperties?.transportType==="wired"||s.connectionProperties?.transportType==="localNetwork");if(l.length===0)throw n.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 a=l[0].identifier;if(l.length>1){n.stop();let s=await jt({message:"Select a device to install on:",options:l.map(c=>({value:c.identifier,label:`${c.deviceProperties?.name||c.name||c.model?.name} (${c.model?.name||"iPhone"}) - ${c.identifier}`}))});if(_t(s))return;a=s,n.start(`Installing on ${a}...`)}else n.message(`Installing on ${l[0].model.name}...`);await Oe("xcrun",["devicectl","device","install","app","--device",a,e],process.cwd(),{},i),n.stop("Installation complete."),A.info(y.blue(`\u{1F680} Launching ${t}...`)),await Oe("xcrun",["devicectl","device","launch","app","--device",a,t],process.cwd(),{},i)}catch(o){n.stop("Installation failed."),A.error(y.red(`Failed to install on device: ${o.message}`)),A.info(y.dim('Make sure your device is unlocked and "Developer Mode" is enabled in Settings -> Privacy & Security.'))}};import Ti from"fs";import ki from"path";import{isCancel as Kt,log as ke,select as xi,spinner as Co,text as No}from"@clack/prompts";import We from"chalk";async function Li(e){let t=await zt(e);t&&(ke.success(We.green(`Maestro run ${t.status||"queued"}: ${t.testRunId}`)),t.launchDeferredReason&&ke.warn(We.yellow(t.launchDeferredReason)),t.dashboardUrl&&ke.info(We.dim("View test run: ")+We.white.underline(t.dashboardUrl)))}async function zt(e){let t=ve(`./${f.configFileName}`),i=e.projectId||t?.projectId,n=e.profile||e.buildProfile||"production";if(!i)return ke.error(`No projectId found. Run \`${f.nameLower} link\` first or pass an internal project id.`),null;let o=e.platform;if(!o&&e.latest){let s=await xi({message:"Select platform for the latest build:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"}]});if(Kt(s))return null;o=s}let r=await To(e);if(!r)return null;if(r.kind==="latest"&&!o)return ke.error("Pass --platform when using --latest."),null;if(r.kind==="artifact-url"&&!o)return ke.error("Pass --platform when using --artifact-url."),null;let l=ko(e.maestroRetries);if(l===null)return null;let a=Co();e.quiet||a.start("Queuing Maestro run...");try{let s=await $.post("/tests/maestro",{projectId:i,platform:o,profile:n,latest:r.kind==="latest",buildId:r.kind==="build-id"?r.value:e.buildId,buildUrl:r.kind==="build-url"?r.value:e.buildUrl,artifactUrl:r.kind==="artifact-url"?r.value:e.artifactUrl,flows:e.maestroFlows||".maestro",device:e.maestroDevice||(o==="ios"?"iphone_15":"pixel_6"),retries:l,record:!!e.maestroRecord});if(s.data.status!=="success")throw new Error(s.data.message||"Failed to queue Maestro run");let c=s.data.testRun,d={testRunId:c.testRunId,status:c.status,projectId:i,buildId:c.buildId,platform:c.platform,dashboardUrl:c.dashboardUrl||`${Qe}/tests/${c.testRunId}`,launchDeferredReason:c.launchDeferredReason};return xo(e,d),e.quiet||a.stop("Maestro run queued"),d}catch(s){e.quiet||a.stop("Could not queue Maestro run");let c=s.response?.data?.message||s.message||"Unknown error";return ke.error(We.red(`Maestro queue failed: ${c}`)),null}}async function To(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 xi({message:"Select app artifact source for Maestro:",options:[{value:"latest",label:"Latest successful build"},{value:"build-id",label:"Build ID"},{value:"build-url",label:`${f.name} build URL`},{value:"artifact-url",label:"Direct artifact URL"}]});if(Kt(t))return null;if(t==="latest")return{kind:"latest"};let i=await No({message:t==="build-id"?"Enter build ID:":t==="build-url"?`Enter ${f.name} build URL:`:"Enter artifact URL:",validate:n=>{let o=String(n||"").trim();if(!o)return"Value is required";if((t==="build-url"||t==="artifact-url")&&!o.startsWith("http"))return"Must be a URL"}});return Kt(i)?null:{kind:t,value:String(i).trim()}}function ko(e){if(e==null||e==="")return 1;let t=Number(e);return!Number.isInteger(t)||t<0||t>10?(ke.error("--maestro-retries must be an integer between 0 and 10."),null):t}function xo(e,t){if(!e.jsonOutput)return;let i=ki.resolve(e.jsonOutput),n={...t,updatedAt:new Date().toISOString()};try{let o=ki.dirname(i);o&&o!=="."&&Ti.mkdirSync(o,{recursive:!0}),Ti.writeFileSync(i,JSON.stringify(n,null,2))}catch(o){ke.warn(We.yellow(`Could not write Maestro metadata JSON: ${o.message}`))}}var Pt=async e=>{e.platform!=="android"&&e.platform!=="ios"&&(R.error(`Platform ${e.platform} is not supported. Use 'android' or 'ios'.`),process.exit(1));let t=Vt(),i=e.buildId||Lo(),n=e.projectId,o=Date.now(),r=!!n,l=async a=>{if(n)try{await $.patch(`/builds/${n}/${i}`,{status:"failed",error:a})}catch{}};if(e.local&&e.buildId){e.quiet||t.start(`Preparing isolated workspace for build: ${e.buildId}`);try{let a=await $.get(`/builds/${n}/${e.buildId}/source-url`);if(a.data.status!=="success")throw new Error("Failed to get source download URL from API");let s=await rt.get(a.data.downloadUrl,{responseType:"stream"}),c=(n||e.projectId||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),d=ye.join(Uo.homedir(),f.workspacesDir,c);re.mkdirSync(d,{recursive:!0});let u=new Set(["node_modules",`.${f.nameLower}-cache-meta`]),p=new Set(["Pods"]);if(re.existsSync(d)){let B=re.readdirSync(d);for(let w of B){if(u.has(w))continue;if(w==="ios"){let b=ye.join(d,"ios");try{let L=re.readdirSync(b);for(let m of L)if(!p.has(m))try{re.rmSync(ye.join(b,m),{recursive:!0,force:!0})}catch{}}catch{}continue}let U=ye.join(d,w);try{re.rmSync(U,{recursive:!0,force:!0})}catch{}}}let g=ye.join(d,"source.zip"),h=s.data,P=re.createWriteStream(g);await new Promise((B,w)=>{h.pipe(P),h.on("error",U=>w(U)),P.on("finish",()=>B())}),new Hi(g).extractAllTo(d,!0);try{re.unlinkSync(g)}catch{}process.chdir(d),R.info(v.green(`\u2713 Persistent workspace ready: ${d}`)),R.info(v.dim(` \u{1F4E6} Cached dirs preserved: node_modules=${re.existsSync(ye.join(d,"node_modules"))?"\u2705":"\u274C"}, Pods=${re.existsSync(ye.join(d,"ios","Pods"))?"\u2705":"\u274C"}`)),t.stop()}catch(a){t.stop(`Failed to prepare isolated workspace: ${a.message}`),n&&await l(`Setup Error: ${a.message}`),process.exit(1)}}try{let a=e.repo;if(!a)try{a=Fi("git config --get remote.origin.url").toString().trim()}catch{R.warn("Could not detect git repository URL.")}!a&&e.dryRun,a||(a="https://github.com/placeholder/repo.git"),R.info(`Build ID: ${v.cyan(i)}`);let s={},c={},d=ve(`./${f.configFileName}`);if(d){n=d.projectId;let m=e.buildProfile||"production",D=Be(d,m);!D&&e.buildProfile&&(R.error(`Build profile '${m}' not found in ${f.configFileName}`),process.exit(1));let S=D||{};process.env.MACH_DEBUG&&R.info(v.dim(`Build profile: ${m} | Platform: ${e.platform} | Distribution: ${S.distribution||"store"} | Environment: ${S.environment||m}`)),S.env&&(c=S.env,R.info(v.blue(`Use Build Profile: ${m}`)));let I=e.platform,x=S[I]||{},W=["developmentClient","simulator","distribution","buildCommand","apk","iosScheme","preBuild","postBuild","scheme","environment","androidPackage","iosBundleIdentifier","name","iosDeploymentTarget","iosApiKeyId","iosApiKeyIssuer","iosApiKeyPath","iosTeamId","iosConfiguration","iosExportMethod","branch","repo","instanceType","ami","bucket","region","nodeVersion"];e.name=d.name,e.appName=d.name,e.androidPackage=d.android?.package,e.iosBundleIdentifier=d.ios?.bundleIdentifier,e.iosScheme=d.ios?.iosScheme,!e.nodeVersion&&d.nodeVersion&&(e.nodeVersion=d.nodeVersion);let j=M=>M==="androidPackage"?x.androidPackage??x.package??S.androidPackage??S.android?.package:M==="iosBundleIdentifier"?x.iosBundleIdentifier??x.bundleIdentifier??S.iosBundleIdentifier??S.ios?.bundleIdentifier:x[M]!==void 0?x[M]:S[M];for(let M of W){let K=j(M),H=M==="androidPackage"||M==="iosBundleIdentifier";K!==void 0&&(e[M]===void 0||H)&&(e[M]=K)}e.branch=e.branch||"main",e.iosConfiguration=e.iosConfiguration||(e.developmentClient||e.simulator?"Debug":"Release"),e.sshUser=e.sshUser||process.env.USER||"ubuntu",e.simulator===void 0&&(e.simulator=!1),e.local===void 0&&(e.local=!1),e.verbose===void 0&&(e.verbose=!1);let O=M=>{if(!M)return M;if(M.startsWith("scripts.")){let K=M.split(".")[1],H=d.scripts?.[K];if(H)return H;R.warn(`Script reference not found: ${M}`)}return M};e.buildCommand=O(e.buildCommand),e.preBuild=O(e.preBuild),e.postBuild=O(e.postBuild),!e.scheme&&d.scheme&&(e.scheme=d.scheme);let F={...Ke(d,f.envPrefix),...Ke(S,`${f.envPrefix}PROFILE_`)};s={...s,...c,...F},process.env.IOS_P12_PASSWORD&&!s.IOS_P12_PASSWORD&&(s.IOS_P12_PASSWORD=process.env.IOS_P12_PASSWORD),process.env.MATCH_PASSWORD&&!s.MATCH_PASSWORD&&(s.MATCH_PASSWORD=process.env.MATCH_PASSWORD),e.platform==="ios"&&(!e.iosTeamId&&S.ios?.appleTeamId&&(e.iosTeamId=S.ios.appleTeamId),!e.iosTeamId&&d.submit?.[m]?.ios?.appleTeamId&&(e.iosTeamId=d.submit[m].ios.appleTeamId),!e.iosTeamId&&d.submit?.production?.ios?.appleTeamId&&(R.warn(v.yellow(`Check: Using 'production' Team ID for '${m}' build.`)),e.iosTeamId=d.submit.production.ios.appleTeamId),e.iosTeamId?R.info(v.magenta(`\u2713 Injected iOS Team ID from config: ${e.iosTeamId}`)):R.warn(v.yellow("\u26A0\uFE0F No iOS Team ID found. Signing might fail if not managed automatically via Expo.")))}let u="unknown";try{u=Fi("git rev-parse --abbrev-ref HEAD").toString().trim()}catch{R.warn("Failed to detect git branch.")}let p="1.0.0";try{re.existsSync("./package.json")&&(p=JSON.parse(re.readFileSync("./package.json","utf-8")).version||"1.0.0")}catch{}let g=e.buildProfile||"production",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 P=e.platform==="ios"?"iOS":"Android",C=e.platform==="ios"&&e.simulator?" (Simulator)":"",B=`${P}${C} v${p} (${h})`;if(st(e,{status:"created",projectId:n,buildId:i,platform:e.platform,profile:g,branch:u,version:p,buildType:h,developmentClient:!!e.developmentClient,summary:B}),n){try{let m=e.buildProfile||"production";R.info(v.blue(`Fetching managed secrets for profile: ${m}...`));let D=e.environment||m,I=(await $.get(`/projects/${n}/secrets/export?env=${D}`)).data;I.status==="success"&&I.secrets&&(s={...s,...I.secrets},Object.keys(I.secrets).length>0&&R.info(v.magenta(`\u2713 Injected ${Object.keys(I.secrets).length} secrets from Dashboard.`)))}catch(m){R.warn(`Failed to load managed secrets from Dashboard: ${m.message}`)}try{R.info(v.blue("Fetching managed credentials..."));let m="development";e.distribution==="store"?m="store":e.distribution==="internal"&&(m=e.platform==="ios"?"adhoc":"internal"),e.developmentClient&&(m="development");let D=await $.get("/credentials/resolve",{params:{projectId:n,platform:e.platform,bundleId:e.iosBundleIdentifier||e.androidPackage,distributionType:m}});if(D.data.status==="success"&&D.data.credentials){let S=D.data.credentials;R.info(v.magenta(`\u2713 Found ${S.length} relevant credentials.`));let I=S.filter(O=>{if(O.distributionType){let F=m==="internal"?"adhoc":m;return O.distributionType===F||O.distributionType===m}return!0});R.info(v.dim(` Filtered to ${I.length} credentials for distributionType: ${m}`));let x=!1,W=!1,j=!1;for(let O of I)if(O.downloadUrl)try{let F="",M=5;for(;M>0;)try{let K=await rt.get(O.downloadUrl,{responseType:"arraybuffer",timeout:3e4,headers:{Connection:"close"}});F=Buffer.from(K.data).toString("base64");break}catch(K){if(M--,M===0)throw K;R.warn(v.dim(` - Temporary network error downloading ${O.name}. Retrying... (${5-M}/5)`)),await new Promise(H=>setTimeout(H,2e3))}if(O.type==="ios_cert"&&!x)s.IOS_DIST_P12=F,O.password?(s.IOS_P12_PASSWORD=O.password,R.info(v.dim(` - Injected ${O.name} as IOS_DIST_P12 with password from credential record`))):R.info(v.dim(` - Injected ${O.name} as IOS_DIST_P12`)),x=!0;else if(O.type==="ios_profile"&&!W)s.IOS_PROVISIONING_PROFILE=F,R.info(v.dim(` - Injected ${O.name} as IOS_PROVISIONING_PROFILE`)),W=!0;else if(O.type==="android_keystore"&&!j){s.ANDROID_KEYSTORE_BASE64=F;let K=O.keystorePassword||O.password,H=O.keyPassword||O.keystorePassword||O.password,z=O.alias||O.meta?.alias;if(K)s.ANDROID_STORE_PASSWORD=K,R.info(v.dim(" - Injected keystore password from credential record"));else{let T=["ANDROID_STORE_PASSWORD",...[m==="store"?"PRODUCTION":m==="internal"?"STAGING":"DEVELOPMENT",m.toUpperCase(),"PRODUCTION","STORE","INTERNAL","STAGING","RELEASE","DEBUG"].map(k=>`KEYSTORE_PASSWORD_${k}`),"KEYSTORE_PASSWORD"].find(k=>!!s[k]);T&&s[T]&&(s.ANDROID_STORE_PASSWORD=s[T])}if(H?(s.ANDROID_KEY_PASSWORD=H,R.info(v.dim(" - Injected key password from credential record"))):s.ANDROID_KEY_PASSWORD=s.ANDROID_STORE_PASSWORD||"",z)s.ANDROID_KEY_ALIAS=z;else{let ne=["ANDROID_KEY_ALIAS","KEYSTORE_ALIAS"].find(he=>!!s[he]);ne&&(s.ANDROID_KEY_ALIAS=s[ne])}R.info(v.dim(` - Injected ${O.name} as ANDROID_KEYSTORE_BASE64`)),j=!0}}catch(F){R.warn(`Failed to download credential ${O.name}: ${F.message}`)}}if(e.platform==="android"){let S=e.buildProfile||"production",I=Be(d,S)||{},j=((I.android||{}).versionCode??I.androidVersionCode??d.android?.versionCode??d.expo?.android?.versionCode)==="auto",O=e.autoVersion||j&&e.distribution==="store";if(j&&!O&&R.info(v.dim(` Skipping Google Play versionCode lookup for ${e.distribution||"non-store"} build. Pass --auto-version to force it.`)),O){t.start("Resolving latest versionCode from Google Play...");try{let F=e.androidPackage||d.android?.package||d.expo?.android?.package||d.name,M=(D.data.credentials||[]).find(T=>T.type==="google_service_account"&&(!T.bundleId||T.bundleId===F));if(!M){let k=((await $.get(`/credentials/${n}`)).data.credentials||[]).filter(V=>V.type==="google_service_account");if(M=k.find(V=>V.type==="google_service_account"&&V.bundleId===F),!M&&k.length>0){let V=k.map(N=>N.bundleId).filter(Boolean).join(", ");throw new Error(`Google Service Account not found for package ${F}. Found service credential(s) for: ${V}.`)}}if(!M)throw new Error(`Google Service Account not found for package ${F}. Upload it under this package in Dashboard or run '${f.nameLower} credentials:service --platform android --package-name ${F}'.`);let K=await $.get(`/credentials/${M.credentialId}/download`,{params:{projectId:n}});if(K.data.status!=="success"||!K.data.downloadUrl)throw new Error("Failed to get secure download URL for service account");let z=(await rt.get(K.data.downloadUrl,{headers:{Connection:"close"}})).data,ne=await vi(F,z);if(ne==null)throw new Error("Could not retrieve any version information from Google Play.");let he=ne+1;s.ANDROID_VERSION_CODE=he.toString(),t.stop(`\u2713 Resolved versionCode: ${v.green(he)} (Latest on Play Store: ${ne})`)}catch(F){t.stop("Version resolution failed");let M=F.response?.data?.error?.message||F.message;throw new Error(`Auto-versioning failed: ${M}. Fix Google Play service account permissions or remove android.versionCode="auto".`)}}}if(e.platform==="ios"&&!e.simulator){let S=!!s.IOS_DIST_P12,I=!!s.IOS_PROVISIONING_PROFILE;if(!S||!I){let x=[...S?[]:["Distribution Certificate"],...I?[]:["Provisioning Profile"]].join(" and ");R.error(v.red(`Missing iOS credentials: ${x}`)),e.quiet&&process.exit(1);let W=e.yes||await Ui({message:"Would you like to generate these credentials now?",initialValue:!0});if(W&&!Mi(W))return await et({platform:"ios",profile:g}),e.quiet||R.info(v.green("\u2713 Credentials setup complete! Restarting build phase...")),Pt(e);e.quiet||R.info(v.yellow(`Run \`${f.nameLower} credentials\` to set up signing credentials manually.`)),process.exit(1)}}if(e.platform==="android"&&!e.developmentClient&&(e.distribution==="internal"||e.distribution==="store")&&!(!!s.ANDROID_KEYSTORE_BASE64||!!s.ANDROID_KEYSTORE)){R.error(v.red("Missing Android credentials: Signing Keystore")),e.quiet&&process.exit(1);let I=e.yes||await Ui({message:"Would you like to automatically create and upload an Android Keystore for this profile now?",initialValue:!0});if(I&&!Mi(I))return await et({platform:"android",profile:g}),e.quiet||R.info(v.green("\u2713 Android Keystore setup complete! Restarting build phase...")),Pt(e);e.quiet||R.info(v.yellow(`Run \`${f.nameLower} credentials --platform android\` to set up a signing keystore manually.`)),process.exit(1)}}catch(m){R.warn(`Failed to resolve credentials: ${m.message}`)}}let w=!!(e.local&&e.buildId),U=!!(e.local||e.sshHost),b=!U&&!w;if(w){R.info(v.magenta("\u{1F3D7}\uFE0F Runner Mode: Executing isolated build task..."));let m=await Gt({...e,interactive:!1},i,s,n,{branch:u,version:p,summary:B,buildType:h});await L(m),process.exit(0)}async function L(m){if(n&&m.length>0){let D=Vt(),S=[];e.quiet||D.start("Uploading artifacts to Dashboard...");try{for(let I of m){let x=ye.basename(I),W=re.readFileSync(I),j=ye.extname(x).toLowerCase(),O="application/octet-stream",F=await $.post(`/builds/${n}/${i}/artifact-upload-url`,{fileName:x,fileType:O});if(F.data.status!=="success")throw new Error(`Failed to get upload URL for ${x}`);let M=!1;for(let K=1;K<=3;K++)try{await rt.put(F.data.uploadUrl,W,{headers:{"Content-Type":O},maxBodyLength:1/0,maxContentLength:1/0,timeout:12e4}),M=!0;break}catch(H){if(R.warn(v.yellow(`Artifact upload attempt ${K}/3 failed (${H.code||H.message})`)),K<3)await new Promise(z=>setTimeout(z,3e3*K));else throw H}M&&S.push({name:x,url:F.data.downloadUrl,size:W.length,type:j.substring(1)})}e.quiet||D.stop("Artifacts uploaded.")}catch(I){e.quiet||D.stop("Failed to upload artifacts."),R.error(v.red(`Upload error: ${I.message}`));try{await $.patch(`/builds/${n}/${i}`,{status:"completed",artifacts:m.map(x=>ye.basename(x)),endTime:Date.now()})}catch(x){R.warn(v.yellow(`Could not set fallback build status: ${x.message}`))}return}if(n&&S.length>0)try{R.info(v.cyan(`
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
\
|
|
1012
|
-
\
|
|
1013
|
-
\
|
|
1014
|
-
\
|
|
1015
|
-
\
|
|
1016
|
-
|
|
1017
|
-
\
|
|
1018
|
-
`)
|
|
1019
|
-
`).filter(r=>!!r.trim()),o=e.some(r=>r.platform==="android"&&r.id.startsWith("emulator-"));n.forEach(r=>{o||e.push({id:r,platform:"android",type:"emulator",name:r.replace(/_/g," "),status:"offline",details:`Android Virtual Device: ${r}`})})}catch{}if(process.platform!=="darwin")return e;try{let t=Pe("/usr/bin/xcrun simctl list devices --json",{stdio:"pipe"}).toString(),i=JSON.parse(t);Object.entries(i.devices).forEach(([n,o])=>{o.forEach(r=>{r.isAvailable&&e.push({id:r.udid,platform:"ios",type:"simulator",name:r.name,status:r.state?.toLowerCase()==="booted"?"online":"offline",runtime:n,details:`${r.name} (${n})`})})})}catch{}try{let t=Pe("/usr/bin/xcrun devicectl list devices --json-output -",{stdio:"pipe"}).toString();(JSON.parse(t).result?.devices||[]).forEach(n=>{let o=n.connectionProperties?.transportType;(o==="wired"||o==="localNetwork")&&e.push({id:n.identifier,platform:"ios",type:"physical",name:n.deviceProperties?.name||"iPhone",status:"online",details:`${n.deviceProperties?.name||"iPhone"} (${n.model?.name||n.hardwareModel||""}) - ${o}`})})}catch{}return e}async function Ki(e){let t=[];for await(let i of e)t.push(Buffer.isBuffer(i)?i:Buffer.from(i));return t.length===0?{}:JSON.parse(Buffer.concat(t).toString("utf-8"))}async function Go(e,t){let i=await Ho({method:"GET",url:e,responseType:"stream",timeout:12e4}),n=Jt.createWriteStream(t);i.data.pipe(n),await new Promise((o,r)=>{n.on("finish",o),n.on("error",r)})}async function Ko(e,t,i){let n=i||(t.toLowerCase().includes(".apk")?"android":"ios"),o=t.toLowerCase().includes(".ipa"),r=Jt.mkdtempSync(Yt.join(Bo.tmpdir(),`${at}-install-`)),l=Yt.join(r,n==="android"?"install.apk":o?"install.ipa":"install.zip");try{if(await Go(t,l),n==="android"){Pe(`adb -s ${JSON.stringify(e)} install -r ${JSON.stringify(l)}`,{stdio:"pipe"});return}if(process.platform!=="darwin")throw new Error("iOS local install requires macOS.");Pe(`unzip -o ${JSON.stringify(l)} -d ${JSON.stringify(r)}`,{stdio:"pipe"});let a="";try{a=Pe(`find ${JSON.stringify(Yt.join(r,"Payload"))} -maxdepth 1 -name "*.app" 2>/dev/null | head -n 1`,{stdio:"pipe"}).toString().trim()}catch{}if(a||(a=Pe(`find ${JSON.stringify(r)} -name "*.app" -type d | head -n 1`,{stdio:"pipe"}).toString().trim()),!a)throw new Error(`No .app bundle found inside the ${o?"IPA":"archive"}.`);try{Pe(`/usr/bin/xcrun devicectl device install app --device ${JSON.stringify(e)} ${JSON.stringify(a)}`,{stdio:"pipe"})}catch(s){try{Pe(`/usr/bin/xcrun simctl install ${JSON.stringify(e)} ${JSON.stringify(a)}`,{stdio:"pipe"})}catch{throw new Error(s.stderr?.toString().trim()||s.message||"iOS install failed.")}}}finally{Jt.rmSync(r,{recursive:!0,force:!0})}}function zo(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 Pe(`/usr/bin/xcrun simctl boot ${JSON.stringify(e)}`,{stdio:"pipe"}),Gi("open",["-a","Simulator"],{detached:!0,stdio:"ignore"}).unref(),"Simulator booting..."}if(t==="android"){let i=`${process.env.ANDROID_HOME||`${process.env.HOME}/Library/Android/sdk`}/emulator/emulator`;return Gi(i,["-avd",e],{detached:!0,stdio:"ignore"}).unref(),"Emulator booting in background..."}throw new Error("Invalid platform.")}async function zi(){process.platform!=="darwin"&&Ye.warn("Running on non-macOS \u2014 iOS discovery unavailable, Android only.");let e=Fo.createServer((n,o)=>{if(o.setHeader("Access-Control-Allow-Origin","*"),o.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),o.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),n.method==="OPTIONS"){o.writeHead(204),o.end();return}let r=new URL(n.url||"/",`http://localhost:${at}`);if(n.method==="GET"&&r.pathname==="/local/devices"){try{let l=jo();o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({status:"success",targets:l}))}catch(l){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({status:"error",message:l.message}))}return}if(n.method==="POST"&&r.pathname==="/install-local"){t(n,o);return}if(n.method==="POST"&&r.pathname==="/local/boot"){i(n,o);return}o.writeHead(404),o.end()}),t=async(n,o)=>{try{let{deviceId:r,artifactUrl:l,platform:a}=await Ki(n);if(!r||!l){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({status:"error",message:"deviceId and artifactUrl are required"}));return}await Ko(r,l,a),o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({status:"success",message:`Installed on ${r}`}))}catch(r){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({status:"error",message:r.message||"Local install failed"}))}},i=async(n,o)=>{try{let{id:r,platform:l}=await Ki(n),a=zo(r,l);o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({status:"success",message:a}))}catch(r){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({status:"error",message:r.message||"Local device launch failed"}))}};e.listen(at,"127.0.0.1",()=>{Ye.success(Wt.green(`Local device agent running on http://localhost:${at}`)),Ye.info(Wt.dim("Keep this running while using the Install Hub on the dashboard.")),Ye.info(Wt.dim("Press Ctrl+C to stop."))}),e.on("error",n=>{n.code==="EADDRINUSE"?Ye.error(`Port ${at} is already in use \u2014 agent may already be running.`):Ye.error(`Agent error: ${n.message}`),process.exit(1)}),await new Promise(()=>{})}import{createRequire as Rs}from"module";import{text as Wo,password as Yo,spinner as Jo,isCancel as Yi}from"@clack/prompts";import Qt from"chalk";import lt from"fs";import Vi from"path";import Vo from"os";var qt=Vi.join(Vo.homedir(),f.configDir),Xt=Vi.join(qt,"config.json");function Zt(){if(!lt.existsSync(Xt))return{};try{return JSON.parse(lt.readFileSync(Xt,"utf-8"))}catch{return{}}}function Wi(e){lt.existsSync(qt)||lt.mkdirSync(qt,{recursive:!0});let i={...Zt(),...e};lt.writeFileSync(Xt,JSON.stringify(i,null,2))}async function Ji(){let e=Zt(),t=await Wo({message:"Enter your email:",placeholder:"user@example.com",initialValue:e.lastLoginEmail,validate(o){if(o.length===0)return"Email is required!"}});if(Yi(t))return;let i=await Yo({message:"Enter your password:",validate(o){if(o.length===0)return"Password is required!"}});if(Yi(i))return;let n=Jo();n.start("Authenticating...");try{let r=await(await fetch(`${At}/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:t,password:i})})).json();r.status==="success"&&r.user.token?(di({id:r.user.id,email:t,token:r.user.token,refreshToken:r.user.refreshToken}),Wi({lastLoginEmail:t}),n.stop(Qt.green("Login successful!"))):n.stop(Qt.red("Login failed: "+(r.message||"Unknown error")))}catch(o){n.stop(Qt.red("Network error: "+o.message))}}import{outro as qo,select as Xo,spinner as Zo,isCancel as Qo}from"@clack/prompts";import $t from"chalk";import ei from"fs";import er from"path";var qi=e=>e==="1234567890"||e==="ABC123DEFG"||e==="XXXXXXXXXX"?"":typeof e=="string"?e:"",tr=()=>process.versions.node.split(".")[0]||"24";async function Xi(){if(!fe()){console.log($t.red(`You are not logged in. Run \`${f.nameLower} login\` first.`));return}let t=Zo();t.start("Fetching projects...");try{let{data:i}=await $.get("/projects");if(t.stop("Projects loaded."),i.status!=="success"||!i.projects||i.projects.length===0){console.log($t.yellow(`No projects found. Run \`${f.nameLower} init\` to create one.`));return}let n=i.projects.map(h=>({value:h.projectId,label:`${h.name} (${h.slug})`})),o=await Xo({message:"Select a project to link:",options:n});if(Qo(o))return;let r=er.join(process.cwd(),f.configFileName),l={};if(ei.existsSync(r))try{l=JSON.parse(ei.readFileSync(r,"utf-8"))}catch{}let a=i.projects.find(h=>h.projectId===o),s=l.android?.package||Te("android"),c=l.ios?.bundleIdentifier||Te("ios"),d=l.android||{},u=l.submit?.production?.android||{},p=l.submit?.production?.ios||{},g={projectId:o,name:a?.name,slug:a?.slug,nodeVersion:l.nodeVersion||tr(),scheme:a?.slug?.toLowerCase()||"app",android:{...d,package:s||"",versionCode:d.versionCode||"auto"},ios:{bundleIdentifier:c||""},build:{development:{environment:"development",distribution:"internal"},staging:{environment:"staging",distribution:"internal"},production:{environment:"production",distribution:"store"}},submit:{production:{android:{...u,track:u.track||"internal",releaseStatus:u.releaseStatus||"completed"},ios:{ascAppId:qi(p.ascAppId),appleTeamId:qi(p.appleTeamId)}}}};ei.writeFileSync(r,JSON.stringify(g,null,2)),qo($t.green(`Linked to project ${g.name} (${g.slug})`))}catch(i){t.stop($t.red("Error fetching projects: "+i.message))}}import{outro as ir,text as Dt,select as nr,spinner as or,isCancel as ct}from"@clack/prompts";import dt from"chalk";import rr from"fs";import sr from"path";import{randomUUID as ar}from"crypto";var lr=()=>process.versions.node.split(".")[0]||"24";async function Zi(){if(!fe()){console.log(dt.red(`You are not logged in. Run \`${f.nameLower} login\` first.`));return}let t=await Dt({message:"Project Name:",placeholder:"My Awesome App",validate(a){if(a.length===0)return"Name is required!"}});if(ct(t))return;let i=await Dt({message:"Project Slug (URL friendly):",placeholder:"my-awesome-app",validate(a){if(a.length===0)return"Slug is required!";if(!/^[a-z0-9-]+$/.test(a))return"Slug must be lowercase alphanumeric with dashes."}});if(ct(i))return;let n=await nr({message:"Platform:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"},{value:"web",label:"Web"},{value:"all",label:"All Platforms"}]});if(ct(n))return;let o="";if(n==="android"||n==="all"){let a=Te("android");if(o=await Dt({message:"Android Package Name:",initialValue:a||"",placeholder:"com.example.app",validate(s){if(s.length===0)return"Package name is required for Android!"}}),ct(o))return}let r="";if(n==="ios"||n==="all"){let a=Te("ios");if(r=await Dt({message:"iOS Bundle Identifier:",initialValue:a||"",placeholder:"com.example.app",validate(s){if(s.length===0)return"Bundle ID is required for iOS!"}}),ct(r))return}let l=or();l.start("Creating project...");try{let a=ar(),c={projectId:a,name:t,slug:i,storageType:"managed",platforms:n==="all"?["android","ios","web"]:[n]},{data:d}=await $.post("/projects",c);if(d.status==="success"){l.stop(dt.green("Project created successfully!"));let u=sr.join(process.cwd(),f.configFileName);rr.writeFileSync(u,JSON.stringify({projectId:a,name:t,slug:i,nodeVersion:lr(),...o?{android:{package:o,versionCode:"auto"}}:{},...r?{ios:{bundleIdentifier:r}}:{},build:{development:{environment:"development",distribution:"internal"},staging:{environment:"staging",distribution:"internal"},production:{environment:"production",distribution:"store"}},submit:{production:{android:{track:"internal",releaseStatus:"completed"},ios:{ascAppId:"",appleTeamId:""}}}},null,2)),ir(dt.green(`Initialized project ${t} and linked locally!`))}else l.stop(dt.red("creation failed: "+d.message))}catch(a){l.stop(dt.red("Network error: "+a.message))}}import{spinner as en,log as Se}from"@clack/prompts";import Rt from"chalk";import Qi from"fs";import cr from"path";async function tn(e,t){let i=fe();if(!i){Se.error(`You are not logged in. Run \`${f.nameLower} login\` first.`);return}let n=cr.join(process.cwd(),f.configFileName);if(!Qi.existsSync(n)){Se.error(`No ${f.configFileName} found. Run \`${f.nameLower} init\` or \`${f.nameLower} link\` first.`);return}let o;try{o=JSON.parse(Qi.readFileSync(n,"utf-8"))}catch{Se.error(`Failed to parse ${f.configFileName}`);return}let{projectId:r}=o;if(!r){Se.error(`${f.configFileName} is missing projectId.`);return}e==="set"?await dr(r,t,i):e==="list"?await ur(r,i):Se.error(`Unknown env action: ${e}. Use 'set' or 'list'.`)}async function dr(e,t,i){if(t.length===0){Se.error(`Usage: ${f.nameLower} env set KEY=VALUE [KEY2=VALUE2 ...]`);return}let n=en();n.start("Setting environment variables...");let o=0,r=0;for(let l of t){let[a,...s]=l.split("="),c=s.join("=");if(!a||c===void 0){Se.warn(`Invalid format for argument: ${l}. Expected KEY=VALUE.`),r++;continue}try{let d={key:a.trim(),value:c,type:"env",environment:"global",visibility:"secret"},{data:u}=await $.post(`/projects/${e}/secrets`,d);u.status==="success"?o++:(Se.error(`Failed to set ${a}: ${u.message}`),r++)}catch(d){Se.error(`Network error setting ${a}: ${d.message}`),r++}}n.stop(`Set ${o} variable(s). ${r>0?`${r} failed.`:""}`)}async function ur(e,t){let i=en();i.start("Fetching environment variables...");try{let{data:n}=await $.get(`/projects/${e}/secrets`);if(n.status==="success"){i.stop("Fetched variables.");let o=n.secrets||[];o.length===0?Se.info("No environment variables found for this project."):(Se.info(Rt.bold("Environment Variables (Global & Scoped):")),o.forEach(r=>{let l=r.visibility==="plain"?r.value:"********";console.log(` ${Rt.cyan(r.key)} = ${l} ${Rt.gray(`[${r.environment}]`)}`)}))}else i.stop(Rt.red(`Failed to fetch variables: ${n.message}`))}catch(n){i.stop("Failed to fetch variables."),Se.error(`Network error: ${n.message}`)}}import{spinner as pt,text as ut,select as ii,isCancel as Ue,cancel as ni}from"@clack/prompts";import se from"chalk";import ie from"fs";import Me from"path";import{spawn as on}from"child_process";import rn from"axios";import oi from"os";import pr from"crypto";async function sn(e){let t=pt(),i=fe(),n=`./${f.configFileName}`;if(!ie.existsSync(n)){pe(`No ${f.configFileName} found. Run \`${f.nameLower} init\` or \`${f.nameLower} link\` first.`);return}let o=JSON.parse(ie.readFileSync(n,"utf-8")),{projectId:r}=o,l=e.profile||e.buildProfile||"production";if(!r){pe(`${f.configFileName} is missing projectId.`);return}Ce(se.dim(`Submit for project: ${o.name||r} | Profile: ${l}`));let a=e.platform;if(!a){let w=await ii({message:"Select platform to submit:",options:[{value:"ios",label:"iOS (App Store Connect / TestFlight)"},{value:"android",label:"Android (Google Play Console)"}]});if(Ue(w)){ni("Operation cancelled");return}a=w}let s=await hr(r,a,e,i?.token);if(!s)return;Ce(`Using artifact: ${se.green(Me.basename(s))} `);let c=a==="android"?fr(o,l):void 0;t.start("Fetching submission credentials from Dashboard...");let d;try{let U=(await $.get(`/credentials/${r}`)).data.credentials||[];if(a==="android"&&!c){t.stop("Package name missing"),pe("Could not resolve Android package name. Set android.package in mach.config.json/app.json.");return}let b=U.filter(L=>a==="ios"?L.type==="asc_api_key":L.type==="google_service_account"&&L.bundleId===c);if(b.length===0){t.stop("Credentials missing"),pe(a==="android"?`No Google Play service credential found for package ${c}.`:`No Service Credentials found for ${a}.`),Ce(a==="android"?`Use '${f.nameLower} credentials:service --platform android --package-name ${c}' or upload it under that package in the Dashboard.`:`Use '${f.nameLower} credentials:service --platform ${a}' or use the Dashboard to upload them.`);return}if(b.length===1)d=b[0],t.stop(`Using: ${d.name}`);else{t.stop("Multiple credentials found");let L=await ii({message:`Choose a ${a==="ios"?"App Store Connect":"Google Play"} credential:`,options:b.map(m=>({value:m.credentialId,label:m.name,hint:`${m.keyId?`ID: ${m.keyId}`:""} ${m.issuerId?`(Issuer: ${m.issuerId.substring(0,8)}...)`:""}`}))});if(Ue(L)){ni("Submission cancelled");return}d=b.find(m=>m.credentialId===L),Ce(`Using selected: ${se.green(d.name)}`)}}catch(w){t.stop("Failed to fetch credentials"),pe(`API Error: ${w.message} `);return}let u=ie.mkdtempSync(Me.join(oi.tmpdir(),`${f.nameLower}-submit-`)),p=d.keyId||d.meta?.keyId,g=d.issuerId||d.meta?.issuerId,h=d.type==="asc_api_key"?`AuthKey_${p}.p8`:"service-account.json",P=Me.join(u,h);t.start("Downloading secure key...");try{let w=await $.get(`/credentials/${d.credentialId}/download`,{params:{projectId:r}});if(w.data.status!=="success"||!w.data.downloadUrl)throw new Error("Failed to get secure download URL");let U=await rn.get(w.data.downloadUrl,{responseType:"arraybuffer"});ie.writeFileSync(P,Buffer.from(U.data)),t.stop("Key downloaded to secure temp storage")}catch(w){t.stop("Download failed"),pe(`Failed to download key: ${w.message}`);try{ie.rmSync(u,{recursive:!0,force:!0})}catch{}return}Ce(se.blue(`Initiating ${a==="ios"?"TestFlight":"Google Play"} submission...`));let C=a==="android"?e.track||o.submit?.[l]?.android?.track||o.submit?.production?.android?.track||"internal":void 0,B=a==="android"?gr(o,l,e.releaseStatus):void 0;try{if(a==="ios"){if(!p){let b=await ut({message:"Enter App Store Connect Key ID (e.g. 2X948D...):",validate:L=>L.length>0?void 0:"Key ID is required"});if(Ue(b))return;p=b}if(!g||g==="undefined"){let b=await ut({message:"Enter App Store Connect Issuer ID (Found on ASC Keys page):",validate:L=>L.length>0?void 0:"Issuer ID is required"});if(Ue(b))return;g=b}Ce(`Using ASC Key ID: ${p}`),Ce(`Using ASC Issuer ID: ${g}`);let w=mr(o,l),U=await yr(s,P,g,p,w);if(U&&U.apiKeyJsonPath)throw Ce(se.cyan(`
|
|
1020
|
-
[
|
|
1021
|
-
`)),new Error("fastlane pilot execution failed");nn(`${a==="ios"?"App Store":"Google Play"} submission successful!`)}else await Sr(s,P,C,c,B),nn("Google Play submission successful!")}catch(w){pe(`Submission failed: ${w.message}`)}finally{Ar(u),s.includes(`${f.nameLower}-artifact-`)}}function fr(e,t){if(e.submit?.[t]?.android?.package)return e.submit[t].android.package;let i=pi(e,t);if(i)return i;let n=Me.join(process.cwd(),"app.json");if(ie.existsSync(n))try{return JSON.parse(ie.readFileSync(n,"utf-8")).expo?.android?.package}catch{}let o=Me.join(process.cwd(),"app.config.json");if(ie.existsSync(o))try{let r=JSON.parse(ie.readFileSync(o,"utf-8"));return r.expo?.android?.package||r.android?.package}catch{}}function mr(e,t){return e.submit?.[t]?.ios?.bundleIdentifier?e.submit[t].ios.bundleIdentifier:e.submit?.[t]?.ios?.bundleId?e.submit[t].ios.bundleId:fi(e,t)}function gr(e,t,i){return i||e.submit?.[t]?.android?.releaseStatus||e.submit?.production?.android?.releaseStatus||"completed"}async function hr(e,t,i,n){let o=i.buildId?"id":i.latest?"latest":null;if(!o){let l=await ii({message:"Select artifact source:",options:[{value:"latest",label:`Latest Production Build (${f.name})`},{value:"id",label:`Input Build ID (${f.name})`},{value:"url",label:"Remote URL"},{value:"local",label:"Local File Path"}]});if(Ue(l))return ni("Operation cancelled"),null;o=l}if(o==="local"){let l=await ut({message:"Enter path to artifact (.ipa/.aab):",validate:a=>{if(!ie.existsSync(a))return"File not found";if(t==="ios"&&!a.endsWith(".ipa"))return"Must be an .ipa file";if(t==="android"&&!a.endsWith(".aab"))return"Must be an .aab file"}});return Ue(l)?null:l}let r=pt();if(o==="latest"){let l=i.profile||i.buildProfile;r.start(`Fetching latest${l?` ${l}`:""} build...`);try{let a=await $.get(`/builds/${e}`,{params:{limit:50}});if(a.data.status!=="success")throw new Error(a.data.message);let s=a.data.builds||[],c=l?.toLowerCase(),d=b=>b.platform?.toLowerCase()===t.toLowerCase()&&b.status?.toLowerCase()==="success",u=b=>c?[b.buildProfile,b.profile,b.profileName,b.buildType].filter(Boolean).some(L=>String(L).toLowerCase()===c):!0,p=s.filter(b=>d(b)&&u(b)),g=p.find(b=>b.buildType?.toLowerCase()==="store"||b.distribution?.toLowerCase()==="store")||p[0],h=s.some(b=>b.platform?.toLowerCase()===t.toLowerCase()&&b.status?.toLowerCase()==="success");if(!g)return r.stop("No suitable build found"),pe(l&&h?`No successful ${t} builds found for profile "${l}".`:"No successful builds found for this platform."),null;r.stop(`Found build: ${g.buildId}`);let P=g.artifacts||[];if(P.length===0||P.every(b=>!(b.url||b.downloadUrl)))try{let b=await $.get(`/builds/${e}/${g.buildId}/artifacts`);b.data.status==="success"&&b.data.artifacts?.length>0?(P=b.data.artifacts.map(L=>({...L,url:L.url||L.downloadUrl})),console.log(se.cyan(` [RECOVERY] Fetched ${P.length} artifact(s) with download URLs.`))):console.log(se.yellow(" [RECOVERY] /artifacts endpoint returned 0 artifacts."))}catch(b){console.log(se.red(` [RECOVERY] /artifacts fetch failed: ${b.message}`))}let B=t==="ios",w=P.find(b=>{let L=(b.type||"").toLowerCase(),m=(b.name||"").toLowerCase();if(console.log(se.dim(` - Checking: ${b.name} (Type: ${b.type}, HasLink: ${!!(b.url||b.downloadUrl)})`)),L)return L===(B?"ipa":"aab");let D=B?".ipa":".aab",S=(b.url||b.downloadUrl||"").toLowerCase();return m.endsWith(D)||S.includes(D)});if(!w||!(w.url||w.downloadUrl))return pe("Build found but artifact URL is missing."),null;let U=w.url||w.downloadUrl;return await ti(U,B?"ios":"android")}catch(a){return r.stop("Fetch failed"),pe(`API Error: ${a.message}`),null}}if(o==="id"){let l=i.buildId||await ut({message:"Enter Build ID:",validate:a=>a.length<5?"Invalid ID":void 0});if(Ue(l))return null;r.start("Fetching build...");try{let a=await $.get(`/build/${l}`);if(a.data.status!=="success")throw new Error(a.data.message);let s=a.data.build;if(!s)throw new Error("Build not found");let c=t==="ios",d=s.artifacts?.find(u=>{if(u.type)return u.type===(c?"ipa":"aab");let p=c?".ipa":".aab";return u.name&&u.name.endsWith(p)||u.url&&u.url.includes(p)});return!d||!d.url?(r.stop("Missing artifact"),pe("Artifact URL not found on build record."),null):(r.stop(`Found build: ${s.buildId}`),await ti(d.url,c?"ios":"android"))}catch(a){return r.stop("Fetch failed"),pe(a.message),null}}if(o==="url"){let l=await ut({message:"Enter Artifact URL:",validate:a=>a.startsWith("http")?void 0:"Must be a valid URL"});return Ue(l)?null:await ti(l,t)}return null}async function ti(e,t,i=3){let n=pt();n.start("Downloading artifact...");let o=ie.mkdtempSync(Me.join(oi.tmpdir(),`${f.nameLower}-artifact-`)),r=`app.${t==="ios"?"ipa":"aab"}`,l=Me.join(o,r);for(let a=1;a<=i;a++)try{a>1&&(n.message(`Downloading artifact (Retry ${a}/${i})...`),await new Promise(d=>setTimeout(d,2e3*a)));let s=ie.createWriteStream(l),c=await rn({url:e,method:"GET",responseType:"stream",timeout:6e4});return await new Promise((d,u)=>{c.data.pipe(s);let p=!1;c.data.on("error",g=>{p||(p=!0,s.close(),u(g))}),s.on("finish",()=>{p||d()}),s.on("error",g=>{p||(p=!0,u(g))})}),n.stop("Download complete"),l}catch(s){if(a===i)throw n.stop("Download failed"),s}throw new Error("Download failed after retries")}async function yr(e,t,i,n,o){let r=pt();if(o&&Ce(`Bundled ID: ${se.green(o)}`),!i||!n)throw pe(`Missing credentials: issuerId=${i}, keyId=${n}. Check your Dashboard.`),new Error("Missing ASC API Key Metadata (IssuerID or KeyID)");let l=ie.readFileSync(t,"utf8"),a;try{a=pr.createPrivateKey(l).export({type:"pkcs8",format:"pem"})}catch{Ce("Key normalization failed, falling back to manual re-wrapping..."),a=`-----BEGIN PRIVATE KEY-----
|
|
1022
|
-
${(l.replace(/-----BEGIN[^-]*-----/g,"").replace(/-----END[^-]*-----/g,"").replace(/\s+/g,"").match(/.{1,64}/g)||[]).join(`
|
|
1081
|
+
`));try{let x=K("security find-identity -v -p codesigning",{encoding:"utf-8"});o(y.magenta(`${x}
|
|
1082
|
+
`))}catch(x){o(y.red(`[DIAGNOSTIC] Failed to list identities: ${x.message}
|
|
1083
|
+
`))}}await xe("xcodebuild",["-exportArchive","-archivePath",h,"-exportPath",w,"-exportOptionsPlist",Z],c,m,o,s),a&&await a("validate");let ge=at(w,[".ipa"]);for(let x of ge)try{K(`unzip -t "${x}"`,{stdio:"pipe"}),o&&o(`[IPA VALID] ${$.basename(x)} \u2014 archive integrity OK
|
|
1084
|
+
`)}catch{let V=`IPA validation failed for ${$.basename(x)}: archive may be corrupt`;throw o&&o(`[IPA CORRUPT] ${V}
|
|
1085
|
+
`),new Error(V)}return ge}},He=e=>{try{let t=$.join(process.cwd(),f.configFileName);if(g.existsSync(t)){let i=JSON.parse(g.readFileSync(t,"utf-8"));if(e==="android"&&i.android?.package)return i.android.package;if(e==="ios"&&i.ios?.bundleIdentifier)return i.ios.bundleIdentifier}if(e==="android"){let i=["android/app/build.gradle","app/build.gradle","build.gradle"];for(let n of i)if(g.existsSync(n)){let o=g.readFileSync(n,"utf-8").match(/applicationId\s+['"]([^'"]+)['"]/);if(o)return o[1]}}else{let i=$.resolve(process.cwd(),g.existsSync("ios")?"ios":"."),n=at(i,["Info.plist"]).filter(s=>!s.includes("/Pods/")&&!s.includes("/build/")&&!s.includes("/DerivedData/"));n.sort((s,l)=>l.split("/").length-s.split("/").length);for(let s of n){let a=g.readFileSync(s,"utf-8").match(/<key>CFBundleIdentifier<\/key>\s*<string>([^<]+)<\/string>/);if(a&&!a[1].includes("$"))return a[1]}let r=at(i,[".xcodeproj"]);if(r.length>0){let s=$.join(r[0],"project.pbxproj");if(g.existsSync(s)){let a=g.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(g.existsSync(s)){let a=g.readFileSync(s,"utf-8").match(/"bundleIdentifier":\s*"([^"]+)"/);if(a)return a[1]}}}catch{return null}return null},go=()=>{try{return K("emulator -version",{stdio:"ignore"}),"emulator"}catch{let t=ue.homedir(),i=[$.join(t,"Library/Android/sdk/emulator/emulator"),$.join(t,"Android/Sdk/emulator/emulator"),"/usr/local/lib/android/sdk/emulator/emulator"];for(let n of i)if(g.existsSync(n))return n}return"emulator"},ho=async(e,t)=>{let i=Mt();try{if(K("adb devices").toString().split(`
|
|
1086
|
+
`).slice(1).map(s=>s.trim()).filter(s=>s.length>0&&!s.startsWith("*")).map(s=>s.split(" ")[0]).length===0){E.warn(y.yellow("No Android devices or emulators found."));let s=go(),l=[];try{l=K(`${s} -list-avds`).toString().split(`
|
|
1087
|
+
`).filter(a=>a.trim().length>0)}catch{}if(l.length>0){let a=await ci({message:"Select an emulator to launch:",options:l.map(u=>({value:u,label:u}))});if(Ht(a))return;i.start(`Launching emulator ${a}...`),dn(s,["-avd",a],{detached:!0,stdio:"ignore"}).unref();let c=0,d=!1;for(;c<60;){try{if(K("adb shell getprop sys.boot_completed",{stdio:"pipe"}).toString().trim()==="1"){d=!0;break}}catch{}await new Promise(u=>setTimeout(u,2e3)),c++}if(!d)throw i.stop("Emulator launch timed out."),new Error("Emulator launch timed out. Please try launching it manually.");i.stop("Emulator launched.")}else throw new Error("No devices found and no emulators available to launch. (Make sure Android SDK is installed)")}i.start("Installing APK on device..."),await xe("adb",["install","-r",e],process.cwd(),{},t),i.stop("Installation complete.");let o=He("android");if(o){E.info(y.blue(`\u{1F680} Launching ${o}...`));try{K(`adb shell dumpsys package ${o}`).toString().split(`
|
|
1088
|
+
`).find(a=>a.includes("android.intent.action.MAIN")&&a.includes("android.intent.category.LAUNCHER"))?K(`adb shell monkey -p ${o} -c android.intent.category.LAUNCHER 1`,{stdio:"ignore"}):K(`adb shell monkey -p ${o} -c android.intent.category.LAUNCHER 1`,{stdio:"ignore"})}catch{E.warn("Could not auto-launch app. You may need to open it manually.")}}}catch(n){i.stop("Installation failed."),E.error(y.red(`Failed to install APK: ${n.message}`))}},yo=async(e,t,i)=>{let n=Mt();try{if(!K("xcrun simctl list devices booted").toString().includes("(Booted)")){E.warn(y.yellow("No iOS Simulator is currently booted."));let o=K("xcrun simctl list devices --json").toString(),s=JSON.parse(o).devices,l=[];Object.keys(s).forEach(u=>{s[u].forEach(p=>{p.isAvailable&&l.push({...p,runtime:u})})});let a=await ci({message:"Select a simulator to launch:",options:l.map(u=>({value:u.udid,label:`${u.name} (${u.runtime.split(".").pop()})`}))});if(Ht(a))return;n.start(`Booting ${a}...`),K(`xcrun simctl boot ${a}`),K(`open -a Simulator --args -CurrentDeviceUDID ${a}`);let c=0,d=!1;for(;c<30;){try{if(K("xcrun simctl list devices booted").toString().includes(a)){d=!0;break}}catch{}await new Promise(u=>setTimeout(u,2e3)),c++}if(!d)throw n.stop("Simulator boot timed out."),new Error("Simulator boot timed out.");n.stop("Simulator booted.")}n.start("Installing on iOS Simulator..."),await xe("xcrun",["simctl","install","booted",e],process.cwd(),{},i),n.stop("Installation complete."),E.info(y.blue(`\u{1F680} Launching ${t}...`)),await xe("xcrun",["simctl","launch","booted",t],process.cwd(),{},i)}catch(r){n.stop("Installation failed."),E.error(y.red(`Failed to install on Simulator: ${r.message}`))}},So=async(e,t,i)=>{let n=Mt();n.start("Scanning for connected iOS devices...");try{let r=K("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 n.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){n.stop();let a=await ci({message:"Select a device to install on:",options:s.map(c=>({value:c.identifier,label:`${c.deviceProperties?.name||c.name||c.model?.name} (${c.model?.name||"iPhone"}) - ${c.identifier}`}))});if(Ht(a))return;l=a,n.start(`Installing on ${l}...`)}else n.message(`Installing on ${s[0].model.name}...`);await xe("xcrun",["devicectl","device","install","app","--device",l,e],process.cwd(),{},i),n.stop("Installation complete."),E.info(y.blue(`\u{1F680} Launching ${t}...`)),await xe("xcrun",["devicectl","device","launch","app","--device",l,t],process.cwd(),{},i)}catch(r){n.stop("Installation failed."),E.error(y.red(`Failed to install on device: ${r.message}`)),E.info(y.dim('Make sure your device is unlocked and "Developer Mode" is enabled in Settings -> Privacy & Security.'))}};import fn from"fs";import mn from"path";import{isCancel as ui,log as Fe,select as gn,spinner as Eo,text as bo}from"@clack/prompts";import lt from"chalk";async function hn(e){let t=await pi(e);t&&(Fe.success(lt.green(`Maestro run ${t.status||"queued"}: ${t.testRunId}`)),t.launchDeferredReason&&Fe.warn(lt.yellow(t.launchDeferredReason)),t.dashboardUrl&&Fe.info(lt.dim("View test run: ")+lt.white.underline(t.dashboardUrl)))}async function pi(e){let t=Te(`./${f.configFileName}`),i=e.projectId||t?.projectId,n=e.profile||e.buildProfile||"production";if(!i)return Fe.error(`No projectId found. Run \`${f.nameLower} link\` first or pass an internal project id.`),null;let r=e.platform;if(!r&&e.latest){let a=await gn({message:"Select platform for the latest build:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"}]});if(ui(a))return null;r=a}let o=await Ao(e);if(!o)return null;if(o.kind==="latest"&&!r)return Fe.error("Pass --platform when using --latest."),null;if(o.kind==="artifact-url"&&!r)return Fe.error("Pass --platform when using --artifact-url."),null;let s=Io(e.maestroRetries);if(s===null)return null;let l=Eo();e.quiet||l.start("Queuing Maestro run...");try{let a=await v.post("/tests/maestro",{projectId:i,platform:r,profile:n,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,flows:e.maestroFlows||".maestro",device:e.maestroDevice||(r==="ios"?"iphone_15":"pixel_6"),retries:s,record:!!e.maestroRecord});if(a.data.status!=="success")throw new Error(a.data.message||"Failed to queue Maestro run");let c=a.data.testRun,d={testRunId:c.testRunId,status:c.status,projectId:i,buildId:c.buildId,platform:c.platform,dashboardUrl:c.dashboardUrl||`${Ge}/tests/${c.testRunId}`,launchDeferredReason:c.launchDeferredReason};return _o(e,d),e.quiet||l.stop("Maestro run queued"),d}catch(a){e.quiet||l.stop("Could not queue Maestro run");let c=a.response?.data?.message||a.message||"Unknown error";return Fe.error(lt.red(`Maestro queue failed: ${c}`)),null}}async function Ao(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 gn({message:"Select app artifact source for Maestro:",options:[{value:"latest",label:"Latest successful build"},{value:"build-id",label:"Build ID"},{value:"build-url",label:`${f.name} build URL`},{value:"artifact-url",label:"Direct artifact URL"}]});if(ui(t))return null;if(t==="latest")return{kind:"latest"};let i=await bo({message:t==="build-id"?"Enter build ID:":t==="build-url"?`Enter ${f.name} build URL:`:"Enter artifact URL:",validate:n=>{let r=String(n||"").trim();if(!r)return"Value is required";if((t==="build-url"||t==="artifact-url")&&!r.startsWith("http"))return"Must be a URL"}});return ui(i)?null:{kind:t,value:String(i).trim()}}function Io(e){if(e==null||e==="")return 1;let t=Number(e);return!Number.isInteger(t)||t<0||t>10?(Fe.error("--maestro-retries must be an integer between 0 and 10."),null):t}function _o(e,t){if(!e.jsonOutput)return;let i=mn.resolve(e.jsonOutput),n={...t,updatedAt:new Date().toISOString()};try{let r=mn.dirname(i);r&&r!=="."&&fn.mkdirSync(r,{recursive:!0}),fn.writeFileSync(i,JSON.stringify(n,null,2))}catch(r){Fe.warn(lt.yellow(`Could not write Maestro metadata JSON: ${r.message}`))}}var Ft=8,wo=e=>new Promise(t=>setTimeout(t,e)),Do=e=>{let t=e.response?.status;return t?t===408||t===429||t>=500:!0},Bt=e=>e.credentialId||e.id,Ro=async(e,t)=>{let i=Bt(e);if(!i)return e.downloadUrl;let n=await v.get(`/credentials/${i}/download`,{params:{projectId:t}});return n.data?.status==="success"&&n.data?.downloadUrl?n.data.downloadUrl:e.downloadUrl},vo=async(e,t)=>{let i=e.downloadUrl;for(let n=1;n<=Ft;n++)try{if((!i||n>1)&&(i=await Ro(e,t)),!i)throw new Error(`Credential ${e.name||Bt(e)||"unknown"} has no download URL.`);let r=await Et.get(i,{responseType:"arraybuffer",timeout:6e4,maxContentLength:1/0,maxBodyLength:1/0,headers:{Connection:"close"}});return Buffer.from(r.data).toString("base64")}catch(r){if(n>=Ft||!Do(r))throw r;let o=Math.min(1500*n*n,15e3);C.warn(T.dim(` - Temporary network error downloading ${e.name}. Retrying... (${n}/${Ft})`)),await wo(o)}throw new Error(`Failed to download credential ${e.name||Bt(e)||"unknown"}.`)},Gt=async e=>{e.platform!=="android"&&e.platform!=="ios"&&(C.error(`Platform ${e.platform} is not supported. Use 'android' or 'ios'.`),process.exit(1));let t=fi(),i=e.buildId||Po(),n=e.projectId,r=Date.now(),o=!!n,s=async l=>{if(n)try{await v.patch(`/builds/${n}/${i}`,{status:"failed",error:l})}catch{}};if(e.local&&e.buildId){e.quiet||t.start(`Preparing isolated workspace for build: ${e.buildId}`);try{let l=await v.get(`/builds/${n}/${e.buildId}/source-url`);if(l.data.status!=="success")throw new Error("Failed to get source download URL from API");let a=await Et.get(l.data.downloadUrl,{responseType:"stream"}),c=(n||e.projectId||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),d=Ee.join($o.homedir(),f.workspacesDir,c);le.mkdirSync(d,{recursive:!0});let u=new Set(["node_modules",`.${f.nameLower}-cache-meta`]),p=new Set(["Pods"]);if(le.existsSync(d)){let H=le.readdirSync(d);for(let F of H){if(u.has(F))continue;if(F==="ios"){let b=Ee.join(d,"ios");try{let G=le.readdirSync(b);for(let _ of G)if(!p.has(_))try{le.rmSync(Ee.join(b,_),{recursive:!0,force:!0})}catch{}}catch{}continue}let z=Ee.join(d,F);try{le.rmSync(z,{recursive:!0,force:!0})}catch{}}}let m=Ee.join(d,"source.zip"),S=a.data,D=le.createWriteStream(m);await new Promise((H,F)=>{S.pipe(D),S.on("error",z=>F(z)),D.on("finish",()=>H())}),new bn(m).extractAllTo(d,!0);try{le.unlinkSync(m)}catch{}process.chdir(d),C.info(T.green(`\u2713 Persistent workspace ready: ${d}`)),C.info(T.dim(` \u{1F4E6} Cached dirs preserved: node_modules=${le.existsSync(Ee.join(d,"node_modules"))?"\u2705":"\u274C"}, Pods=${le.existsSync(Ee.join(d,"ios","Pods"))?"\u2705":"\u274C"}`)),t.stop()}catch(l){t.stop(`Failed to prepare isolated workspace: ${l.message}`),n&&await s(`Setup Error: ${l.message}`),process.exit(1)}}try{let l=e.repo;if(!l)try{l=En("git config --get remote.origin.url").toString().trim()}catch{C.warn("Could not detect git repository URL.")}!l&&e.dryRun,l||(l="https://github.com/placeholder/repo.git"),C.info(`Build ID: ${T.cyan(i)}`);let a={},c={},d=Te(`./${f.configFileName}`);if(d){n=d.projectId;let _=e.buildProfile||"production",h=Je(d,_);!h&&e.buildProfile&&(C.error(`Build profile '${_}' not found in ${f.configFileName}`),process.exit(1));let w=h||{};process.env.MACH_DEBUG&&C.info(T.dim(`Build profile: ${_} | Platform: ${e.platform} | Distribution: ${w.distribution||"store"} | Environment: ${w.environment||_}`)),w.env&&(c=w.env,C.info(T.blue(`Use Build Profile: ${_}`)));let R=e.platform,L=w[R]||{},U=["developmentClient","simulator","distribution","buildCommand","apk","iosScheme","preBuild","postBuild","scheme","environment","androidPackage","iosBundleIdentifier","name","iosDeploymentTarget","iosApiKeyId","iosApiKeyIssuer","iosApiKeyPath","iosTeamId","iosConfiguration","iosExportMethod","branch","repo","instanceType","ami","bucket","region","nodeVersion"];e.name=d.name,e.appName=d.name,e.androidPackage=d.android?.package,e.iosBundleIdentifier=d.ios?.bundleIdentifier,e.iosScheme=d.ios?.iosScheme,!e.nodeVersion&&d.nodeVersion&&(e.nodeVersion=d.nodeVersion);let P=N=>N==="androidPackage"?L.androidPackage??L.package??w.androidPackage??w.android?.package:N==="iosBundleIdentifier"?L.iosBundleIdentifier??L.bundleIdentifier??w.iosBundleIdentifier??w.ios?.bundleIdentifier:L[N]!==void 0?L[N]:w[N];for(let N of U){let B=P(N),j=N==="androidPackage"||N==="iosBundleIdentifier";B!==void 0&&(e[N]===void 0||j)&&(e[N]=B)}e.branch=e.branch||"main",e.iosConfiguration=e.iosConfiguration||(e.developmentClient||e.simulator?"Debug":"Release"),e.sshUser=e.sshUser||process.env.USER||"ubuntu",e.simulator===void 0&&(e.simulator=!1),e.local===void 0&&(e.local=!1),e.verbose===void 0&&(e.verbose=!1);let k=N=>{if(!N)return N;if(N.startsWith("scripts.")){let B=N.split(".")[1],j=d.scripts?.[B];if(j)return j;C.warn(`Script reference not found: ${N}`)}return N};e.buildCommand=k(e.buildCommand),e.preBuild=k(e.preBuild),e.postBuild=k(e.postBuild),!e.scheme&&d.scheme&&(e.scheme=d.scheme);let I={...rt(d,f.envPrefix),...rt(w,`${f.envPrefix}PROFILE_`)};a={...a,...c,...I},process.env.IOS_P12_PASSWORD&&!a.IOS_P12_PASSWORD&&(a.IOS_P12_PASSWORD=process.env.IOS_P12_PASSWORD),process.env.MATCH_PASSWORD&&!a.MATCH_PASSWORD&&(a.MATCH_PASSWORD=process.env.MATCH_PASSWORD),e.platform==="ios"&&(!e.iosTeamId&&w.ios?.appleTeamId&&(e.iosTeamId=w.ios.appleTeamId),!e.iosTeamId&&d.submit?.[_]?.ios?.appleTeamId&&(e.iosTeamId=d.submit[_].ios.appleTeamId),!e.iosTeamId&&d.submit?.production?.ios?.appleTeamId&&(C.warn(T.yellow(`Check: Using 'production' Team ID for '${_}' build.`)),e.iosTeamId=d.submit.production.ios.appleTeamId),e.iosTeamId?C.info(T.magenta(`\u2713 Injected iOS Team ID from config: ${e.iosTeamId}`)):C.warn(T.yellow("\u26A0\uFE0F No iOS Team ID found. Signing might fail if not managed automatically via Expo.")))}let u="unknown";try{u=En("git rev-parse --abbrev-ref HEAD").toString().trim()}catch{C.warn("Failed to detect git branch.")}let p="1.0.0";try{le.existsSync("./package.json")&&(p=JSON.parse(le.readFileSync("./package.json","utf-8")).version||"1.0.0")}catch{}let m=e.buildProfile||"production",S="Internal";e.developmentClient?S="DevelopmentClient":m.toLowerCase().includes("store")||m.toLowerCase()==="production"?S="Store":m.toLowerCase().includes("preview")||m.toLowerCase().includes("staging")?S="Staging":(m.toLowerCase().includes("development")||m.toLowerCase().includes("dev"))&&(S="Development");let D=e.platform==="ios"?"iOS":"Android",A=e.platform==="ios"&&e.simulator?" (Simulator)":"",H=`${D}${A} v${p} (${S})`;if(bt(e,{status:"created",projectId:n,buildId:i,platform:e.platform,profile:m,branch:u,version:p,buildType:S,developmentClient:!!e.developmentClient,summary:H}),n){try{let _=e.buildProfile||"production",h=e.environment||_;C.info(T.blue(`Fetching managed secrets for profile: ${_} (environment: ${h})...`));let R=(await v.get(`/projects/${n}/secrets/export?env=${h}`)).data;R.status==="success"&&R.secrets&&(a={...a,...R.secrets},Object.keys(R.secrets).length>0&&C.info(T.magenta(`\u2713 Injected ${Object.keys(R.secrets).length} secrets from Dashboard.`)))}catch(_){C.warn(`Failed to load managed secrets from Dashboard: ${_.message}`)}try{C.info(T.blue("Fetching managed credentials..."));let _="development";e.distribution==="store"?_="store":e.distribution==="internal"&&(_=e.platform==="ios"?"adhoc":"internal"),e.developmentClient&&(_="development");let h=await v.get("/credentials/resolve",{params:{projectId:n,platform:e.platform,bundleId:e.iosBundleIdentifier||e.androidPackage,distributionType:_}});if(h.data.status==="success"&&h.data.credentials){let w=h.data.credentials;C.info(T.magenta(`\u2713 Found ${w.length} relevant credentials.`));let R=w.filter(I=>{if(I.distributionType){let N=_==="internal"?"adhoc":_;return I.distributionType===N||I.distributionType===_}return!0});C.info(T.dim(` Filtered to ${R.length} credentials for distributionType: ${_}`));let L=!1,U=!1,P=!1,k=[];for(let I of R)if(!(I.type==="ios_cert"&&L||I.type==="ios_profile"&&U||I.type==="android_keystore"&&P)&&["ios_cert","ios_profile","android_keystore"].includes(I.type)&&(I.downloadUrl||Bt(I)))try{let B=await vo(I,n);if(I.type==="ios_cert"&&!L)a.IOS_DIST_P12=B,I.password?(a.IOS_P12_PASSWORD=I.password,C.info(T.dim(` - Injected ${I.name} as IOS_DIST_P12 with password from credential record`))):C.info(T.dim(` - Injected ${I.name} as IOS_DIST_P12`)),L=!0;else if(I.type==="ios_profile"&&!U)a.IOS_PROVISIONING_PROFILE=B,C.info(T.dim(` - Injected ${I.name} as IOS_PROVISIONING_PROFILE`)),U=!0;else if(I.type==="android_keystore"&&!P){a.ANDROID_KEYSTORE_BASE64=B;let j=I.keystorePassword||I.password,se=I.keyPassword||I.keystorePassword||I.password,Z=I.alias||I.meta?.alias;if(j)a.ANDROID_STORE_PASSWORD=j,C.info(T.dim(" - Injected keystore password from credential record"));else{let x=["ANDROID_STORE_PASSWORD",...[_==="store"?"PRODUCTION":_==="internal"?"STAGING":"DEVELOPMENT",_.toUpperCase(),"PRODUCTION","STORE","INTERNAL","STAGING","RELEASE","DEBUG"].map(O=>`KEYSTORE_PASSWORD_${O}`),"KEYSTORE_PASSWORD"].find(O=>!!a[O]);x&&a[x]&&(a.ANDROID_STORE_PASSWORD=a[x])}if(se?(a.ANDROID_KEY_PASSWORD=se,C.info(T.dim(" - Injected key password from credential record"))):a.ANDROID_KEY_PASSWORD=a.ANDROID_STORE_PASSWORD||"",Z)a.ANDROID_KEY_ALIAS=Z;else{let Pe=["ANDROID_KEY_ALIAS","KEYSTORE_ALIAS"].find(ge=>!!a[ge]);Pe&&(a.ANDROID_KEY_ALIAS=a[Pe])}C.info(T.dim(` - Injected ${I.name} as ANDROID_KEYSTORE_BASE64`)),P=!0}}catch(B){k.push(`${I.name||I.type}: ${B.message}`)}if(k.length>0)throw new Error(`Credential download failed after ${Ft} attempts:
|
|
1089
|
+
${k.map(I=>`- ${I}`).join(`
|
|
1090
|
+
`)}`)}if(e.platform==="android"){let w=e.buildProfile||"production",R=Je(d,w)||{},P=((R.android||{}).versionCode??R.androidVersionCode??d.android?.versionCode??d.expo?.android?.versionCode)==="auto",k=e.autoVersion||P&&e.distribution==="store";if(P&&!k&&C.info(T.dim(` Skipping Google Play versionCode lookup for ${e.distribution||"non-store"} build. Pass --auto-version to force it.`)),k){t.start("Resolving latest versionCode from Google Play...");try{let I=e.androidPackage||d.android?.package||d.expo?.android?.package||d.name,N=(h.data.credentials||[]).find(ge=>ge.type==="google_service_account"&&(!ge.bundleId||ge.bundleId===I));if(!N){let x=((await v.get(`/credentials/${n}`)).data.credentials||[]).filter(O=>O.type==="google_service_account");if(N=x.find(O=>O.type==="google_service_account"&&O.bundleId===I),!N&&x.length>0){let O=x.map(V=>V.bundleId).filter(Boolean).join(", ");throw new Error(`Google Service Account not found for package ${I}. Found service credential(s) for: ${O}.`)}}if(!N)throw new Error(`Google Service Account not found for package ${I}. Upload it under this package in Dashboard or run '${f.nameLower} credentials:service --platform android --package-name ${I}'.`);let B=await v.get(`/credentials/${N.credentialId}/download`,{params:{projectId:n}});if(B.data.status!=="success"||!B.data.downloadUrl)throw new Error("Failed to get secure download URL for service account");let se=(await Et.get(B.data.downloadUrl,{headers:{Connection:"close"}})).data,Z=await on(I,se);if(Z==null)throw new Error("Could not retrieve any version information from Google Play.");let Pe=Z+1;a.ANDROID_VERSION_CODE=Pe.toString(),t.stop(`\u2713 Resolved versionCode: ${T.green(Pe)} (Latest on Play Store: ${Z})`)}catch(I){t.stop("Version resolution failed");let N=I.response?.data?.error?.message||I.message;throw new Error(`Auto-versioning failed: ${N}. Fix Google Play service account permissions or remove android.versionCode="auto".`)}}}if(e.platform==="ios"&&!e.simulator){let w=!!a.IOS_DIST_P12,R=!!a.IOS_PROVISIONING_PROFILE;if(!w||!R){let L=[...w?[]:["Distribution Certificate"],...R?[]:["Provisioning Profile"]].join(" and ");C.error(T.red(`Missing iOS credentials: ${L}`)),e.quiet&&process.exit(1);let U=e.yes||await yn({message:"Would you like to generate these credentials now?",initialValue:!0});if(U&&!Sn(U))return await gt({platform:"ios",profile:m}),e.quiet||C.info(T.green("\u2713 Credentials setup complete! Restarting build phase...")),Gt(e);e.quiet||C.info(T.yellow(`Run \`${f.nameLower} credentials\` to set up signing credentials manually.`)),process.exit(1)}}if(e.platform==="android"&&!e.developmentClient&&(e.distribution==="internal"||e.distribution==="store")&&!(!!a.ANDROID_KEYSTORE_BASE64||!!a.ANDROID_KEYSTORE)){C.error(T.red("Missing Android credentials: Signing Keystore")),e.quiet&&process.exit(1);let R=e.yes||await yn({message:"Would you like to automatically create and upload an Android Keystore for this profile now?",initialValue:!0});if(R&&!Sn(R))return await gt({platform:"android",profile:m}),e.quiet||C.info(T.green("\u2713 Android Keystore setup complete! Restarting build phase...")),Gt(e);e.quiet||C.info(T.yellow(`Run \`${f.nameLower} credentials --platform android\` to set up a signing keystore manually.`)),process.exit(1)}}catch(_){String(_.message||"").startsWith("Credential download failed")&&(C.error(T.red(_.message)),process.exit(1)),C.warn(`Failed to resolve credentials: ${_.message}`)}}let F=!!(e.local&&e.buildId),z=!!(e.local||e.sshHost),b=!z&&!F;if(F){C.info(T.magenta("\u{1F3D7}\uFE0F Runner Mode: Executing isolated build task..."));let _=await di({...e,interactive:!1},i,a,n,{branch:u,version:p,summary:H,buildType:S});await G(_),process.exit(0)}async function G(_){if(n&&_.length>0){let h=fi(),w=[];e.quiet||h.start("Uploading artifacts to Dashboard...");try{for(let R of _){let L=Ee.basename(R),U=le.readFileSync(R),P=Ee.extname(L).toLowerCase(),k="application/octet-stream",I=await v.post(`/builds/${n}/${i}/artifact-upload-url`,{fileName:L,fileType:k});if(I.data.status!=="success")throw new Error(`Failed to get upload URL for ${L}`);let N=!1;for(let B=1;B<=3;B++)try{await Et.put(I.data.uploadUrl,U,{headers:{"Content-Type":k},maxBodyLength:1/0,maxContentLength:1/0,timeout:12e4}),N=!0;break}catch(j){if(C.warn(T.yellow(`Artifact upload attempt ${B}/3 failed (${j.code||j.message})`)),B<3)await new Promise(se=>setTimeout(se,3e3*B));else throw j}N&&w.push({name:L,url:I.data.downloadUrl,size:U.length,type:P.substring(1)})}e.quiet||h.stop("Artifacts uploaded.")}catch(R){e.quiet||h.stop("Failed to upload artifacts."),C.error(T.red(`Upload error: ${R.message}`));try{await v.patch(`/builds/${n}/${i}`,{status:"completed",artifacts:_.map(L=>Ee.basename(L)),endTime:Date.now()})}catch(L){C.warn(T.yellow(`Could not set fallback build status: ${L.message}`))}return}if(n&&w.length>0)try{C.info(T.cyan(`
|
|
1091
|
+
\u{1F517} Download Links:`));for(let R of w)C.info(T.dim(` - ${R.name}: `)+T.blue.underline(R.url));await v.patch(`/builds/${n}/${i}`,{status:"success",artifacts:w,endTime:Date.now()}),bt(e,{status:"success",projectId:n,buildId:i,platform:e.platform,profile:m,branch:u,version:p,buildType:S,developmentClient:!!e.developmentClient,summary:H,artifacts:w}),C.success(T.green(`
|
|
1092
|
+
\u2713 Build completed and reported to dashboard.`)),e.maestro&&!F&&await An(n,i,e,m)}catch(R){C.warn(T.yellow(`
|
|
1093
|
+
\u26A0\uFE0F Could not report to dashboard: ${R.message}`))}}else if(n)try{await v.patch(`/builds/${n}/${i}`,{status:"completed",endTime:Date.now()}),bt(e,{status:"completed",projectId:n,buildId:i,platform:e.platform,profile:m,branch:u,version:p,buildType:S,developmentClient:!!e.developmentClient,summary:H})}catch{}}if(z){if(C.info(T.cyan(`\u{1F680} Direct Build Mode: Executing on ${e.sshHost||"local"}...`)),n&&!o){let _=process.argv.slice(3).join(" ");await v.post("/builds",{projectId:n,buildId:i,platform:e.platform,status:"building",branch:u,version:p,summary:H,startTime:r,buildType:S,buildProfile:m,buildArgs:_,simulator:!!e.simulator,developmentClient:!!e.developmentClient})}if(e.sshHost&&e.platform==="ios"){let _=await nn(e,i,a,n)}else{let _=await di({...e,interactive:!!e.local},i,a,n,{branch:u,version:p,summary:H,buildType:S});await G(_)}return}if(b&&(C.info(T.blue("\u{1F6F0}\uFE0F Cloud Initiator Mode: Preparing orchestration...")),!e.dryRun)){e.quiet||t.start("Zipping and uploading local source...");let _=await v.post("/builds/source-upload-url",{projectId:n,buildId:i});if(_.data.status!=="success")throw t.stop("Failed to get upload URL."),new Error("Failed to get source upload URL from API");let h=new bn,w=le.readdirSync("."),R=["node_modules",".git","dist","build","builds",".gradle",".idea","android/build","ios/build","ios/Pods",`.${f.nameLower}_cli`];for(let P of w){if(R.includes(P))continue;le.statSync(P).isDirectory()?h.addLocalFolder(P,P):h.addLocalFile(P)}let L=h.toBuffer();e.quiet||t.message(`Uploading source (${(L.length/1024/1024).toFixed(1)} MB)...`);let U=!1;for(let P=1;P<=3;P++)try{await Et.put(_.data.uploadUrl,L,{headers:{"Content-Type":"application/zip"},maxBodyLength:1/0,maxContentLength:1/0,timeout:12e4}),U=!0;break}catch(k){if(P<3)t.message(`Upload attempt ${P} failed (${k.code||k.message}), retrying...`),await new Promise(I=>setTimeout(I,2e3*P));else throw k}if(e.quiet||t.stop("Source uploaded"),n){let P=process.argv.slice(3).join(" ");await v.post("/builds",{projectId:n,buildId:i,platform:e.platform,status:"pending",branch:u,version:p,summary:H,startTime:r,buildType:S,buildProfile:m,buildArgs:P,simulator:!!e.simulator,developmentClient:!!e.developmentClient}),C.info(T.green("\u2713 Cloud build registered."))}e.platform==="android"&&await Qi(e,i,a,n,e.preBuild),e.quiet||C.info(T.cyan("\u{1F4E1} Connecting to build stream...")),await Oo(n,i,e),e.maestro&&await An(n,i,e,m);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."),n&&!e.local&&await s(a),C.error(T.red(`\u2717 Build failed: ${a}`)),process.exit(1)}};async function An(e,t,i,n){C.info(T.cyan(`
|
|
1094
|
+
\u{1F3BC} Queuing managed Maestro test...`)),await pi({projectId:e,buildId:t,platform:i.platform,profile:n,maestroFlows:i.maestroFlows,maestroDevice:i.maestroDevice,maestroRetries:i.maestroRetries,maestroRecord:i.maestroRecord,quiet:i.quiet})}function In(e){return`${Ge}/build/${e}`}function bt(e,t){if(!e.jsonOutput)return;let i=Ee.resolve(e.jsonOutput),n={...t,url:t.url||In(t.buildId),dashboardUrl:t.dashboardUrl||In(t.buildId),updatedAt:new Date().toISOString()};try{let r=Ee.dirname(i);r&&r!=="."&&le.mkdirSync(r,{recursive:!0}),le.writeFileSync(i,JSON.stringify(n,null,2))}catch(r){C.warn(T.yellow(`Could not write build metadata JSON: ${r.message}`))}}async function Oo(e,t,i){let n=fi(),r="pending",o=0,s=0;for(i.quiet||n.start("Connecting to build stream...");;){try{let a=(await v.get(`/builds/${e}/${t}`)).data.build;if(a){if(r=a.status,r==="building")i.quiet||n.message("Build in progress...");else if(r==="failed")i.quiet||n.stop("Build failed."),bt(i,{status:"failed",projectId:e,buildId:t,platform:i.platform,profile:a.buildProfile,buildType:a.buildType,developmentClient:!!a.developmentClient,version:a.version,summary:a.summary,error:a.error||"Unknown error",artifacts:a.artifacts||[]}),C.error(T.red(`
|
|
1095
|
+
\u2717 Build failed: ${a.error||"Unknown error"}`)),process.exit(1);else if(r==="completed"||r==="success"){i.quiet||n.stop("Build successful!"),bt(i,{status:r,projectId:e,buildId:t,platform:i.platform,profile:a.buildProfile,buildType:a.buildType,developmentClient:!!a.developmentClient,version:a.version,summary:a.summary,artifacts:a.artifacts||[]}),C.success(T.green(`
|
|
1096
|
+
\u2713 Build completed successfully!`));try{i.quiet||(C.info(T.magenta(`
|
|
1097
|
+
\u{1F4F1} Installation Hub:`)),C.info(T.dim(" - View & Install Build: ")+T.white.underline(`${Ge}/build/${t}`)))}catch{}return}else if(r!=="pending"){i.quiet||n.stop(`Build status: ${r}`);return}}try{let d=(await v.get(`/builds/${e}/${t}/logs`)).data;if(d&&typeof d=="string"&&!i.quiet){let u=d.split(`
|
|
1098
|
+
`);if(u.length>o){for(let p=o;p<u.length;p++)u[p].trim()&&console.log(T.dim(` ${u[p]}`));o=u.length}}}catch{}s=0}catch{s++,s>10&&(n.stop("Connection lost."),C.error(T.red(`
|
|
1099
|
+
\u2717 Lost connection to Dashboard API.`)),process.exit(1))}await new Promise(l=>setTimeout(l,3e3))}}import Co from"http";import{execSync as De,spawn as _n}from"child_process";import mi from"chalk";import{log as ct}from"@clack/prompts";import No from"axios";import hi from"fs";import To from"os";import gi from"path";var At=7070;function ko(){let e=[];try{let t=De("adb devices -l",{stdio:"pipe"}).toString(),i=new Set;t.split(`
|
|
1100
|
+
`).forEach(n=>{if(n.includes("List of devices")||!n.trim())return;let r=n.split(/\s+/);if(r.length<2||r[1]!=="device")return;let o=r[0];i.add(o);let s=n.match(/model:([^\s]+)/);e.push({id:o,platform:"android",type:o.startsWith("emulator-")?"emulator":"physical",name:s?s[1].replace(/_/g," "):o,status:"online",details:n.trim()})})}catch{}try{let t=`${process.env.ANDROID_HOME||`${process.env.HOME}/Library/Android/sdk`}/emulator/emulator`,n=De(`${t} -list-avds`,{stdio:"pipe"}).toString().split(`
|
|
1101
|
+
`).filter(o=>!!o.trim()),r=e.some(o=>o.platform==="android"&&o.id.startsWith("emulator-"));n.forEach(o=>{r||e.push({id:o,platform:"android",type:"emulator",name:o.replace(/_/g," "),status:"offline",details:`Android Virtual Device: ${o}`})})}catch{}if(process.platform!=="darwin")return e;try{let t=De("/usr/bin/xcrun simctl list devices --json",{stdio:"pipe"}).toString(),i=JSON.parse(t);Object.entries(i.devices).forEach(([n,r])=>{r.forEach(o=>{o.isAvailable&&e.push({id:o.udid,platform:"ios",type:"simulator",name:o.name,status:o.state?.toLowerCase()==="booted"?"online":"offline",runtime:n,details:`${o.name} (${n})`})})})}catch{}try{let t=De("/usr/bin/xcrun devicectl list devices --json-output -",{stdio:"pipe"}).toString();(JSON.parse(t).result?.devices||[]).forEach(n=>{let r=n.connectionProperties?.transportType;(r==="wired"||r==="localNetwork")&&e.push({id:n.identifier,platform:"ios",type:"physical",name:n.deviceProperties?.name||"iPhone",status:"online",details:`${n.deviceProperties?.name||"iPhone"} (${n.model?.name||n.hardwareModel||""}) - ${r}`})})}catch{}return e}async function Pn(e){let t=[];for await(let i of e)t.push(Buffer.isBuffer(i)?i:Buffer.from(i));return t.length===0?{}:JSON.parse(Buffer.concat(t).toString("utf-8"))}async function xo(e,t){let i=await No({method:"GET",url:e,responseType:"stream",timeout:12e4}),n=hi.createWriteStream(t);i.data.pipe(n),await new Promise((r,o)=>{n.on("finish",r),n.on("error",o)})}async function Lo(e,t,i){let n=i||(t.toLowerCase().includes(".apk")?"android":"ios"),r=t.toLowerCase().includes(".ipa"),o=hi.mkdtempSync(gi.join(To.tmpdir(),`${At}-install-`)),s=gi.join(o,n==="android"?"install.apk":r?"install.ipa":"install.zip");try{if(await xo(t,s),n==="android"){De(`adb -s ${JSON.stringify(e)} install -r ${JSON.stringify(s)}`,{stdio:"pipe"});return}if(process.platform!=="darwin")throw new Error("iOS local install requires macOS.");De(`unzip -o ${JSON.stringify(s)} -d ${JSON.stringify(o)}`,{stdio:"pipe"});let l="";try{l=De(`find ${JSON.stringify(gi.join(o,"Payload"))} -maxdepth 1 -name "*.app" 2>/dev/null | head -n 1`,{stdio:"pipe"}).toString().trim()}catch{}if(l||(l=De(`find ${JSON.stringify(o)} -name "*.app" -type d | head -n 1`,{stdio:"pipe"}).toString().trim()),!l)throw new Error(`No .app bundle found inside the ${r?"IPA":"archive"}.`);try{De(`/usr/bin/xcrun devicectl device install app --device ${JSON.stringify(e)} ${JSON.stringify(l)}`,{stdio:"pipe"})}catch(a){try{De(`/usr/bin/xcrun simctl install ${JSON.stringify(e)} ${JSON.stringify(l)}`,{stdio:"pipe"})}catch{throw new Error(a.stderr?.toString().trim()||a.message||"iOS install failed.")}}}finally{hi.rmSync(o,{recursive:!0,force:!0})}}function Uo(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 De(`/usr/bin/xcrun simctl boot ${JSON.stringify(e)}`,{stdio:"pipe"}),_n("open",["-a","Simulator"],{detached:!0,stdio:"ignore"}).unref(),"Simulator booting..."}if(t==="android"){let i=`${process.env.ANDROID_HOME||`${process.env.HOME}/Library/Android/sdk`}/emulator/emulator`;return _n(i,["-avd",e],{detached:!0,stdio:"ignore"}).unref(),"Emulator booting in background..."}throw new Error("Invalid platform.")}async function $n(){process.platform!=="darwin"&&ct.warn("Running on non-macOS \u2014 iOS discovery unavailable, Android only.");let e=Co.createServer((n,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"),n.method==="OPTIONS"){r.writeHead(204),r.end();return}let o=new URL(n.url||"/",`http://localhost:${At}`);if(n.method==="GET"&&o.pathname==="/local/devices"){try{let s=ko();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(n.method==="POST"&&o.pathname==="/install-local"){t(n,r);return}if(n.method==="POST"&&o.pathname==="/local/boot"){i(n,r);return}r.writeHead(404),r.end()}),t=async(n,r)=>{try{let{deviceId:o,artifactUrl:s,platform:l}=await Pn(n);if(!o||!s){r.writeHead(400,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"error",message:"deviceId and artifactUrl are required"}));return}await Lo(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"}))}},i=async(n,r)=>{try{let{id:o,platform:s}=await Pn(n),l=Uo(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(At,"127.0.0.1",()=>{ct.success(mi.green(`Local device agent running on http://localhost:${At}`)),ct.info(mi.dim("Keep this running while using the Install Hub on the dashboard.")),ct.info(mi.dim("Press Ctrl+C to stop."))}),e.on("error",n=>{n.code==="EADDRINUSE"?ct.error(`Port ${At} is already in use \u2014 agent may already be running.`):ct.error(`Agent error: ${n.message}`),process.exit(1)}),await new Promise(()=>{})}import{createRequire as qa}from"module";import{text as Ho,password as Fo,spinner as Bo,isCancel as Rn}from"@clack/prompts";import bi from"chalk";import It from"fs";import wn from"path";import Mo from"os";var yi=wn.join(Mo.homedir(),f.configDir),Si=wn.join(yi,"config.json");function Ei(){if(!It.existsSync(Si))return{};try{return JSON.parse(It.readFileSync(Si,"utf-8"))}catch{return{}}}function Dn(e){It.existsSync(yi)||It.mkdirSync(yi,{recursive:!0});let i={...Ei(),...e};It.writeFileSync(Si,JSON.stringify(i,null,2))}async function vn(){let e=Ei(),t=await Ho({message:"Enter your email:",placeholder:"user@example.com",initialValue:e.lastLoginEmail,validate(r){if(r.length===0)return"Email is required!"}});if(Rn(t))return;let i=await Fo({message:"Enter your password:",validate(r){if(r.length===0)return"Password is required!"}});if(Rn(i))return;let n=Bo();n.start("Authenticating...");try{let o=await(await fetch(`${xt}/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:t,password:i})})).json();o.status==="success"&&o.user.token?(Li({id:o.user.id,email:t,token:o.user.token,refreshToken:o.user.refreshToken}),Dn({lastLoginEmail:t}),n.stop(bi.green("Login successful!"))):n.stop(bi.red("Login failed: "+(o.message||"Unknown error")))}catch(r){n.stop(bi.red("Network error: "+r.message))}}import{outro as Go,select as jo,spinner as Ko,isCancel as Vo}from"@clack/prompts";import jt from"chalk";import Ai from"fs";import zo from"path";var On=e=>e==="1234567890"||e==="ABC123DEFG"||e==="XXXXXXXXXX"?"":typeof e=="string"?e:"",Wo=()=>process.versions.node.split(".")[0]||"24";async function Cn(){if(!he()){console.log(jt.red(`You are not logged in. Run \`${f.nameLower} login\` first.`));return}let t=Ko();t.start("Fetching projects...");try{let{data:i}=await v.get("/projects");if(t.stop("Projects loaded."),i.status!=="success"||!i.projects||i.projects.length===0){console.log(jt.yellow(`No projects found. Run \`${f.nameLower} init\` to create one.`));return}let n=i.projects.map(S=>({value:S.projectId,label:`${S.name} (${S.slug})`})),r=await jo({message:"Select a project to link:",options:n});if(Vo(r))return;let o=zo.join(process.cwd(),f.configFileName),s={};if(Ai.existsSync(o))try{s=JSON.parse(Ai.readFileSync(o,"utf-8"))}catch{}let l=i.projects.find(S=>S.projectId===r),a=s.android?.package||He("android"),c=s.ios?.bundleIdentifier||He("ios"),d=s.android||{},u=s.submit?.production?.android||{},p=s.submit?.production?.ios||{},m={projectId:r,name:l?.name,slug:l?.slug,nodeVersion:s.nodeVersion||Wo(),scheme:l?.slug?.toLowerCase()||"app",android:{...d,package:a||"",versionCode:d.versionCode||"auto"},ios:{bundleIdentifier:c||""},build:{development:{environment:"development",distribution:"internal"},staging:{environment:"staging",distribution:"internal"},production:{environment:"production",distribution:"store"}},submit:{production:{android:{...u,track:u.track||"internal",releaseStatus:u.releaseStatus||"completed"},ios:{ascAppId:On(p.ascAppId),appleTeamId:On(p.appleTeamId)}}}};Ai.writeFileSync(o,JSON.stringify(m,null,2)),Go(jt.green(`Linked to project ${m.name} (${m.slug})`))}catch(i){t.stop(jt.red("Error fetching projects: "+i.message))}}import{outro as Yo,text as Kt,select as Jo,spinner as qo,isCancel as _t}from"@clack/prompts";import Pt from"chalk";import Xo from"fs";import Zo from"path";import{randomUUID as Qo}from"crypto";var es=()=>process.versions.node.split(".")[0]||"24";async function Nn(){if(!he()){console.log(Pt.red(`You are not logged in. Run \`${f.nameLower} login\` first.`));return}let t=await Kt({message:"Project Name:",placeholder:"My Awesome App",validate(l){if(l.length===0)return"Name is required!"}});if(_t(t))return;let i=await Kt({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(_t(i))return;let n=await Jo({message:"Platform:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"},{value:"web",label:"Web"},{value:"all",label:"All Platforms"}]});if(_t(n))return;let r="";if(n==="android"||n==="all"){let l=He("android");if(r=await Kt({message:"Android Package Name:",initialValue:l||"",placeholder:"com.example.app",validate(a){if(a.length===0)return"Package name is required for Android!"}}),_t(r))return}let o="";if(n==="ios"||n==="all"){let l=He("ios");if(o=await Kt({message:"iOS Bundle Identifier:",initialValue:l||"",placeholder:"com.example.app",validate(a){if(a.length===0)return"Bundle ID is required for iOS!"}}),_t(o))return}let s=qo();s.start("Creating project...");try{let l=Qo(),c={projectId:l,name:t,slug:i,storageType:"managed",platforms:n==="all"?["android","ios","web"]:[n]},{data:d}=await v.post("/projects",c);if(d.status==="success"){s.stop(Pt.green("Project created successfully!"));let u=Zo.join(process.cwd(),f.configFileName);Xo.writeFileSync(u,JSON.stringify({projectId:l,name:t,slug:i,nodeVersion:es(),...r?{android:{package:r,versionCode:"auto"}}:{},...o?{ios:{bundleIdentifier:o}}:{},build:{development:{environment:"development",distribution:"internal"},staging:{environment:"staging",distribution:"internal"},production:{environment:"production",distribution:"store"}},submit:{production:{android:{track:"internal",releaseStatus:"completed"},ios:{ascAppId:"",appleTeamId:""}}}},null,2)),Yo(Pt.green(`Initialized project ${t} and linked locally!`))}else s.stop(Pt.red("creation failed: "+d.message))}catch(l){s.stop(Pt.red("Network error: "+l.message))}}import{spinner as kn,log as be}from"@clack/prompts";import Vt from"chalk";import Tn from"fs";import ts from"path";async function xn(e,t){let i=he();if(!i){be.error(`You are not logged in. Run \`${f.nameLower} login\` first.`);return}let n=ts.join(process.cwd(),f.configFileName);if(!Tn.existsSync(n)){be.error(`No ${f.configFileName} found. Run \`${f.nameLower} init\` or \`${f.nameLower} link\` first.`);return}let r;try{r=JSON.parse(Tn.readFileSync(n,"utf-8"))}catch{be.error(`Failed to parse ${f.configFileName}`);return}let{projectId:o}=r;if(!o){be.error(`${f.configFileName} is missing projectId.`);return}e==="set"?await is(o,t,i):e==="list"?await ns(o,i):be.error(`Unknown env action: ${e}. Use 'set' or 'list'.`)}async function is(e,t,i){if(t.length===0){be.error(`Usage: ${f.nameLower} env set KEY=VALUE [KEY2=VALUE2 ...]`);return}let n=kn();n.start("Setting environment variables...");let r=0,o=0;for(let s of t){let[l,...a]=s.split("="),c=a.join("=");if(!l||c===void 0){be.warn(`Invalid format for argument: ${s}. Expected KEY=VALUE.`),o++;continue}try{let d={key:l.trim(),value:c,type:"env",environment:"global",visibility:"secret"},{data:u}=await v.post(`/projects/${e}/secrets`,d);u.status==="success"?r++:(be.error(`Failed to set ${l}: ${u.message}`),o++)}catch(d){be.error(`Network error setting ${l}: ${d.message}`),o++}}n.stop(`Set ${r} variable(s). ${o>0?`${o} failed.`:""}`)}async function ns(e,t){let i=kn();i.start("Fetching environment variables...");try{let{data:n}=await v.get(`/projects/${e}/secrets`);if(n.status==="success"){i.stop("Fetched variables.");let r=n.secrets||[];r.length===0?be.info("No environment variables found for this project."):(be.info(Vt.bold("Environment Variables (Global & Scoped):")),r.forEach(o=>{let s=o.visibility==="plain"?o.value:"********";console.log(` ${Vt.cyan(o.key)} = ${s} ${Vt.gray(`[${o.environment}]`)}`)}))}else i.stop(Vt.red(`Failed to fetch variables: ${n.message}`))}catch(n){i.stop("Failed to fetch variables."),be.error(`Network error: ${n.message}`)}}import{spinner as Ve,text as $t,select as $i,isCancel as Ke,cancel as wi,log as Un}from"@clack/prompts";import q from"chalk";import W from"fs";import ce from"path";import{spawn as rs,spawnSync as Ze}from"child_process";import Mn from"axios";import et from"os";import vi from"crypto";var os=5e3,ss=12,as={completed:"completed",draft:"draft",halted:"halted",inprogress:"inProgress","in-progress":"inProgress"},ls=e=>e?.type==="google_service_account",zt=e=>e?.bundleId||e?.packageName||e?.meta?.packageName||e?.meta?.bundleId;async function Hn(e){let t=Ve(),i=he(),n=cs(e);if(!n){process.exitCode=1;return}let r=e.projectId||n.projectId,o=e.profile||e.buildProfile||"production";if(!r){J(`${f.configFileName} is missing projectId. Pass --project-id in runner mode.`),process.exitCode=1;return}n.projectId=r,ne(q.dim(`Submit for project: ${n.name||r} | Profile: ${o}`));let s=e.platform;if(!s){let P=await $i({message:"Select platform to submit:",options:[{value:"ios",label:"iOS (App Store Connect / TestFlight)"},{value:"android",label:"Android (Google Play Console)"}]});if(Ke(P)){wi("Operation cancelled");return}s=P}if(s=String(s).toLowerCase(),s!=="ios"&&s!=="android"){J(`Platform ${s} is not supported. Use 'ios' or 'android'.`),process.exitCode=1;return}let l=s==="ios"&&!e.local&&e.sshHost?Ps(n,o,e):null;if(s==="ios"&&!e.local&&!l){await ds(n,o,e);return}let a=e.submitId,c=!!(e.local&&a),d=a||null,u=async(P,k={})=>{d&&await ms(r,d,{status:P,...k})},p=s==="android"?As(n,o):void 0,m=s==="ios"?_s(n,o):void 0,S,D,A,H=!1;try{s==="android"&&(S=e.track||n.submit?.[o]?.android?.track||n.submit?.production?.android?.track||"internal",D=$s(n,o,e.releaseStatus),A=Ds(n,o,e.rollout),H=Rs(n,o,e.changesNotSentForReview),vs(D,A))}catch(P){J(P.message),process.exitCode=1;return}if(s==="android"&&!c&&(d=await us(n,r,s,o,e,{packageName:p,track:S,releaseStatus:D,rollout:A,changesNotSentForReview:H}),!d)){J("Could not create submission tracking record. Submission was not started."),process.exitCode=1;return}await u("running",{platform:s,profile:o,packageName:p,track:S,releaseStatus:D,rollout:A,startTime:Date.now()});let F=null,z=null;try{z=await Os(r,s,e,i?.token),F=z?.filePath||null}catch(P){await u("failed",{error:`Failed to resolve submission artifact: ${P.message}`,endTime:Date.now()}),J(`Failed to resolve submission artifact: ${P.message}`),process.exitCode=1;return}if(!F){await u("failed",{error:"No suitable artifact found for submission.",endTime:Date.now()}),process.exitCode=1;return}await u("running",{buildId:z?.buildId,artifactName:z?.artifactName,artifactSource:z?.source}),ne(`Using artifact: ${q.green(ce.basename(F))} `),t.start("Fetching submission credentials from Dashboard...");let b;try{let k=(await v.get(`/credentials/${r}`)).data.credentials||[];if(s==="android"&&!p){t.stop("Package name missing"),J("Could not resolve Android package name. Set android.package in mach.config.json/app.json."),await u("failed",{error:"Could not resolve Android package name.",endTime:Date.now()}),process.exitCode=1;return}let I=k.filter(ls),N=s==="ios"?k.filter(B=>B.type==="asc_api_key"):Is(I,p);if(N.length===0){if(t.stop("Credentials missing"),J(s==="android"?`No Google Play service credential found for package ${p}.`:`No Service Credentials found for ${s}.`),s==="android"){let B=I.map(zt).filter(Boolean).join(", ");B&&ne(`Found Google Play service credential(s) for: ${B}`),ne(`Use '${f.nameLower} credentials:service --platform android --package-name ${p}' or upload it under that package in the Dashboard.`)}else ne(`Use '${f.nameLower} credentials:service --platform ${s}' or use the Dashboard to upload them.`);await u("failed",{error:`No submission credentials found for ${s}.`,endTime:Date.now()}),process.exitCode=1;return}if(b=ys(N,e.credentialId),!b&&s==="ios"&&m&&(b=Ss(N,m)),b||N.length===1)b=b||N[0],t.stop(`Using: ${b.name}`),s==="android"&&zt(b)==="*"&&ne(q.yellow(`Using legacy wildcard Google Play credential for ${p}. Upload a package-scoped credential when possible.`));else{if(t.stop("Multiple credentials found"),Es()){let j=N.map(se=>`${se.name||"credential"} (${se.credentialId||se.id||"no-id"})`).join(", ");J(`Multiple ${s==="ios"?"App Store Connect":"Google Play"} credentials found. Use --credential-id in CI. Available: ${j}`),await u("failed",{error:"Multiple submission credentials found; --credential-id is required in CI.",endTime:Date.now()}),process.exitCode=1;return}let B=await $i({message:`Choose a ${s==="ios"?"App Store Connect":"Google Play"} credential:`,options:N.map(j=>({value:j.credentialId,label:j.name,hint:`${j.keyId?`ID: ${j.keyId}`:""} ${j.issuerId?`(Issuer: ${j.issuerId.substring(0,8)}...)`:""}`}))});if(Ke(B)){wi("Submission cancelled"),await u("failed",{error:"Submission cancelled while selecting credential.",endTime:Date.now()}),process.exitCode=1;return}b=N.find(j=>j.credentialId===B),ne(`Using selected: ${q.green(b.name)}`)}}catch(P){t.stop("Failed to fetch credentials"),J(`API Error: ${P.message} `),await u("failed",{error:`Failed to fetch credentials: ${P.message}`,endTime:Date.now()}),process.exitCode=1;return}let G=W.mkdtempSync(ce.join(et.tmpdir(),`${f.nameLower}-submit-`)),_=b.keyId||b.meta?.keyId,h=b.issuerId||b.meta?.issuerId,w=b.type==="asc_api_key"?`AuthKey_${_}.p8`:"service-account.json",R=ce.join(G,w);t.start("Downloading secure key...");try{let P=await v.get(`/credentials/${b.credentialId}/download`,{params:{projectId:r}});if(P.data.status!=="success"||!P.data.downloadUrl)throw new Error("Failed to get secure download URL");let k=await Mn.get(P.data.downloadUrl,{responseType:"arraybuffer"});W.writeFileSync(R,Buffer.from(k.data)),t.stop("Key downloaded to secure temp storage")}catch(P){t.stop("Download failed"),J(`Failed to download key: ${P.message}`);try{W.rmSync(G,{recursive:!0,force:!0})}catch{}await u("failed",{error:`Failed to download credential key: ${P.message}`,endTime:Date.now()}),process.exitCode=1;return}ne(q.blue(`Initiating ${s==="ios"?"TestFlight":"Google Play"} submission...`));let L=!1,U;try{if(s==="ios"){if(!_){let k=await $t({message:"Enter App Store Connect Key ID (e.g. 2X948D...):",validate:I=>I.length>0?void 0:"Key ID is required"});if(Ke(k)){await u("failed",{error:"Submission cancelled while entering ASC Key ID.",endTime:Date.now()}),process.exitCode=1;return}_=k}if(!h||h==="undefined"){let k=await $t({message:"Enter App Store Connect Issuer ID (Found on ASC Keys page):",validate:I=>I.length>0?void 0:"Issuer ID is required"});if(Ke(k)){await u("failed",{error:"Submission cancelled while entering ASC Issuer ID.",endTime:Date.now()}),process.exitCode=1;return}h=k}ne(`Using ASC Key ID: ${_}`),ne(`Using ASC Issuer ID: ${h}`);let P=l?await Ns(F,R,h,_,m,l):await Cs(F,R,h,_,m);Ri(`${s==="ios"?"App Store":"Google Play"} submission successful!`),L=!0}else U=await Us(F,R,S||"internal",p,D||"completed",A,H,o),Ri("Google Play submission successful!"),L=!0}catch(P){J(`Submission failed: ${P.message}`),await u("failed",{error:P.message,endTime:Date.now()}),dt(e,{status:"failed",projectId:r,submitId:d,platform:s,profile:o,buildId:z?.buildId||e.buildId,artifactName:z?.artifactName,error:P.message,dashboardUrl:d?Qe(d,r):void 0}),process.exitCode=1}finally{L&&(await u("success",{endTime:Date.now(),versionCode:U?.versionCode,track:S,releaseStatus:D}),dt(e,{status:"success",projectId:r,submitId:d,platform:s,profile:o,buildId:z?.buildId||e.buildId,artifactName:z?.artifactName,versionCode:U?.versionCode,track:S,releaseStatus:D,dashboardUrl:d?Qe(d,r):void 0})),js(G),F&&F.includes(`${f.nameLower}-artifact-`)}}function cs(e){let t=`./${f.configFileName}`;if(W.existsSync(t))try{return JSON.parse(W.readFileSync(t,"utf-8"))}catch(i){return J(`Failed to read ${f.configFileName}: ${i.message}`),null}return e.projectId?{projectId:e.projectId}:(J(`No ${f.configFileName} found. Run \`${f.nameLower} init\` or \`${f.nameLower} link\` first.`),null)}async function ds(e,t,i){let n=i.projectId||e.projectId;if(!n){J(`${f.configFileName} is missing projectId.`),process.exitCode=1;return}let r=i.submitId||vi.randomUUID(),o=!!i.latest||!i.buildId,s=ps({...i,latest:o,profile:t,projectId:n,submitId:r}),l={projectId:n,submitId:r,platform:"ios",profile:t,latest:o,buildId:i.buildId,credentialId:i.credentialId,status:"pending",source:"cli",submitArgs:process.argv.slice(3).join(" "),runnerArgs:s,runnerCommand:[f.nameLower,"submit",...s].map(bs).join(" "),appName:e.name,startTime:Date.now()},a=Ve();a.start("Queuing iOS submit on macOS runner...");try{let c=await v.post("/submissions",l),d=c.data?.submission||c.data?.submit||{},u=c.data?.pipelineUrl||c.data?.pipeline?.web_url||d.pipelineUrl,p=c.data?.dashboardUrl||Qe(r,n);a.stop("iOS submit queued"),ne(`Submission ID: ${q.cyan(r)}`),u&&ne(`GitLab pipeline: ${q.blue.underline(u)}`),ne(`Dashboard: ${q.blue.underline(p)}`),dt(i,{status:"pending",projectId:n,submitId:r,platform:"ios",profile:t,latest:o,buildId:i.buildId,dashboardUrl:p,pipelineUrl:u}),await fs(n,r,i)}catch(c){a.stop("Could not queue iOS submit"),J(hs(c)),process.exitCode=1}}async function us(e,t,i,n,r,o={}){let s=r.submitId||vi.randomUUID(),l=!!r.latest||!r.buildId,a={projectId:t,submitId:s,platform:i,profile:n,latest:l,buildId:r.buildId,credentialId:r.credentialId,status:"running",source:"cli-direct",submitArgs:process.argv.slice(3).join(" "),appName:e.name,startTime:Date.now(),...o};try{let c=await v.post("/submissions",a),d=c.data?.submission||c.data?.submit||{},u=c.data?.dashboardUrl||d.dashboardUrl||Qe(s,t);return ne(`Submission ID: ${q.cyan(s)}`),ne(`Dashboard: ${q.blue.underline(u)}`),dt(r,{status:"running",projectId:t,submitId:s,platform:i,profile:n,latest:l,buildId:r.buildId,dashboardUrl:u}),s}catch(c){let d=c.response?.data?.message||c.response?.data?.error||c.message;return ne(q.yellow(`Could not create submission tracking record: ${d}`)),null}}function ps(e){let t=["--local","--submit-id",e.submitId,"--project-id",e.projectId,"--platform","ios","--profile",e.profile||"production"];return e.buildId?t.push("--build-id",e.buildId):t.push("--latest"),e.credentialId&&t.push("--credential-id",e.credentialId),e.quiet&&t.push("--quiet"),e.jsonOutput&&t.push("--json-output",e.jsonOutput),t.filter(i=>i!=null&&i!=="")}async function fs(e,t,i){let n=Ve(),r=0,o=0;for(i.quiet||n.start("Waiting for iOS submit runner...");;)try{let s=await v.get(`/submissions/${e}/${t}`),l=s.data?.submission||s.data?.submit||s.data,a=String(l?.status||"pending").toLowerCase();r=0;let c=Array.isArray(l?.logs)?l.logs:[];for(let d=o;d<c.length;d++){let u=c[d];u&&console.log(q.dim(String(u)))}if(o=c.length,["success","completed","succeeded"].includes(a)){i.quiet||n.stop("iOS submit completed"),Ri("App Store submission successful!"),dt(i,{status:"success",projectId:e,submitId:t,platform:"ios",profile:l?.profile||i.profile||"production",buildId:l?.buildId||i.buildId,artifactName:l?.artifactName,dashboardUrl:l?.dashboardUrl||Qe(t,e),pipelineUrl:l?.pipelineUrl});return}if(["failed","error","cancelled","canceled"].includes(a)){i.quiet||n.stop("iOS submit failed");let d=l?.error||l?.message||"Unknown iOS submit failure.";J(d),dt(i,{status:"failed",projectId:e,submitId:t,platform:"ios",profile:l?.profile||i.profile||"production",buildId:l?.buildId||i.buildId,artifactName:l?.artifactName,error:d,dashboardUrl:l?.dashboardUrl||Qe(t,e),pipelineUrl:l?.pipelineUrl}),process.exitCode=1;return}i.quiet||n.message(`iOS submit ${a}...`),await Di(os)}catch(s){if(r++,r>=ss){i.quiet||n.stop("Lost connection to iOS submit status"),J(`Could not fetch iOS submit status after ${r} attempts: ${s.message}`),process.exitCode=1;return}await Di(Math.min(2e3*r,15e3))}}async function ms(e,t,i){let n;for(let r=1;r<=3;r++)try{await v.patch(`/submissions/${e}/${t}`,i);return}catch(o){if(n=o,r>=3||!gs(o))break;await Di(1e3*r)}Un.warn(q.dim(`Could not report submission status: ${n?.message||n}`))}function gs(e){let t=e.response?.status;return!t||t===408||t===409||t===425||t===429||t>=500}function hs(e){let t=e.response?.status,i=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(`
|
|
1102
|
+
`):i||e.message||String(e)}function Qe(e,t){if(!e)return Ge;let i=t?`?projectId=${encodeURIComponent(t)}`:"";return`${Ge}/submissions/${e}${i}`}function dt(e,t){if(!e.jsonOutput)return;let i=ce.resolve(e.jsonOutput),n={...t,url:t.url||t.dashboardUrl||Qe(t.submitId,t.projectId),updatedAt:new Date().toISOString()};try{let r=ce.dirname(i);r&&r!=="."&&W.mkdirSync(r,{recursive:!0}),W.writeFileSync(i,JSON.stringify(n,null,2))}catch(r){Un.warn(q.yellow(`Could not write submission metadata JSON: ${r.message}`))}}function ys(e,t){return t&&e.find(i=>i.credentialId===t||i.id===t||i.keyId===t||i.meta?.keyId===t)||null}function Ss(e,t){let i=e.filter(n=>[n.bundleId,n.bundleIdentifier,n.appIdentifier,n.meta?.bundleId,n.meta?.bundleIdentifier,n.meta?.appIdentifier].filter(Boolean).map(String).includes(t));return i.length===1?i[0]:null}function Es(){return process.env.CI==="true"||process.env.CI==="1"||!process.stdin.isTTY}function Di(e){return new Promise(t=>setTimeout(t,e))}function bs(e){return/^[a-zA-Z0-9_./:=@-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function As(e,t){if(e.submit?.[t]?.android?.package)return e.submit[t].android.package;let i=Mi(e,t);if(i)return i;let n=ce.join(process.cwd(),"app.json");if(W.existsSync(n))try{return JSON.parse(W.readFileSync(n,"utf-8")).expo?.android?.package}catch{}let r=ce.join(process.cwd(),"app.config.json");if(W.existsSync(r))try{let o=JSON.parse(W.readFileSync(r,"utf-8"));return o.expo?.android?.package||o.android?.package}catch{}}function Is(e,t){let i=e.filter(o=>zt(o)===t);if(i.length>0)return i;let n=e.filter(o=>{let s=zt(o);return!s||s==="*"});return e.length>0&&e.length===n.length?n:[]}function _s(e,t){return e.submit?.[t]?.ios?.bundleIdentifier?e.submit[t].ios.bundleIdentifier:e.submit?.[t]?.ios?.bundleId?e.submit[t].ios.bundleId:Hi(e,t)}function Ps(e,t,i){let n=e.submit?.[t]?.ios||{},r=e.submit?.production?.ios||{},o=i.sshHost||n.sshHost||r.sshHost||process.env.MACH_IOS_SUBMIT_SSH_HOST;return o?{sshHost:o,sshUser:i.sshUser||n.sshUser||r.sshUser||process.env.MACH_IOS_SUBMIT_SSH_USER||process.env.USER||"ubuntu",sshKey:i.sshKey||n.sshKey||r.sshKey||process.env.MACH_IOS_SUBMIT_SSH_KEY}:null}function $s(e,t,i){let n=i||e.submit?.[t]?.android?.releaseStatus||e.submit?.production?.android?.releaseStatus||"completed";return ws(n)}function ws(e){let t=as[String(e).trim().toLowerCase()];if(!t)throw new Error(`Invalid Android release status "${e}". Use completed, draft, halted, or inProgress.`);return t}function Ds(e,t,i){let n=i??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(n==null||n==="")return;let r=Number(n);if(!Number.isFinite(r)||r<=0||r>=1)throw new Error(`Invalid Android rollout fraction "${n}". Use a number greater than 0 and less than 1, for example 0.1.`);return r}function Rs(e,t,i){let n=i??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 n===!0||n==="true"||n==="1"}function vs(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 Os(e,t,i,n){let r=i.buildId?"id":i.latest?"latest":null;if(!r){let s=await $i({message:"Select artifact source:",options:[{value:"latest",label:`Latest Production Build (${f.name})`},{value:"id",label:`Input Build ID (${f.name})`},{value:"url",label:"Remote URL"},{value:"local",label:"Local File Path"}]});if(Ke(s))return wi("Operation cancelled"),null;r=s}if(r==="local"){let s=await $t({message:"Enter path to artifact (.ipa/.aab):",validate:l=>{if(!W.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 Ke(s)?null:{filePath:s,source:"local"}}let o=Ve();if(r==="latest"){let s=i.profile||i.buildProfile;o.start(`Fetching latest${s?` ${s}`:""} build...`);try{let l=await v.get(`/builds/${e}`,{params:{limit:50}});if(l.data.status!=="success")throw new Error(l.data.message);let a=l.data.builds||[],c=s?.toLowerCase(),d=b=>b.platform?.toLowerCase()===t.toLowerCase()&&b.status?.toLowerCase()==="success",u=b=>c?[b.buildProfile,b.profile,b.profileName,b.buildType].filter(Boolean).some(G=>String(G).toLowerCase()===c):!0,p=a.filter(b=>d(b)&&u(b)),m=p.find(b=>b.buildType?.toLowerCase()==="store"||b.distribution?.toLowerCase()==="store")||p[0],S=a.some(b=>b.platform?.toLowerCase()===t.toLowerCase()&&b.status?.toLowerCase()==="success");if(!m)return o.stop("No suitable build found"),J(s&&S?`No successful ${t} builds found for profile "${s}".`:"No successful builds found for this platform."),null;o.stop(`Found build: ${m.buildId}`);let D=m.artifacts||[];if(D.length===0||D.every(b=>!(b.url||b.downloadUrl)))try{let b=await v.get(`/builds/${e}/${m.buildId}/artifacts`);b.data.status==="success"&&b.data.artifacts?.length>0?(D=b.data.artifacts.map(G=>({...G,url:G.url||G.downloadUrl})),console.log(q.cyan(` [RECOVERY] Fetched ${D.length} artifact(s) with download URLs.`))):console.log(q.yellow(" [RECOVERY] /artifacts endpoint returned 0 artifacts."))}catch(b){console.log(q.red(` [RECOVERY] /artifacts fetch failed: ${b.message}`))}let H=t==="ios",F=D.find(b=>{let G=(b.type||"").toLowerCase(),_=(b.name||"").toLowerCase();if(console.log(q.dim(` - Checking: ${b.name} (Type: ${b.type}, HasLink: ${!!(b.url||b.downloadUrl)})`)),G)return G===(H?"ipa":"aab");let h=H?".ipa":".aab",w=(b.url||b.downloadUrl||"").toLowerCase();return _.endsWith(h)||w.includes(h)});if(!F||!(F.url||F.downloadUrl))return J("Build found but artifact URL is missing."),null;let z=F.url||F.downloadUrl;return{filePath:await Ii(z,H?"ios":"android"),buildId:m.buildId,artifactName:F.name,source:"latest"}}catch(l){return o.stop("Fetch failed"),J(`API Error: ${l.message}`),null}}if(r==="id"){let s=i.buildId||await $t({message:"Enter Build ID:",validate:l=>l.length<5?"Invalid ID":void 0});if(Ke(s))return null;o.start("Fetching build...");try{let l=await v.get(`/build/${s}`);if(l.data.status!=="success")throw new Error(l.data.message);let a=l.data.build;if(!a)throw new Error("Build not found");let c=t==="ios",d=a.artifacts?.find(u=>{if(u.type)return u.type===(c?"ipa":"aab");let p=c?".ipa":".aab";return u.name&&u.name.endsWith(p)||u.url&&u.url.includes(p)});return!d||!d.url?(o.stop("Missing artifact"),J("Artifact URL not found on build record."),null):(o.stop(`Found build: ${a.buildId}`),{filePath:await Ii(d.url,c?"ios":"android"),buildId:a.buildId||String(s),artifactName:d.name,source:"id"})}catch(l){return o.stop("Fetch failed"),J(l.message),null}}if(r==="url"){let s=await $t({message:"Enter Artifact URL:",validate:l=>l.startsWith("http")?void 0:"Must be a valid URL"});return Ke(s)?null:{filePath:await Ii(s,t),source:"url"}}return null}async function Ii(e,t,i=3){let n=Ve();n.start("Downloading artifact...");let r=W.mkdtempSync(ce.join(et.tmpdir(),`${f.nameLower}-artifact-`)),o=`app.${t==="ios"?"ipa":"aab"}`,s=ce.join(r,o);for(let l=1;l<=i;l++)try{l>1&&(n.message(`Downloading artifact (Retry ${l}/${i})...`),await new Promise(d=>setTimeout(d,2e3*l)));let a=W.createWriteStream(s),c=await Mn({url:e,method:"GET",responseType:"stream",timeout:6e4});return await new Promise((d,u)=>{c.data.pipe(a);let p=!1;c.data.on("error",m=>{p||(p=!0,a.close(),u(m))}),a.on("finish",()=>{p||d()}),a.on("error",m=>{p||(p=!0,u(m))})}),n.stop("Download complete"),s}catch(a){if(l===i)throw n.stop("Download failed"),a}throw new Error("Download failed after retries")}async function Cs(e,t,i,n,r){let o=Ve();if(r&&ne(`Bundle ID: ${q.green(r)}`),!i||!n)throw J(`Missing credentials: issuerId=${i}, keyId=${n}. Check your Dashboard.`),new Error("Missing ASC API Key Metadata (IssuerID or KeyID)");let s=Fn(t,i,n),l=Hs();return o.start("Uploading to TestFlight (pilot)..."),new Promise((a,c)=>{let d=rs(l.command,["pilot","upload","--ipa",e,"--api_key_path",s,"--skip_submission","true","--skip_waiting_for_build_processing","true"],{stdio:"inherit",env:l.env});d.on("close",u=>{if(u!==0){o.stop("Pilot failed");try{W.unlinkSync(s)}catch{}c(new Error(`fastlane pilot failed with exit code ${u??"unknown"}.`))}else{o.stop("IPA uploaded to TestFlight");try{W.unlinkSync(s)}catch{}a({})}}),d.on("error",u=>{try{W.unlinkSync(s)}catch{}o.stop("Pilot execution error"),c(Bs(u))})})}async function Ns(e,t,i,n,r,o){let s=Ve();if(r&&ne(`Bundle ID: ${q.green(r)}`),!i||!n)throw J(`Missing credentials: issuerId=${i}, keyId=${n}. Check your Dashboard.`),new Error("Missing ASC API Key Metadata (IssuerID or KeyID)");let l=Fn(t,i,n),a=`${o.sshUser}@${o.sshHost}`,c=Ts(o),d=ks(o),u="",p="";try{if(s.start(`Preparing remote iOS submit runner (${a})...`),u=xs("ssh",[...c,"mktemp -d /tmp/mach-submit.XXXXXX"]).trim(),!u)throw new Error("Remote runner did not return a temp directory.");s.stop(`Remote runner ready: ${a}`),s.start("Uploading IPA and App Store Connect key to remote runner..."),_i("scp",[...d,e,`${a}:${u}/app.ipa`],"IPA upload to remote runner"),_i("scp",[...d,l,`${a}:${u}/api_key.json`],"ASC key upload to remote runner"),p=ce.join(et.tmpdir(),`${f.nameLower}-ios-submit-${Date.now()}.sh`),W.writeFileSync(p,Ls(u)),_i("scp",[...d,p,`${a}:${u}/submit.sh`],"submit script upload to remote runner"),s.stop("Remote submit inputs uploaded"),s.start("Uploading to TestFlight on remote runner...");let m=`chmod +x ${wt(`${u}/submit.sh`)} && bash ${wt(`${u}/submit.sh`)}`,S=Ze("ssh",[...c,m],{stdio:"inherit"});if(S.error)throw Oi("ssh",S.error);if(S.status!==0)throw new Error(`Remote iOS submit failed with exit code ${S.status}.`);return s.stop("IPA uploaded to TestFlight"),{apiKeyJsonPath:null}}catch(m){throw s.stop("Remote iOS submit failed"),m}finally{try{W.unlinkSync(l)}catch{}if(p)try{W.unlinkSync(p)}catch{}if(u)try{Ze("ssh",[...c,`rm -rf ${wt(u)}`],{stdio:"ignore"})}catch{}}}function Fn(e,t,i){let n=W.readFileSync(e,"utf8"),r;try{r=vi.createPrivateKey(n).export({type:"pkcs8",format:"pem"})}catch{ne("Key normalization failed, falling back to manual re-wrapping..."),r=`-----BEGIN PRIVATE KEY-----
|
|
1103
|
+
${(n.replace(/-----BEGIN[^-]*-----/g,"").replace(/-----END[^-]*-----/g,"").replace(/\s+/g,"").match(/.{1,64}/g)||[]).join(`
|
|
1023
1104
|
`)}
|
|
1024
|
-
-----END PRIVATE KEY-----`}
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1105
|
+
-----END PRIVATE KEY-----`}let o=ce.join(et.tmpdir(),`api_key_${i}_${Date.now()}.json`),s={key_id:i,issuer_id:t,key:r,in_house:!1};return W.writeFileSync(o,JSON.stringify(s,null,2)),o}function Ts(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 ks(e){let t=["-o","StrictHostKeyChecking=no","-o","ServerAliveInterval=30"];return e.sshKey&&t.push("-i",e.sshKey),t}function xs(e,t){let i=Ze(e,t,{encoding:"utf-8",stdio:["ignore","pipe","inherit"]});if(i.error)throw Oi(e,i.error);if(i.status!==0)throw new Error(`${e} failed with exit code ${i.status}.`);return i.stdout||""}function _i(e,t,i){let n=Ze(e,t,{stdio:"inherit"});if(n.error)throw Oi(e,n.error);if(n.status!==0)throw new Error(`${i} failed with exit code ${n.status}.`)}function Oi(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 wt(e){return`'${e.replace(/'/g,"'\\''")}'`}function Ls(e){let t=wt(`${e}/app.ipa`),i=wt(`${e}/api_key.json`);return`#!/bin/bash
|
|
1106
|
+
set -euo pipefail
|
|
1107
|
+
|
|
1108
|
+
export PATH="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:$HOME/.local/share/fastlane/3.4.0/bin:$PATH"
|
|
1109
|
+
export FASTLANE_SKIP_UPDATE_CHECK=1
|
|
1110
|
+
export FASTLANE_HIDE_CHANGELOG=1
|
|
1111
|
+
export CI="\${CI:-1}"
|
|
1112
|
+
|
|
1113
|
+
if ! command -v fastlane >/dev/null 2>&1; then
|
|
1114
|
+
if ! command -v gem >/dev/null 2>&1; then
|
|
1115
|
+
echo "fastlane was not found and gem is unavailable on the remote macOS runner."
|
|
1116
|
+
exit 127
|
|
1117
|
+
fi
|
|
1118
|
+
|
|
1119
|
+
FASTLANE_GEM_HOME="\${FASTLANE_GEM_HOME:-$HOME/.local/share/fastlane/3.4.0}"
|
|
1120
|
+
FASTLANE_BIN_DIR="$FASTLANE_GEM_HOME/bin"
|
|
1121
|
+
mkdir -p "$FASTLANE_BIN_DIR"
|
|
1122
|
+
export GEM_HOME="$FASTLANE_GEM_HOME"
|
|
1123
|
+
export GEM_PATH="$FASTLANE_GEM_HOME:\${GEM_PATH:-}"
|
|
1124
|
+
export PATH="$FASTLANE_BIN_DIR:$PATH"
|
|
1125
|
+
gem install fastlane -NV --install-dir "$FASTLANE_GEM_HOME" --bindir "$FASTLANE_BIN_DIR"
|
|
1126
|
+
fi
|
|
1127
|
+
|
|
1128
|
+
fastlane pilot upload \\
|
|
1129
|
+
--ipa ${t} \\
|
|
1130
|
+
--api_key_path ${i} \\
|
|
1131
|
+
--skip_submission true \\
|
|
1132
|
+
--skip_waiting_for_build_processing true
|
|
1133
|
+
`}async function Us(e,t,i="internal",n,r="completed",o,s=!1,l="production"){let a=Ve();if(!n||n==="*")throw new Error("Android package name is required for Google Play submission.");let c=o!==void 0?` (${o} rollout)`:"";a.start(`Uploading to Google Play ${i} track with ${r} release status${c}...`);try{let d=JSON.parse(W.readFileSync(t,"utf-8"));Ms(d);let u=await sn({packageName:n,serviceAccount:d,aabPath:e,track:i,releaseStatus:r,userFraction:o,changesNotSentForReview:s});return a.stop(`AAB uploaded to ${i} track (versionCode ${u.versionCode})`),u}catch(d){throw a.stop("Google Play upload failed"),new Error(Gs(d,i,n,l))}}function Ms(e){if(!e?.client_email||!e?.private_key)throw new Error("Invalid Google service account JSON: missing client_email or private_key.")}function Pi(){let e=process.env.HOME||et.homedir(),t=process.env.FASTLANE_GEM_HOME||ce.join(e,".local/share/fastlane/3.4.0"),i=[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",ce.join(t,"bin"),process.env.PATH].filter(Boolean).join(":");return{...process.env,PATH:i,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",CI:process.env.CI||"1"}}function Hs(){let e=Pi(),t=Ln(e);if(t)return t;if(process.env.MACH_SKIP_FASTLANE_INSTALL!=="1"){Fs(e);let i=Ln(Pi());if(i)return i}return{command:"fastlane",env:Pi()}}function Ln(e){let t=process.env.HOME||et.homedir(),i=[process.env.FASTLANE_BINARY,"/usr/local/bin/fastlane","/opt/homebrew/bin/fastlane","/usr/local/Cellar/fastlane/2.227.0/libexec/bin/fastlane",ce.join(process.env.FASTLANE_GEM_HOME||ce.join(t,".local/share/fastlane/3.4.0"),"bin/fastlane"),"fastlane"].filter(Boolean);for(let n of i){if(n.includes("/")&&!W.existsSync(n))continue;if(!Ze(n,["--version"],{env:e,stdio:"ignore"}).error)return{command:n,env:e}}return null}function Fs(e){let t=Ze("gem",["--version"],{env:e,stdio:"ignore"});if(t.error||t.status!==0)return;let i=process.env.HOME||et.homedir(),n=process.env.FASTLANE_GEM_HOME||ce.join(i,".local/share/fastlane/3.4.0"),r=ce.join(n,"bin");W.mkdirSync(r,{recursive:!0}),ne(q.dim("fastlane not found. Installing fastlane into the local Mach runner cache..."));let o=Ze("gem",["install","fastlane","-NV","--install-dir",n,"--bindir",r],{env:{...e,GEM_HOME:n,GEM_PATH:[n,e.GEM_PATH].filter(Boolean).join(":")},stdio:"inherit"});(o.error||o.status!==0)&&ne(q.yellow("Automatic fastlane install failed; Mach will try PATH resolution once more."))}function Bs(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(`
|
|
1134
|
+
`))}function Gs(e,t,i,n="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: ${i||"unknown"} | Track: ${t}`,`Retry with: ${f.nameLower} submit --latest --platform android --profile ${n} --track ${t} --changes-not-sent-for-review`,"Then send the change for review from Google Play Console if required."].join(`
|
|
1135
|
+
`);if(/caller does not have permission|permission denied|insufficient permissions|not authorized/i.test(r))return["Google Play rejected the service account permissions.",`Package: ${i||"unknown"} | Track: ${t}`,"Grant this service account access to the app in Play Console with release permissions, then retry."].join(`
|
|
1136
|
+
`);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: ${i||"unknown"} | Track: ${t}`,"Check android.package / submit.<profile>.android.package and make sure the app exists in this Play Console account."].join(`
|
|
1137
|
+
`);if(/only releases with status draft|draft app/i.test(r))return["Google Play requires a draft release for this app state.",`Package: ${i||"unknown"} | Track: ${t}`,`Retry with: ${f.nameLower} submit --latest --platform android --profile ${n} --track ${t} --release-status draft`].join(`
|
|
1138
|
+
`);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: ${i||"unknown"} | Track: ${t}`,"Build a new Android artifact with a higher versionCode, then submit that build.",`Recommended: ${f.nameLower} build --platform android --profile ${n} --auto-version`,`Then: ${f.nameLower} submit --latest --platform android --profile ${n} --track ${t}`].join(`
|
|
1139
|
+
`);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: ${i||"unknown"} | Track: ${t}`,"Build a new Android artifact with a higher versionCode, then submit that build.",`Recommended: ${f.nameLower} build --platform android --profile ${n} --auto-version`].join(`
|
|
1140
|
+
`);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 js(e){try{W.existsSync(e)&&W.rmSync(e,{recursive:!0,force:!0})}catch{}}function J(e){console.log(q.red(`\u274C ${e}`))}function ne(e){console.log(q.gray(`\u2022 ${e}`))}function Ri(e){console.log(q.green(`\u2713 ${e}`))}import{spinner as Ks,log as tt,outro as Vs}from"@clack/prompts";import Ci from"chalk";import Bn from"fs";import zs from"path";import{execSync as Ws}from"child_process";import Ys from"adm-zip";import Js from"axios";import{randomUUID as qs}from"crypto";async function Gn(e){tt.info(Ci.magenta("\u{1F680} Starting Over-The-Air (OTA) Update via Mach..."));let t=Te();(!t||!t.projectId)&&(tt.error(`No ${f.configFileName} found or missing projectId. Run \`mach link\` first.`),process.exit(1));let i=t.projectId,n=e.branch||"production",r="1.0.0";try{r=JSON.parse(Bn.readFileSync("./package.json","utf-8")).version||"1.0.0"}catch{tt.warn("Could not read package.json version. Defaulting to 1.0.0")}let o=Ks();o.start(`Compiling JavaScript bundles for OTA (Channel: ${n}, Runtime: ${r})...`);try{Ws("npx expo export --platform all",{stdio:"ignore"})}catch(c){o.stop("Compilation failed."),tt.error(`Failed to export JS bundles using Expo: ${c.message}`),process.exit(1)}o.message("Zipping artifact payload...");let s=zs.join(process.cwd(),"dist");Bn.existsSync(s)||(o.stop("Missing dist folder."),tt.error("The `dist` directory was not created. Export failed."),process.exit(1));let l=new Ys;l.addLocalFolder(s,"dist");let a=l.toBuffer();o.message("Uploading payload to Mach Cloud...");try{let c=qs(),d=await v.post("/builds/source-upload-url",{projectId:i,buildId:c});if(d.data.status!=="success")throw new Error("Could not secure upload bucket URL");let{uploadUrl:u,key:p}=d.data;await Js.put(u,a,{headers:{"Content-Type":"application/zip"},maxBodyLength:1/0,maxContentLength:1/0}),o.message(`Promoting Update to ${n}...`),await v.post("/updates/publish",{projectId:i,channelName:n,runtimeVersion:r,platform:"android",updateId:`${c}-android`,manifestKey:p}),await v.post("/updates/publish",{projectId:i,channelName:n,runtimeVersion:r,platform:"ios",updateId:`${c}-ios`,manifestKey:p}),o.stop("Update Live!"),Vs(Ci.green(`\u2713 OTA Update natively shipped to the '${n}' channel.`)),tt.info(Ci.dim(`Any app running runtime '${r}' will download this bundle smoothly.`))}catch(c){o.stop("Update failed during Cloud Sync."),tt.error(`Upload error: ${c.message}`),process.exit(1)}}import{intro as Xs,outro as jn,log as ut}from"@clack/prompts";import Le from"chalk";async function Kn(){Xs(Le.blue(`${f.name} CLI - User Profile`));let e=he();if(!e){ut.warn(Le.yellow("You are not logged in.")),ut.info(`Run \`${f.nameLower} login\` to authenticate.`),jn();return}ut.info(`${Le.bold("Logged in as:")} ${Le.green(e.email)}`);try{await v.get("/projects");let i=he().token.split(".");if(i.length===3){let n=JSON.parse(Buffer.from(i[1],"base64").toString());if(n.exp){let r=new Date(n.exp*1e3),o=new Date,s=r.getTime()-o.getTime();if(s>0){let l=Math.round(s/6e4),a=(l/60).toFixed(1);ut.info(`${Le.bold("Token status:")} Valid (Expires in ~${a}h / ${l}m)`)}else ut.warn(`${Le.bold("Token status:")} ${Le.red("Expired")} (Auto-refresh failed)`)}}}catch{ut.warn(`${Le.bold("Token status:")} ${Le.red("Unreachable")} (Session might be truly expired)${xt}`)}jn(Le.blue("---"))}import{spawn as ea}from"child_process";import{log as ze}from"@clack/prompts";import Ae from"chalk";import ta from"fs";import Zs from"net";async function Qs(e){return new Promise(t=>{let i=Zs.createServer();i.once("error",n=>{n.code==="EADDRINUSE"?t(!0):t(!1)}),i.once("listening",()=>{i.close(),t(!1)}),i.listen(e,"0.0.0.0")})}async function Vn(e,t=20){let i=e;for(;i<e+t;){if(!await Qs(i))return i;i++}throw new Error(`Could not find an available port after ${t} attempts starting from ${e}.`)}var zn=async e=>{ze.info(Ae.blue(`Starting ${f.name} Dev Orchestrator...`));let t=Te(),i=e.buildProfile||"development",n=t?Je(t,i):null,r={...process.env};if(t?.projectId)try{ze.info(Ae.dim(`Fetching managed secrets for profile: ${i}...`));let u=await v.get(`/projects/${t.projectId}/secrets/export?env=${i}`);u.data?.status==="success"&&u.data.secrets&&(Object.assign(r,u.data.secrets),ze.info(Ae.magenta(`\u2713 Injected secrets from ${f.name} Dashboard.`)))}catch{ze.warn("Could not fetch managed secrets. Running with local env only.")}t&&Object.assign(r,rt(t,f.envPrefix)),n&&(Object.assign(r,rt(n,`${f.envPrefix}PROFILE_`)),n.env&&Object.assign(r,n.env));let o=!1;try{let u=JSON.parse(ta.readFileSync("package.json","utf-8"));o=!!(u.dependencies?.expo||u.devDependencies?.expo)}catch{ze.warn("Could not parse package.json. Defaulting to Bare React Native mode.")}let s=Number(e.port||n?.port||8081),l=await Vn(s);l!==s&&ze.info(Ae.yellow(`Port ${s} is busy. ${f.name} is using ${l} instead.`));let a=process.platform==="win32"?"npx.cmd":"npx",c=[];if(o?(c=["expo","start","--port",String(l)],e.clear&&c.push("--clear"),e.tunnel&&c.push("--tunnel"),e.lan&&c.push("--lan"),e.localhost&&c.push("--localhost"),e.ios&&c.push("--ios"),e.android&&c.push("--android"),e.web&&c.push("--web")):(c=["react-native","start","--port",String(l)],e.clear&&c.push("--clear")),o){let u=[`${Ae.cyan("i")} open iOS simulator`,`${Ae.cyan("a")} open Android emulator/device`,`${Ae.cyan("w")} open web`,`${Ae.cyan("r")} reload app`];ze.info([Ae.bold("Launch controls"),...u.map(p=>` ${p}`),"",Ae.dim("Direct launch: mach start --ios | --android | --web"),Ae.dim(`Metro URL: http://localhost:${l}`)].join(`
|
|
1141
|
+
`))}else ze.info(Ae.dim(`Metro URL: http://localhost:${l}`));let d=ea(a,c,{stdio:"inherit",env:r});return new Promise((u,p)=>{d.on("exit",m=>{m===0?u():p(new Error(`Dev server exited with code ${m}`))}),d.on("error",m=>{p(m)})})};import{log as ye}from"@clack/prompts";import Re from"chalk";var Wn=async e=>{let t=Te();t||(ye.error(Re.red(`No ${f.configFileName} found in the current directory.`)),process.exit(1));let i=e.profile||"development",n=Je(t,i);if(e.json){console.log(JSON.stringify({project:t,resolved:n},null,2));return}ye.info(Re.bgBlue.white(` Resolved ${f.name} Config [${i}] `)),ye.info(Re.dim("----------------------------------------")),ye.info(`${Re.blue("Project ID:")} ${t.projectId}`),ye.info(`${Re.blue("Name:")} ${t.name}`),ye.info(`${Re.blue("Scheme:")} ${t.scheme}`),n?(ye.info(Re.dim(`
|
|
1142
|
+
Profile Settings:`)),ye.info(`${Re.cyan("Distribution:")} ${n.distribution||"none"}`),ye.info(`${Re.cyan("Development Client:")} ${n.developmentClient||"false"}`),n.env&&Object.keys(n.env).length>0&&(ye.info(Re.dim(`
|
|
1143
|
+
Environment Variables:`)),Object.entries(n.env).forEach(([r,o])=>{ye.info(` ${r}=${o}`)}))):ye.warn(`Profile '${i}' not found.`),ye.info(Re.dim("----------------------------------------"))};import{log as ve,spinner as vt,text as Yn,select as Jn,confirm as ia,isCancel as Dt,cancel as Rt,outro as Ot,note as na}from"@clack/prompts";import X from"chalk";import{execSync as ra}from"child_process";async function oa(){try{let e=ra("xcrun devicectl list devices --json-output -",{stdio:["pipe","pipe","pipe"]}).toString();return(JSON.parse(e).result?.devices||[]).filter(n=>n.connectionProperties?.transportType==="wired"||n.connectionProperties?.transportType==="localNetwork").map(n=>({udid:n.identifier,name:n.deviceProperties?.name||"Unknown Device",model:n.hardwareProperties?.marketingName||"iPhone"}))}catch{return[]}}async function sa(e){let t=e.udid,i=e.name,n="";if(!t){let o=vt();o.start("Scanning for connected iOS devices...");let s=await oa();if(o.stop(s.length>0?`Found ${s.length} device(s)`:"No devices detected"),s.length===1)t=s[0].udid,i=i||s[0].name,n=s[0].model,ve.info(`Detected: ${X.bold(i)} (${X.dim(t.substring(0,12)+"...")})`);else if(s.length>1){let l=await Jn({message:"Select a device to register:",options:s.map(c=>({value:c.udid,label:`${c.name} (${c.model})`,hint:c.udid.substring(0,12)+"..."}))});if(Dt(l)){Rt("Cancelled");return}t=l;let a=s.find(c=>c.udid===t);i=i||a.name,n=a.model}else{ve.info(X.dim("No connected devices found. Enter UDID manually."));let l=await Yn({message:"Device UDID:",placeholder:"00008101-XXXXXXXXXXXX",validate(a){if(a.length<10)return"UDID seems too short"}});if(Dt(l)){Rt("Cancelled");return}t=l}}if(!i){let o=await Yn({message:"Device name:",placeholder:"Nitesh's iPhone",validate(s){if(s.length===0)return"Name is required"}});if(Dt(o)){Rt("Cancelled");return}i=o}let r=vt();r.start("Registering device...");try{await v.post("/devices",{udid:t,name:i,platform:"ios",model:n||void 0,addedVia:"cli"}),r.stop(X.green("Device registered!")),ve.info(` ${X.bold("Name:")} ${i}`),ve.info(` ${X.bold("UDID:")} ${X.dim(t)}`)}catch(o){r.stop(X.red("Failed to register device")),ve.error(o.response?.data?.message||o.message)}Ot(X.blue("---"))}async function aa(){let e=vt();e.start("Fetching registered devices...");try{let i=(await v.get("/devices")).data.devices||[];if(e.stop(`${i.length} device(s) registered`),i.length===0){ve.info(X.dim(`No devices registered yet. Run \`${f.nameLower} device register\` to add one.`)),Ot(X.blue("---"));return}let n=i.map(r=>{let o=new Date(r.createdAt).toLocaleDateString();return` ${X.bold(r.name.padEnd(24))} ${X.dim(r.udid.padEnd(28))} ${X.cyan(r.addedVia.padEnd(10))} ${X.dim(o)}`});na(` ${X.bold("Name".padEnd(24))} ${"UDID".padEnd(28)} ${"Via".padEnd(10)} Date
|
|
1031
1144
|
`+n.join(`
|
|
1032
|
-
`),"Registered Devices")}catch(t){e.stop(
|
|
1033
|
-
`),c=
|
|
1034
|
-
`),d=
|
|
1035
|
-
`),d=
|
|
1036
|
-
`),d=
|
|
1037
|
-
`);/__DEV__/.test(
|
|
1038
|
-
Running expo prebuild for deeper analysis...`));try{
|
|
1039
|
-
Skipping manifest/plist checks \u2014 no android/ios dirs. Use --prebuild to generate them.`)),
|
|
1040
|
-
`)),
|
|
1041
|
-
`));for(let s of l)ee.error(Z.red(`${Z.bold(s.name)} ${Z.dim(`(${s.arch})`)}`)),ee.info(Z.dim(` PT_LOAD alignment: 2**${Math.log2(s.align)} (${s.align} bytes, needs 2**14 = ${Bn})`))}return a.length>0&&(console.log(""),ee.success(Z.green(`${a.length} librar${a.length===1?"y":"ies"} correctly aligned (2**14 or higher).`))),console.log(""),l.length===0?(ee.success(Z.green.bold("ELF Verification Successful. APK is 16KB compatible.")),!0):(ee.error(Z.red.bold(`Found ${l.length} unaligned lib${l.length===1?"":"s"} (arm64-v8a/x86_64 libs need to be aligned).`)),console.log(""),ee.info(Z.yellow("To fix this:")),ee.info(Z.dim(" 1. Rebuild with NDK r28+ which defaults to 16KB page alignment")),ee.info(Z.dim(" 2. Or set -DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON in CMake")),ee.info(Z.dim(" 3. Update third-party libraries that ship prebuilt .so files")),ee.info(Z.dim(" 4. After rebuilding: zipalign -p -f -v 16 input.apk output.apk")),console.log(""),ee.info(Z.dim("Reference: https://developer.android.com/guide/practices/page-sizes")),!1)}catch(o){return i.stop("Analysis failed."),ee.error(Z.red(`Failed to analyze APK: ${o.message}`)),!1}finally{try{xe.rmSync(n,{recursive:!0,force:!0})}catch{}}}function ys(e){let t=xe.openSync(e,"r");try{let i=Buffer.alloc(64);if(xe.readSync(t,i,0,64,0),!i.subarray(0,4).equals(hs))return null;let n=i[4]===2,o=i[5]===1,r=(p,g)=>o?p.readUInt16LE(g):p.readUInt16BE(g),l=(p,g)=>o?p.readUInt32LE(g):p.readUInt32BE(g),a=(p,g)=>Number(o?p.readBigUInt64LE(g):p.readBigUInt64BE(g)),s,c,d;n?(s=a(i,32),c=r(i,54),d=r(i,56)):(s=l(i,28),c=r(i,42),d=r(i,44));let u=null;for(let p=0;p<d;p++){let g=Buffer.alloc(c);if(xe.readSync(t,g,0,c,s+p*c),l(g,0)!==gs)continue;let P;n?P=a(g,48):P=l(g,28),P>0&&(u===null||P<u)&&(u=P)}return u??0}catch{return null}finally{xe.closeSync(t)}}function Gn(e){let t=[];if(!xe.existsSync(e))return t;let i=xe.readdirSync(e,{withFileTypes:!0});for(let n of i){let o=Xe.join(e,n.name);n.isDirectory()?t.push(...Gn(o)):n.name.endsWith(".so")&&t.push(o)}return t}function Ss(e){return e.includes("arm64-v8a")?"arm64-v8a":e.includes("x86_64")?"x86_64":"unknown"}var Vn=async e=>{if(fe()||(be.error(we.red(`You are not logged in. Run \`${f.nameLower} login\` first.`)),process.exit(1)),e.apk){await bs(e);return}let i=process.cwd(),n=Mt.join(i,"package.json");Et.existsSync(n)||(be.error(we.red("No package.json found. Run this command from a project root.")),process.exit(1));let o=JSON.parse(Et.readFileSync(n,"utf-8")),r=!!(o.dependencies?.expo||o.devDependencies?.expo);e.json||(be.info(we.dim(`Project: ${o.name||"unknown"} v${o.version||"0.0.0"}`)),be.info(we.dim(`Type: ${r?"Expo":"Bare React Native"}`)),be.info(""));let l={json:e.json,fix:e.fix,category:e.category,severity:e.severity,prebuild:e.prebuild},a=await Mn(i,l);e.json?console.log(JSON.stringify(Hn(a,o),null,2)):Fn(a,e.severity);let s=a.some(d=>d.findings.some(u=>u.severity==="critical")),c=a.some(d=>d.findings.some(u=>u.severity==="high"));(s||c)&&process.exit(1)},Kn=["16kb"];async function bs(e){let t=e.category?.toLowerCase();t&&!Kn.includes(t)&&(be.error(we.red(`Unknown APK check category: "${t}"`)),be.info(we.dim(`Available APK checks: ${Kn.join(", ")}`)),process.exit(1));let i=await Is(e.apk);i||process.exit(1);let n=!t,o=!1;(n||t==="16kb")&&(await jn(i)||(o=!0)),o&&process.exit(1)}async function Is(e){if(e.startsWith("build:")){let i=e.slice(6);return await _s(i)}if(e.startsWith("http://")||e.startsWith("https://"))return await Wn(e);let t=Mt.resolve(e);return Et.existsSync(t)?t:(be.error(we.red(`APK file not found: ${t}`)),null)}async function _s(e){let t=zn();t.start(`Fetching APK from build ${e}...`);try{let i=await $.get(`/build/${e}`);if(i.data.status!=="success")throw new Error(i.data.message);let n=i.data.build;if(!n)throw new Error("Build not found");let o=n.artifacts?.find(r=>r.type?r.type==="apk":r.name?.endsWith(".apk")||r.url?.includes(".apk"));return!o||!o.url?(t.stop("No APK artifact found"),be.error(we.red("This build does not have an APK artifact.")),be.info(we.dim("Make sure the build produced an APK (not just an AAB).")),null):(t.stop(`Found build: ${n.buildId||e}`),await Wn(o.url))}catch(i){return t.stop("Failed to fetch build"),be.error(we.red(i.message)),null}}async function Wn(e){let t=zn();t.start("Downloading APK...");try{let i=Et.mkdtempSync(Mt.join(Es.tmpdir(),`${f.nameLower}-audit-`)),n=Mt.join(i,"app.apk"),o=await As.get(e,{responseType:"arraybuffer"});Et.writeFileSync(n,o.data);let r=(o.data.length/(1024*1024)).toFixed(1);return t.stop(`Downloaded APK (${r} MB)`),n}catch(i){return t.stop("Download failed"),be.error(we.red(`Failed to download APK: ${i.message}`)),null}}var Ds=console.log;console.log=()=>{};$s();console.log=Ds;ue(ae.bgCyan.black(f.cliTag("Production Build Orchestrator")));var ws=Rs(import.meta.url),vs=ws("../package.json"),Y=new Ps;Y.name(f.nameLower).description(`${f.name} CLI: Powerful Cloud Infrastructure Tools`).version(vs.version).option("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1);Y.command("agent").description("Start local device discovery agent for the Install Hub (port 7070)").action(async()=>{await zi()});Y.command("host").description("Setup AWS S3 static hosting and CloudFront").action(async()=>{ue(ae.bgCyan.black(f.cliTag("Hosting"))),await hi()});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=>{ue(ae.bgCyan.black(f.cliTag("Sitemap Generator"))),await Ai(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)","production").option("--profile <name>","Build Profile (alias for --build-profile)").option("--dry-run","Generate User Data script without launching").option("--keep-instance","Do not terminate the instance after build").option("--subnet <id>","VPC Subnet ID to launch the instance in").option("--security-group <id>","VPC Security Group ID to use").option("--ssh-host <host>","Remote host for iOS build (SSH)").option("--ssh-user <user>","SSH username for remote host").option("--ssh-key <path>","Path to private SSH key for remote host").option("--ios-scheme <scheme>","iOS Scheme to build").option("--ios-team-id <id>","Apple Development Team ID").option("--ios-configuration <config>","Xcode configuration (Release/Debug)").option("--ios-export-method <method>","Export method (ad-hoc, app-store, development, enterprise)").option("--ios-api-key-id <id>","App Store Connect API Key ID").option("--ios-api-key-issuer <id>","App Store Connect API Key Issuer ID").option("--ios-api-key-path <path>","Path to App Store Connect API Key (.p8) file").option("--simulator","Build for iOS Simulator (no signing required)").addOption(new Yn("--build-id <id>","Internal build ID").hideHelp()).addOption(new Yn("--project-id <id>","Internal project ID").hideHelp()).option("--local","Run build on local machine").option("--auto-version","Automatically fetch and increment versionCode from Google Play").option("--verbose","Enable verbose logging").option("--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("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1).action(async(e,t)=>{let i=Y.opts();t.yes=t.yes||i.yes,t.quiet=t.quiet||i.quiet,t.platform=e||t.platform,t.buildProfile=t.profile||t.buildProfile,t.quiet||ue(ae.bgCyan.black(f.cliTag("Cloud Build"))),await Pt(t)});Y.command("maestro").description("Run managed Maestro tests for an existing Mach build or artifact").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("--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("--json-output <path>","Write test run metadata JSON to a file for CI/CD").action(async e=>{ue(ae.bgCyan.black(f.cliTag("Maestro Testing"))),await Li(e)});Y.command("update").description("Deploy an Over-The-Air (OTA) update to your live channel").option("--branch <name>","Channel or Branch to deploy to (e.g., production)","production").action(async e=>{ue(ae.bgCyan.black(f.cliTag("OTA Update"))),await cn(e)});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("--latest","Use the latest successful build for submission").option("--build-id <id>","Use a specific build ID for submission").action(async e=>{ue(ae.bgCyan.black(f.cliTag("Store Submission"))),await sn(e)});Y.command("login").description(`Login to ${f.name} Dashboard`).action(async()=>{ue(ae.bgCyan.black(f.cliTag("Login"))),await Ji()});Y.command("link").description(`Link local directory to a ${f.name} Project`).action(async()=>{ue(ae.bgCyan.black(f.cliTag("Link Project"))),await Xi()});Y.command("me").description("Display currently logged in user details").action(async()=>{await un()});Y.command("init").description(`Create a new ${f.name} Project`).action(async()=>{ue(ae.bgCyan.black(f.cliTag("Init Project"))),await Zi()});Y.command("env").description("Manage Environment Variables").argument("<action>","Action to perform: set or list").argument("[args...]","Key=Value pairs for set action").action(async(e,t)=>{ue(ae.bgCyan.black(f.cliTag("Env Manager"))),await tn(e,t)});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=>{ue(ae.bgCyan.black(f.cliTag("Dev Server"))),await fn(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 mn(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-UTJERDGT.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=>{ue(ae.bgCyan.black(f.cliTag("Credentials Setup"))),await et(e),Jn(ae.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=>{ue(ae.bgCyan.black(f.cliTag("Service Credentials"))),await mi(e),Jn(ae.green("Done!"))});var ci=Y.command("device").description("Manage registered iOS test devices");ci.command("register").description("Register a connected iOS device or enter UDID manually").option("--udid <udid>","Device UDID (skip auto-detection)").option("--name <name>","Device name").action(async e=>{await wt("register",e)});ci.command("list").description("List all registered devices").action(async()=>{await wt("list",{})});ci.command("remove").description("Remove a registered device").option("--udid <udid>","Device UDID to remove").action(async e=>{await wt("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=>{ue(ae.bgCyan.black(f.cliTag(e.apk?"APK Audit":"Security Audit"))),await Vn(e)});var Os=new Set(["login"]);Y.hook("preAction",(e,t)=>{let i=t.name();Os.has(i)||ui()});Y.on("command:*",()=>{console.error(`Invalid command: %s
|
|
1145
|
+
`),"Registered Devices")}catch(t){e.stop(X.red("Failed to fetch devices")),ve.error(t.response?.data?.message||t.message)}Ot(X.blue("---"))}async function la(e){let t=e.udid;if(!t){let r=vt();r.start("Fetching registered devices...");try{let s=(await v.get("/devices")).data.devices||[];if(r.stop(`${s.length} device(s) found`),s.length===0){ve.info(X.dim("No devices to remove.")),Ot(X.blue("---"));return}let l=await Jn({message:"Select device to remove:",options:s.map(a=>({value:a.udid,label:a.name,hint:a.udid.substring(0,12)+"..."}))});if(Dt(l)){Rt("Cancelled");return}t=l}catch(o){r.stop(X.red("Failed to fetch devices")),ve.error(o.response?.data?.message||o.message);return}}let i=await ia({message:`Remove device ${X.dim(t.substring(0,12)+"...")}?`});if(Dt(i)||!i){Rt("Cancelled");return}let n=vt();n.start("Removing device...");try{await v.delete(`/devices/${encodeURIComponent(t)}`),n.stop(X.green("Device removed"))}catch(r){n.stop(X.red("Failed to remove device")),ve.error(r.response?.data?.message||r.message)}Ot(X.blue("---"))}async function Wt(e,t){switch(e){case"register":await sa(t);break;case"list":await aa();break;case"remove":await la(t);break;default:ve.error(`Unknown action: ${e}`)}}import{log as _e,spinner as Pr}from"@clack/prompts";import Ce from"chalk";import ni from"path";import Tt from"fs";import Ga from"os";import ja from"axios";var Ie=(o=>(o.CRITICAL="critical",o.HIGH="high",o.MEDIUM="medium",o.LOW="low",o.INFO="info",o))(Ie||{}),Oe=(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))(Oe||{});import{spinner as mr,log as Nt}from"@clack/prompts";import Se from"chalk";import{execSync as Na}from"child_process";import gr from"fs";import hr from"path";import We from"fs";import Ct from"path";import{execSync as ca}from"child_process";var qn={"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"}},da={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 ua(e){try{let i=ca("npx expo config --type introspect --json 2>/dev/null",{cwd:e,encoding:"utf-8",timeout:3e4});return JSON.parse(i)}catch{}let t=Ct.join(e,"app.json");if(We.existsSync(t))try{let i=JSON.parse(We.readFileSync(t,"utf-8"));return i.expo||i}catch{}return null}function pa(e){let t=[],i=Ct.join(e,"node_modules");if(!We.existsSync(i))return t;let n=/<uses-permission\s+android:name="([^"]+)"/g;function r(o,s){let l=Ct.join(o,"android","src","main","AndroidManifest.xml");if(!We.existsSync(l))return;let a=We.readFileSync(l,"utf-8"),c;for(;(c=n.exec(a))!==null;)t.push({pkg:s,permission:c[1]});n.lastIndex=0}for(let o of We.readdirSync(i)){if(o.startsWith("."))continue;let s=Ct.join(i,o);if(o.startsWith("@")){if(!We.statSync(s).isDirectory())continue;for(let l of We.readdirSync(s))r(Ct.join(s,l),`${o}/${l}`)}else r(s,o)}return t}async function Xn(e,t){let i=[],n=1,r=ua(e),o=r?.android?.permissions||[],s=r?.android?.blockedPermissions||[];for(let c of o){let d=qn[c];d&&i.push({id:`PERM-${String(n++).padStart(3,"0")}`,title:`${c.split(".").pop()} declared`,description:d.description,severity:d.severity,category:"permissions",file:"app.config.ts",recommendation:"Remove from permissions if not needed, or add justification."})}let l=pa(e);for(let{pkg:c,permission:d}of l){let u=qn[d];u&&(s.includes(d)||o.includes(d)||i.push({id:`PERM-${String(n++).padStart(3,"0")}`,title:`${d.split(".").pop()} injected by ${c}`,description:`${u.description}. Auto-injected via ${c} AndroidManifest.xml`,severity:u.severity,category:"permissions",file:`node_modules/${c}/android/src/main/AndroidManifest.xml`,recommendation:`Add "${d}" to blockedPermissions if not needed.`,autoFixable:!0}))}let a=r?.ios?.infoPlist||{};for(let[c,d]of Object.entries(da))c in a&&i.push({id:`PERM-${String(n++).padStart(3,"0")}`,title:`iOS: ${c} declared`,description:d.description,severity:d.severity,category:"permissions",file:"app.config.ts",recommendation:`Remove ${c} from infoPlist if the app does not use this capability.`});return{category:"permissions",label:"Permission Audit",findings:i,durationMs:0}}import Ni from"fs";import Yt from"path";var fa=[{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"}],ma=new Set([".ts",".tsx",".js",".jsx"]),ga=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function Zn(e){let t=[],i=Ni.readdirSync(e,{withFileTypes:!0});for(let n of i){if(ga.has(n.name))continue;let r=Yt.join(e,n.name);n.isDirectory()?t.push(...Zn(r)):ma.has(Yt.extname(n.name))&&t.push(r)}return t}function ha(e){let t=e.trim();return t.startsWith("//")||t.startsWith("*")||t.startsWith("/*")}function ya(e){return/process\.env\./i.test(e)||/import\.meta\.env/i.test(e)}async function Qn(e,t){let i=[],n=Yt.join(e,"src"),r=Ni.existsSync(n)?n:e,o=Zn(r);for(let s of o){let a=Ni.readFileSync(s,"utf-8").split(`
|
|
1146
|
+
`),c=Yt.relative(e,s);for(let d=0;d<a.length;d++){let u=a[d];if(!ha(u)&&!ya(u))for(let{id:p,pattern:m,severity:S,label:D}of fa)m.lastIndex=0,m.test(u)&&i.push({id:p,title:D,description:`Potential ${D.toLowerCase()} found in source code`,severity:S,category:"secrets",file:c,line:d+1,recommendation:`Move to environment variables or a secrets manager. Use \`${f.nameLower} env set\` for managed secrets.`})}}return{category:"secrets",label:"Secrets Detection",findings:i,durationMs:0}}import{execSync as Sa}from"child_process";var Ea={critical:"critical",high:"high",moderate:"medium",low:"low",info:"info"};async function er(e,t){let i=[],n=1,r;try{r=Sa("npm audit --json 2>/dev/null",{cwd:e,encoding:"utf-8",timeout:6e4})}catch(l){if(r=l.stdout||"",!r)return{category:"dependencies",label:"Dependency CVEs",findings:[],durationMs:0,error:"Failed to run npm audit. Ensure npm is available and dependencies are installed."}}let o;try{o=JSON.parse(r)}catch{return{category:"dependencies",label:"Dependency CVEs",findings:[],durationMs:0,error:"Failed to parse npm audit output."}}let s=o.vulnerabilities||{};for(let[l,a]of Object.entries(s)){let c=Ea[a.severity]||"info",d=Array.isArray(a.via)?a.via.map(u=>typeof u=="string"?u:u.title||u.name).join(", "):String(a.via);i.push({id:`DEP-${String(n++).padStart(3,"0")}`,title:`${l} \u2014 ${a.severity}`,description:`Via: ${d}. Range: ${a.range||"unknown"}`,severity:c,category:"dependencies",recommendation:a.fixAvailable?`Run \`npm audit fix\` or update ${l} to a patched version.`:"No fix available yet. Monitor for updates or evaluate alternatives.",autoFixable:!!a.fixAvailable})}return{category:"dependencies",label:"Dependency CVEs",findings:i,durationMs:0}}import Jt from"fs";import qt from"path";var ba=/(?:token|password|credential|secret|apiKey|api_key|session|auth|jwt|refresh_token|access_token|private_key|pin|otp)/i,tr=/AsyncStorage\s*\.\s*(?:setItem|mergeItem)\s*\(\s*['"`]([^'"`]+)['"`]/g,Aa=/from\s+['"]@react-native-async-storage\/async-storage['"]|from\s+['"]react-native['"].*AsyncStorage/,Ia=new Set([".ts",".tsx",".js",".jsx"]),_a=new Set(["node_modules",".expo",".git","android","ios","dist","build"]);function ir(e){let t=[];if(!Jt.existsSync(e))return t;let i=Jt.readdirSync(e,{withFileTypes:!0});for(let n of i){if(_a.has(n.name))continue;let r=qt.join(e,n.name);n.isDirectory()?t.push(...ir(r)):Ia.has(qt.extname(n.name))&&t.push(r)}return t}async function nr(e,t){let i=[],n=1,r=qt.join(e,"src"),o=Jt.existsSync(r)?r:e,s=ir(o);for(let l of s){let a=Jt.readFileSync(l,"utf-8");if(!Aa.test(a))continue;let c=a.split(`
|
|
1147
|
+
`),d=qt.relative(e,l);for(let u=0;u<c.length;u++){let p=c[u];tr.lastIndex=0;let m;for(;(m=tr.exec(p))!==null;){let S=m[1];ba.test(S)&&i.push({id:`STOR-${String(n++).padStart(3,"0")}`,title:`AsyncStorage used for "${S}"`,description:`Sensitive data key "${S}" stored in AsyncStorage (unencrypted).`,severity:"high",category:"storage",file:d,line:u+1,recommendation:"Use expo-secure-store (SecureStore) for sensitive data instead of AsyncStorage."})}}}return{category:"storage",label:"Insecure Storage",findings:i,durationMs:0}}import Xt from"fs";import Zt from"path";var rr=/['"`](http:\/\/(?!localhost|127\.0\.0\.1|10\.|192\.168\.|0\.0\.0\.0|172\.(?:1[6-9]|2\d|3[01])\.)[^'"`\s]+)['"`]/g,Pa=/\/api\/|\/v[0-9]+\/|\/graphql|\/rest\//i,$a=new Set([".ts",".tsx",".js",".jsx"]),wa=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function or(e){let t=[];if(!Xt.existsSync(e))return t;let i=Xt.readdirSync(e,{withFileTypes:!0});for(let n of i){if(wa.has(n.name))continue;let r=Zt.join(e,n.name);n.isDirectory()?t.push(...or(r)):$a.has(Zt.extname(n.name))&&t.push(r)}return t}async function sr(e,t){let i=[],n=1,r=Zt.join(e,"src"),o=Xt.existsSync(r)?r:e,s=or(o);for(let l of s){let c=Xt.readFileSync(l,"utf-8").split(`
|
|
1148
|
+
`),d=Zt.relative(e,l);for(let u=0;u<c.length;u++){let p=c[u],m=p.trim();if(m.startsWith("//")||m.startsWith("*"))continue;rr.lastIndex=0;let S;for(;(S=rr.exec(p))!==null;){let D=S[1],A=Pa.test(D);i.push({id:`NET-${String(n++).padStart(3,"0")}`,title:`Insecure HTTP URL${A?" (API endpoint)":""}`,description:`Plain HTTP URL found: ${D}`,severity:A?"high":"medium",category:"network",file:d,line:u+1,recommendation:"Use HTTPS instead of HTTP for all network requests."})}}}return{category:"network",label:"HTTP URLs",findings:i,durationMs:0}}import Qt from"fs";import ei from"path";var ar=/(?:debug|debugMode|devMode|enableDebug)\s*[:=]\s*true/gi,lr=/console\.(?:log|warn|info|debug)\s*\([^)]*(?:token|password|secret|credential|key|auth)/gi,Da=new Set([".ts",".tsx",".js",".jsx"]),Ra=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function cr(e){let t=[];if(!Qt.existsSync(e))return t;let i=Qt.readdirSync(e,{withFileTypes:!0});for(let n of i){if(Ra.has(n.name))continue;let r=ei.join(e,n.name);n.isDirectory()?t.push(...cr(r)):Da.has(ei.extname(n.name))&&t.push(r)}return t}async function dr(e,t){let i=[],n=1,r=ei.join(e,"src"),o=Qt.existsSync(r)?r:e,s=cr(o);for(let l of s){let c=Qt.readFileSync(l,"utf-8").split(`
|
|
1149
|
+
`),d=ei.relative(e,l);for(let u=0;u<c.length;u++){let p=c[u],m=p.trim();if(!(m.startsWith("//")||m.startsWith("*"))&&(ar.lastIndex=0,ar.test(p)&&i.push({id:`DBG-${String(n++).padStart(3,"0")}`,title:"Hardcoded debug flag",description:"Debug/dev mode enabled in source code",severity:"medium",category:"debug",file:d,line:u+1,recommendation:"Use __DEV__ or environment variables instead of hardcoded debug flags."}),lr.lastIndex=0,lr.test(p))){let S=c.slice(Math.max(0,u-3),u).join(`
|
|
1150
|
+
`);/__DEV__/.test(S)||i.push({id:`DBG-${String(n++).padStart(3,"0")}`,title:"Sensitive data in console log",description:"Console log may expose sensitive data (token, password, etc.) in production",severity:"medium",category:"debug",file:d,line:u+1,recommendation:"Wrap in __DEV__ check or remove sensitive data from console output."})}}}return{category:"debug",label:"Debug/Dev Flags",findings:i,durationMs:0}}import ur from"fs";import Ti from"path";var va=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 Oa(e){let t=[Ti.join(e,"android","app","src","main","AndroidManifest.xml"),Ti.join(e,"android","AndroidManifest.xml")];for(let i of t)if(ur.existsSync(i))return i;return null}async function pr(e,t){let i=[],n=1,r=Oa(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=ur.readFileSync(r,"utf-8"),s=Ti.relative(e,r),l=/<(activity|service|receiver|provider)\s+([^>]*?)(?:\/>|>)/gs,a;for(;(a=l.exec(o))!==null;){let c=a[1],d=a[2],p=d.match(/android:name="([^"]+)"/)?.[1]||"unknown";if(va.has(p))continue;let m=/android:exported="true"/.test(d),S=/android:permission="/.test(d);m&&!S&&i.push({id:`MAN-${String(n++).padStart(3,"0")}`,title:`Exported ${c}: ${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)&&i.push({id:`MAN-${String(n++).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)&&i.push({id:`MAN-${String(n++).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:i,durationMs:0}}import ti from"fs";import ki from"path";function Ca(e){let t=ki.join(e,"ios");if(!ti.existsSync(t))return null;let i=ti.readdirSync(t,{withFileTypes:!0});for(let n of i){if(!n.isDirectory()||n.name==="Pods"||n.name.startsWith("."))continue;let r=ki.join(t,n.name,"Info.plist");if(ti.existsSync(r))return r}return null}async function fr(e,t){let i=[],n=1,r=Ca(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=ti.readFileSync(r,"utf-8"),s=ki.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)&&i.push({id:`ATS-${String(n++).padStart(3,"0")}`,title:"ATS disabled \u2014 NSAllowsArbitraryLoads",description:"App Transport Security is completely disabled. All HTTP connections are allowed.",severity:"critical",category:"ats",file:s,recommendation:"Remove NSAllowsArbitraryLoads or set to false. Use domain-specific exceptions only if absolutely necessary."});let c=a.match(/<key>NSExceptionDomains<\/key>\s*<dict>([\s\S]*?)<\/dict>/);if(c){let d=c[1].match(/<key>([^<]+)<\/key>/g);if(d)for(let u of d){let p=u.replace(/<\/?key>/g,"");p!=="NSExceptionDomains"&&i.push({id:`ATS-${String(n++).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:i,durationMs:0}}var Ta=[{category:"permissions",label:"Permission Audit",fn:Xn,requiresPrebuild:!1},{category:"secrets",label:"Secrets Detection",fn:Qn,requiresPrebuild:!1},{category:"dependencies",label:"Dependency CVEs",fn:er,requiresPrebuild:!1},{category:"storage",label:"Insecure Storage",fn:nr,requiresPrebuild:!1},{category:"network",label:"HTTP URLs",fn:sr,requiresPrebuild:!1},{category:"debug",label:"Debug/Dev Flags",fn:dr,requiresPrebuild:!1},{category:"manifest",label:"Android Manifest",fn:pr,requiresPrebuild:!0},{category:"ats",label:"iOS ATS Config",fn:fr,requiresPrebuild:!0}];async function yr(e,t){let i=Ta;t.category&&(i=i.filter(s=>s.category===t.category),i.length===0&&(Nt.error(Se.red(`Unknown category: ${t.category}`)),Nt.info(Se.dim(`Available: ${Object.values(Oe).join(", ")}`)),process.exit(1)));let n=i.filter(s=>!s.requiresPrebuild),r=i.filter(s=>s.requiresPrebuild),o=[];for(let s of n){let l=mr();l.start(Se.dim(`Running ${s.label}...`));try{let a=Date.now(),c=await s.fn(e,t);c.durationMs=Date.now()-a,o.push(c);let d=c.findings.length;l.stop(d>0?Se.yellow(`${s.label} \u2014 ${d} finding(s)`):Se.green(`${s.label} \u2014 clean`))}catch(a){l.stop(Se.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=hr.join(e,"android"),l=hr.join(e,"ios"),a=gr.existsSync(s)||gr.existsSync(l);if(!a&&t.prebuild){t.json||Nt.info(Se.dim(`
|
|
1151
|
+
Running expo prebuild for deeper analysis...`));try{Na("npx expo prebuild --no-install",{cwd:e,stdio:"pipe"})}catch{return Nt.warn(Se.yellow("Prebuild failed \u2014 skipping manifest/plist checks.")),o}}else if(!a)return t.json||Nt.info(Se.dim(`
|
|
1152
|
+
Skipping manifest/plist checks \u2014 no android/ios dirs. Use --prebuild to generate them.`)),o;for(let c of r){let d=mr();d.start(Se.dim(`Running ${c.label}...`));try{let u=Date.now(),p=await c.fn(e,t);p.durationMs=Date.now()-u,o.push(p);let m=p.findings.length;d.stop(m>0?Se.yellow(`${c.label} \u2014 ${m} finding(s)`):Se.green(`${c.label} \u2014 clean`))}catch(u){d.stop(Se.red(`${c.label} \u2014 error`)),o.push({category:c.category,label:c.label,findings:[],durationMs:0,error:u.message})}}}return o}import ae from"chalk";import{log as re}from"@clack/prompts";var pt={critical:ae.bgRed.white.bold,high:ae.red.bold,medium:ae.yellow.bold,low:ae.blue,info:ae.dim},ii={critical:0,high:1,medium:2,low:3,info:4};function ka(e,t){if(!t)return!0;let i=ii[t];return i===void 0?!0:ii[e]<=i}function Sr(e,t){let i=0,n={critical:0,high:0,medium:0,low:0,info:0};for(let s of e){let l=s.findings.filter(c=>ka(c.severity,t));if(l.length===0&&!s.error)continue;if(re.info(""),re.info(ae.bold(` ${s.label}`)+ae.dim(` ${l.length} finding(s)`)),re.info(ae.dim(" "+"\u2500".repeat(60))),s.error){re.error(ae.red(` Error: ${s.error}`));continue}let a=[...l].sort((c,d)=>ii[c.severity]-ii[d.severity]);for(let c of a){let d=pt[c.severity](` ${c.severity.toUpperCase()} `);re.info(` ${d} ${ae.bold(c.id)} ${c.title}`),re.info(ae.dim(` ${c.description}`)),c.file&&re.info(ae.dim(` File: ${c.file}${c.line?`:${c.line}`:""}`)),re.info(ae.cyan(` Fix: ${c.recommendation}`)),re.info(""),n[c.severity]++,i++}}re.info(""),re.info(ae.bold(" Summary")),re.info(ae.dim(" "+"\u2500".repeat(60))),re.info(` Total: ${ae.bold(String(i))} finding(s)`),re.info(` ${pt.critical(` ${n.critical} Critical `)} ${pt.high(` ${n.high} High `)} ${pt.medium(` ${n.medium} Medium `)} ${pt.low(` ${n.low} Low `)} ${pt.info(` ${n.info} Info `)}`);let r=n.critical>0,o=n.high>0;r||o?(re.info(""),re.error(ae.red.bold(` FAIL \u2014 ${n.critical} critical, ${n.high} high issue(s) found`))):i>0?(re.info(""),re.warn(ae.yellow(" PASS (with warnings) \u2014 no critical or high issues"))):(re.info(""),re.success(ae.green.bold(" PASS \u2014 no issues found")))}function Er(e,t){let i=e.flatMap(r=>r.findings),n={};for(let r of Object.values(Ie))n[r]=i.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:i.length,...n},passed:n.critical===0&&n.high===0,checks:e.map(r=>({category:r.category,label:r.label,findingCount:r.findings.length,durationMs:r.durationMs,error:r.error||null})),findings:i}}import{log as oe,spinner as xa}from"@clack/prompts";import te from"chalk";import Be from"fs";import La from"os";import ft from"path";import{execSync as Ua}from"child_process";var br=16384,Ma=1,Ha=Buffer.from([127,69,76,70]);async function Ar(e){oe.info(te.bold.underline("16KB Page Alignment Check")),console.log("");let t=ft.resolve(e);if(!Be.existsSync(t))return oe.error(te.red(`APK file not found: ${t}`)),!1;if(!t.endsWith(".apk"))return oe.error(te.red("The provided file is not an APK file.")),!1;let i=xa();i.start("Extracting and analyzing native libraries...");let n=Be.mkdtempSync(ft.join(La.tmpdir(),"mach-16kb-"));try{try{Ua(`unzip -o -q "${t}" "lib/arm64-v8a/*.so" "lib/x86_64/*.so" -d "${n}" 2>/dev/null`,{encoding:"utf-8",maxBuffer:50*1024*1024})}catch{}let r=Ir(ft.join(n,"lib"));if(r.length===0)return i.stop("Analysis complete."),oe.info(te.yellow("No arm64-v8a or x86_64 native libraries found in the APK.")),oe.info(te.dim("16KB alignment check only applies to arm64-v8a and x86_64 architectures.")),!0;let o=[];for(let a of r){let c=ft.relative(n,a),d=Ba(c),u=ft.basename(a),p=Fa(a);p!==null&&o.push({name:u,filePath:c,arch:d,align:p,compatible:p>=br})}if(i.stop("Analysis complete."),o.length===0)return oe.info(te.yellow("No valid ELF shared libraries found.")),!0;let s=o.filter(a=>!a.compatible),l=o.filter(a=>a.compatible);if(oe.info(te.dim(`Checked ${o.length} native librar${o.length===1?"y":"ies"}
|
|
1153
|
+
`)),s.length>0){oe.info(te.red.bold(`Incompatible libraries:
|
|
1154
|
+
`));for(let a of s)oe.error(te.red(`${te.bold(a.name)} ${te.dim(`(${a.arch})`)}`)),oe.info(te.dim(` PT_LOAD alignment: 2**${Math.log2(a.align)} (${a.align} bytes, needs 2**14 = ${br})`))}return l.length>0&&(console.log(""),oe.success(te.green(`${l.length} librar${l.length===1?"y":"ies"} correctly aligned (2**14 or higher).`))),console.log(""),s.length===0?(oe.success(te.green.bold("ELF Verification Successful. APK is 16KB compatible.")),!0):(oe.error(te.red.bold(`Found ${s.length} unaligned lib${s.length===1?"":"s"} (arm64-v8a/x86_64 libs need to be aligned).`)),console.log(""),oe.info(te.yellow("To fix this:")),oe.info(te.dim(" 1. Rebuild with NDK r28+ which defaults to 16KB page alignment")),oe.info(te.dim(" 2. Or set -DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON in CMake")),oe.info(te.dim(" 3. Update third-party libraries that ship prebuilt .so files")),oe.info(te.dim(" 4. After rebuilding: zipalign -p -f -v 16 input.apk output.apk")),console.log(""),oe.info(te.dim("Reference: https://developer.android.com/guide/practices/page-sizes")),!1)}catch(r){return i.stop("Analysis failed."),oe.error(te.red(`Failed to analyze APK: ${r.message}`)),!1}finally{try{Be.rmSync(n,{recursive:!0,force:!0})}catch{}}}function Fa(e){let t=Be.openSync(e,"r");try{let i=Buffer.alloc(64);if(Be.readSync(t,i,0,64,0),!i.subarray(0,4).equals(Ha))return null;let n=i[4]===2,r=i[5]===1,o=(p,m)=>r?p.readUInt16LE(m):p.readUInt16BE(m),s=(p,m)=>r?p.readUInt32LE(m):p.readUInt32BE(m),l=(p,m)=>Number(r?p.readBigUInt64LE(m):p.readBigUInt64BE(m)),a,c,d;n?(a=l(i,32),c=o(i,54),d=o(i,56)):(a=s(i,28),c=o(i,42),d=o(i,44));let u=null;for(let p=0;p<d;p++){let m=Buffer.alloc(c);if(Be.readSync(t,m,0,c,a+p*c),s(m,0)!==Ma)continue;let D;n?D=l(m,48):D=s(m,28),D>0&&(u===null||D<u)&&(u=D)}return u??0}catch{return null}finally{Be.closeSync(t)}}function Ir(e){let t=[];if(!Be.existsSync(e))return t;let i=Be.readdirSync(e,{withFileTypes:!0});for(let n of i){let r=ft.join(e,n.name);n.isDirectory()?t.push(...Ir(r)):n.name.endsWith(".so")&&t.push(r)}return t}function Ba(e){return e.includes("arm64-v8a")?"arm64-v8a":e.includes("x86_64")?"x86_64":"unknown"}var $r=async e=>{if(he()||(_e.error(Ce.red(`You are not logged in. Run \`${f.nameLower} login\` first.`)),process.exit(1)),e.apk){await Ka(e);return}let i=process.cwd(),n=ni.join(i,"package.json");Tt.existsSync(n)||(_e.error(Ce.red("No package.json found. Run this command from a project root.")),process.exit(1));let r=JSON.parse(Tt.readFileSync(n,"utf-8")),o=!!(r.dependencies?.expo||r.devDependencies?.expo);e.json||(_e.info(Ce.dim(`Project: ${r.name||"unknown"} v${r.version||"0.0.0"}`)),_e.info(Ce.dim(`Type: ${o?"Expo":"Bare React Native"}`)),_e.info(""));let s={json:e.json,fix:e.fix,category:e.category,severity:e.severity,prebuild:e.prebuild},l=await yr(i,s);e.json?console.log(JSON.stringify(Er(l,r),null,2)):Sr(l,e.severity);let a=l.some(d=>d.findings.some(u=>u.severity==="critical")),c=l.some(d=>d.findings.some(u=>u.severity==="high"));(a||c)&&process.exit(1)},_r=["16kb"];async function Ka(e){let t=e.category?.toLowerCase();t&&!_r.includes(t)&&(_e.error(Ce.red(`Unknown APK check category: "${t}"`)),_e.info(Ce.dim(`Available APK checks: ${_r.join(", ")}`)),process.exit(1));let i=await Va(e.apk);i||process.exit(1);let n=!t,r=!1;(n||t==="16kb")&&(await Ar(i)||(r=!0)),r&&process.exit(1)}async function Va(e){if(e.startsWith("build:")){let i=e.slice(6);return await za(i)}if(e.startsWith("http://")||e.startsWith("https://"))return await wr(e);let t=ni.resolve(e);return Tt.existsSync(t)?t:(_e.error(Ce.red(`APK file not found: ${t}`)),null)}async function za(e){let t=Pr();t.start(`Fetching APK from build ${e}...`);try{let i=await v.get(`/build/${e}`);if(i.data.status!=="success")throw new Error(i.data.message);let n=i.data.build;if(!n)throw new Error("Build not found");let r=n.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"),_e.error(Ce.red("This build does not have an APK artifact.")),_e.info(Ce.dim("Make sure the build produced an APK (not just an AAB).")),null):(t.stop(`Found build: ${n.buildId||e}`),await wr(r.url))}catch(i){return t.stop("Failed to fetch build"),_e.error(Ce.red(i.message)),null}}async function wr(e){let t=Pr();t.start("Downloading APK...");try{let i=Tt.mkdtempSync(ni.join(Ga.tmpdir(),`${f.nameLower}-audit-`)),n=ni.join(i,"app.apk"),r=await ja.get(e,{responseType:"arraybuffer"});Tt.writeFileSync(n,r.data);let o=(r.data.length/(1024*1024)).toFixed(1);return t.stop(`Downloaded APK (${o} MB)`),n}catch(i){return t.stop("Download failed"),_e.error(Ce.red(`Failed to download APK: ${i.message}`)),null}}var Ja=console.log;console.log=()=>{};Ya();console.log=Ja;pe(de.bgCyan.black(f.cliTag("Production Build Orchestrator")));var Xa=qa(import.meta.url),Za=Xa("../package.json"),Y=new Wa;Y.name(f.nameLower).description(`${f.name} CLI: Powerful Cloud Infrastructure Tools`).version(Za.version).option("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1);Y.command("agent").description("Start local device discovery agent for the Install Hub (port 7070)").action(async()=>{await $n()});Y.command("host").description("Setup AWS S3 static hosting and CloudFront").action(async()=>{pe(de.bgCyan.black(f.cliTag("Hosting"))),await Gi()});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=>{pe(de.bgCyan.black(f.cliTag("Sitemap Generator"))),await zi(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)","production").option("--profile <name>","Build Profile (alias for --build-profile)").option("--dry-run","Generate User Data script without launching").option("--keep-instance","Do not terminate the instance after build").option("--subnet <id>","VPC Subnet ID to launch the instance in").option("--security-group <id>","VPC Security Group ID to use").option("--ssh-host <host>","Remote host for iOS build (SSH)").option("--ssh-user <user>","SSH username for remote host").option("--ssh-key <path>","Path to private SSH key for remote host").option("--ios-scheme <scheme>","iOS Scheme to build").option("--ios-team-id <id>","Apple Development Team ID").option("--ios-configuration <config>","Xcode configuration (Release/Debug)").option("--ios-export-method <method>","Export method (ad-hoc, app-store, development, enterprise)").option("--ios-api-key-id <id>","App Store Connect API Key ID").option("--ios-api-key-issuer <id>","App Store Connect API Key Issuer ID").option("--ios-api-key-path <path>","Path to App Store Connect API Key (.p8) file").option("--simulator","Build for iOS Simulator (no signing required)").addOption(new ri("--build-id <id>","Internal build ID").hideHelp()).addOption(new ri("--project-id <id>","Internal project ID").hideHelp()).option("--local","Run build on local machine").option("--auto-version","Automatically fetch and increment versionCode from Google Play").option("--verbose","Enable verbose logging").option("--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("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1).action(async(e,t)=>{let i=Y.opts();t.yes=t.yes||i.yes,t.quiet=t.quiet||i.quiet,t.platform=e||t.platform,t.buildProfile=t.profile||t.buildProfile,t.quiet||pe(de.bgCyan.black(f.cliTag("Cloud Build"))),await Gt(t)});Y.command("maestro").description("Run managed Maestro tests for an existing Mach build or artifact").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("--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("--json-output <path>","Write test run metadata JSON to a file for CI/CD").action(async e=>{pe(de.bgCyan.black(f.cliTag("Maestro Testing"))),await hn(e)});Y.command("update").description("Deploy an Over-The-Air (OTA) update to your live channel").option("--branch <name>","Channel or Branch to deploy to (e.g., production)","production").action(async e=>{pe(de.bgCyan.black(f.cliTag("OTA Update"))),await Gn(e)});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 ri("--submit-id <id>","Internal submission ID").hideHelp()).addOption(new ri("--project-id <id>","Internal project ID").hideHelp()).option("--json-output <path>","Write submission metadata JSON to a file for CI/CD").option("--latest","Use the latest successful build for submission").option("--build-id <id>","Use a specific build ID for submission").action(async e=>{let t=Y.opts();e.quiet=e.quiet||t.quiet,e.yes=e.yes||t.yes,pe(de.bgCyan.black(f.cliTag("Store Submission"))),await Hn(e)});Y.command("login").description(`Login to ${f.name} Dashboard`).action(async()=>{pe(de.bgCyan.black(f.cliTag("Login"))),await vn()});Y.command("link").description(`Link local directory to a ${f.name} Project`).action(async()=>{pe(de.bgCyan.black(f.cliTag("Link Project"))),await Cn()});Y.command("me").description("Display currently logged in user details").action(async()=>{await Kn()});Y.command("init").description(`Create a new ${f.name} Project`).action(async()=>{pe(de.bgCyan.black(f.cliTag("Init Project"))),await Nn()});Y.command("env").description("Manage Environment Variables").argument("<action>","Action to perform: set or list").argument("[args...]","Key=Value pairs for set action").action(async(e,t)=>{pe(de.bgCyan.black(f.cliTag("Env Manager"))),await xn(e,t)});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=>{pe(de.bgCyan.black(f.cliTag("Dev Server"))),await zn(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 Wn(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-UTJERDGT.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=>{pe(de.bgCyan.black(f.cliTag("Credentials Setup"))),await gt(e),Dr(de.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=>{pe(de.bgCyan.black(f.cliTag("Service Credentials"))),await Fi(e),Dr(de.green("Done!"))});var xi=Y.command("device").description("Manage registered iOS test devices");xi.command("register").description("Register a connected iOS device or enter UDID manually").option("--udid <udid>","Device UDID (skip auto-detection)").option("--name <name>","Device name").action(async e=>{await Wt("register",e)});xi.command("list").description("List all registered devices").action(async()=>{await Wt("list",{})});xi.command("remove").description("Remove a registered device").option("--udid <udid>","Device UDID to remove").action(async e=>{await Wt("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=>{pe(de.bgCyan.black(f.cliTag(e.apk?"APK Audit":"Security Audit"))),await $r(e)});var Qa=new Set(["login"]);Y.hook("preAction",(e,t)=>{let i=t.name();Qa.has(i)||Ui()});Y.on("command:*",()=>{console.error(`Invalid command: %s
|
|
1042
1155
|
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);
|