@radhya/mach 2.0.11 → 2.0.13
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 +7 -7
- package/dist/index.js +353 -256
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as
|
|
3
|
-
`;s+=`Region: ${
|
|
4
|
-
`,s+=`S3 Website URL: ${
|
|
2
|
+
import{a as fn,b as fr,c as mr,d as gr,e as $e,f as lt,g as hr,h as Sr,i as Pt,j as yr,l as Ht}from"./chunk-YMJWGZX6.js";import{a as m,b as cr,c as Pe,d as ur,e as pr,f as vt,g as Je,h as k}from"./chunk-HIP5BA3H.js";import{Command as bf,Option as Fe}from"commander";import{configDotenv as Ef}from"dotenv";import{intro as we,outro as Oa}from"@clack/prompts";import Ee from"chalk";import{text as br,confirm as Ta,spinner as ka,isCancel as ni,cancel as jt,note as xa,outro as La}from"@clack/prompts";import Gt from"chalk";async function Er(){try{let e=await br({message:"Enter Bucket Name:",placeholder:"e.g. my-app-dev",validate(r){if(r.length===0)return"Bucket name is required"}});ni(e)&&(jt("Operation cancelled."),process.exit(0));let t=await br({message:"Enter Region:",initialValue:"ap-south-1"});ni(t)&&(jt("Operation cancelled."),process.exit(0));let n=await Ta({message:"Do you want to create a CloudFront Distribution for this bucket?",initialValue:!0});ni(n)&&(jt("Operation cancelled."),process.exit(0));let i=ka();i.start("Setting up hosting infrastructure...");try{let r=await k.post("/hosting/setup",{bucketName:e,region:t,createCloudFront:n});if(r.data.status!=="success")throw new Error(r.data.message||"Hosting setup failed");i.stop("Hosting setup complete!");let o=r.data,s=`Bucket Name: ${Gt.cyan(o.bucketName)}
|
|
3
|
+
`;s+=`Region: ${Gt.cyan(o.region)}
|
|
4
|
+
`,s+=`S3 Website URL: ${Gt.blue(o.s3WebsiteUrl)}`,o.cloudFrontId&&(s+=`
|
|
5
5
|
|
|
6
|
-
CloudFront ID: ${
|
|
7
|
-
CloudFront URL: ${
|
|
6
|
+
CloudFront ID: ${Gt.cyan(o.cloudFrontId)}`,s+=`
|
|
7
|
+
CloudFront URL: ${Gt.blue(o.cloudFrontUrl)}`),xa(s,"Setup Complete!"),La("You are all set!")}catch(r){i.stop("Setup failed"),jt(`Error: ${r.response?.data?.message||r.message}`)}}catch(e){jt(`An unexpected error occurred: ${e.message}`)}}import{readdir as Ma,writeFile as Ua,access as Fa,mkdir as Ba}from"fs/promises";import{join as Ar}from"path";import{spinner as Ha,text as Ir,isCancel as wr,cancel as ii,note as ja,outro as Ga}from"@clack/prompts";import Ka from"chalk";async function Va(){let e=["./app","./src/app"];for(let t of e)try{return await Fa(t),t}catch{}return null}async function _r(e){try{let n=await Va()||"./app",i=await Ir({message:"Enter path to your app directory:",placeholder:n,initialValue:n,validate(u){if(u.length===0)return"Path is required"}});wr(i)&&(ii("Operation cancelled."),process.exit(0));let r=await Ir({message:"Enter your website base URL:",placeholder:"https://example.com",validate(u){if(u.length===0)return"Base URL is required";if(!u.startsWith("http"))return"URL must start with http:// or https://"}});wr(r)&&(ii("Operation cancelled."),process.exit(0));let o=Ha();o.start("Scanning app directory for routes...");let s=await Rr(i);o.stop(`Found ${s.length} routes`);let l=za(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 Ba(c,{recursive:!0})}catch{}await Ua(a,l,"utf-8"),o.stop("Sitemap generated successfully!"),ja(`Routes included:
|
|
8
8
|
${s.map(u=>` \u2022 ${u.path}`).join(`
|
|
9
|
-
`)}`,"Sitemap Summary"),
|
|
9
|
+
`)}`,"Sitemap Summary"),Ga(`Sitemap saved to ${Ka.cyan(a)}`)}catch(t){ii(`An error occurred: ${t.message}`)}}async function Rr(e,t=""){let n=[];try{let i=await Ma(e,{withFileTypes:!0});for(let r of i){let o=Ar(e,r.name);if(!(r.name.startsWith("_")||r.name.startsWith("."))){if(r.isDirectory()){let s=await Rr(o,Ar(t,r.name));n.push(...s)}else if(r.isFile()){if(r.name==="index.tsx"||r.name==="index.ts"||r.name==="index.jsx"||r.name==="index.js"){let s=t===""?"/":`/${t}`;n.push({path:s,file:o})}else if(r.name.match(/\.(tsx|ts|jsx|js)$/)&&!r.name.includes("_layout")&&!r.name.includes("+")){let s=r.name.replace(/\.(tsx|ts|jsx|js)$/,""),l=`/${t}/${s}`.replace(/\/+/g,"/");n.push({path:l,file:o})}}}}}catch(i){throw new Error(`Failed to scan directory ${e}: ${i.message}`)}return n}function za(e,t){let n=new Date().toISOString().split("T")[0];return`<?xml version="1.0" encoding="UTF-8"?>
|
|
10
10
|
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
|
11
11
|
${e.map(r=>{let o=r.path;return o=o.replace(/\/\([^)]+\)/g,""),o=o.replace(/\/\[.*?\]/g,"/:id"),o=o.replace(/\/+/g,"/"),o===""&&(o="/"),` <url>
|
|
12
12
|
<loc>${t}${o}</loc>
|
|
@@ -15,7 +15,7 @@ ${e.map(r=>{let o=r.path;return o=o.replace(/\/\([^)]+\)/g,""),o=o.replace(/\/\[
|
|
|
15
15
|
<priority>0.8</priority>
|
|
16
16
|
</url>`}).join(`
|
|
17
17
|
`)}
|
|
18
|
-
</urlset>`}import{randomUUID as
|
|
18
|
+
</urlset>`}import{randomUUID as Tc}from"crypto";import ge from"path";import $n from"axios";import kc from"os";import{spinner as Fi,select as Mo,confirm as Uo,isCancel as vn,cancel as Fo,log as $}from"@clack/prompts";import v from"chalk";import de from"fs";import{execSync as Bo}from"child_process";import Ho from"adm-zip";import{spinner as tl,log as mn}from"@clack/prompts";import Pr from"chalk";import Or from"fs";import Dr from"path";var $r=`#!/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,12 +28,6 @@ echo "Starting build setup..."
|
|
|
28
28
|
|
|
29
29
|
# Forward environment variables (includes PRESIGNED_* URLs + project secrets)
|
|
30
30
|
{{ENV_VARS}}
|
|
31
|
-
export MACH_FRAMEWORK="\${MACH_FRAMEWORK:-react-native}"
|
|
32
|
-
echo "[ENV] MACH_FRAMEWORK=$MACH_FRAMEWORK"
|
|
33
|
-
if [ "$MACH_FRAMEWORK" = "expo" ]; then
|
|
34
|
-
export EXPO_NO_DOTENV="\${EXPO_NO_DOTENV:-1}"
|
|
35
|
-
echo "[ENV] EXPO_NO_DOTENV=$EXPO_NO_DOTENV"
|
|
36
|
-
fi
|
|
37
31
|
export HUSKY=0
|
|
38
32
|
export CI=true
|
|
39
33
|
export npm_config_engine_strict=false
|
|
@@ -214,13 +208,23 @@ cd /home/ubuntu/build
|
|
|
214
208
|
unzip -q -o /tmp/source.zip
|
|
215
209
|
rm -f /tmp/source.zip
|
|
216
210
|
|
|
211
|
+
SOURCE_HAS_ANDROID_PROJECT=false
|
|
212
|
+
if [ -f "/home/ubuntu/build/android/app/build.gradle" ]; then
|
|
213
|
+
SOURCE_HAS_ANDROID_PROJECT=true
|
|
214
|
+
fi
|
|
215
|
+
|
|
217
216
|
# Now overlay node_modules and android/ caches on top of extracted source
|
|
218
217
|
if [ -f /tmp/node-modules-cache.tar.gz ]; then
|
|
219
218
|
tar $TAR_COMPRESS -xf /tmp/node-modules-cache.tar.gz -C /home/ubuntu/build && rm -f /tmp/node-modules-cache.tar.gz && echo "node_modules cache restored."
|
|
220
219
|
fi
|
|
221
220
|
|
|
222
221
|
if [ -f /tmp/android-cache.tar.gz ]; then
|
|
223
|
-
|
|
222
|
+
if [ "$SOURCE_HAS_ANDROID_PROJECT" = "true" ]; then
|
|
223
|
+
rm -f /tmp/android-cache.tar.gz
|
|
224
|
+
echo "[CACHE] Skipping android/ cache restore because source includes android/app/build.gradle."
|
|
225
|
+
else
|
|
226
|
+
tar $TAR_COMPRESS -xf /tmp/android-cache.tar.gz -C /home/ubuntu/build && rm -f /tmp/android-cache.tar.gz && echo "android/ cache restored."
|
|
227
|
+
fi
|
|
224
228
|
fi
|
|
225
229
|
|
|
226
230
|
# Older android/ caches may include Gradle outputs and pre-bundled JS from a
|
|
@@ -284,49 +288,10 @@ clear_js_transform_caches
|
|
|
284
288
|
# Apply before Expo prebuild so generated Gradle files receive the new versionCode.
|
|
285
289
|
if [ ! -z "$ANDROID_VERSION_CODE" ]; then
|
|
286
290
|
echo "[VERSIONING] Applying injected versionCode: $ANDROID_VERSION_CODE"
|
|
287
|
-
|
|
288
|
-
node -e "const fs=require('fs');const p='app.json';if(fs.existsSync(p)){const j=JSON.parse(fs.readFileSync(p,'utf8'));j.expo=j.expo||{};j.expo.android=j.expo.android||{};j.expo.android.versionCode=Number(process.env.ANDROID_VERSION_CODE);fs.writeFileSync(p,JSON.stringify(j,null,2));console.log('[VERSIONING] app.json expo.android.versionCode updated');}"
|
|
289
|
-
fi
|
|
291
|
+
{{FRAMEWORK_ANDROID_VERSION_CODE}}
|
|
290
292
|
fi
|
|
291
293
|
|
|
292
|
-
|
|
293
|
-
# Compute a hash of native-affecting files and the Mach-injected app env to
|
|
294
|
-
# decide if android/ cache is still valid. Env names are project-defined, so the
|
|
295
|
-
# CLI precomputes MACH_ENV_FINGERPRINT from all relevant managed values.
|
|
296
|
-
if [ "$MACH_FRAMEWORK" = "expo" ]; then
|
|
297
|
-
if [ -f "app.json" ] || [ -f "app.config.ts" ] || [ -f "app.config.js" ]; then
|
|
298
|
-
PREBUILD_HASH_FILE="/home/ubuntu/build/.mach-prebuild-hash"
|
|
299
|
-
PREBUILD_ENV_HASH="\${MACH_ENV_FINGERPRINT:-missing-env-fingerprint}"
|
|
300
|
-
PREBUILD_CURRENT_HASH=$(
|
|
301
|
-
{
|
|
302
|
-
cat app.json app.config.ts app.config.js 2>/dev/null
|
|
303
|
-
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
|
|
304
|
-
printf '%s\\n' "$PREBUILD_ENV_HASH"
|
|
305
|
-
} | md5sum | cut -d' ' -f1
|
|
306
|
-
)
|
|
307
|
-
|
|
308
|
-
ANDROID_CACHE_VALID=false
|
|
309
|
-
if [ -f "$PREBUILD_HASH_FILE" ] && [ -d "android" ] && [ -f "android/gradlew" ]; then
|
|
310
|
-
STORED_HASH=$(cat "$PREBUILD_HASH_FILE" 2>/dev/null)
|
|
311
|
-
if [ "$PREBUILD_CURRENT_HASH" = "$STORED_HASH" ]; then
|
|
312
|
-
ANDROID_CACHE_VALID=true
|
|
313
|
-
echo "[PREBUILD] android/ cache is valid (hash match) \u2014 skipping expo prebuild."
|
|
314
|
-
fi
|
|
315
|
-
fi
|
|
316
|
-
|
|
317
|
-
if [ "$ANDROID_CACHE_VALID" = "false" ]; then
|
|
318
|
-
echo "[PREBUILD] Running expo prebuild..."
|
|
319
|
-
if [ -f "node_modules/.bin/expo" ]; then
|
|
320
|
-
node_modules/.bin/expo prebuild --platform android --no-install
|
|
321
|
-
else
|
|
322
|
-
npx expo prebuild --platform android --no-install
|
|
323
|
-
fi
|
|
324
|
-
echo "$PREBUILD_CURRENT_HASH" > "$PREBUILD_HASH_FILE"
|
|
325
|
-
fi
|
|
326
|
-
fi
|
|
327
|
-
else
|
|
328
|
-
echo "[PREBUILD] Skipping Expo prebuild for framework: $MACH_FRAMEWORK"
|
|
329
|
-
fi
|
|
294
|
+
{{FRAMEWORK_ANDROID_PREBUILD}}
|
|
330
295
|
|
|
331
296
|
# Build
|
|
332
297
|
step_marker build
|
|
@@ -368,9 +333,7 @@ echo "org.gradle.workers.max=8" >> gradle.properties
|
|
|
368
333
|
echo "org.gradle.configureondemand=true" >> gradle.properties
|
|
369
334
|
# Use Gradle build cache (works with the restored ~/.gradle cache)
|
|
370
335
|
echo "org.gradle.caching=true" >> gradle.properties
|
|
371
|
-
|
|
372
|
-
echo "expo.enableHermes=true" >> gradle.properties
|
|
373
|
-
fi
|
|
336
|
+
{{FRAMEWORK_ANDROID_GRADLE_PROPERTIES}}
|
|
374
337
|
# Disable Sentry Gradle plugin upload \u2014 runs after Gradle via sentry-cli instead (avoids hangs).
|
|
375
338
|
# These env vars are read directly by @sentry/react-native's sentry.gradle.
|
|
376
339
|
export SENTRY_DISABLE_AUTO_UPLOAD=true
|
|
@@ -390,9 +353,7 @@ if printf "%s" "{{BUILD_COMMAND}}" | grep -iq "release"; then
|
|
|
390
353
|
echo "[OPTIMIZATION] Release build uses ARM device ABI(s): $ANDROID_RELEASE_ABIS"
|
|
391
354
|
fi
|
|
392
355
|
|
|
393
|
-
|
|
394
|
-
echo "expo.enableProguardInReleaseBuilds=true" >> gradle.properties
|
|
395
|
-
fi
|
|
356
|
+
{{FRAMEWORK_ANDROID_RELEASE_GRADLE_PROPERTIES}}
|
|
396
357
|
fi
|
|
397
358
|
# --- EAS-style Android Signing (via Gradle injection) ---
|
|
398
359
|
SIGNING_FLAGS=()
|
|
@@ -531,7 +492,9 @@ if [ -d "/home/ubuntu/build/node_modules" ] && [ ! -z "$PRESIGNED_CACHE_NODE_MOD
|
|
|
531
492
|
cache_pids+=($!)
|
|
532
493
|
fi
|
|
533
494
|
|
|
534
|
-
if [
|
|
495
|
+
if [ "$SOURCE_HAS_ANDROID_PROJECT" = "true" ]; then
|
|
496
|
+
echo "[CACHE] Skipping android/ cache save because source owns the Android project."
|
|
497
|
+
elif [ -d "/home/ubuntu/build/android" ] && [ ! -z "$PRESIGNED_CACHE_ANDROID_UPLOAD" ]; then
|
|
535
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.") &
|
|
536
499
|
cache_pids+=($!)
|
|
537
500
|
fi
|
|
@@ -548,16 +511,103 @@ for pid in "\${cache_pids[@]}"; do wait "$pid" || true; done
|
|
|
548
511
|
echo "Build orchestrator finished. Auto-terminating instance in 5 seconds..."
|
|
549
512
|
sleep 5
|
|
550
513
|
sudo shutdown -h now
|
|
551
|
-
`;import
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
export
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
514
|
+
`;import Xa from"crypto";import{log as Oe}from"@clack/prompts";import De from"chalk";import{execSync as Wa}from"child_process";import Ce from"fs";import Ot from"path";var vr={id:"expo",displayName:"Expo",applyLocalProcessEnv:e=>{e.developmentClient?(Oe.info(De.blue("\u2139\uFE0F Configuring Expo build to INCLUDE expo-dev-client (Development Client mode)...")),delete process.env.EXPO_NO_DEV_CLIENT,delete process.env.EXPO_AUTOLINKING_EXCLUDE):(Oe.info(De.blue("\u2139\uFE0F Configuring Expo build to EXCLUDE expo-dev-client (Production/Staging mode)...")),process.env.EXPO_NO_DEV_CLIENT="1",process.env.EXPO_AUTOLINKING_EXCLUDE="expo-dev-client")},localAndroidEnv:(e,t)=>({EXPO_NO_DOTENV:"1",MACH_FRAMEWORK:"expo",MACH_BUILD_PROFILE:t}),remoteEnvSetupScript:()=>`
|
|
515
|
+
export MACH_FRAMEWORK="expo"
|
|
516
|
+
echo "[ENV] MACH_FRAMEWORK=$MACH_FRAMEWORK"
|
|
517
|
+
export EXPO_NO_DOTENV="\${EXPO_NO_DOTENV:-1}"
|
|
518
|
+
echo "[ENV] EXPO_NO_DOTENV=$EXPO_NO_DOTENV"
|
|
519
|
+
`,iosRemotePrebuildScript:()=>`
|
|
520
|
+
echo "[STEP_START:prebuild] $(date +%s)"
|
|
521
|
+
echo "Expo framework configured. Running prebuild..."
|
|
522
|
+
# Use --no-install so we can patch the Podfile before pod install.
|
|
523
|
+
CI=1 npx expo prebuild --platform ios --clean --no-install
|
|
524
|
+
`,androidRemoteVersionCodeScript:()=>`
|
|
525
|
+
if [ ! -z "$ANDROID_VERSION_CODE" ]; then
|
|
526
|
+
node -e "const fs=require('fs');const p='app.json';if(fs.existsSync(p)){const j=JSON.parse(fs.readFileSync(p,'utf8'));j.expo=j.expo||{};j.expo.android=j.expo.android||{};j.expo.android.versionCode=Number(process.env.ANDROID_VERSION_CODE);fs.writeFileSync(p,JSON.stringify(j,null,2));console.log('[VERSIONING] app.json expo.android.versionCode updated');}"
|
|
527
|
+
fi
|
|
528
|
+
`,androidRemotePrebuildScript:()=>`
|
|
529
|
+
# Compute a hash of native-affecting files and the Mach-injected app env to
|
|
530
|
+
# decide if android/ cache is still valid. Env names are project-defined, so the
|
|
531
|
+
# CLI precomputes MACH_ENV_FINGERPRINT from all relevant managed values.
|
|
532
|
+
if [ -f "app.json" ] || [ -f "app.config.ts" ] || [ -f "app.config.js" ]; then
|
|
533
|
+
PREBUILD_HASH_FILE="/home/ubuntu/build/.mach-prebuild-hash"
|
|
534
|
+
PREBUILD_ENV_HASH="\${MACH_ENV_FINGERPRINT:-missing-env-fingerprint}"
|
|
535
|
+
PREBUILD_CURRENT_HASH=$(
|
|
536
|
+
{
|
|
537
|
+
cat app.json app.config.ts app.config.js 2>/dev/null
|
|
538
|
+
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
|
|
539
|
+
printf '%s\\n' "$PREBUILD_ENV_HASH"
|
|
540
|
+
} | md5sum | cut -d' ' -f1
|
|
541
|
+
)
|
|
542
|
+
|
|
543
|
+
ANDROID_CACHE_VALID=false
|
|
544
|
+
if [ -f "$PREBUILD_HASH_FILE" ] && [ -d "android" ] && [ -f "android/gradlew" ]; then
|
|
545
|
+
STORED_HASH=$(cat "$PREBUILD_HASH_FILE" 2>/dev/null)
|
|
546
|
+
if [ "$PREBUILD_CURRENT_HASH" = "$STORED_HASH" ]; then
|
|
547
|
+
ANDROID_CACHE_VALID=true
|
|
548
|
+
echo "[PREBUILD] android/ cache is valid (hash match) \u2014 skipping expo prebuild."
|
|
549
|
+
fi
|
|
550
|
+
fi
|
|
551
|
+
|
|
552
|
+
if [ "$ANDROID_CACHE_VALID" = "false" ]; then
|
|
553
|
+
echo "[PREBUILD] Running expo prebuild..."
|
|
554
|
+
if [ -f "node_modules/.bin/expo" ]; then
|
|
555
|
+
node_modules/.bin/expo prebuild --platform android --no-install
|
|
556
|
+
else
|
|
557
|
+
npx expo prebuild --platform android --no-install
|
|
558
|
+
fi
|
|
559
|
+
echo "$PREBUILD_CURRENT_HASH" > "$PREBUILD_HASH_FILE"
|
|
560
|
+
fi
|
|
561
|
+
fi
|
|
562
|
+
`,androidRemoteGradlePropertiesScript:()=>`
|
|
563
|
+
echo "expo.enableHermes=true" >> gradle.properties
|
|
564
|
+
`,androidRemoteReleaseGradlePropertiesScript:()=>`
|
|
565
|
+
echo "expo.enableProguardInReleaseBuilds=true" >> gradle.properties
|
|
566
|
+
`,prepareLocalProject:async e=>{let{platform:t,options:n,cacheMeta:i,cacheMetaDir:r,currentBuildEnv:o,reportStep:s,loggedRun:l,configureXcodeNodeBinary:a,podsFingerprint:c,writeCacheMeta:u}=e,d=n.iosBundleIdentifier||"",f=n.name||"",p=Ot.join(process.cwd(),"app.json"),g=null;Oe.info(De.blue(`Running Expo prebuild for ${t}...`));try{if(Ce.existsSync(p)){g=Ce.readFileSync(p,"utf-8");let _=JSON.parse(g);_.expo=_.expo||{},f||(f=_.expo.name||""),t==="ios"&&!d&&(d=_.expo?.ios?.bundleIdentifier||""),n.name&&(_.expo.name=n.name),n.scheme&&(_.expo.scheme=n.scheme),t==="ios"&&n.iosBundleIdentifier?(_.expo.ios=_.expo.ios||{},_.expo.ios.bundleIdentifier=n.iosBundleIdentifier):t==="android"&&n.androidPackage&&(_.expo.android=_.expo.android||{},_.expo.android.package=n.androidPackage),Ce.writeFileSync(p,JSON.stringify(_,null,2))}let y=["exec","--","expo","prebuild","--platform",t,"--no-install"];if(await s("prebuild"),await l("npm",y,process.cwd(),o()),t!=="ios"||!Ce.existsSync("ios"))return{appName:f,bundleId:d};await s("pods"),Oe.info(De.blue("Running pod install..."));try{let _=Ot.resolve("ios"),D=Ot.join(_,"Podfile");if(!Ce.existsSync(D))throw new Error("ios/Podfile not found. Skipping pod install.");let b=o();a(_,b);let x=Ce.readFileSync(D,"utf-8"),A=n.iosDeploymentTarget||"13.4";if(!n.developmentClient&&(Oe.info(De.blue("\u2139\uFE0F Patching Podfile to EXCLUDE expo-dev-client...")),x.includes("use_expo_modules!")&&!x.includes("exclude:"))){let C=/use_expo_modules!(\s*)$/m;C.test(x)?x=x.replace(C,'use_expo_modules!(exclude: ["expo-dev-client"])$1'):x=x.replace("use_expo_modules!",'use_expo_modules!(exclude: ["expo-dev-client"])')}let B=`
|
|
567
|
+
installer.generated_projects.each do |project|
|
|
568
|
+
project.targets.each do |target|
|
|
569
|
+
target.build_configurations.each do |config|
|
|
570
|
+
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '${A}'
|
|
571
|
+
end
|
|
572
|
+
end
|
|
573
|
+
end
|
|
574
|
+
installer.pods_project.targets.each do |target|
|
|
575
|
+
target.build_configurations.each do |config|
|
|
576
|
+
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '${A}'
|
|
577
|
+
end
|
|
578
|
+
end
|
|
579
|
+
`,q=/post_install\s+do\s+\|installer\|/;if(q.test(x))Oe.info(De.dim(`Injecting deployment target (${A}) into existing post_install hook...`)),x=x.replace(q,`post_install do |installer|
|
|
580
|
+
${B}`),Ce.writeFileSync(D,x);else{Oe.info(De.dim(`Appending new post_install hook for deployment target (${A})...`));let C=`
|
|
581
|
+
post_install do |installer|
|
|
582
|
+
${B}
|
|
583
|
+
end
|
|
584
|
+
`;Ce.appendFileSync(D,C)}let P="/opt/homebrew/bin/pod",I=Ce.existsSync(P)?P:"pod",T=c(_);Ce.existsSync(Ot.join(_,"Pods"))&&i.pods&&i.pods!==T&&(await e.reportLog(`[CACHE] Podfile/Podfile.lock changed \u2014 wiping ios/Pods
|
|
585
|
+
`),Oe.info(De.dim("Podfile fingerprint changed \u2014 clearing Pods for clean install...")),Ce.rmSync(Ot.join(_,"Pods"),{recursive:!0,force:!0})),Oe.info(De.dim(`Using pod command: ${I} in ${_}`)),await l(I,["install"],_,b),i.pods=T,u(r,i)}catch(_){let D=_.message||"Unknown error";Oe.warn(De.yellow(`Native "pod" command failed: ${D}`)),Oe.info(De.dim("Falling back to npm exec pod-install..."));let b=o();a(Ot.resolve("ios"),b),Oe.info(De.magenta(`${m.nameUpper}_DEBUG: Executing pod-install override via npx --yes pod-install@latest`)),await l("npx",["--yes","pod-install@latest","ios"],process.cwd(),b)}if(Ce.existsSync("ios/Pods")){Oe.info(De.dim("Disabling signing for Pod targets to prevent conflicts..."));try{Wa(`find ios/Pods -name "project.pbxproj" -exec sed -i '' 's/buildSettings = {/buildSettings = { CODE_SIGNING_ALLOWED = NO; CODE_SIGNING_REQUIRED = NO; PROVISIONING_PROFILE_SPECIFIER = ""; EXPANDED_CODE_SIGN_IDENTITY = "";/g' {} +`,{stdio:"ignore"})}catch{}}return{appName:f,bundleId:d}}finally{g&&Ce.writeFileSync(p,g)}}};import{log as St}from"@clack/prompts";import yt from"chalk";import Ze from"fs";import Kt from"path";var Ya=(e,t)=>!Ze.existsSync(e)||!Ze.existsSync(t)?!1:Ze.readFileSync(e,"utf-8")!==Ze.readFileSync(t,"utf-8"),ri={id:"react-native",displayName:"React Native",applyLocalProcessEnv:e=>{delete process.env.EXPO_NO_DEV_CLIENT,delete process.env.EXPO_AUTOLINKING_EXCLUDE,delete process.env.EXPO_NO_DOTENV},localAndroidEnv:(e,t)=>({MACH_FRAMEWORK:"react-native",MACH_BUILD_PROFILE:t}),remoteEnvSetupScript:()=>`
|
|
586
|
+
export MACH_FRAMEWORK="react-native"
|
|
587
|
+
echo "[ENV] MACH_FRAMEWORK=$MACH_FRAMEWORK"
|
|
588
|
+
unset EXPO_NO_DOTENV
|
|
589
|
+
`,iosRemotePrebuildScript:()=>`
|
|
590
|
+
echo "[STEP_START:prebuild] $(date +%s)"
|
|
591
|
+
echo "[PREBUILD] React Native framework configured. Skipping Expo prebuild."
|
|
592
|
+
`,androidRemoteVersionCodeScript:()=>`
|
|
593
|
+
echo "[VERSIONING] React Native framework configured. Version code will be injected through Gradle."
|
|
594
|
+
`,androidRemotePrebuildScript:()=>`
|
|
595
|
+
echo "[PREBUILD] React Native framework configured. Skipping Expo prebuild."
|
|
596
|
+
`,androidRemoteGradlePropertiesScript:()=>`
|
|
597
|
+
:
|
|
598
|
+
`,androidRemoteReleaseGradlePropertiesScript:()=>`
|
|
599
|
+
:
|
|
600
|
+
`,prepareLocalProject:async e=>{let{platform:t,cacheMeta:n,cacheMetaDir:i,currentBuildEnv:r,reportStep:o,reportLog:s,loggedRun:l,configureXcodeNodeBinary:a,podsFingerprint:c,writeCacheMeta:u}=e;if(t!=="ios")return{};let d=Kt.resolve("ios"),f=Kt.join(d,"Podfile");if(!Ze.existsSync(f))throw new Error("React Native iOS build requires ios/Podfile. Commit the ios directory for vanilla React Native projects.");await o("pods"),St.info(yt.blue("Running React Native pod install..."));let p=r();a(d,p);let g=Kt.join(d,"Pods"),y=Kt.join(d,"Podfile.lock"),_=Kt.join(g,"Manifest.lock"),D=Ze.existsSync(g),b=c(d);D&&n.reactNativePods&&n.reactNativePods!==b?(await s(`[CACHE] React Native Podfile/Podfile.lock changed - wiping ios/Pods
|
|
601
|
+
`),St.info(yt.dim("React Native Podfile fingerprint changed - clearing Pods for clean install...")),Ze.rmSync(g,{recursive:!0,force:!0})):D&&Ya(y,_)&&(await s(`[CACHE] React Native Pods Manifest.lock is out of sync - wiping ios/Pods
|
|
602
|
+
`),St.info(yt.dim("React Native Pods manifest is out of sync - clearing Pods for clean install...")),Ze.rmSync(g,{recursive:!0,force:!0}));let x="/opt/homebrew/bin/pod",A=Ze.existsSync(x)?x:"pod";try{St.info(yt.dim(`Using pod command: ${A} in ${d}`)),await l(A,["install"],d,p)}catch(B){let q=B.message||"Unknown error";St.warn(yt.yellow(`Native "pod" command failed: ${q}`)),St.info(yt.dim("Falling back to npx pod-install..."));let P=r();a(d,P),St.info(yt.magenta(`${m.nameUpper}_DEBUG: Executing pod-install fallback via npx --yes pod-install@latest`)),await l("npx",["--yes","pod-install@latest","ios"],process.cwd(),P)}return n.reactNativePods=c(d),u(i,n),{}}};var Ja={expo:vr,"react-native":ri};function Qe(e){if(!e)return ri;if(e!=="flutter")return Ja[e];throw new Error('Flutter builds are not implemented yet. Set framework to "expo" or "react-native" for this build.')}var qa="mach-env-v2-js-bundle-cache",Za=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"]),Qa=["PRESIGNED_","KEYSTORE_PASSWORD_"],el=e=>!e||Za.has(e)?!1:!Qa.some(t=>e.startsWith(t)),bt=(e,t,n)=>{let i=Qe(n.framework);return{...e,...i.localAndroidEnv(n,t),MACH_APP_NAME:n.appName||n.name||"App"}},Dt=e=>{let t=Object.entries(e).filter(([n])=>el(n)).sort(([n],[i])=>n.localeCompare(i));return Xa.createHash("sha256").update(JSON.stringify({version:qa,entries:t})).digest("hex")};var oi=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`"),si=e=>["1","true","yes","on"].includes(String(e||"").trim().toLowerCase()),nl=e=>/(^|[-_])(maestro|e2e|test|emulator)([-_]|$)/i.test(e),il=(e,t,n)=>{let i=n.MACH_ANDROID_RELEASE_ABIS||n.MACH_ANDROID_ABIS||n.MACH_PROFILE_ANDROID_RELEASE_ABIS||n.MACH_PROFILE_ANDROID_ABIS||n.MACH_PROFILE_ANDROID_ARCHITECTURES||n.MACH_PROFILE_ANDROID_REACT_NATIVE_ARCHITECTURES;return i||(!!e.maestro||nl(t)||si(n.MACH_PROFILE_ANDROID_EMULATOR)||si(n.MACH_ANDROID_INCLUDE_EMULATOR_ABIS)||si(n.MACH_PROFILE_ANDROID_INCLUDE_EMULATOR_ABIS)?"armeabi-v7a,arm64-v8a,x86_64":"armeabi-v7a,arm64-v8a")},Cr=async(e,t,n={},i,r)=>{let o=tl(),s=Qe(e.framework),l=e.buildProfile||"production",a=l==="production",c=e.apk===!0,u=e.developmentClient?"assembleDebug":a?"bundleRelease":"assembleRelease",d=e.buildCommand||(c?"assembleRelease":u),f=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(`
|
|
603
|
+
`):"",p;if(r){let b=Dr.isAbsolute(r)?r:Dr.resolve(process.cwd(),r);Or.existsSync(b)?(p=Or.readFileSync(b,"utf-8"),mn.info(Pr.magenta(`\u2713 Loaded preBuild hook: ${r}`))):mn.warn(`preBuild script not found at ${b} \u2014 skipping`)}let g=il(e,l,n),y={...bt(n,l,e),MACH_ANDROID_RELEASE_ABIS:g},_=Dt(y),D=$r.replace(/\{\{BUILD_ID\}\}/g,t).replace(/\{\{BUILD_COMMAND\}\}/g,d).replace("{{NODE_VERSION_SETUP}}",f).replace("{{ENV_VARS}}",`
|
|
604
|
+
export MACH_APP_NAME="${oi(y.MACH_APP_NAME)}"
|
|
605
|
+
export MACH_BUILD_PROFILE="${oi(l)}"
|
|
606
|
+
export MACH_ANDROID_RELEASE_ABIS="${oi(g)}"
|
|
607
|
+
export MACH_ENV_FINGERPRINT="${_}"
|
|
608
|
+
${s.remoteEnvSetupScript().trim()}
|
|
559
609
|
{{ENV_VARS}}
|
|
560
|
-
`);if(e.dryRun){
|
|
610
|
+
`).replace("{{FRAMEWORK_ANDROID_VERSION_CODE}}",s.androidRemoteVersionCodeScript().trim()).replace("{{FRAMEWORK_ANDROID_PREBUILD}}",s.androidRemotePrebuildScript().trim()).replace("{{FRAMEWORK_ANDROID_GRADLE_PROPERTIES}}",s.androidRemoteGradlePropertiesScript().trim()).replace("{{FRAMEWORK_ANDROID_RELEASE_GRADLE_PROPERTIES}}",s.androidRemoteReleaseGradlePropertiesScript().trim());if(e.dryRun){mn.info("User Data Script (dry run):"),console.log(D);return}o.start("Requesting cloud build instance...");try{let b=await k.post("/builds/launch-android",{projectId:i,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:n,dryRun:e.dryRun,userDataScript:D,preBuildScriptContent:p});if(b.data.status!=="success")throw new Error(b.data.message||"Failed to launch build instance");let x=b.data.instanceId;return o.stop("Build Started"),mn.success(Pr.green(`Build initiated on cloud instance (${x}).`)),{instanceId:x}}catch(b){o.stop("Android Build Failed");let x=b.response?.data?.message||b.message;throw new Error(`Failed to launch Android build: ${x}`)}};import{spinner as rl,log as Et}from"@clack/prompts";import et from"chalk";import ol from"fs";import{execSync as Vt}from"child_process";var Nr=`#!/bin/bash
|
|
561
611
|
# --- Mach Cloud Build Script (iOS) ---
|
|
562
612
|
# All S3 operations use presigned URLs via curl \u2014 zero AWS credentials on Mac.
|
|
563
613
|
|
|
@@ -584,12 +634,6 @@ set -e
|
|
|
584
634
|
|
|
585
635
|
# 4. Forward environment variables (includes PRESIGNED_* URLs + project secrets)
|
|
586
636
|
{{ENV_VARS}}
|
|
587
|
-
export MACH_FRAMEWORK="\${MACH_FRAMEWORK:-react-native}"
|
|
588
|
-
echo "[ENV] MACH_FRAMEWORK=$MACH_FRAMEWORK"
|
|
589
|
-
if [ "$MACH_FRAMEWORK" = "expo" ]; then
|
|
590
|
-
export EXPO_NO_DOTENV="\${EXPO_NO_DOTENV:-1}"
|
|
591
|
-
echo "[ENV] EXPO_NO_DOTENV=$EXPO_NO_DOTENV"
|
|
592
|
-
fi
|
|
593
637
|
|
|
594
638
|
BUILD_ID="{{BUILD_ID}}"
|
|
595
639
|
BUILD_ENV_HASH="\${MACH_ENV_FINGERPRINT:-missing-env-fingerprint}"
|
|
@@ -677,6 +721,22 @@ clear_js_transform_caches() {
|
|
|
677
721
|
rm -rf "$HOME/Library/Caches/metro" "$HOME/Library/Caches/react-native-packager" "$HOME/.cache/metro" .expo node_modules/.cache/metro 2>/dev/null || true
|
|
678
722
|
}
|
|
679
723
|
|
|
724
|
+
configure_xcode_node_binary() {
|
|
725
|
+
CURRENT_NODE="$(command -v node || true)"
|
|
726
|
+
if [ -z "$CURRENT_NODE" ] || [ ! -x "$CURRENT_NODE" ]; then
|
|
727
|
+
echo "Error: node executable not found for Xcode build scripts."
|
|
728
|
+
exit 1
|
|
729
|
+
fi
|
|
730
|
+
|
|
731
|
+
export NODE_BINARY="$CURRENT_NODE"
|
|
732
|
+
export PATH="$(dirname "$CURRENT_NODE"):$PATH"
|
|
733
|
+
|
|
734
|
+
if [ -d "ios" ]; then
|
|
735
|
+
printf 'export NODE_BINARY="%s"\\n' "$CURRENT_NODE" > ios/.xcode.env.local
|
|
736
|
+
echo "[NODE] Xcode NODE_BINARY: $CURRENT_NODE"
|
|
737
|
+
fi
|
|
738
|
+
}
|
|
739
|
+
|
|
680
740
|
# 1. Node Modules Cache \u2014 download via presigned URL
|
|
681
741
|
if [ ! -d "node_modules" ] || [ -z "$(ls -A node_modules 2>/dev/null)" ]; then
|
|
682
742
|
echo "Checking node_modules cache..."
|
|
@@ -714,15 +774,9 @@ if [ ! -z "$PRESIGNED_CACHE_NODE_UPLOAD" ]; then
|
|
|
714
774
|
rm node_modules.tar.gz
|
|
715
775
|
fi
|
|
716
776
|
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
echo "Expo framework configured. Running prebuild..."
|
|
721
|
-
# Use --no-install so we can patch the Podfile before pod install
|
|
722
|
-
CI=1 npx expo prebuild --platform ios --clean --no-install
|
|
723
|
-
else
|
|
724
|
-
echo "Skipping Expo prebuild for framework: $MACH_FRAMEWORK"
|
|
725
|
-
fi
|
|
777
|
+
{{FRAMEWORK_PREBUILD}}
|
|
778
|
+
|
|
779
|
+
configure_xcode_node_binary
|
|
726
780
|
|
|
727
781
|
# 5. Apply simulator fix to Podfile dynamically (keeps project source clean)
|
|
728
782
|
IS_SIMULATOR="{{IS_SIMULATOR}}"
|
|
@@ -872,6 +926,7 @@ security unlock-keychain -p "\${TEMP_KEYCHAIN_PASSWORD}" "\${TEMP_KEYCHAIN_PATH}
|
|
|
872
926
|
# Build IPA
|
|
873
927
|
echo "[STEP_START:build] $(date +%s)"
|
|
874
928
|
clear_js_transform_caches
|
|
929
|
+
configure_xcode_node_binary
|
|
875
930
|
if [ -f "Fastfile" ] || [ -d "fastlane" ]; then
|
|
876
931
|
bundle exec fastlane ios build
|
|
877
932
|
elif [ -d "ios" ]; then
|
|
@@ -894,7 +949,8 @@ elif [ -d "ios" ]; then
|
|
|
894
949
|
|
|
895
950
|
if [ "$IS_SIMULATOR" == "true" ]; then
|
|
896
951
|
SDK="iphonesimulator"
|
|
897
|
-
EXTRA_ARGS="COMPILER_INDEX_STORE_ENABLE=NO CODE_SIGNING_ALLOWED=NO CODE_SIGNING_REQUIRED=NO"
|
|
952
|
+
EXTRA_ARGS="COMPILER_INDEX_STORE_ENABLE=NO CODE_SIGNING_ALLOWED=NO CODE_SIGNING_REQUIRED=NO ONLY_ACTIVE_ARCH=NO EXCLUDED_ARCHS= SUPPORTED_PLATFORMS=iphonesimulator"
|
|
953
|
+
echo "Building for iOS simulator with standard simulator architectures"
|
|
898
954
|
fi
|
|
899
955
|
|
|
900
956
|
resolve_simulator_destination() {
|
|
@@ -987,6 +1043,45 @@ NODE
|
|
|
987
1043
|
return $STATUS
|
|
988
1044
|
}
|
|
989
1045
|
|
|
1046
|
+
validate_simulator_app() {
|
|
1047
|
+
APP_PATH="$1"
|
|
1048
|
+
PLIST_PATH="$APP_PATH/Info.plist"
|
|
1049
|
+
if [ ! -f "$PLIST_PATH" ]; then
|
|
1050
|
+
echo "Error: Simulator app is missing Info.plist: $APP_PATH"
|
|
1051
|
+
exit 1
|
|
1052
|
+
fi
|
|
1053
|
+
|
|
1054
|
+
EXECUTABLE_NAME=$(/usr/libexec/PlistBuddy -c "Print :CFBundleExecutable" "$PLIST_PATH" 2>/dev/null || true)
|
|
1055
|
+
if [ -z "$EXECUTABLE_NAME" ] || [ ! -f "$APP_PATH/$EXECUTABLE_NAME" ]; then
|
|
1056
|
+
echo "Error: Simulator app executable is missing in $APP_PATH"
|
|
1057
|
+
exit 1
|
|
1058
|
+
fi
|
|
1059
|
+
|
|
1060
|
+
EXECUTABLE_PATH="$APP_PATH/$EXECUTABLE_NAME"
|
|
1061
|
+
REQUIRED_ARCH="$(uname -m)"
|
|
1062
|
+
if [ "$REQUIRED_ARCH" != "arm64" ]; then
|
|
1063
|
+
REQUIRED_ARCH="x86_64"
|
|
1064
|
+
fi
|
|
1065
|
+
|
|
1066
|
+
LIPO_INFO=$(lipo -info "$EXECUTABLE_PATH" 2>/dev/null || true)
|
|
1067
|
+
if ! echo "$LIPO_INFO" | grep -Eq "\\b$REQUIRED_ARCH\\b"; then
|
|
1068
|
+
echo "Error: iOS simulator app $(basename "$APP_PATH") does not include required $REQUIRED_ARCH simulator architecture."
|
|
1069
|
+
echo "lipo output: $LIPO_INFO"
|
|
1070
|
+
exit 1
|
|
1071
|
+
fi
|
|
1072
|
+
|
|
1073
|
+
BUILD_INFO=$(xcrun vtool -show-build "$EXECUTABLE_PATH" 2>/dev/null || true)
|
|
1074
|
+
if ! echo "$BUILD_INFO" | grep -Eiq "\\bplatform[[:space:]]+IOSSIMULATOR\\b"; then
|
|
1075
|
+
echo "Error: iOS simulator app $(basename "$APP_PATH") was built for the wrong Apple platform."
|
|
1076
|
+
echo "Expected PLATFORM IOSSIMULATOR. vtool output:"
|
|
1077
|
+
echo "$BUILD_INFO"
|
|
1078
|
+
exit 1
|
|
1079
|
+
fi
|
|
1080
|
+
|
|
1081
|
+
echo "Simulator executable architecture: $LIPO_INFO"
|
|
1082
|
+
echo "$BUILD_INFO" | grep -Ei "\\bplatform\\b" | head -n 1 | sed 's/^/Simulator executable /'
|
|
1083
|
+
}
|
|
1084
|
+
|
|
990
1085
|
if [ ! -z "$WORKSPACE" ]; then
|
|
991
1086
|
if [ -z "$USER_SCHEME" ]; then
|
|
992
1087
|
# Try to find scheme matching workspace name
|
|
@@ -1004,12 +1099,12 @@ NODE
|
|
|
1004
1099
|
if [ "$IS_SIMULATOR" == "true" ]; then
|
|
1005
1100
|
SIMULATOR_DESTINATION=$(resolve_simulator_destination -workspace "$WORKSPACE")
|
|
1006
1101
|
if [ -z "$SIMULATOR_DESTINATION" ]; then
|
|
1007
|
-
|
|
1102
|
+
SIMULATOR_DESTINATION="generic/platform=iOS Simulator"
|
|
1103
|
+
echo "No specific simulator destination found during preflight. Using generic simulator destination: $SIMULATOR_DESTINATION"
|
|
1008
1104
|
else
|
|
1009
1105
|
echo "Using simulator destination: $SIMULATOR_DESTINATION"
|
|
1010
1106
|
fi
|
|
1011
|
-
SIMULATOR_DESTINATION_ARGS=()
|
|
1012
|
-
[ ! -z "$SIMULATOR_DESTINATION" ] && SIMULATOR_DESTINATION_ARGS=(-destination "$SIMULATOR_DESTINATION")
|
|
1107
|
+
SIMULATOR_DESTINATION_ARGS=(-destination "$SIMULATOR_DESTINATION")
|
|
1013
1108
|
run_simulator_xcodebuild xcodebuild build -workspace "$WORKSPACE" -scheme "$SCHEME" -configuration "$USER_CONFIG" -sdk "$SDK" "\${SIMULATOR_DESTINATION_ARGS[@]}" -derivedDataPath "$DERIVED_DATA_PATH" $EXTRA_ARGS || exit 1
|
|
1014
1109
|
else
|
|
1015
1110
|
ARCHIVE_SIGN_ARGS=("CODE_SIGN_STYLE=Manual")
|
|
@@ -1034,12 +1129,12 @@ NODE
|
|
|
1034
1129
|
if [ "$IS_SIMULATOR" == "true" ]; then
|
|
1035
1130
|
SIMULATOR_DESTINATION=$(resolve_simulator_destination -project "$PROJECT")
|
|
1036
1131
|
if [ -z "$SIMULATOR_DESTINATION" ]; then
|
|
1037
|
-
|
|
1132
|
+
SIMULATOR_DESTINATION="generic/platform=iOS Simulator"
|
|
1133
|
+
echo "No specific simulator destination found during preflight. Using generic simulator destination: $SIMULATOR_DESTINATION"
|
|
1038
1134
|
else
|
|
1039
1135
|
echo "Using simulator destination: $SIMULATOR_DESTINATION"
|
|
1040
1136
|
fi
|
|
1041
|
-
SIMULATOR_DESTINATION_ARGS=()
|
|
1042
|
-
[ ! -z "$SIMULATOR_DESTINATION" ] && SIMULATOR_DESTINATION_ARGS=(-destination "$SIMULATOR_DESTINATION")
|
|
1137
|
+
SIMULATOR_DESTINATION_ARGS=(-destination "$SIMULATOR_DESTINATION")
|
|
1043
1138
|
run_simulator_xcodebuild xcodebuild build -project "$PROJECT" -scheme "$SCHEME" -configuration "$USER_CONFIG" -sdk "$SDK" "\${SIMULATOR_DESTINATION_ARGS[@]}" -derivedDataPath "$DERIVED_DATA_PATH" $EXTRA_ARGS || exit 1
|
|
1044
1139
|
else
|
|
1045
1140
|
ARCHIVE_SIGN_ARGS=("CODE_SIGN_STYLE=Manual")
|
|
@@ -1065,16 +1160,34 @@ NODE
|
|
|
1065
1160
|
# Export IPA or Extract .app for Simulator
|
|
1066
1161
|
echo "[STEP_START:export] $(date +%s)"
|
|
1067
1162
|
if [ "$IS_SIMULATOR" == "true" ]; then
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1163
|
+
SIMULATOR_PRODUCTS_DIR="$DERIVED_DATA_PATH/Build/Products/\${USER_CONFIG}-iphonesimulator"
|
|
1164
|
+
APP_DIR=""
|
|
1165
|
+
if [ -d "$SIMULATOR_PRODUCTS_DIR" ]; then
|
|
1166
|
+
PREFERRED_APP="$SIMULATOR_PRODUCTS_DIR/$SCHEME.app"
|
|
1167
|
+
if [ -d "$PREFERRED_APP" ]; then
|
|
1168
|
+
APP_DIR="$PREFERRED_APP"
|
|
1169
|
+
else
|
|
1170
|
+
APP_COUNT=$(find "$SIMULATOR_PRODUCTS_DIR" -maxdepth 1 -name "*.app" -type d | wc -l | tr -d ' ')
|
|
1171
|
+
if [ "$APP_COUNT" = "1" ]; then
|
|
1172
|
+
APP_DIR=$(find "$SIMULATOR_PRODUCTS_DIR" -maxdepth 1 -name "*.app" -type d | sort | head -n 1)
|
|
1173
|
+
elif [ "$APP_COUNT" -gt "1" ]; then
|
|
1174
|
+
echo "Error: Multiple top-level iOS simulator apps were found in $SIMULATOR_PRODUCTS_DIR."
|
|
1175
|
+
find "$SIMULATOR_PRODUCTS_DIR" -maxdepth 1 -name "*.app" -type d -print
|
|
1176
|
+
echo "Set ios.scheme in mach.config.json so Mach can select the app target safely."
|
|
1177
|
+
exit 1
|
|
1178
|
+
fi
|
|
1179
|
+
fi
|
|
1071
1180
|
fi
|
|
1072
1181
|
|
|
1073
|
-
if [
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
cd export && zip -r ../build.app.zip *.app && cd ..
|
|
1182
|
+
if [ -z "$APP_DIR" ]; then
|
|
1183
|
+
echo "Error: No top-level iOS simulator .app was found in $SIMULATOR_PRODUCTS_DIR"
|
|
1184
|
+
exit 1
|
|
1077
1185
|
fi
|
|
1186
|
+
|
|
1187
|
+
validate_simulator_app "$APP_DIR"
|
|
1188
|
+
mkdir -p export
|
|
1189
|
+
cp -R "$APP_DIR" export/
|
|
1190
|
+
cd export && zip -r ../build.app.zip *.app && cd ..
|
|
1078
1191
|
elif [ -d "build.xcarchive" ]; then
|
|
1079
1192
|
EXPORT_METHOD="{{EXPORT_METHOD}}"
|
|
1080
1193
|
|
|
@@ -1154,143 +1267,127 @@ touch done
|
|
|
1154
1267
|
if [ ! -z "$PRESIGNED_DONE_MARKER" ]; then
|
|
1155
1268
|
curl -X PUT -T done "$PRESIGNED_DONE_MARKER" --silent
|
|
1156
1269
|
fi
|
|
1157
|
-
`;var
|
|
1158
|
-
`:
|
|
1159
|
-
`);r.message("Generating macOS build script...");let
|
|
1160
|
-
`:"";if(n)for(let[
|
|
1161
|
-
`}let
|
|
1162
|
-
`),
|
|
1163
|
-
`):"",
|
|
1164
|
-
${
|
|
1165
|
-
${
|
|
1166
|
-
${it.dim("Note: Links are valid for 7 days.")}`)}else F&&It.warn("Simulator build completed. No artifacts uploaded.")}catch(g){r.stop("Could not fetch artifacts"),It.warn(it.yellow(`Artifact listing failed: ${g.message}`))}}}catch(d){throw r.stop("iOS Build Failed"),d}};import Na from"crypto";import Le from"axios";import wr from"fs";var Ye=6e4,Ta=12e4,ei=4,Xe=e=>encodeURIComponent(e),ka=e=>new Promise(t=>setTimeout(t,e));async function Ue(e,t){let n;for(let i=1;i<=ei;i++)try{return await t()}catch(r){if(n=r,i>=ei||!xa(r))throw r;let o=Number(r.response?.headers?.["retry-after"]),s=Number.isFinite(o)&&o>0?o*1e3:Math.min(2e3*i*i,15e3);console.log(`[Google Play] ${e} failed (attempt ${i}/${ei}); retrying in ${Math.round(s/1e3)}s...`),await ka(s)}throw n}function xa(e){let t=e.response?.status;return t?t===408||t===409||t===425||t===429||t>=500:!0}async function _r(e,t){let n;try{let i=await un(t),r=Xe(e);if(n=(await Ue("create edit",()=>Le.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits`,{},{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Ye}))).data.id,!n)throw new Error("Google Play edit insert succeeded but did not return an edit id.");let s=Xe(n),l=0,c=(await Ue("list tracks",()=>Le.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits/${s}/tracks`,{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Ye}))).data.tracks||[];for(let u of c)if(u.releases){for(let d of u.releases)if(d.versionCodes)for(let p of d.versionCodes){let f=parseInt(p,10);f>l&&(l=f)}}try{let d=(await Ue("list bundles",()=>Le.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits/${s}/bundles`,{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Ye}))).data.bundles||[];for(let p of d)p.versionCode&&p.versionCode>l&&(l=p.versionCode)}catch{}try{let d=(await Ue("list APKs",()=>Le.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits/${s}/apks`,{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Ye}))).data.apks||[];for(let p of d)p.versionCode&&p.versionCode>l&&(l=p.versionCode)}catch{}return l}catch(i){let r=i.response?.data?.error?.message||i.message;throw new Error(`Google Play API Error: ${r}`)}finally{if(n)try{let i=await un(t);await Ue("delete edit",()=>Le.delete(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${Xe(e)}/edits/${Xe(n)}`,{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Ye}))}catch{}}}async function $r(e){let{packageName:t,serviceAccount:n,aabPath:i,track:r,releaseStatus:o,userFraction:s,changesNotSentForReview:l}=e,a;try{let u={Authorization:`Bearer ${await un(n)}`,Connection:"close"},d=Xe(t);if(a=(await Ue("create edit",()=>Le.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${d}/edits`,{},{headers:u,timeout:Ye}))).data.id,!a)throw new Error("Google Play edit insert succeeded but did not return an edit id.");let f=Xe(a),h=wr.statSync(i),S=await Ue("upload AAB",()=>Le.post(`https://androidpublisher.googleapis.com/upload/androidpublisher/v3/applications/${d}/edits/${f}/bundles`,wr.createReadStream(i),{headers:{...u,"Content-Type":"application/octet-stream","Content-Length":h.size},maxBodyLength:1/0,maxContentLength:1/0,params:{uploadType:"media"},timeout:Ta})),L=Number(S.data.versionCode);if(!L)throw new Error("Google Play upload succeeded but did not return a versionCode.");let x={versionCodes:[String(L)],status:o};return(o==="inProgress"||o==="halted")&&typeof s=="number"&&(x.userFraction=s),await Ue("update track",()=>Le.put(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${d}/edits/${f}/tracks/${Xe(r)}`,{releases:[x]},{headers:u,timeout:Ye})),await Ue("commit edit",()=>Le.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${d}/edits/${f}:commit`,{},{headers:u,params:l?{changesNotSentForReview:!0}:void 0,timeout:Ye})),{editId:a,versionCode:L,track:r,releaseStatus:o,userFraction:s}}catch(c){if(a)try{let d=await un(n);await Ue("delete edit",()=>Le.delete(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${Xe(t)}/edits/${Xe(a)}`,{headers:{Authorization:`Bearer ${d}`,Connection:"close"},timeout:Ye}))}catch{}let u=c.response?.data?.error?.message||c.message;throw new Error(`Google Play API Error: ${u}`)}}async function un(e){let t=Math.floor(Date.now()/1e3),n=t+3600,i={alg:"RS256",typ:"JWT"},r={iss:e.client_email,sub:e.client_email,aud:"https://oauth2.googleapis.com/token",iat:t,exp:n,scope:"https://www.googleapis.com/auth/androidpublisher"},o=Buffer.from(JSON.stringify(i)).toString("base64url"),s=Buffer.from(JSON.stringify(r)).toString("base64url"),l=`${o}.${s}`,a=Na.createSign("RSA-SHA256");a.update(l);let c=a.sign(e.private_key,"base64url"),u=`${l}.${c}`;return(await Ue("OAuth token exchange",()=>Le.post("https://oauth2.googleapis.com/token",{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:u},{headers:{Connection:"close"},timeout:Ye}))).data.access_token}import Ma from"crypto";import vr from"axios";var ni="https://api.appstoreconnect.apple.com/v1",Rr=6e4,ti=4,La=e=>new Promise(t=>setTimeout(t,e));function Ua(e,t,n){let i=Math.floor(Date.now()/1e3),r=Buffer.from(JSON.stringify({alg:"ES256",kid:e,typ:"JWT"})).toString("base64url"),o=Buffer.from(JSON.stringify({iss:t,iat:i,exp:i+1200,aud:"appstoreconnect-v1"})).toString("base64url"),s=`${r}.${o}`,l=Ma.createSign("SHA256");l.update(s);let a=l.sign({key:n,dsaEncoding:"ieee-p1363"}).toString("base64url");return`${s}.${a}`}function Fa(e){let t=e.response?.status;return t?t===408||t===409||t===425||t===429||t>=500:!0}async function Pr(e,t){let n;for(let i=1;i<=ti;i++)try{return await t()}catch(r){if(n=r,i>=ti||!Fa(r))throw r;let o=Number(r.response?.headers?.["retry-after"]),s=Number.isFinite(o)&&o>0?o*1e3:Math.min(2e3*i*i,15e3);console.log(`[App Store Connect] ${e} failed (attempt ${i}/${ti}); retrying in ${Math.round(s/1e3)}s...`),await La(s)}throw n}function Or(e){return{Authorization:`Bearer ${Ua(e.keyId,e.issuerId,e.privateKey)}`,"Content-Type":"application/json",Connection:"close"}}function Ba(e){let t=e.response?.data?.errors;return Array.isArray(t)&&t.length>0?t.map(n=>n.detail||n.title||n.code).filter(Boolean).join("; "):e.response?.data?.error?.message||e.message||"Unknown App Store Connect error"}function fn(e){let t=String(e||"").trim();if(/^\d+(?:\.\d+){0,2}$/.test(t))return t.split(".").map(n=>Number(n))}function Ha(e,t){let n=fn(e),i=fn(t);if(!n&&!i)return 0;if(!n)return-1;if(!i)return 1;let r=Math.max(n.length,i.length);for(let o=0;o<r;o++){let s=n[o]||0,l=i[o]||0;if(s!==l)return s>l?1:-1}return 0}function ja(e){let t=fn(e);return!t||t.length===0?"1":(t[t.length-1]+=1,t.join("."))}async function Ga(e,t,n){if(t)return t;if(!n)throw new Error("Set ios.ascAppId or ios.bundleIdentifier so Mach can find the App Store Connect app.");let r=(await Pr("lookup app by bundle ID",()=>vr.get(`${ni}/apps`,{headers:Or(e),params:{"filter[bundleId]":n,limit:1},timeout:Rr}))).data?.data?.[0];if(!r?.id)throw new Error(`No App Store Connect app found for bundle ID ${n}. Set ios.ascAppId in mach.config.json if the app exists.`);return r.id}async function Dr(e){let t={keyId:e.keyId,issuerId:e.issuerId,privateKey:e.privateKey};try{let n=await Ga(t,e.ascAppId,e.bundleId),i=`${ni}/builds`,r="0",o,s=0;for(;i&&s<10;){s+=1;let l=await Pr("list builds",()=>vr.get(i,{headers:Or(t),params:i===`${ni}/builds`?{"filter[app]":n,"fields[builds]":"version,uploadedDate",sort:"-uploadedDate",limit:200}:void 0,timeout:Rr})),a=l.data?.data||[];for(let c of a){let u=String(c.attributes?.version||"").trim();fn(u)&&Ha(u,r)>0&&(r=u,o=c.attributes?.uploadedDate)}i=l.data?.links?.next}return{appId:n,latestBuildNumber:r,nextBuildNumber:ja(r),latestUploadedDate:o}}catch(n){throw new Error(`App Store Connect API Error: ${Ba(n)}`)}}import{spinner as pn,log as I,isCancel as mn,confirm as Ka,select as ri}from"@clack/prompts";import A from"chalk";import y from"fs";import _ from"path";import{execFileSync as Lt,execSync as te,spawn as kr}from"child_process";import Ee from"os";import Va from"crypto";var xr=(e,t)=>t.filter(n=>y.existsSync(_.join(e,n))).reduce((n,i)=>n.update(y.readFileSync(_.join(e,i))),Va.createHash("sha256")).digest("hex").slice(0,16),za=e=>xr(e,["package.json","yarn.lock","package-lock.json","bun.lockb"]),Wa=e=>xr(e,["Podfile","Podfile.lock"]),Ya=e=>{let t=_.join(e,"fingerprint.json");try{return JSON.parse(y.readFileSync(t,"utf-8"))}catch{return{}}},Cr=(e,t)=>{y.mkdirSync(e,{recursive:!0}),y.writeFileSync(_.join(e,"fingerprint.json"),JSON.stringify(t,null,2))},Ja=7200*1e3,qa=(e,t)=>{y.mkdirSync(e,{recursive:!0});let n=_.join(e,"build.lock");if(y.existsSync(n))try{let i=JSON.parse(y.readFileSync(n,"utf-8")),r=Date.now()-(i.timestamp||0);if(r<Ja)throw new Error(`Another build is already running for this project (build ${i.buildId}, started ${Math.round(r/6e4)}m ago). Cancel it from the dashboard first, or wait for it to complete.`)}catch(i){if(i.message.includes("Another build"))throw i}y.writeFileSync(n,JSON.stringify({buildId:t,pid:process.pid,timestamp:Date.now()}))},Xa=(e,t)=>{let n=_.join(e,"build.lock");try{y.existsSync(n)&&JSON.parse(y.readFileSync(n,"utf-8")).buildId===t&&y.unlinkSync(n)}catch{}},Nr=15e5,Tr=(e,t)=>{let n=e+t;return n.length>Nr?n.slice(-Nr):n},Mr=e=>e.replace(/\u001b\[[0-9;]*m/g,""),Lr=e=>/\berror:|fatal error:|xcodebuild: error|The following build commands failed|Command PhaseScriptExecution failed|PhaseScriptExecution|Command .* failed|CodeSign|Provisioning profile|No profiles|requires a provisioning profile|Undefined symbols|ld:|clang: error|SwiftCompile|CompileC|node: command not found|env: node|No such file or directory|Permission denied/i.test(e),Za=e=>{let t=new Set,n=[];e.forEach((r,o)=>{Lr(r)&&n.push(o)});for(let r of n){let o=/PhaseScriptExecution|Command PhaseScriptExecution failed|The following build commands failed/i.test(e[r])?18:8,s=/The following build commands failed/i.test(e[r])?18:10;for(let l=Math.max(0,r-o);l<=Math.min(e.length-1,r+s);l++)t.add(l)}if(t.size===0)return e.slice(-120);let i=Array.from(t).sort((r,o)=>r-o).map(r=>e[r]);return i.length>160?i.slice(-160):i},Qa=(e,t,n,i)=>{let r=Mr(i).replace(/\r/g,`
|
|
1270
|
+
`;var Tr=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`"),kr=async(e,t,n={},i)=>{let r=rl(),o=Qe(e.framework);e.sshHost||(e.sshHost="localhost",Et.message(et.yellow("No SSH host provided, defaulting to localhost."))),r.start(`Connecting to remote Mac at ${et.cyan(e.sshHost)}...`);let s=e.sshUser||process.env.USER||"ubuntu",l=e.sshKey,a=`${s}@${e.sshHost}`,c=`ssh ${l?`-i ${l}`:""} -o StrictHostKeyChecking=no ${a}`,u=`scp ${l?`-i ${l}`:""} -o StrictHostKeyChecking=no`;try{let d=s==="ubuntu"?"/home/ubuntu":`/Users/${s}`,f=(n.PROJECT_ID||"default_project").replace(/[^a-zA-Z0-9-_]/g,"_"),p=`${d}/${m.remoteWorkspacesDir}/${f}`;r.message(`Preparing stable workspace: ${p}...`),Vt(`${c} "mkdir -p ${p}"`,{stdio:"inherit"}),r.message("Transferring source code...");let g=`/tmp/${m.nameLower}-source-${t}.zip`;Vt(`${u} ${g} ${a}:${p}/source.zip`,{stdio:"inherit"});let y=e.iosApiKeyPath?`${p}/api_key.p8`:"",_="";e.iosApiKeyPath&&(r.message("Uploading App Store Connect API key..."),Vt(`${u} ${e.iosApiKeyPath} ${a}:${y}`),e.iosApiKeyId&&e.iosApiKeyIssuer&&(_=`-authenticationKeyID ${e.iosApiKeyId} -authenticationKeyIssuerID ${e.iosApiKeyIssuer} -authenticationKeyPath ${y}`));let D={};if(i)try{let h=await k.post(`/builds/${i}/${t}/build-urls`,{platform:"ios"});h.data.status==="success"&&(D=h.data.urls)}catch(h){Et.warn(et.yellow(`Could not fetch build URLs: ${h.message}`))}let b="";if(D.credentials&&D.credentials.length>0)for(let h of D.credentials)h.type==="p12"?b+=`curl -sf -o "$CERT_DIR/${h.name}" "${h.downloadUrl}" || true
|
|
1271
|
+
`:h.type==="mobileprovision"&&(b+=`curl -sf -o "$PROV_TEMP/${h.name}" "${h.downloadUrl}" || true
|
|
1272
|
+
`);r.message("Generating macOS build script...");let x=process.env.CODEARTIFACT_AUTH_TOKEN?`export CODEARTIFACT_AUTH_TOKEN="${process.env.CODEARTIFACT_AUTH_TOKEN}"
|
|
1273
|
+
`:"";if(n)for(let[h,M]of Object.entries(n)){let U=M.replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");x+=`export ${h}="${U}"
|
|
1274
|
+
`}let A=e.buildProfile||"production",B=bt(n,A,e),q=Dt(B);Et.info(et.dim(`iOS remote build config: simulator=${String(!!e.simulator)}, configuration=${e.iosConfiguration||"Release"}, scheme=${e.iosScheme||"auto"}`));let P=[x,D.logUpload?`export PRESIGNED_LOG_UPLOAD="${D.logUpload}"`:"",D.doneMarker?`export PRESIGNED_DONE_MARKER="${D.doneMarker}"`:"",D.cacheDerivedDataDownload?`export PRESIGNED_CACHE_DD_DOWNLOAD="${D.cacheDerivedDataDownload}"`:"",D.cacheDerivedDataUpload?`export PRESIGNED_CACHE_DD_UPLOAD="${D.cacheDerivedDataUpload}"`:"",D.cacheNodeModulesDownload?`export PRESIGNED_CACHE_NODE_DOWNLOAD="${D.cacheNodeModulesDownload}"`:"",D.cacheNodeModulesUpload?`export PRESIGNED_CACHE_NODE_UPLOAD="${D.cacheNodeModulesUpload}"`:"",D.cachePodsDownload?`export PRESIGNED_CACHE_PODS_DOWNLOAD="${D.cachePodsDownload}"`:"",D.cachePodsUpload?`export PRESIGNED_CACHE_PODS_UPLOAD="${D.cachePodsUpload}"`:"",D.artifactIpaUpload?`export PRESIGNED_ARTIFACT_IPA_UPLOAD="${D.artifactIpaUpload}"`:"",D.artifactAppZipUpload?`export PRESIGNED_ARTIFACT_APP_ZIP_UPLOAD="${D.artifactAppZipUpload}"`:"",`export BUILD_ID="${t}"`,`export MACH_BUILD_PROFILE="${Tr(A)}"`,`export MACH_APP_NAME="${Tr(B.MACH_APP_NAME)}"`,`export MACH_ENV_FINGERPRINT="${q}"`,o.remoteEnvSetupScript().trim(),`export ${m.envPrefix}PROJECT_ID="${f}"`,n.MATCH_ENCRYPTION_PASSPHRASE?`export MATCH_PASSWORD="${n.MATCH_ENCRYPTION_PASSPHRASE}"`:"",n.APPLE_TEAM_ID?`export FASTLANE_TEAM_ID="${n.APPLE_TEAM_ID}"`:"",`export MATCH_KEYCHAIN_NAME="${m.credentialsKeychain}"`,`export MATCH_KEYCHAIN_PASSWORD="${m.keychainPassword}"`].filter(Boolean).join(`
|
|
1275
|
+
`),I=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(`
|
|
1276
|
+
`):"",T=Nr,w={"{{REMOTE_DIR}}":p,"{{ENV_VARS}}":P,"{{CREDENTIAL_DOWNLOADS}}":b,"{{IOS_SCHEME}}":e.iosScheme||"","{{IOS_CONFIG}}":e.iosConfiguration||"Release","{{TEAM_ID}}":e.iosTeamId||"","{{AUTH_PARAMS}}":_,"{{IS_SIMULATOR}}":e.simulator?"true":"false","{{BUILD_ID}}":t,"{{EXPORT_METHOD}}":e.iosExportMethod||"ad-hoc","{{NODE_VERSION_SETUP}}":I,"{{FRAMEWORK_PREBUILD}}":o.iosRemotePrebuildScript().trim()};Object.entries(w).forEach(([h,M])=>{T=T.split(h).join(M)});let C=`/tmp/${m.nameLower}-mac-build-${t}.sh`;if(ol.writeFileSync(C,T),Vt(`${u} ${C} ${a}:${p}/build.sh`),r.stop("Remote script uploaded."),Et.info(et.cyan("Executing remote build. This might take a while...")),Vt(`${c} "bash ${p}/build.sh"`,{stdio:"inherit"}),r.stop("Remote build finished!"),i){r.start("Fetching artifact links...");try{let M=(await k.get(`/builds/${i}/${t}/artifacts`)).data.artifacts||[],U=e.simulator===!0;if(M.length===0&&!U)throw r.stop("Build Failed!"),new Error("Build completed but no artifacts were generated. Check build logs for errors.");if(r.stop("Build Successful!"),M.length>0){Et.success("Build Artifacts Ready:");for(let j of M)console.log(`
|
|
1277
|
+
${et.yellow(j.name)}:
|
|
1278
|
+
${et.cyan(j.downloadUrl)}`);console.log(`
|
|
1279
|
+
${et.dim("Note: Links are valid for 7 days.")}`)}else U&&Et.warn("Simulator build completed. No artifacts uploaded.")}catch(h){r.stop("Could not fetch artifacts"),Et.warn(et.yellow(`Artifact listing failed: ${h.message}`))}}}catch(d){throw r.stop("iOS Build Failed"),d}};import sl from"crypto";import He from"axios";import xr from"fs";var Xe=6e4,al=12e4,ai=4,tt=e=>encodeURIComponent(e),ll=e=>new Promise(t=>setTimeout(t,e));async function je(e,t){let n;for(let i=1;i<=ai;i++)try{return await t()}catch(r){if(n=r,i>=ai||!dl(r))throw r;let o=Number(r.response?.headers?.["retry-after"]),s=Number.isFinite(o)&&o>0?o*1e3:Math.min(2e3*i*i,15e3);console.log(`[Google Play] ${e} failed (attempt ${i}/${ai}); retrying in ${Math.round(s/1e3)}s...`),await ll(s)}throw n}function dl(e){let t=e.response?.status;return t?t===408||t===409||t===425||t===429||t>=500:!0}async function Lr(e,t){let n;try{let i=await gn(t),r=tt(e);if(n=(await je("create edit",()=>He.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits`,{},{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Xe}))).data.id,!n)throw new Error("Google Play edit insert succeeded but did not return an edit id.");let s=tt(n),l=0,c=(await je("list tracks",()=>He.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits/${s}/tracks`,{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Xe}))).data.tracks||[];for(let u of c)if(u.releases){for(let d of u.releases)if(d.versionCodes)for(let f of d.versionCodes){let p=parseInt(f,10);p>l&&(l=p)}}try{let d=(await je("list bundles",()=>He.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits/${s}/bundles`,{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Xe}))).data.bundles||[];for(let f of d)f.versionCode&&f.versionCode>l&&(l=f.versionCode)}catch{}try{let d=(await je("list APKs",()=>He.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits/${s}/apks`,{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Xe}))).data.apks||[];for(let f of d)f.versionCode&&f.versionCode>l&&(l=f.versionCode)}catch{}return l}catch(i){let r=i.response?.data?.error?.message||i.message;throw new Error(`Google Play API Error: ${r}`)}finally{if(n)try{let i=await gn(t);await je("delete edit",()=>He.delete(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${tt(e)}/edits/${tt(n)}`,{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Xe}))}catch{}}}async function Mr(e){let{packageName:t,serviceAccount:n,aabPath:i,track:r,releaseStatus:o,userFraction:s,changesNotSentForReview:l}=e,a;try{let u={Authorization:`Bearer ${await gn(n)}`,Connection:"close"},d=tt(t);if(a=(await je("create edit",()=>He.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${d}/edits`,{},{headers:u,timeout:Xe}))).data.id,!a)throw new Error("Google Play edit insert succeeded but did not return an edit id.");let p=tt(a),g=xr.statSync(i),y=await je("upload AAB",()=>He.post(`https://androidpublisher.googleapis.com/upload/androidpublisher/v3/applications/${d}/edits/${p}/bundles`,xr.createReadStream(i),{headers:{...u,"Content-Type":"application/octet-stream","Content-Length":g.size},maxBodyLength:1/0,maxContentLength:1/0,params:{uploadType:"media"},timeout:al})),_=Number(y.data.versionCode);if(!_)throw new Error("Google Play upload succeeded but did not return a versionCode.");let D={versionCodes:[String(_)],status:o};return(o==="inProgress"||o==="halted")&&typeof s=="number"&&(D.userFraction=s),await je("update track",()=>He.put(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${d}/edits/${p}/tracks/${tt(r)}`,{releases:[D]},{headers:u,timeout:Xe})),await je("commit edit",()=>He.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${d}/edits/${p}:commit`,{},{headers:u,params:l?{changesNotSentForReview:!0}:void 0,timeout:Xe})),{editId:a,versionCode:_,track:r,releaseStatus:o,userFraction:s}}catch(c){if(a)try{let d=await gn(n);await je("delete edit",()=>He.delete(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${tt(t)}/edits/${tt(a)}`,{headers:{Authorization:`Bearer ${d}`,Connection:"close"},timeout:Xe}))}catch{}let u=c.response?.data?.error?.message||c.message;throw new Error(`Google Play API Error: ${u}`)}}async function gn(e){let t=Math.floor(Date.now()/1e3),n=t+3600,i={alg:"RS256",typ:"JWT"},r={iss:e.client_email,sub:e.client_email,aud:"https://oauth2.googleapis.com/token",iat:t,exp:n,scope:"https://www.googleapis.com/auth/androidpublisher"},o=Buffer.from(JSON.stringify(i)).toString("base64url"),s=Buffer.from(JSON.stringify(r)).toString("base64url"),l=`${o}.${s}`,a=sl.createSign("RSA-SHA256");a.update(l);let c=a.sign(e.private_key,"base64url"),u=`${l}.${c}`;return(await je("OAuth token exchange",()=>He.post("https://oauth2.googleapis.com/token",{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:u},{headers:{Connection:"close"},timeout:Xe}))).data.access_token}import cl from"crypto";import Ur from"axios";var di="https://api.appstoreconnect.apple.com/v1",Fr=6e4,li=4,ul=e=>new Promise(t=>setTimeout(t,e));function pl(e,t,n){let i=Math.floor(Date.now()/1e3),r=Buffer.from(JSON.stringify({alg:"ES256",kid:e,typ:"JWT"})).toString("base64url"),o=Buffer.from(JSON.stringify({iss:t,iat:i,exp:i+1200,aud:"appstoreconnect-v1"})).toString("base64url"),s=`${r}.${o}`,l=cl.createSign("SHA256");l.update(s);let a=l.sign({key:n,dsaEncoding:"ieee-p1363"}).toString("base64url");return`${s}.${a}`}function fl(e){let t=e.response?.status;return t?t===408||t===409||t===425||t===429||t>=500:!0}async function Br(e,t){let n;for(let i=1;i<=li;i++)try{return await t()}catch(r){if(n=r,i>=li||!fl(r))throw r;let o=Number(r.response?.headers?.["retry-after"]),s=Number.isFinite(o)&&o>0?o*1e3:Math.min(2e3*i*i,15e3);console.log(`[App Store Connect] ${e} failed (attempt ${i}/${li}); retrying in ${Math.round(s/1e3)}s...`),await ul(s)}throw n}function Hr(e){return{Authorization:`Bearer ${pl(e.keyId,e.issuerId,e.privateKey)}`,"Content-Type":"application/json",Connection:"close"}}function ml(e){let t=e.response?.data?.errors;return Array.isArray(t)&&t.length>0?t.map(n=>n.detail||n.title||n.code).filter(Boolean).join("; "):e.response?.data?.error?.message||e.message||"Unknown App Store Connect error"}function hn(e){let t=String(e||"").trim();if(/^\d+(?:\.\d+){0,2}$/.test(t))return t.split(".").map(n=>Number(n))}function gl(e,t){let n=hn(e),i=hn(t);if(!n&&!i)return 0;if(!n)return-1;if(!i)return 1;let r=Math.max(n.length,i.length);for(let o=0;o<r;o++){let s=n[o]||0,l=i[o]||0;if(s!==l)return s>l?1:-1}return 0}function hl(e){let t=hn(e);return!t||t.length===0?"1":(t[t.length-1]+=1,t.join("."))}async function Sl(e,t,n){if(t)return t;if(!n)throw new Error("Set ios.ascAppId or ios.bundleIdentifier so Mach can find the App Store Connect app.");let r=(await Br("lookup app by bundle ID",()=>Ur.get(`${di}/apps`,{headers:Hr(e),params:{"filter[bundleId]":n,limit:1},timeout:Fr}))).data?.data?.[0];if(!r?.id)throw new Error(`No App Store Connect app found for bundle ID ${n}. Set ios.ascAppId in mach.config.json if the app exists.`);return r.id}async function jr(e){let t={keyId:e.keyId,issuerId:e.issuerId,privateKey:e.privateKey};try{let n=await Sl(t,e.ascAppId,e.bundleId),i=`${di}/builds`,r="0",o,s=0;for(;i&&s<10;){s+=1;let l=await Br("list builds",()=>Ur.get(i,{headers:Hr(t),params:i===`${di}/builds`?{"filter[app]":n,"fields[builds]":"version,uploadedDate",sort:"-uploadedDate",limit:200}:void 0,timeout:Fr})),a=l.data?.data||[];for(let c of a){let u=String(c.attributes?.version||"").trim();hn(u)&&gl(u,r)>0&&(r=u,o=c.attributes?.uploadedDate)}i=l.data?.links?.next}return{appId:n,latestBuildNumber:r,nextBuildNumber:hl(r),latestUploadedDate:o}}catch(n){throw new Error(`App Store Connect API Error: ${ml(n)}`)}}import{spinner as yn,log as O,isCancel as bn,confirm as yl,select as ui}from"@clack/prompts";import R from"chalk";import S from"fs";import E from"path";import{execFileSync as nt,execSync as te,spawn as Yr}from"child_process";import Ae from"os";import bl from"crypto";var Jr=(e,t)=>t.filter(n=>S.existsSync(E.join(e,n))).reduce((n,i)=>n.update(S.readFileSync(E.join(e,i))),bl.createHash("sha256")).digest("hex").slice(0,16),El=e=>Jr(e,["package.json","yarn.lock","package-lock.json","bun.lockb"]),Al=e=>Jr(e,["Podfile","Podfile.lock"]),Il=e=>{let t=E.join(e,"fingerprint.json");try{return JSON.parse(S.readFileSync(t,"utf-8"))}catch{return{}}},Gr=(e,t)=>{S.mkdirSync(e,{recursive:!0}),S.writeFileSync(E.join(e,"fingerprint.json"),JSON.stringify(t,null,2))},wl=7200*1e3,_l=(e,t)=>{S.mkdirSync(e,{recursive:!0});let n=E.join(e,"build.lock");if(S.existsSync(n))try{let i=JSON.parse(S.readFileSync(n,"utf-8")),r=Date.now()-(i.timestamp||0);if(r<wl)throw new Error(`Another build is already running for this project (build ${i.buildId}, started ${Math.round(r/6e4)}m ago). Cancel it from the dashboard first, or wait for it to complete.`)}catch(i){if(i.message.includes("Another build"))throw i}S.writeFileSync(n,JSON.stringify({buildId:t,pid:process.pid,timestamp:Date.now()}))},Rl=(e,t)=>{let n=E.join(e,"build.lock");try{S.existsSync(n)&&JSON.parse(S.readFileSync(n,"utf-8")).buildId===t&&S.unlinkSync(n)}catch{}},Kr=15e5,Vr=(e,t)=>{let n=e+t;return n.length>Kr?n.slice(-Kr):n},Xr=e=>e.replace(/\u001b\[[0-9;]*m/g,""),qr=e=>/\berror:|fatal error:|xcodebuild: error|The following build commands failed|Command PhaseScriptExecution failed|PhaseScriptExecution|Command .* failed|CodeSign|Provisioning profile|No profiles|requires a provisioning profile|Undefined symbols|ld:|clang: error|SwiftCompile|CompileC|node: command not found|env: node|No such file or directory|Permission denied/i.test(e),$l=e=>{let t=new Set,n=[];e.forEach((r,o)=>{qr(r)&&n.push(o)});for(let r of n){let o=/PhaseScriptExecution|Command PhaseScriptExecution failed|The following build commands failed/i.test(e[r])?18:8,s=/The following build commands failed/i.test(e[r])?18:10;for(let l=Math.max(0,r-o);l<=Math.min(e.length-1,r+s);l++)t.add(l)}if(t.size===0)return e.slice(-120);let i=Array.from(t).sort((r,o)=>r-o).map(r=>e[r]);return i.length>160?i.slice(-160):i},vl=(e,t,n,i)=>{let r=Xr(i).replace(/\r/g,`
|
|
1167
1280
|
`).split(`
|
|
1168
|
-
`).map(a=>a.trimEnd()).filter(Boolean),o=r.filter(
|
|
1281
|
+
`).map(a=>a.trimEnd()).filter(Boolean),o=r.filter(qr),s=o.length>0?$l(r):r.slice(-80),l=o.length>0?"Key failure output":"Last command output";return[`Command failed with code ${n}: ${e} ${t.join(" ")}`,s.length>0?`
|
|
1169
1282
|
${l}:
|
|
1170
1283
|
${s.join(`
|
|
1171
|
-
`)}`:""].join("")},
|
|
1172
|
-
`)){if(/Ineligible destinations/i.test(d)&&(u=!0),u||!d.includes("platform:iOS Simulator")||d.includes("error:"))continue;let
|
|
1173
|
-
`)),r(
|
|
1174
|
-
`)),r(
|
|
1175
|
-
`)));let
|
|
1176
|
-
`)))}let
|
|
1284
|
+
`)}`:""].join("")},Pl=e=>e==="xcodebuild"&&process.env.MACH_XCODE_FULL_LOGS!=="1",Ol=e=>{let t=Xr(e).trim();return t?/\berror:|fatal error:|xcodebuild: error|The following build commands failed|Command PhaseScriptExecution failed|CodeSign|Provisioning profile|No profiles|requires a provisioning profile|Undefined symbols|ld:|clang: error|SwiftCompile|CompileC|CFBundleVersion|ARCHIVE SUCCEEDED|ARCHIVE FAILED|EXPORT SUCCEEDED|EXPORT FAILED|Exported .* to:|\[IPA VALID\]/i.test(t):!1},ke=e=>{try{S.existsSync(e)&&S.rmSync(e,{recursive:!0,force:!0})}catch{}},Dl=(e,t)=>{try{if(!S.existsSync(e))return;for(let n of S.readdirSync(e))t(n)&&ke(E.join(e,n))}catch{}},ci=e=>{O.info(R.dim("Clearing Metro/Hermes JS transform caches..."));let t=Ae.tmpdir();Dl(t,n=>n==="metro-cache"||n.startsWith("metro-")||n.startsWith("haste-map-")||n.startsWith("react-native-packager-cache-")),ke(E.join(e,".expo")),ke(E.join(e,"node_modules/.cache/metro")),ke(E.join(Ae.homedir(),".cache/metro")),ke(E.join(Ae.homedir(),".cache/react-native-packager")),ke(E.join(Ae.homedir(),"Library/Caches/metro")),ke(E.join(Ae.homedir(),"Library/Caches/react-native-packager"))},Cl=e=>/Internal inconsistency error|never received target ended message/i.test(String(e?.message||e)),Nl=e=>{O.warn(R.yellow("Xcode build system hit an internal inconsistency. Clearing simulator build state and retrying once...")),ke(E.join(e,"Build")),ke(E.join(e,"Index.noindex")),ke(E.join(e,"ModuleCache.noindex")),ke(E.join(e,"SourcePackages"))},Tl=e=>{let t=String(e?.message||e);return/Permission denied/i.test(t)&&/Pods\/.*\.sh/i.test(t)},Zr=e=>{let t=E.join(e,"Pods"),i=[E.join(t,"Target Support Files"),t].filter(l=>S.existsSync(l)),r=new Set,o=0,s=l=>{let a=l;try{a=S.realpathSync(l)}catch{}if(r.has(a))return;r.add(a);let c;try{c=S.readdirSync(l,{withFileTypes:!0})}catch{return}for(let u of c){let d=E.join(l,u.name);if(u.isDirectory()){s(d);continue}if(!(!u.isFile()||!u.name.endsWith(".sh")))try{let f=S.statSync(d),p=f.mode|493;p!==f.mode&&(S.chmodSync(d,p),o+=1)}catch{}}};for(let l of i)s(l);return o>0&&O.info(R.dim(`Repaired executable permissions on ${o} CocoaPods script${o===1?"":"s"}.`)),o},kl=(e,t,n,i,r)=>{let o=a=>{let c=a.filter(d=>d?.id&&String(d?.platform||"").includes("iOS Simulator")&&!d?.error),u=c.find(d=>/iphone/i.test(d.name||""))||c[0];return u?.id?`id=${u.id}`:void 0},s=a=>{let c=[],u=!1;for(let d of a.split(`
|
|
1285
|
+
`)){if(/Ineligible destinations/i.test(d)&&(u=!0),u||!d.includes("platform:iOS Simulator")||d.includes("error:"))continue;let f=d.match(/\bid:([^,}]+)/)?.[1]?.trim(),p=d.match(/\bname:([^,}]+)/)?.[1]?.trim();f&&c.push({id:f,name:p,platform:"iOS Simulator"})}return o(c)},l=[t?"-workspace":"-project",t||n,"-scheme",i,"-configuration",r,"-sdk","iphonesimulator","-showdestinations"];try{let a=nt("xcodebuild",[...l,"-json"],{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}),c=JSON.parse(a),u=Array.isArray(c.destinations)?c.destinations:Array.isArray(c.availableDestinations)?c.availableDestinations:[],d=o(u);if(d)return d}catch{}try{let a=nt("xcodebuild",l,{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]});return s(a)}catch{}},it=(e,t,n=process.cwd(),i={},r,o)=>new Promise((s,l)=>{let a="",c=Pl(e),u=Date.now(),d=["/opt/homebrew/bin","/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin",E.join(Ae.homedir(),".npm-global/bin")],p=[...(process.env.PATH||"").split(":"),...d].filter((b,x,A)=>b&&A.indexOf(b)===x).join(":");process.env[`${m.envPrefix}DEBUG`]&&console.log(R.magenta(`[${m.nameUpper}_DEBUG] Execution PATH: ${p}`));let g={...process.env,...i,PATH:p,LANG:"en_US.UTF-8",LC_ALL:"en_US.UTF-8"};r&&process.env[`${m.envPrefix}DEBUG`]&&(r(R.magenta(`[ENVIRONMENT] node: ${process.execPath}
|
|
1286
|
+
`)),r(R.magenta(`[ENVIRONMENT] PATH: ${p}
|
|
1287
|
+
`)),r(R.magenta(`[ENVIRONMENT] command: ${e} ${t.join(" ")}
|
|
1288
|
+
`)));let y=e;if(["node","npm","npx","pod"].includes(e)){let b=E.dirname(process.execPath),x=E.join(b,e);S.existsSync(x)&&(y=x,r&&r(R.dim(`[EXEC] Using absolute path: ${y}
|
|
1289
|
+
`)))}let _=Yr(y,t,{stdio:"pipe",cwd:n,shell:!0,env:g,detached:process.platform!=="win32"});if(o){if(o.aborted){if(_.pid)try{process.kill(-_.pid,"SIGTERM")}catch{_.kill()}return l(new Error("Command aborted"))}o.addEventListener("abort",()=>{if(_.pid)try{process.kill(-_.pid,"SIGTERM")}catch{_.kill()}l(new Error("Command aborted"))})}let D=(b,x)=>{if(!c){x.write(b);return}let A=b.replace(/\r/g,`
|
|
1177
1290
|
`).split(`
|
|
1178
|
-
`).filter(
|
|
1291
|
+
`).filter(Ol);if(A.length>0){x.write(`${A.join(`
|
|
1179
1292
|
`)}
|
|
1180
|
-
`),u=Date.now();return}let
|
|
1181
|
-
`),u=
|
|
1182
|
-
`).find(r=>/^Payload\/[^/]+\.app\/Info\.plist$/.test(r.trim()));if(!n)throw new Error(`Could not validate iOS build number: ${
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
`)),
|
|
1187
|
-
`)
|
|
1188
|
-
`)
|
|
1189
|
-
`)
|
|
1190
|
-
`)
|
|
1191
|
-
`),
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '${ae}'
|
|
1202
|
-
end
|
|
1203
|
-
end
|
|
1204
|
-
`,qe=/post_install\s+do\s+\|installer\|/;if(qe.test(Z))I.info(A.dim(`Injecting deployment target (${ae}) into existing post_install hook...`)),Z=Z.replace(qe,`post_install do |installer|
|
|
1205
|
-
${Se}`),y.writeFileSync(K,Z);else{I.info(A.dim(`Appending new post_install hook for deployment target (${ae})...`));let ut=`
|
|
1206
|
-
post_install do |installer|
|
|
1207
|
-
${Se}
|
|
1208
|
-
end
|
|
1209
|
-
`;y.appendFileSync(K,ut)}let Ct="/opt/homebrew/bin/pod",on=y.existsSync(Ct)?Ct:"pod",sn=Wa(T);y.existsSync(_.join(T,"Pods"))&&D.pods&&D.pods!==sn&&(await z(`[CACHE] Podfile/Podfile.lock changed \u2014 wiping ios/Pods
|
|
1210
|
-
`),I.info(A.dim("Podfile fingerprint changed \u2014 clearing Pods for clean install...")),y.rmSync(_.join(T,"Pods"),{recursive:!0,force:!0})),I.info(A.dim(`Using pod command: ${on} in ${T}`)),await O(on,["install"],T,u()),D.pods=sn,Cr(S,D)}catch(T){let K=T.message||"Unknown error";I.warn(A.yellow(`Native "pod" command failed: ${K}`)),I.info(A.dim("Falling back to npm exec pod-install...")),I.info(A.magenta(`${m.nameUpper}_DEBUG: Executing pod-install override via npx --yes pod-install@latest`)),await O("npx",["--yes","pod-install@latest","ios"],process.cwd(),u())}if(y.existsSync("ios/Pods")){I.info(A.dim("Disabling signing for Pod targets to prevent conflicts..."));try{te(`find ios/Pods -name "project.pbxproj" -exec sed -i '' 's/buildSettings = {/buildSettings = { CODE_SIGNING_ALLOWED = NO; CODE_SIGNING_REQUIRED = NO; PROVISIONING_PROFILE_SPECIFIER = ""; EXPANDED_CODE_SIGN_IDENTITY = "";/g' {} +`,{stdio:"ignore"})}catch{}}}}finally{j&&y.writeFileSync(G,j)}o.stop(`Expo prebuild complete (${m.name} config enforced).`)}let q=[];if(l==="android")await Q("build"),q=await cl(e,a,n,G=>z(G),f);else if(l==="ios"){await Q("signing"),I.info(A.dim("Preparing credentials..."));let G=r?.distributionType;q=await ul(e,t,a,n,i,j=>z(j),f,G,j=>Q(j))}e.postBuild&&(I.info(A.blue("Running post-build hook...")),I.info(A.dim(`> ${e.postBuild}`)),await O(e.postBuild,[],process.cwd(),u()));let ye=sl(Date.now()-s);if(I.success(A.green(`
|
|
1211
|
-
\u2713 Local build completed successfully in ${ye}`)),await d("building",{...H&&{bundleId:H},...P&&{appName:P}}),q.length>0&&(I.info(A.cyan(`
|
|
1212
|
-
\u{1F4E6} Generated Artifacts:`)),q.forEach(G=>{let j=_.resolve(G);I.info(A.dim(` - ${G}`)),I.info(A.gray(` Path: ${j}`))}),e.interactive)){let G=await Ka({message:"Install on connected device?"});if(!mn(G)&&G){if(l==="android"){let j=q.find(X=>X.endsWith(".apk"))||q[0];await pl(j,X=>z(X))}else if(l==="ios"){let j=q.find(T=>T.endsWith(".ipa"))||q.find(T=>T.endsWith(".app"))||q[0],X=Ze("ios");e.simulator?await ml(j,X||"",T=>z(T)):await gl(j,X||"",T=>z(T))}}}await Q("upload");let Ae=[];for(let G of q)try{let j=_.join(Ee.tmpdir(),`${t}-${_.basename(G)}`);y.copyFileSync(G,j),Ae.push(j),I.info(A.dim(` \u{1F4CB} Preserved artifact: ${_.basename(G)}`))}catch{I.warn(A.yellow(` Failed to preserve artifact: ${_.basename(G)}`))}q=Ae,I.info(A.dim("\u{1F9F9} Cleaning workspace (preserving dependency cache)..."));try{let G=process.cwd(),j=new Set(["node_modules"]),X=y.readdirSync(G),T=0;for(let K of X)if(!j.has(K)){if(K==="ios"){let Z=_.join(G,"ios"),ae=y.readdirSync(Z);for(let Se of ae)if(Se!=="Pods")try{y.rmSync(_.join(Z,Se),{recursive:!0,force:!0}),T++}catch{}continue}try{y.rmSync(_.join(G,K),{recursive:!0,force:!0}),T++}catch{}}I.info(A.dim(` Cleaned ${T} items. Cached: node_modules${y.existsSync(_.join(G,"ios","Pods"))?", ios/Pods":""}`)),I.info(A.green("\u{1F512} Security: No source code retained on build server. Only public dependencies cached."))}catch{I.warn(A.yellow("Post-build cleanup encountered errors (non-fatal)."))}try{let j=_.join(Ee.homedir(),m.workspacesDir),X=te(`df -k "${j}" | tail -1 | awk '{print $4}'`,{encoding:"utf8"}).trim(),T=parseInt(X,10)*1024;if(T<53687091200&&y.existsSync(j)){I.info(A.dim(` \u26A0\uFE0F Low disk space (${(T/1024/1024/1024).toFixed(0)} GB free). Running cache eviction...`));let K=_.basename(process.cwd()),Z=y.readdirSync(j).filter(ae=>ae!==K).map(ae=>{let Se=_.join(j,ae);try{let qe=y.statSync(Se);return qe.isDirectory()?{name:ae,dir:Se,mtime:qe.mtimeMs}:null}catch{return null}}).filter(Boolean);Z.sort((ae,Se)=>ae.mtime-Se.mtime);for(let ae of Z){if(T>=53687091200)break;try{y.rmSync(ae.dir,{recursive:!0,force:!0}),I.info(A.dim(` \u{1F5D1}\uFE0F Evicted stale workspace: ${ae.name}`));let Se=te(`df -k "${j}" | tail -1 | awk '{print $4}'`,{encoding:"utf8"}).trim();if(parseInt(Se,10)*1024>=53687091200)break}catch{}}}}catch{}return await w(),q}catch(E){throw await w(),E.message==="Command aborted"?(I.warn(A.yellow(`
|
|
1213
|
-
\u274C Build aborted.`)),await d("failed",{error:"Aborted by user"}),E):(I.error(A.red(`
|
|
1214
|
-
\u2717 Local build failed: ${E.message}`)),await d("failed",{error:E.message}),E)}},cl=async(e,t,n={},i,r)=>{let o=y.existsSync("android/gradlew")?"android/gradlew":y.existsSync("gradlew")?"./gradlew":null;if(!o)throw new Error("Could not find gradlew. Is this an Android project?");let s=e.developmentClient?"assembleDebug":"assembleRelease";!e.developmentClient&&e.distribution==="store"?s="bundleRelease":!e.developmentClient&&e.distribution==="internal"&&(s="assembleRelease");let l=e.buildCommand||s;I.info(A.blue(`Running Android build: ${l}...`));let a=o.includes("android/")?"android":".",c=(o.includes("android/"),"./gradlew"),u=[l],d=e.framework||"react-native",p={...n,...d==="expo"?{EXPO_NO_DOTENV:"1"}:{},MACH_FRAMEWORK:d,MACH_BUILD_PROFILE:t,MACH_APP_NAME:e.appName||e.name||"App"};if(n.ANDROID_VERSION_CODE){let h=_.join(a,"app/build.gradle");if(y.existsSync(h)){let S=n.ANDROID_VERSION_CODE,L=y.readFileSync(h,"utf-8");L=L.replace(/versionCode\s+\d+/,`versionCode ${S}`),y.writeFileSync(h,L),I.info(A.green(`\u2713 Applied Android versionCode ${S}`))}u.push(`-Pandroid.injected.version.code=${n.ANDROID_VERSION_CODE}`)}for(let h of["app/build","build",".cxx"]){let S=_.join(a,h);y.existsSync(S)&&y.rmSync(S,{recursive:!0,force:!0})}ii(process.cwd()),await Be(c,u,a,p,i,r);let f=_.join(a,"app/build/outputs");return pt(f,[".apk",".aab"])},ul=async(e,t,n,i={},r,o,s,l,a)=>{if(process.platform!=="darwin")throw new Error("iOS builds can only be run on macOS.");let c=_.resolve(process.cwd(),y.existsSync("ios")?"ios":"."),u=y.readdirSync(c),d=u.find(D=>D.endsWith(".xcworkspace")),p=u.find(D=>D.endsWith(".xcodeproj")),f=ft(i,n,e),h=oi(f.BUILD_NUMBER||f.CURRENT_PROJECT_VERSION);if((f.BUILD_NUMBER||f.CURRENT_PROJECT_VERSION)&&!h)throw new Error(`Invalid iOS BUILD_NUMBER/CURRENT_PROJECT_VERSION: "${f.BUILD_NUMBER||f.CURRENT_PROJECT_VERSION}". Apple requires one to three period-separated integers. Fix the Dashboard secret or remove it so Mach can use its auto build number.`);let S=h?[`BUILD_NUMBER=${h}`,`CURRENT_PROJECT_VERSION=${h}`]:[];if(h&&(f.BUILD_NUMBER=h,f.CURRENT_PROJECT_VERSION=h,I.info(A.dim(`Using iOS build number: ${h}`))),!d&&!p)throw new Error("Could not find Xcode workspace or project in ios/ directory.");try{let D=te("xcode-select -p").toString().trim();I.info(A.dim(`Using Xcode at: ${D}`))}catch{I.warn(A.dim("Could not detect Xcode path."))}I.info(A.blue("Running iOS build via xcodebuild..."));let L=d?d.replace(".xcworkspace",""):p?.replace(".xcodeproj",""),x=e.iosScheme||L||e.scheme,b=e.developmentClient?"Debug":e.iosConfiguration||"Release",U=(r||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),w=_.join(Ee.homedir(),`Library/Developer/Xcode/DerivedData/${m.nameLower}`,U);y.mkdirSync(w,{recursive:!0});let z=Et(f),Q=_.join(w,".mach-env-hash"),O=_.join(w,"Build"),E=y.existsSync(Q)?y.readFileSync(Q,"utf-8").trim():"";if(y.existsSync(O)){let D=E&&E!==z?"Build environment changed \u2014 clearing iOS DerivedData build products.":E?"Clearing iOS DerivedData build products to force a fresh JS bundle.":"DerivedData has no environment stamp \u2014 clearing iOS build products.";I.info(A.dim(D)),y.rmSync(O,{recursive:!0,force:!0})}if(y.writeFileSync(Q,z),ii(process.cwd()),e.simulator){let D=ol(c,d,p,x,b),$=D?["-destination",D]:[];I.info(A.dim(D?`Building for simulator (Scheme: ${x}, Config: ${b}, Destination: ${D})...`:`Building for simulator (Scheme: ${x}, Config: ${b}; xcodebuild will choose destination)...`));let C=[d?"-workspace":"-project",d||p,"-scheme",x,"-configuration",b,"-sdk","iphonesimulator",...$,"-derivedDataPath",w,...S,"COMPILER_INDEX_STORE_ENABLE=NO","CODE_SIGNING_ALLOWED=NO","CODE_SIGNING_REQUIRED=NO"];try{await Be("xcodebuild",C,c,f,o,s)}catch(F){if(!il(F))throw F;rl(w),ii(process.cwd()),await Be("xcodebuild",C,c,f,o,s)}let g=_.join(w,"Build/Products",`${b}-iphonesimulator`),k=pt(g,[".app"]);if(k.length>0){let F=k[0],V=_.basename(F,".app"),J=_.join(g,`${V}_simulator.zip`);return I.info(A.dim(`Creating simulator artifact: ${J}...`)),te(`cd "${g}" && zip -r "${J}" "${_.basename(F)}"`),[J]}return[]}else{I.info(A.dim(`Archiving (Scheme: ${x}, Config: ${b})...`));let D=_.join(c,"build.xcarchive"),$=_.join(c,"export");y.rmSync(D,{recursive:!0,force:!0}),y.rmSync($,{recursive:!0,force:!0});let C=i.IOS_DIST_P12,g=i.IOS_PROVISIONING_PROFILE,k=i.IOS_P12_PASSWORD||"",F=[],V,J,H={isAppStore:!1,isDevelopment:!1};if(C&&g){I.info(A.blue("\u{1F510} CI/CD Signing: Importing certificates..."));try{let T=`${m.buildPrefix}-${t}.keychain-db`,K=_.join(Ee.tmpdir(),T),Z=m.keychainPassword;te(`security create-keychain -p "${Z}" "${K}" 2>/dev/null || true`),te(`security set-keychain-settings -t 3600 -l "${K}"`),te(`security unlock-keychain -p "${Z}" "${K}"`);let ae=_.join(Ee.tmpdir(),`cert-${t}.p12`),Se=Buffer.from(C,"base64");y.writeFileSync(ae,Se),I.info(A.dim(`P12 data size: ${Se.length} bytes, first bytes: ${Se.slice(0,4).toString("hex")}`)),(Se.length<100||Se[0]!==48)&&(I.warn(A.yellow("\u26A0\uFE0F P12 data looks corrupted or was not decrypted correctly.")),I.warn(A.yellow(" This usually means MACH_ENCRYPTION_KEY on the Remote API differs from when credentials were uploaded.")));let qe=[k,"",m.keychainPassword],Ct=!1;for(let _e of qe)try{te(`security import "${ae}" -k "${K}" -P "${_e}" -A -T /usr/bin/codesign -T /usr/bin/security`,{stdio:"pipe"}),Ct=!0,I.info(A.dim(`\u2713 P12 imported successfully with password: ${_e?"[set]":"[empty]"}`));break}catch(Me){I.info(A.dim(` P12 import attempt with password ${_e?`"${_e.substring(0,3)}..."`:"[empty]"} failed: ${Me.message?.split(`
|
|
1215
|
-
`)[0]||"unknown"}`))}if(!Ct)throw new Error("Failed to import P12.");y.unlinkSync(ae),te(`security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "${Z}" "${K}"`);let on=te("security list-keychains -d user",{encoding:"utf-8"}).split(`
|
|
1216
|
-
`).map(_e=>_e.trim().replace(/^"|"$/g,"")).filter(_e=>_e.length>0),sn=[K,...on].map(_e=>`"${_e}"`).join(" ");te(`security list-keychains -d user -s ${sn}`),te(`security default-keychain -s "${K}"`);let an=_.join(Ee.homedir(),"Library/MobileDevice/Provisioning Profiles");y.mkdirSync(an,{recursive:!0});let ut=Buffer.from(g,"base64"),Wn=_.join(an,`${m.nameLower}-temp-${t}.mobileprovision`);y.writeFileSync(Wn,ut);let Yn=ut.toString("utf-8"),Xi=/<key>get-task-allow<\/key>\s*<true\/>/.test(Yn);H={isAppStore:!Yn.includes("<key>ProvisionedDevices</key>")&&!Xi,isDevelopment:Xi};try{let Me=te(`security cms -D -i "${Wn}"`,{encoding:"utf-8"}).match(/<key>UUID<\/key>\s*<string>([^<]+)<\/string>/);J=Me?Me[1]:void 0}catch{let Me=Yn.match(/<key>UUID<\/key>\s*<string>([^<]+)<\/string>/);J=Me?Me[1]:void 0}J||(I.warn("Could not extract UUID from provisioning profile. Using fallback."),J=`${m.nameLower}-${t}`);let Jn=_.join(an,`${J}.mobileprovision`);y.existsSync(Jn)&&y.unlinkSync(Jn),y.renameSync(Wn,Jn);try{let _e=te(`security find-identity -v -p codesigning "${K}"`,{encoding:"utf-8"}),Me=Array.from(_e.matchAll(/"((?:Apple|iPhone) (?:Distribution|Developer|Development)[^"]*)"/g),Nt=>Nt[1]),Zi=H.isDevelopment?Me.find(Nt=>/\b(Development|Developer)\b/.test(Nt)):Me.find(Nt=>/\bDistribution\b/.test(Nt)),Qi=Me[0];(Zi||Qi)&&(V=Zi||Qi,I.info(A.blue(`Identity auto-detected from keychain: "${V}"`)))}catch{}V||(V=H.isDevelopment?"Apple Development":"Apple Distribution",I.info(A.blue(`Identity fallback (profile heuristic): "${V}"`))),I.info(A.dim(`Profile type: ${H.isDevelopment?"Development":H.isAppStore?"App Store":"Ad-Hoc"}`)),I.info(A.dim(`Identity Detection: get-task-allow=${H.isDevelopment}, Selected Identity="${V}"`)),F.push("CODE_SIGN_STYLE=Manual"),F.push(`CODE_SIGN_IDENTITY="${V}"`),F.push(`PROVISIONING_PROFILE_SPECIFIER=${J}`),e.iosTeamId&&F.push(`DEVELOPMENT_TEAM=${e.iosTeamId}`)}catch(T){throw I.error(`Signing setup failed: ${T.message}`),T}}else F.push("-allowProvisioningUpdates"),e.iosTeamId&&F.push(`DEVELOPMENT_TEAM=${e.iosTeamId}`);a&&await a("archive"),I.info(A.blue(`Archive detected Identity: "${V}"`)),I.info(A.blue(`Archive detected UUID: "${J}"`)),await Be("xcodebuild",["archive",d?"-workspace":"-project",d||p,"-scheme",x,"-configuration",b,"-archivePath",D,"-derivedDataPath",w,...S,...F],c,f,o,s);let P=pt(_.join(D,"Products","Applications"),[".app"]);for(let T of P){let K=ll(T);I.info(A.dim(`Validated iOS CFBundleVersion ${K} in ${_.basename(T)}`))}let q;J?(H.isAppStore?q="app-store":H.isDevelopment?q="development":q="ad-hoc",I.info(A.blue(`Export method from profile: "${q}"`))):(q=e.distribution==="store"?"app-store":e.distribution==="internal"?"ad-hoc":"development",I.warn(A.yellow(`No profile UUID detected. Export method from distribution flag: "${q}"`)));let ye=e.iosExportMethod||q,Ae=e.iosBundleIdentifier||Ze("ios"),G=_.join(c,"ExportOptions.plist"),j=`<?xml version="1.0" encoding="UTF-8"?>
|
|
1293
|
+
`),u=Date.now();return}let B=Date.now();B-u>3e4&&(x.write(`[xcodebuild] still running; detailed output is streamed to Mach logs.
|
|
1294
|
+
`),u=B)};_.stdout.on("data",b=>{let x=b.toString();a=Vr(a,x),D(x,process.stdout),r&&r(x)}),_.stderr.on("data",b=>{let x=b.toString();a=Vr(a,x),D(x,process.stderr),r&&r(x)}),_.on("close",b=>{b===0?s(b):l(new Error(vl(e,t,b,a)))}),_.on("error",b=>l(b))}),Sn=async(e,t,n,i,r)=>{try{await it("xcodebuild",e,t,n,i,r)}catch(o){if(!Tl(o))throw o;O.warn(R.yellow("CocoaPods script permission denied. Repairing Pods script permissions and retrying xcodebuild once...")),Zr(t),await it("xcodebuild",e,t,n,i,r)}},xl=e=>{let t=Math.floor(e/1e3%60),n=Math.floor(e/(1e3*60)%60),i=Math.floor(e/(1e3*60*60)%24),r=[];return i>0&&r.push(`${i}h`),n>0&&r.push(`${n}m`),(t>0||r.length===0)&&r.push(`${t}s`),r.join(" ")},At=(e,t)=>{let n=[];try{if(!S.existsSync(e))return n;let i=S.readdirSync(e);for(let r of i){let o=E.join(e,r);try{let s=S.statSync(o);if(t.some(a=>r.endsWith(a))){n.push(E.resolve(o));continue}s.isDirectory()&&(n=n.concat(At(o,t)))}catch{}}}catch{}return n},Ll=/^\d+(?:\.\d+){0,2}$/,pi=e=>{let t=String(e||"").trim();return!t||t==="undefined"||t==="null"?null:Ll.test(t)?t:null},Qr=(e,t)=>{let n=pi(e);if(!n)throw new Error(`Invalid iOS CFBundleVersion from ${t}: "${e||""}". Apple requires one to three period-separated integers, for example "42" or "1.2.3". If you see "[Decryption Failed]", fix/remove the broken BUILD_NUMBER secret and rebuild.`);return n},fi=(e,t)=>nt("/usr/libexec/PlistBuddy",["-c",`Print :${t}`,e],{encoding:"utf-8"}).trim(),Ct=(e,t)=>{try{return fi(e,t)}catch{return""}},zr=e=>String(e||"").replace(/\.app$/i,"").replace(/[^a-z0-9]/gi,"").toLowerCase(),Ml=e=>{try{return S.statSync(e).isDirectory()}catch{return!1}},Ul=(e,t,n)=>{if(!S.existsSync(e))throw new Error(`iOS simulator build output directory was not found: ${e}`);let i=S.readdirSync(e).filter(c=>c.endsWith(".app")).map(c=>E.join(e,c)).filter(Ml);if(i.length===0){let u=At(e,[".app"]).map(d=>E.relative(e,d)).join(", ");throw new Error(`No top-level iOS simulator .app product was found in ${e}.`+(u?` Nested .app bundles found but ignored: ${u}`:""))}let r=new Set([t,n.iosScheme,n.scheme,n.appName].filter(Boolean).map(c=>zr(String(c))).filter(Boolean)),o=i.map(c=>{let u=E.join(c,"Info.plist"),d=S.existsSync(u)?Ct(u,"CFBundleName"):"",f=S.existsSync(u)?Ct(u,"CFBundleDisplayName"):"",p=S.existsSync(u)?Ct(u,"CFBundleExecutable"):"",g=S.existsSync(u)?Ct(u,"CFBundleIdentifier"):"",y=p?E.join(c,p):"";return{appPath:c,bundleIdentifier:g,executable:p,isValid:S.existsSync(u)&&!!p&&S.existsSync(y),names:[E.basename(c,".app"),d,f,p].map(zr).filter(Boolean)}}),s=o.filter(c=>c.isValid);if(s.length===0)throw new Error(`No valid iOS simulator .app product was found in ${e}. Candidates: `+o.map(c=>E.basename(c.appPath)).join(", "));let a=s.find(c=>c.names.some(u=>r.has(u)))||(s.length===1?s[0]:null);if(!a)throw new Error(`Multiple iOS simulator .app products were found in ${e}: `+s.map(c=>{let u=c.bundleIdentifier?` (${c.bundleIdentifier})`:"";return`${E.basename(c.appPath)}${u}`}).join(", ")+`. Set ios.scheme in ${m.configFileName} so ${m.name} can select the app target safely.`);return a.appPath},Wr=e=>{let t=E.join(e,"Info.plist");if(!S.existsSync(t))throw new Error(`Could not validate iOS build number: ${t} not found.`);return Qr(fi(t,"CFBundleVersion"),t)},eo=e=>{let t=E.join(e,"Info.plist");if(!S.existsSync(t))throw new Error(`Could not validate iOS app executable: ${t} not found.`);let n=Ct(t,"CFBundleExecutable");if(!n)throw new Error(`Could not validate iOS app executable: CFBundleExecutable missing in ${t}.`);let i=E.join(e,n);if(!S.existsSync(i))throw new Error(`Could not validate iOS app executable: ${i} not found.`);return i},Fl=()=>process.arch==="arm64"?"arm64":"x86_64",to=e=>{let t=eo(e),n="";try{n=nt("lipo",["-info",t],{encoding:"utf-8"}).trim()}catch(r){throw new Error(`Could not inspect iOS simulator executable architecture for ${E.basename(e)}: ${r.message}`)}let i=Fl();if(!new RegExp(`\\b${i}\\b`).test(n))throw new Error(`iOS simulator app ${E.basename(e)} cannot be installed on this runner because its executable does not include the required ${i} simulator architecture. lipo output: ${n}. Check the React Native iOS project ARCHS/EXCLUDED_ARCHS settings for iphonesimulator builds.`);return n},Bl=e=>{try{return nt("xcrun",["vtool","-show-build",e],{encoding:"utf-8"}).trim()}catch(t){throw new Error(`Could not inspect iOS executable build platform for ${E.basename(e)}: ${t.message}`)}},no=e=>{let t=eo(e),n=Bl(t);if(!/\bplatform\s+IOSSIMULATOR\b/i.test(n))throw new Error(`iOS simulator app ${E.basename(e)} was built for the wrong Apple platform. A simulator artifact must contain PLATFORM IOSSIMULATOR, not an iPhone device binary. vtool output: ${n}`);return n},Hl=e=>{let n=nt("unzip",["-Z1",e],{encoding:"utf-8"}).split(`
|
|
1295
|
+
`).find(r=>/^Payload\/[^/]+\.app\/Info\.plist$/.test(r.trim()));if(!n)throw new Error(`Could not validate iOS build number: ${E.basename(e)} has no Payload/*.app/Info.plist.`);let i=S.mkdtempSync(E.join(Ae.tmpdir(),`${m.nameLower}-ipa-plist-`));try{let r=E.join(i,"Info.plist"),o=nt("unzip",["-p",e,n.trim()]);return S.writeFileSync(r,o),Qr(fi(r,"CFBundleVersion"),`${E.basename(e)}:${n.trim()}`)}finally{S.rmSync(i,{recursive:!0,force:!0})}},jl=e=>`'${e.replace(/'/g,"'\\''")}'`,Gl=()=>process.execPath&&S.existsSync(process.execPath)?process.execPath:nt("which",["node"],{encoding:"utf-8"}).trim(),io=(e,t,n)=>{if(!S.existsSync(e))return;let i=Gl();t.NODE_BINARY=i;let r=E.join(e,".xcode.env.local");S.writeFileSync(r,`export NODE_BINARY=${jl(i)}
|
|
1296
|
+
`);let o=`[NODE] Xcode NODE_BINARY: ${i}
|
|
1297
|
+
`;n&&n(R.dim(o)),O.info(R.dim(o.trim()))},mi=async(e,t,n={},i,r={})=>{let o=yn(),s=Date.now(),l=e.platform,a=e.buildProfile||"production",c=Qe(e.framework),u=()=>bt(n,a,e),d=async(I,T={})=>{if(i)for(let w=1;w<=3;w++)try{await k.patch(`/builds/${i}/${t}`,{status:I,...T});return}catch(C){let h=C?.response?.data?.message||C?.message||String(C);console.error(`[reportStatus] attempt ${w}/3 failed (status=${I}): ${h}`),w<3&&await new Promise(M=>setTimeout(M,2e3))}},f=new AbortController,{signal:p}=f,g=null;i&&(g=setInterval(async()=>{try{(await k.get(`/builds/${i}/${t}`)).data.status==="cancelled"&&(O.warn(R.yellow(`
|
|
1298
|
+
\u{1F6D1} Build cancelled from dashboard. Terminating...`)),f.abort(),g&&clearInterval(g))}catch{}},5e3));let y=E.join(process.cwd(),".mach-cache"),_="setup",D="",b=null,x=async()=>{if(!D||!i)return;let I=D;D="";try{let T=I;Object.values(n).forEach(w=>{if(w&&w.length>5){let C=w.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");T=T.replace(new RegExp(C,"g"),"[SECRET]")}}),await k.post(`/builds/${i}/${t}/logs`,{log:T,step:_})}catch{}},A=async()=>{b&&(clearTimeout(b),b=null),await x(),Rl(y,t),g&&(clearInterval(g),g=null);try{let I=E.join(Ae.tmpdir(),`${m.buildPrefix}-${t}.keychain-db`);S.existsSync(I)&&(te(`security delete-keychain "${I}"`,{stdio:"ignore"}),O.info(R.dim("\u{1F511} Build keychain deleted.")))}catch{}try{let I=E.join(Ae.homedir(),"Library/MobileDevice/Provisioning Profiles");if(S.existsSync(I)){let T=S.readdirSync(I).filter(w=>w.includes(t)||w.startsWith(`${m.nameLower}-temp-${t}`));for(let w of T)S.unlinkSync(E.join(I,w))}}catch{}},B=async I=>{i&&(D+=I,D.length>=8192?(b&&(clearTimeout(b),b=null),await x()):b||(b=setTimeout(()=>{b=null,x()},2e3)))},q=async I=>{_=I,await B(`[STEP_START:${I}] ${Math.floor(Date.now()/1e3)}
|
|
1299
|
+
`)},P=async(I,T,w,C)=>await it(I,T,w,C,h=>{B(h)},p);O.info(R.blue(`\u{1F680} Starting local build for ${l} (${a})...`));try{_l(y,t)}catch(I){throw await d("failed",{error:I.message,endTime:Date.now()}),I}if(await d("building"),await q("setup"),l==="ios"&&!e.simulator&&n.MACH_IOS_BUILD_NUMBER_LOCKED==="1"&&n.BUILD_NUMBER)O.info(R.dim(`Auto build number: ${n.BUILD_NUMBER}`)),await B(`[BUILD_NUMBER] ${n.BUILD_NUMBER}
|
|
1300
|
+
`);else if(i&&l==="ios"&&!e.simulator)try{let I=parseInt(n.BUILD_NUMBER||"0",10),T=Number.isFinite(I)?I:0,w=await k.post(`/projects/${i}/next-build-number`,{platform:"ios",startFrom:T});if(w.data.status==="success"){let C=pi(String(w.data.buildNumber||""));if(!C)throw new Error(`Dashboard returned invalid iOS build number: "${w.data.buildNumber||""}"`);let h=parseInt(C,10),M=T>0&&Number.isFinite(h)&&h<T?String(T):C;M!==C&&(O.warn(R.yellow(`Dashboard build counter returned ${C}; using minimum ${M}.`)),await B(`[BUILD_NUMBER] Dashboard returned ${C}; using minimum ${M}
|
|
1301
|
+
`)),n.BUILD_NUMBER=M,O.info(R.dim(`Auto build number: ${n.BUILD_NUMBER}`)),await B(`[BUILD_NUMBER] ${n.BUILD_NUMBER}
|
|
1302
|
+
`)}}catch(I){O.warn(R.yellow(`Could not fetch auto build number: ${I.message}`))}await q("lock"),c.applyLocalProcessEnv(e);try{await q("clone"),O.info(R.dim("Preparing source...")),await q("read_config");let I=E.join(process.cwd(),m.configFileName);if(S.existsSync(I)){let G=JSON.parse(S.readFileSync(I,"utf-8"))?.build?.[a]||{};await B(`[CONFIG] Profile: ${a}, distribution: ${G.distribution||"not set"}, simulator: ${G.simulator||!1}
|
|
1303
|
+
`)}if(await q("read_package"),e.nodeVersion){let V=process.env.NVM_DIR||E.join(Ae.homedir(),".nvm"),G=E.join(V,"versions","node"),Q;if(S.existsSync(G)){let z=S.readdirSync(G).sort().reverse(),J=e.nodeVersion.startsWith("v")?e.nodeVersion:`v${e.nodeVersion}`,ae=z.find(ye=>ye===J||ye.startsWith(J+".")||ye.startsWith(`v${e.nodeVersion}.`));ae&&(Q=E.join(G,ae,"bin"))}if(Q&&S.existsSync(Q)){let z=process.env.PATH||"";process.env.PATH=`${Q}:${z}`,await B(`[NODE] Switched to Node ${e.nodeVersion} \u2014 using ${Q}
|
|
1304
|
+
`),O.info(R.green(`\u2713 Node switched to ${e.nodeVersion} (${Q})`))}else await B(`[NODE] Warning: Node ${e.nodeVersion} not found in nvm. Run: nvm install ${e.nodeVersion} on the build machine.
|
|
1305
|
+
`),O.warn(R.yellow(`Node ${e.nodeVersion} not found in nvm \u2014 using system default`))}await q("deps"),o.start("Checking dependencies...");let T=Il(y),w=El(process.cwd()),C=S.existsSync("node_modules"),h=S.existsSync("yarn.lock"),M=S.existsSync("bun.lockb");C&&T.node&&T.node!==w&&(o.stop("Dependency fingerprint changed \u2014 clearing node_modules for clean install..."),await B(`[CACHE] package.json/lockfile changed \u2014 wiping node_modules
|
|
1306
|
+
`),S.rmSync(E.join(process.cwd(),"node_modules"),{recursive:!0,force:!0}),C=!1);let U="npm",j=["install","--prefer-offline"];h?(U="yarn",j=["install","--prefer-offline"]):M&&(U="bun",j=["install"]),C?o.stop("Cached node_modules found. Syncing dependencies..."):o.stop("No cached dependencies. Running fresh install..."),e.preBuild&&(O.info(R.blue("Running pre-install hook...")),O.info(R.dim(`> ${e.preBuild}`)),await q("prebuild"),await P("bash",[e.preBuild],process.cwd(),u())),O.info(R.dim(`Running ${U} ${j.join(" ")}...`)),await P(U,j,process.cwd(),u()),T.node=w,Gr(y,T);let X=await c.prepareLocalProject({platform:l,options:e,cacheMeta:T,cacheMetaDir:y,currentBuildEnv:u,reportStep:q,reportLog:B,loggedRun:P,configureXcodeNodeBinary:io,podsFingerprint:Al,writeCacheMeta:Gr}),H=X.bundleId||e.iosBundleIdentifier||"",N=X.appName||e.name||"",W=[];if(l==="android")await q("build"),W=await Kl(e,a,n,V=>B(V),p);else if(l==="ios"){await q("signing"),O.info(R.dim("Preparing credentials..."));let V=r?.distributionType;W=await Vl(e,t,a,n,i,G=>B(G),p,V,G=>q(G))}e.postBuild&&(O.info(R.blue("Running post-build hook...")),O.info(R.dim(`> ${e.postBuild}`)),await P(e.postBuild,[],process.cwd(),u()));let ce=xl(Date.now()-s);if(O.success(R.green(`
|
|
1307
|
+
\u2713 Local build completed successfully in ${ce}`)),await d("building",{...H&&{bundleId:H},...N&&{appName:N}}),W.length>0&&(O.info(R.cyan(`
|
|
1308
|
+
\u{1F4E6} Generated Artifacts:`)),W.forEach(V=>{let G=E.resolve(V);O.info(R.dim(` - ${V}`)),O.info(R.gray(` Path: ${G}`))}),e.interactive)){let V=await yl({message:"Install on connected device?"});if(!bn(V)&&V){if(l==="android"){let G=W.find(Q=>Q.endsWith(".apk"))||W[0];await Wl(G,Q=>B(Q))}else if(l==="ios"){let G=W.find(z=>z.endsWith(".ipa"))||W.find(z=>z.endsWith(".app"))||W[0],Q=rt("ios");e.simulator?await Yl(G,Q||"",z=>B(z)):await Jl(G,Q||"",z=>B(z))}}}await q("upload");let ue=[];for(let V of W)try{let G=E.join(Ae.tmpdir(),`${t}-${E.basename(V)}`);S.copyFileSync(V,G),ue.push(G),O.info(R.dim(` \u{1F4CB} Preserved artifact: ${E.basename(V)}`))}catch{O.warn(R.yellow(` Failed to preserve artifact: ${E.basename(V)}`))}W=ue,O.info(R.dim("\u{1F9F9} Cleaning workspace (preserving dependency cache)..."));try{let V=process.cwd(),G=new Set(["node_modules"]),Q=S.readdirSync(V),z=0;for(let J of Q)if(!G.has(J)){if(J==="ios"){let ae=E.join(V,"ios"),ye=S.readdirSync(ae);for(let _e of ye)if(_e!=="Pods")try{S.rmSync(E.join(ae,_e),{recursive:!0,force:!0}),z++}catch{}continue}try{S.rmSync(E.join(V,J),{recursive:!0,force:!0}),z++}catch{}}O.info(R.dim(` Cleaned ${z} items. Cached: node_modules${S.existsSync(E.join(V,"ios","Pods"))?", ios/Pods":""}`)),O.info(R.green("\u{1F512} Security: No source code retained on build server. Only public dependencies cached."))}catch{O.warn(R.yellow("Post-build cleanup encountered errors (non-fatal)."))}try{let G=E.join(Ae.homedir(),m.workspacesDir),Q=te(`df -k "${G}" | tail -1 | awk '{print $4}'`,{encoding:"utf8"}).trim(),z=parseInt(Q,10)*1024;if(z<53687091200&&S.existsSync(G)){O.info(R.dim(` \u26A0\uFE0F Low disk space (${(z/1024/1024/1024).toFixed(0)} GB free). Running cache eviction...`));let J=E.basename(process.cwd()),ae=S.readdirSync(G).filter(ye=>ye!==J).map(ye=>{let _e=E.join(G,ye);try{let $t=S.statSync(_e);return $t.isDirectory()?{name:ye,dir:_e,mtime:$t.mtimeMs}:null}catch{return null}}).filter(Boolean);ae.sort((ye,_e)=>ye.mtime-_e.mtime);for(let ye of ae){if(z>=53687091200)break;try{S.rmSync(ye.dir,{recursive:!0,force:!0}),O.info(R.dim(` \u{1F5D1}\uFE0F Evicted stale workspace: ${ye.name}`));let _e=te(`df -k "${G}" | tail -1 | awk '{print $4}'`,{encoding:"utf8"}).trim();if(parseInt(_e,10)*1024>=53687091200)break}catch{}}}}catch{}return await A(),W}catch(I){throw await A(),I.message==="Command aborted"?(O.warn(R.yellow(`
|
|
1309
|
+
\u274C Build aborted.`)),await d("failed",{error:"Aborted by user",endTime:Date.now()}),I):(O.error(R.red(`
|
|
1310
|
+
\u2717 Local build failed: ${I.message}`)),await d("failed",{error:I.message,endTime:Date.now()}),I)}},Kl=async(e,t,n={},i,r)=>{let o=S.existsSync("android/gradlew")?"android/gradlew":S.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;O.info(R.blue(`Running Android build: ${l}...`));let a=o.includes("android/")?"android":".",c=(o.includes("android/"),"./gradlew"),u=[l],d=Qe(e.framework),f={...n,...d.localAndroidEnv(e,t),MACH_APP_NAME:e.appName||e.name||"App"};if(n.ANDROID_VERSION_CODE){let g=E.join(a,"app/build.gradle");if(S.existsSync(g)){let y=n.ANDROID_VERSION_CODE,_=S.readFileSync(g,"utf-8");_=_.replace(/versionCode\s+\d+/,`versionCode ${y}`),S.writeFileSync(g,_),O.info(R.green(`\u2713 Applied Android versionCode ${y}`))}u.push(`-Pandroid.injected.version.code=${n.ANDROID_VERSION_CODE}`)}for(let g of["app/build","build",".cxx"]){let y=E.join(a,g);S.existsSync(y)&&S.rmSync(y,{recursive:!0,force:!0})}ci(process.cwd()),await it(c,u,a,f,i,r);let p=E.join(a,"app/build/outputs");return At(p,[".apk",".aab"])},Vl=async(e,t,n,i={},r,o,s,l,a)=>{if(process.platform!=="darwin")throw new Error("iOS builds can only be run on macOS.");let c=E.resolve(process.cwd(),S.existsSync("ios")?"ios":".");Zr(c);let u=S.readdirSync(c),d=u.find(T=>T.endsWith(".xcworkspace")),f=u.find(T=>T.endsWith(".xcodeproj")),p=bt(i,n,e);io(c,p,o);let g=pi(p.BUILD_NUMBER||p.CURRENT_PROJECT_VERSION);if((p.BUILD_NUMBER||p.CURRENT_PROJECT_VERSION)&&!g)throw new Error(`Invalid iOS BUILD_NUMBER/CURRENT_PROJECT_VERSION: "${p.BUILD_NUMBER||p.CURRENT_PROJECT_VERSION}". Apple requires one to three period-separated integers. Fix the Dashboard secret or remove it so Mach can use its auto build number.`);let y=g?[`BUILD_NUMBER=${g}`,`CURRENT_PROJECT_VERSION=${g}`]:[];if(g&&(p.BUILD_NUMBER=g,p.CURRENT_PROJECT_VERSION=g,O.info(R.dim(`Using iOS build number: ${g}`))),!d&&!f)throw new Error("Could not find Xcode workspace or project in ios/ directory.");try{let T=te("xcode-select -p").toString().trim();O.info(R.dim(`Using Xcode at: ${T}`))}catch{O.warn(R.dim("Could not detect Xcode path."))}O.info(R.blue("Running iOS build via xcodebuild..."));let _=d?d.replace(".xcworkspace",""):f?.replace(".xcodeproj",""),D=e.iosScheme||_||e.scheme,b=e.developmentClient?"Debug":e.iosConfiguration||"Release",x=(r||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),A=E.join(Ae.homedir(),`Library/Developer/Xcode/DerivedData/${m.nameLower}`,x);S.mkdirSync(A,{recursive:!0});let B=Dt(p),q=E.join(A,".mach-env-hash"),P=E.join(A,"Build"),I=S.existsSync(q)?S.readFileSync(q,"utf-8").trim():"";if(S.existsSync(P)){let T=I&&I!==B?"Build environment changed \u2014 clearing iOS DerivedData build products.":I?"Clearing iOS DerivedData build products to force a fresh JS bundle.":"DerivedData has no environment stamp \u2014 clearing iOS build products.";O.info(R.dim(T)),S.rmSync(P,{recursive:!0,force:!0})}if(S.writeFileSync(q,B),ci(process.cwd()),e.simulator){let T=kl(c,d,f,D,b),w=T||"generic/platform=iOS Simulator",C=["-destination",w];O.info(R.dim(T?`Building for simulator (Scheme: ${D}, Config: ${b}, Destination: ${w})...`:`Building for simulator (Scheme: ${D}, Config: ${b}, Destination: ${w})...`));let h=[d?"-workspace":"-project",d||f,"-scheme",D,"-configuration",b,"-sdk","iphonesimulator",...C,"-derivedDataPath",A,...y,"COMPILER_INDEX_STORE_ENABLE=NO","CODE_SIGNING_ALLOWED=NO","CODE_SIGNING_REQUIRED=NO","ONLY_ACTIVE_ARCH=NO","EXCLUDED_ARCHS=","SUPPORTED_PLATFORMS=iphonesimulator"];try{await Sn(h,c,p,o,s)}catch(ue){if(!Cl(ue))throw ue;Nl(A),ci(process.cwd()),await Sn(h,c,p,o,s)}let M=E.join(A,"Build/Products",`${b}-iphonesimulator`),U=Ul(M,D,e),j=E.basename(U,".app"),X=Ct(E.join(U,"Info.plist"),"CFBundleIdentifier")||"unknown bundle",H=Wr(U),N=to(U),W=no(U),ce=E.join(M,`${j}_simulator.zip`);return O.info(R.dim(`Selected simulator app: ${E.relative(M,U)} (${X}, build ${H})`)),O.info(R.dim(`Simulator executable architecture: ${N}`)),O.info(R.dim(`Simulator executable platform: ${W.split(`
|
|
1311
|
+
`).find(ue=>/\bplatform\b/i.test(ue))?.trim()||"IOSSIMULATOR"}`)),O.info(R.dim(`Creating simulator artifact: ${ce}...`)),ke(ce),nt("zip",["-r",ce,E.basename(U)],{cwd:E.dirname(U),stdio:"pipe"}),[ce]}else{O.info(R.dim(`Archiving (Scheme: ${D}, Config: ${b})...`));let T=E.join(c,"build.xcarchive"),w=E.join(c,"export");S.rmSync(T,{recursive:!0,force:!0}),S.rmSync(w,{recursive:!0,force:!0});let C=i.IOS_DIST_P12,h=i.IOS_PROVISIONING_PROFILE,M=i.IOS_P12_PASSWORD||"",U=[],j,X,H={isAppStore:!1,isDevelopment:!1};if(C&&h){O.info(R.blue("\u{1F510} CI/CD Signing: Importing certificates..."));try{let z=`${m.buildPrefix}-${t}.keychain-db`,J=E.join(Ae.tmpdir(),z),ae=m.keychainPassword;te(`security create-keychain -p "${ae}" "${J}" 2>/dev/null || true`),te(`security set-keychain-settings -t 3600 -l "${J}"`),te(`security unlock-keychain -p "${ae}" "${J}"`);let ye=E.join(Ae.tmpdir(),`cert-${t}.p12`),_e=Buffer.from(C,"base64");S.writeFileSync(ye,_e),O.info(R.dim(`P12 data size: ${_e.length} bytes, first bytes: ${_e.slice(0,4).toString("hex")}`)),(_e.length<100||_e[0]!==48)&&(O.warn(R.yellow("\u26A0\uFE0F P12 data looks corrupted or was not decrypted correctly.")),O.warn(R.yellow(" This usually means MACH_ENCRYPTION_KEY on the Remote API differs from when credentials were uploaded.")));let $t=[M,"",m.keychainPassword],or=!1;for(let Re of $t)try{te(`security import "${ye}" -k "${J}" -P "${Re}" -A -T /usr/bin/codesign -T /usr/bin/security`,{stdio:"pipe"}),or=!0,O.info(R.dim(`\u2713 P12 imported successfully with password: ${Re?"[set]":"[empty]"}`));break}catch(Be){O.info(R.dim(` P12 import attempt with password ${Re?`"${Re.substring(0,3)}..."`:"[empty]"} failed: ${Be.message?.split(`
|
|
1312
|
+
`)[0]||"unknown"}`))}if(!or)throw new Error("Failed to import P12.");S.unlinkSync(ye),te(`security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "${ae}" "${J}"`);let Ca=te("security list-keychains -d user",{encoding:"utf-8"}).split(`
|
|
1313
|
+
`).map(Re=>Re.trim().replace(/^"|"$/g,"")).filter(Re=>Re.length>0),Na=[J,...Ca].map(Re=>`"${Re}"`).join(" ");te(`security list-keychains -d user -s ${Na}`),te(`security default-keychain -s "${J}"`);let Zn=E.join(Ae.homedir(),"Library/MobileDevice/Provisioning Profiles");S.mkdirSync(Zn,{recursive:!0});let sr=Buffer.from(h,"base64"),Qn=E.join(Zn,`${m.nameLower}-temp-${t}.mobileprovision`);S.writeFileSync(Qn,sr);let ei=sr.toString("utf-8"),ar=/<key>get-task-allow<\/key>\s*<true\/>/.test(ei);H={isAppStore:!ei.includes("<key>ProvisionedDevices</key>")&&!ar,isDevelopment:ar};try{let Be=te(`security cms -D -i "${Qn}"`,{encoding:"utf-8"}).match(/<key>UUID<\/key>\s*<string>([^<]+)<\/string>/);X=Be?Be[1]:void 0}catch{let Be=ei.match(/<key>UUID<\/key>\s*<string>([^<]+)<\/string>/);X=Be?Be[1]:void 0}X||(O.warn("Could not extract UUID from provisioning profile. Using fallback."),X=`${m.nameLower}-${t}`);let ti=E.join(Zn,`${X}.mobileprovision`);S.existsSync(ti)&&S.unlinkSync(ti),S.renameSync(Qn,ti);try{let Re=te(`security find-identity -v -p codesigning "${J}"`,{encoding:"utf-8"}),Be=Array.from(Re.matchAll(/"((?:Apple|iPhone) (?:Distribution|Developer|Development)[^"]*)"/g),Bt=>Bt[1]),lr=H.isDevelopment?Be.find(Bt=>/\b(Development|Developer)\b/.test(Bt)):Be.find(Bt=>/\bDistribution\b/.test(Bt)),dr=Be[0];(lr||dr)&&(j=lr||dr,O.info(R.blue(`Identity auto-detected from keychain: "${j}"`)))}catch{}j||(j=H.isDevelopment?"Apple Development":"Apple Distribution",O.info(R.blue(`Identity fallback (profile heuristic): "${j}"`))),O.info(R.dim(`Profile type: ${H.isDevelopment?"Development":H.isAppStore?"App Store":"Ad-Hoc"}`)),O.info(R.dim(`Identity Detection: get-task-allow=${H.isDevelopment}, Selected Identity="${j}"`)),U.push("CODE_SIGN_STYLE=Manual"),U.push(`CODE_SIGN_IDENTITY="${j}"`),U.push(`PROVISIONING_PROFILE_SPECIFIER=${X}`),e.iosTeamId&&U.push(`DEVELOPMENT_TEAM=${e.iosTeamId}`)}catch(z){throw O.error(`Signing setup failed: ${z.message}`),z}}else U.push("-allowProvisioningUpdates"),e.iosTeamId&&U.push(`DEVELOPMENT_TEAM=${e.iosTeamId}`);a&&await a("archive"),O.info(R.blue(`Archive detected Identity: "${j}"`)),O.info(R.blue(`Archive detected UUID: "${X}"`)),await Sn(["archive",d?"-workspace":"-project",d||f,"-scheme",D,"-configuration",b,"-archivePath",T,"-derivedDataPath",A,...y,...U],c,p,o,s);let N=At(E.join(T,"Products","Applications"),[".app"]);for(let z of N){let J=Wr(z);O.info(R.dim(`Validated iOS CFBundleVersion ${J} in ${E.basename(z)}`))}let W;X?(H.isAppStore?W="app-store":H.isDevelopment?W="development":W="ad-hoc",O.info(R.blue(`Export method from profile: "${W}"`))):(W=e.distribution==="store"?"app-store":e.distribution==="internal"?"ad-hoc":"development",O.warn(R.yellow(`No profile UUID detected. Export method from distribution flag: "${W}"`)));let ce=e.iosExportMethod||W,ue=e.iosBundleIdentifier||rt("ios"),V=E.join(c,"ExportOptions.plist"),G=`<?xml version="1.0" encoding="UTF-8"?>
|
|
1217
1314
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
1218
1315
|
<plist version="1.0">
|
|
1219
1316
|
<dict>
|
|
1220
1317
|
<key>method</key>
|
|
1221
|
-
<string>${
|
|
1318
|
+
<string>${ce}</string>
|
|
1222
1319
|
<key>destination</key>
|
|
1223
1320
|
<string>export</string>
|
|
1224
1321
|
<key>signingStyle</key>
|
|
1225
|
-
<string>${
|
|
1322
|
+
<string>${X?"manual":"automatic"}</string>
|
|
1226
1323
|
<key>thinning</key>
|
|
1227
1324
|
<string><none></string>
|
|
1228
1325
|
${e.iosTeamId?`<key>teamID</key><string>${e.iosTeamId}</string>`:""}
|
|
1229
|
-
${
|
|
1326
|
+
${ue&&X?`
|
|
1230
1327
|
<key>provisioningProfiles</key>
|
|
1231
1328
|
<dict>
|
|
1232
|
-
<key>${
|
|
1233
|
-
<string>${
|
|
1329
|
+
<key>${ue}</key>
|
|
1330
|
+
<string>${X}</string>
|
|
1234
1331
|
</dict>`:""}
|
|
1235
1332
|
</dict>
|
|
1236
|
-
</plist>`;if(
|
|
1237
|
-
${
|
|
1333
|
+
</plist>`;if(S.writeFileSync(V,G),process.env[`${m.envPrefix}DEBUG`]&&O.info(R.magenta(`[${m.nameUpper}_DEBUG] ExportOptions.plist:
|
|
1334
|
+
${G}`)),a&&await a("export"),O.info(R.blue(`Exporting with Bundle ID: "${ue}"`)),O.info(R.blue(`Exporting with Method: "${ce}"`)),o){o(R.magenta(`
|
|
1238
1335
|
[DIAGNOSTIC] Checking available signing identities...
|
|
1239
|
-
`));try{let
|
|
1240
|
-
`))}catch(
|
|
1241
|
-
`))}}await
|
|
1242
|
-
`),o&&o(`[IPA VALID] CFBundleVersion ${
|
|
1243
|
-
`)}catch(
|
|
1244
|
-
`),new Error(
|
|
1245
|
-
`).slice(1).map(s=>s.trim()).filter(s=>s.length>0&&!s.startsWith("*")).map(s=>s.split(" ")[0]).length===0){
|
|
1246
|
-
`).filter(a=>a.trim().length>0)}catch{}if(l.length>0){let a=await
|
|
1247
|
-
`).find(a=>a.includes("android.intent.action.MAIN")&&a.includes("android.intent.category.LAUNCHER"))?te(`adb shell monkey -p ${o} -c android.intent.category.LAUNCHER 1`,{stdio:"ignore"}):te(`adb shell monkey -p ${o} -c android.intent.category.LAUNCHER 1`,{stdio:"ignore"})}catch{
|
|
1336
|
+
`));try{let z=te("security find-identity -v -p codesigning",{encoding:"utf-8"});o(R.magenta(`${z}
|
|
1337
|
+
`))}catch(z){o(R.red(`[DIAGNOSTIC] Failed to list identities: ${z.message}
|
|
1338
|
+
`))}}await Sn(["-exportArchive","-archivePath",T,"-exportPath",w,"-exportOptionsPlist",V],c,p,o,s),a&&await a("validate");let Q=At(w,[".ipa"]);for(let z of Q)try{te(`unzip -t "${z}"`,{stdio:"pipe"});let J=Hl(z);o&&o(`[IPA VALID] ${E.basename(z)} \u2014 archive integrity OK
|
|
1339
|
+
`),o&&o(`[IPA VALID] CFBundleVersion ${J}
|
|
1340
|
+
`)}catch(J){let ae=`IPA validation failed for ${E.basename(z)}: ${J.message||"archive may be corrupt"}`;throw o&&o(`[IPA CORRUPT] ${ae}
|
|
1341
|
+
`),new Error(ae)}return Q}},rt=e=>{try{let t=E.join(process.cwd(),m.configFileName);if(S.existsSync(t)){let n=JSON.parse(S.readFileSync(t,"utf-8"));if(e==="android"&&n.android?.package)return n.android.package;if(e==="ios"&&n.ios?.bundleIdentifier)return n.ios.bundleIdentifier}if(e==="android"){let n=["android/app/build.gradle","app/build.gradle","build.gradle"];for(let i of n)if(S.existsSync(i)){let o=S.readFileSync(i,"utf-8").match(/applicationId\s+['"]([^'"]+)['"]/);if(o)return o[1]}}else{let n=E.resolve(process.cwd(),S.existsSync("ios")?"ios":"."),i=At(n,["Info.plist"]).filter(s=>!s.includes("/Pods/")&&!s.includes("/build/")&&!s.includes("/DerivedData/"));i.sort((s,l)=>l.split("/").length-s.split("/").length);for(let s of i){let a=S.readFileSync(s,"utf-8").match(/<key>CFBundleIdentifier<\/key>\s*<string>([^<]+)<\/string>/);if(a&&!a[1].includes("$"))return a[1]}let r=At(n,[".xcodeproj"]);if(r.length>0){let s=E.join(r[0],"project.pbxproj");if(S.existsSync(s)){let a=S.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(S.existsSync(s)){let a=S.readFileSync(s,"utf-8").match(/"bundleIdentifier":\s*"([^"]+)"/);if(a)return a[1]}}}catch{return null}return null},zl=()=>{try{return te("emulator -version",{stdio:"ignore"}),"emulator"}catch{let t=Ae.homedir(),n=[E.join(t,"Library/Android/sdk/emulator/emulator"),E.join(t,"Android/Sdk/emulator/emulator"),"/usr/local/lib/android/sdk/emulator/emulator"];for(let i of n)if(S.existsSync(i))return i}return"emulator"},Wl=async(e,t)=>{let n=yn();try{if(te("adb devices").toString().split(`
|
|
1342
|
+
`).slice(1).map(s=>s.trim()).filter(s=>s.length>0&&!s.startsWith("*")).map(s=>s.split(" ")[0]).length===0){O.warn(R.yellow("No Android devices or emulators found."));let s=zl(),l=[];try{l=te(`${s} -list-avds`).toString().split(`
|
|
1343
|
+
`).filter(a=>a.trim().length>0)}catch{}if(l.length>0){let a=await ui({message:"Select an emulator to launch:",options:l.map(d=>({value:d,label:d}))});if(bn(a))return;n.start(`Launching emulator ${a}...`),Yr(s,["-avd",a],{detached:!0,stdio:"ignore"}).unref();let c=0,u=!1;for(;c<60;){try{if(te("adb shell getprop sys.boot_completed",{stdio:"pipe"}).toString().trim()==="1"){u=!0;break}}catch{}await new Promise(d=>setTimeout(d,2e3)),c++}if(!u)throw n.stop("Emulator launch timed out."),new Error("Emulator launch timed out. Please try launching it manually.");n.stop("Emulator launched.")}else throw new Error("No devices found and no emulators available to launch. (Make sure Android SDK is installed)")}n.start("Installing APK on device..."),await it("adb",["install","-r",e],process.cwd(),{},t),n.stop("Installation complete.");let o=rt("android");if(o){O.info(R.blue(`\u{1F680} Launching ${o}...`));try{te(`adb shell dumpsys package ${o}`).toString().split(`
|
|
1344
|
+
`).find(a=>a.includes("android.intent.action.MAIN")&&a.includes("android.intent.category.LAUNCHER"))?te(`adb shell monkey -p ${o} -c android.intent.category.LAUNCHER 1`,{stdio:"ignore"}):te(`adb shell monkey -p ${o} -c android.intent.category.LAUNCHER 1`,{stdio:"ignore"})}catch{O.warn("Could not auto-launch app. You may need to open it manually.")}}}catch(i){n.stop("Installation failed."),O.error(R.red(`Failed to install APK: ${i.message}`))}},Yl=async(e,t,n)=>{let i=yn();try{if(!te("xcrun simctl list devices booted").toString().includes("(Booted)")){O.warn(R.yellow("No iOS Simulator is currently booted."));let o=te("xcrun simctl list devices --json").toString(),s=JSON.parse(o).devices,l=[];Object.keys(s).forEach(d=>{s[d].forEach(f=>{f.isAvailable&&l.push({...f,runtime:d})})});let a=await ui({message:"Select a simulator to launch:",options:l.map(d=>({value:d.udid,label:`${d.name} (${d.runtime.split(".").pop()})`}))});if(bn(a))return;i.start(`Booting ${a}...`),te(`xcrun simctl boot ${a}`),te(`open -a Simulator --args -CurrentDeviceUDID ${a}`);let c=0,u=!1;for(;c<30;){try{if(te("xcrun simctl list devices booted").toString().includes(a)){u=!0;break}}catch{}await new Promise(d=>setTimeout(d,2e3)),c++}if(!u)throw i.stop("Simulator boot timed out."),new Error("Simulator boot timed out.");i.stop("Simulator booted.")}i.start("Installing on iOS Simulator..."),to(e),no(e),await it("xcrun",["simctl","install","booted",e],process.cwd(),{},n),i.stop("Installation complete."),O.info(R.blue(`\u{1F680} Launching ${t}...`)),await it("xcrun",["simctl","launch","booted",t],process.cwd(),{},n)}catch(r){i.stop("Installation failed."),O.error(R.red(`Failed to install on Simulator: ${r.message}`))}},Jl=async(e,t,n)=>{let i=yn();i.start("Scanning for connected iOS devices...");try{let r=te("xcrun devicectl list devices --json-output -").toString(),s=(JSON.parse(r).result?.devices||[]).filter(a=>a.connectionProperties?.transportType==="wired"||a.connectionProperties?.transportType==="localNetwork");if(s.length===0)throw i.stop("No connected iOS devices found."),new Error("Please connect your iPhone via USB or ensure it is on the same Wi-Fi for wireless debugging.");let l=s[0].identifier;if(s.length>1){i.stop();let a=await ui({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(bn(a))return;l=a,i.start(`Installing on ${l}...`)}else i.message(`Installing on ${s[0].model.name}...`);await it("xcrun",["devicectl","device","install","app","--device",l,e],process.cwd(),{},n),i.stop("Installation complete."),O.info(R.blue(`\u{1F680} Launching ${t}...`)),await it("xcrun",["devicectl","device","launch","app","--device",l,t],process.cwd(),{},n)}catch(r){i.stop("Installation failed."),O.error(R.red(`Failed to install on device: ${r.message}`)),O.info(R.dim('Make sure your device is unlocked and "Developer Mode" is enabled in Settings -> Privacy & Security.'))}};import L from"fs";import Tt from"os";import Y from"path";import{spawn as po,spawnSync as Ge}from"child_process";import{randomUUID as Xl}from"crypto";import{pipeline as ql}from"stream/promises";import{isCancel as yi,log as F,select as fo,spinner as Wt,text as Zl}from"@clack/prompts";import zt from"axios";import K from"chalk";import En from"adm-zip";async function mo(e){if(e.localRunner){let n=await id(e);process.exitCode=n?n.exitCode:1;return}if(e.local){let n=await rd(e);n&&(process.exitCode=n.exitCode);return}let t=await Ii(e);if(t&&(F.success(K.green(`Maestro run ${t.status||"queued"}: ${t.testRunId}`)),t.launchDeferredReason&&F.warn(K.yellow(t.launchDeferredReason)),t.dashboardUrl&&F.info(K.dim("View test run: ")+K.white.underline(t.dashboardUrl)),e.wait)){let n=await od(e,t);n&&(process.exitCode=n.status==="passed"?0:1)}}var Ql=new Set(["passed","failed","cancelled","interrupted"]),ro=Number(process.env.MACH_FLOW_UPLOAD_MAX_ATTEMPTS||4),ed=Number(process.env.MACH_FLOW_UPLOAD_TIMEOUT_MS||12e4),go=process.env.MACH_MAESTRO_FAST_FAIL_RETRY==="1";function Ai(e){let t=Array.isArray(e)?e:e?[e]:[];return[...new Set(t.flatMap(n=>String(n||"").split(",")).map(n=>n.trim()).filter(Boolean))]}function td(e){let t=Ai(e);if(t.length===0)return;let n={};for(let i of t){let r=process.env[i];r!==void 0&&(n[i]=r)}return Object.keys(n).length>0?n:void 0}function nd(e){let t={};for(let[i,r]of Object.entries(process.env))i.startsWith("MAESTRO_TEST_")&&r!==void 0&&(t[i]=r);let n=Ai(e);for(let i of n){let r=process.env[i];r!==void 0&&(t[i]=r)}return t}async function id(e){let t=e.projectId,n=e.testRunId,i=e.runnerToken||process.env.MACH_RUNNER_TOKEN||process.env.MACH_TOKEN,r=(process.env.MACH_API_URL||vt).replace(/\/$/,""),o=L.mkdtempSync(Y.join(Tt.tmpdir(),"mach-maestro-runner-")),s=Y.join(o,"mach-maestro-output"),l=Y.join(o,"runner.log");if(L.mkdirSync(s,{recursive:!0}),!t||!n||!i)return F.error(K.red("--local-runner requires --project-id, --test-run-id, and a runner token.")),{status:"failed",exitCode:1,attempts:0,flows:".maestro",platform:e.platform};let a=null,c=null,u=null,d=p=>{L.appendFileSync(l,`${p}${p.endsWith(`
|
|
1248
1345
|
`)?"":`
|
|
1249
|
-
`}`)},p=async(f,h)=>{try{await Ut.post(`${r}/internal/tests/${encodeURIComponent(n)}/runner`,{projectId:t,runnerToken:i,status:f,error:h,logPreview:Tl(l),junitUrl:a?.urls?.junitDownloadUrl,logsUrl:a?.urls?.logsDownloadUrl,artifactsUrl:a?.urls?.artifactsDownloadUrl})}catch(S){d(`[WARN] Could not post runner update: ${S.message||S}`)}};try{d(`Mach Maestro local runner starting for ${n}`);let f=await Ut.post(`${r}/internal/tests/${encodeURIComponent(n)}/runner-payload`,{projectId:t,runnerToken:i});if(f.data?.status!=="success"||!f.data?.payload)throw new Error(f.data?.message||"Runner payload was not returned.");a=f.data.payload;let h=Object.keys(a.env||{});d(`Using Maestro env vars: ${h.length>0?h.join(", "):"none"}`);let S={...process.env,...a.env||{}},L=kl(a.env);L.length>0&&d(`Passing Maestro env vars to test command: ${h.sort().join(", ")}`),await p("running");let x=a.platform==="android"?"app.apk":"app.zip",b=Y.join(o,x),U=Y.join(o,"source.zip"),w=Y.join(o,"source");M.mkdirSync(w,{recursive:!0}),d("Downloading app artifact..."),await ui(a.artifactUrl,b),d(`Downloaded app artifact: ${x} (${jr(M.statSync(b).size)})`),d("Downloading Maestro source..."),await ui(a.urls.sourceUrl,U),d(`Downloaded Maestro source: source.zip (${jr(M.statSync(U).size)})`),new gn(U).extractAllTo(w,!0);let z=xl(w,a.flowPath||".maestro");if(!M.existsSync(z))throw new Error(`Maestro flow path not found: ${a.flowPath||".maestro"}`);if(d(`Resolved Maestro flow path: ${Y.relative(w,z)||"."}`),a.platform==="ios"){await Hl(a.device||"iphone_15",l);let C=jl(b,o),g=no(C,l);d(`Resolved iOS app bundle: ${C}`),d(`Resolved iOS bundle id: ${g||"unknown"}`),Kl(C,l),fi("xcrun",["simctl","install","booted",C],l),g&&(u={platform:a.platform,appId:g}),g&&Qe("xcrun",["simctl","get_app_container","booted",g,"app"],l),ai(s,l,"ios-before-maestro.png"),a.record&&(c=Gl(s,l))}else{let C=Wl(b,l),g=zl(a.device,l),k=g?["-s",g]:[];d(`Resolved Android application id: ${C||"unknown"}`),fi("adb",[...k,"install","-r",b],l),C&&(u={platform:a.platform,appId:C,deviceId:g||void 0})}let O=Math.max(0,Math.min(10,Number(a.retries??1)))+1,E=Y.join(s,"report.xml"),D=Fl(l);if(!D)throw new Error("Maestro CLI not found on this runner. Install Maestro or set MAESTRO_BIN to the full maestro path.");let $=1;for(let C=1;C<=O;C+=1){d(`Running Maestro attempt ${C}/${O}...`);let g=["test","--platform",a.platform,...L,z,"--format","junit","--output",E,"--test-output-dir",s];if(qr&&C<O?$=(await to(D,g,{logPath:l,env:S,fastFailOnFlowFailure:!0})).exitCode:$=Qe(D,g,l,void 0,S),$===0)break}return a.platform==="ios"&&ai(s,l,"ios-after-maestro.png"),await Gr(c,l),c=null,await zr(a.urls,o,s,l),$===0?(await p("passed"),B.success(W.green(`Managed Maestro run passed: ${n}`)),{status:"passed",exitCode:0,attempts:O,flows:a.flowPath,platform:a.platform}):(await p("failed",`Maestro exited with code ${$}`),B.error(W.red(`Managed Maestro run failed with exit code ${$}`)),{status:"failed",exitCode:$,attempts:O,flows:a.flowPath,platform:a.platform})}catch(f){let h=f.message||String(f);return d(`MACH_MAESTRO_RUN_FAILED: ${h}`),a?.platform==="ios"&&ai(s,l,"ios-after-failure.png"),await Gr(c,l),a?.urls&&await zr(a.urls,o,s,l),await p("failed",h),B.error(W.red(`Managed Maestro runner failed: ${h}`)),{status:"failed",exitCode:1,attempts:0,flows:a?.flowPath||".maestro",platform:a?.platform||e.platform}}finally{Vl(u,l)}}async function _l(e){let t=e.maestroFlows||".maestro",n=Zr(e.maestroRetries);if(n===null)return null;let i=Y.resolve(t);if(!M.existsSync(i))return B.error(W.red(`Maestro flows not found: ${t}`)),{status:"failed",exitCode:1,attempts:0,flows:t,platform:e.platform};let r=await Dl(e);if(r?.url){if(!await Nl(r))return{status:"failed",exitCode:1,attempts:0,flows:t,platform:r.platform||e.platform}}else if(e.buildId||e.buildUrl||e.artifactUrl||e.latest)return{status:"failed",exitCode:1,attempts:0,flows:t,platform:e.platform};e.maestroRecord&&B.warn(W.yellow("--maestro-record is managed-runner only and is ignored in --local mode."));let o=r?.platform||e.platform,s=["test"];o&&s.push("--platform",o),e.maestroDevice&&s.push("--device",String(e.maestroDevice));let l=Il(e.maestroEnv),a=Object.keys(l);if(a.length>0){B.info(W.dim(`Passing Maestro env vars to local run: ${a.join(", ")}`));for(let[f,h]of Object.entries(l))s.push("-e",`${f}=${h}`)}s.push(t);let c=n+1,u=1;for(let f=1;f<=c;f+=1){if(B.info(W.dim(`Running local Maestro attempt ${f}/${c}...`)),qr&&f<c){let h=await to("maestro",s,{cwd:process.cwd(),env:process.env,echoOutput:!0,fastFailOnFlowFailure:!0});if(h.error){let S=h.error.message||"Failed to run Maestro";B.error(W.red(`Local Maestro failed to start: ${S}`)),B.info(W.dim("Install Maestro locally, then retry: https://maestro.mobile.dev/getting-started/installing-maestro")),u=1;break}u=h.exitCode}else{let h=He("maestro",s,{cwd:process.cwd(),stdio:"inherit",env:process.env});if(h.error){let S=h.error.message||"Failed to run Maestro";B.error(W.red(`Local Maestro failed to start: ${S}`)),B.info(W.dim("Install Maestro locally, then retry: https://maestro.mobile.dev/getting-started/installing-maestro")),u=1;break}u=typeof h.status=="number"?h.status:1}if(u===0)break}let d=u===0?"passed":"failed",p={status:d,exitCode:u,attempts:c,flows:t,platform:o};return ed(e,p),d==="passed"?B.success(W.green("Local Maestro run passed")):B.error(W.red(`Local Maestro run failed with exit code ${u}`)),p}async function mi(e){let t=$e(`./${m.configFileName}`),n=e.projectId||t?.projectId,i=String(e.profile||e.buildProfile||"production").toLowerCase();if(!n)return B.error(`No projectId found. Run \`${m.nameLower} link\` first or pass an internal project id.`),null;let r=e.platform;if(!r&&e.latest){let d=await Yr({message:"Select platform for the latest build:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"}]});if(ci(d))return null;r=d}let o=await Ol(e);if(!o)return null;if(o.kind==="latest"&&!r)return B.error("Pass --platform when using --latest."),null;if(o.kind==="artifact-url"&&!r)return B.error("Pass --platform when using --artifact-url."),null;let s=Zr(e.maestroRetries);if(s===null)return null;let l=pi(e.maestroEnv),a=El(e.maestroEnv);!e.quiet&&l.length>0&&B.info(W.dim(`Forwarding Maestro env vars by name: ${l.join(", ")}`));let c=await vl(e,n);if(c===null)return null;let u=Ft();e.quiet||u.start("Queuing Maestro run...");try{let d=await N.post("/tests/maestro",{projectId:n,platform:r,profile:i,latest:o.kind==="latest",buildId:o.kind==="build-id"?o.value:e.buildId,buildUrl:o.kind==="build-url"?o.value:e.buildUrl,artifactUrl:o.kind==="artifact-url"?o.value:e.artifactUrl,flowSourceKey:c,flows:e.maestroFlows||".maestro",device:e.maestroDevice||(r==="ios"?"iphone_15":"pixel_6"),retries:s,record:!!e.maestroRecord,...l.length>0?{envNames:l}:{},...a?{env:a}:{}});if(d.data.status!=="success")throw new Error(d.data.message||"Failed to queue Maestro run");let p=d.data.testRun,f={testRunId:p.testRunId,status:p.status,projectId:n,buildId:p.buildId,platform:p.platform,dashboardUrl:p.dashboardUrl||`${We}/tests/${p.testRunId}`,launchDeferredReason:p.launchDeferredReason};return ro(e,f),e.quiet||u.stop("Maestro run queued"),f}catch(d){e.quiet||u.stop("Could not queue Maestro run");let p=d.response?.data?.message||d.message||"Unknown error";return B.error(W.red(`Maestro queue failed: ${p}`)),null}}async function $l(e,t){let n=Hr(e.waitTimeout,60,"--wait-timeout"),i=Hr(e.waitInterval,15,"--wait-interval");if(n===null||i===null)return null;let r=n*60*1e3,o=Math.max(5,i)*1e3,s=Date.now(),l=t.status||"queued";for(B.info(W.dim(`Waiting for Maestro run ${t.testRunId} to finish...`));Date.now()-s<=r;){let a=await Pl(t.projectId,t.testRunId);if(!a)return null;if(a.status&&a.status!==l&&(l=a.status,B.info(W.dim(`Maestro status: ${l}`))),bl.has(String(a.status)))return ro(e,a),a.status==="passed"?B.success(W.green(`Maestro run passed: ${a.testRunId}`)):(B.error(W.red(`Maestro run ${a.status}: ${a.testRunId}`)),a.error&&B.error(W.red(String(a.error)))),a;await gi(o)}return B.error(W.red(`Timed out waiting for Maestro run ${t.testRunId} after ${n} minute(s).`)),{...t,status:"timeout"}}async function vl(e,t){if(e.maestroUseBuildSource)return;let n=e.maestroFlows||".maestro",i=Y.resolve(n);if(!M.existsSync(i))return e.maestroFlows?(B.error(W.red(`Maestro flows not found: ${n}`)),null):void 0;let r=Y.relative(process.cwd(),i);if(!r||r.startsWith("..")||Y.isAbsolute(r))return B.error(W.red("Managed Maestro flow uploads must be inside the current project directory.")),null;let o=Ft();e.quiet||o.start(`Uploading Maestro flows from ${r}...`);try{let s=await N.post("/tests/maestro/source-upload-url",{projectId:t,uploadId:hl()});if(s.data.status!=="success"||!s.data.uploadUrl||!s.data.key)throw new Error(s.data.message||"Failed to get Maestro flow upload URL");let l=new gn;if(M.statSync(i).isDirectory())l.addLocalFolder(i,r);else{let u=Y.dirname(r);l.addLocalFile(i,u==="."?void 0:u,Y.basename(r))}let c=l.toBuffer();return await Rl(s.data.uploadUrl,c,"application/zip","Maestro flow upload",u=>{e.quiet||o.message(u)}),e.quiet||o.stop("Maestro flows uploaded"),s.data.key}catch(s){e.quiet||o.stop("Could not upload Maestro flows");let l=s.response?.data?.message||s.message||"Unknown error";return B.error(W.red(`Maestro flow upload failed: ${l}`)),null}}function Xr(e){let t=e.response?.status,n=e.code||"",i=e.message||"";return t&&![408,409,425,429].includes(t)&&t<500?!1:/ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|ECONNABORTED|socket hang up|network|timeout/i.test(`${n} ${i}`)||!t}async function Rl(e,t,n,i,r){let o;for(let s=1;s<=Br;s+=1)try{await Ut.put(e,t,{headers:{"Content-Type":n},maxBodyLength:1/0,maxContentLength:1/0,timeout:Al});return}catch(l){if(o=l,!Xr(l)||s>=Br)break;let a=Math.min(2e4,2e3*s),c=l.code||l.response?.status||l.message||"network error";r?.(`${i} attempt ${s} failed (${c}), retrying...`),await gi(a)}throw o}async function Pl(e,t){try{let n=await N.get(`/tests/${encodeURIComponent(t)}`,{params:{projectId:e}});if(n.data.status!=="success")throw new Error(n.data.message||"Failed to fetch Maestro run");let i=n.data.testRun;return{testRunId:i.testRunId,status:i.status,projectId:e,buildId:i.buildId,platform:i.platform,dashboardUrl:i.dashboardUrl||`${We}/tests/${i.testRunId}`,launchDeferredReason:i.launchDeferredReason,...i.error?{error:i.error}:{}}}catch(n){let i=n.response?.data?.message||n.message||"Unknown error";return B.error(W.red(`Could not fetch Maestro run status: ${i}`)),null}}async function Ol(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 Yr({message:"Select app artifact source for Maestro:",options:[{value:"latest",label:"Latest successful build"},{value:"build-id",label:"Build ID"},{value:"build-url",label:`${m.name} build URL`},{value:"artifact-url",label:"Direct artifact URL"}]});if(ci(t))return null;if(t==="latest")return{kind:"latest"};let n=await Sl({message:t==="build-id"?"Enter build ID:":t==="build-url"?`Enter ${m.name} build URL:`:"Enter artifact URL:",validate:i=>{let r=String(i||"").trim();if(!r)return"Value is required";if((t==="build-url"||t==="artifact-url")&&!r.startsWith("http"))return"Must be a URL"}});return ci(n)?null:{kind:t,value:String(n).trim()}}function Hr(e,t,n){if(e==null||e==="")return t;let i=Number(e);return!Number.isFinite(i)||i<=0?(B.error(`${n} must be a positive number.`),null):i}function gi(e){return new Promise(t=>setTimeout(t,e))}function Zr(e){if(e==null||e==="")return 1;let t=Number(e);return!Number.isInteger(t)||t<0||t>10?(B.error("--maestro-retries must be an integer between 0 and 10."),null):t}async function Dl(e){if(e.artifactUrl)return{url:e.artifactUrl,platform:e.platform||yi(e.artifactUrl),name:io(e.artifactUrl)};let t=e.buildId||Ql(e.buildUrl);return t?Qr(t,e.platform):e.latest?Cl(e):null}async function Qr(e,t){let n=Ft();n.start(`Resolving build ${e}...`);try{let i=await N.get(`/public/builds/${encodeURIComponent(e)}`);if(i.data.status!=="success")throw new Error(i.data.message||"Build lookup failed");let r=t||i.data.build?.platform,o=Zl(i.data.artifacts||[],r);if(!o?.downloadUrl)throw new Error("No installable APK or simulator app artifact found for this build.");return n.stop("Build artifact resolved"),{url:o.downloadUrl,platform:r||yi(o.name||o.downloadUrl),name:o.name}}catch(i){n.stop("Could not resolve build artifact");let r=i.response?.data?.message||i.message||"Unknown error";return B.error(W.red(`Local Maestro artifact lookup failed: ${r}`)),null}}async function Cl(e){let t=$e(`./${m.configFileName}`),n=e.projectId||t?.projectId,i=String(e.profile||e.buildProfile||"production").toLowerCase();if(!n)return B.error(`No projectId found. Run \`${m.nameLower} link\` first or pass --build-id/--artifact-url.`),null;if(!e.platform)return B.error("Pass --platform when using --latest with --local."),null;let r=Ft();r.start("Resolving latest build...");try{let o=await N.get(`/builds/${n}`,{params:{limit:100}}),l=(Array.isArray(o.data.builds)?o.data.builds:[]).find(a=>a.status==="success"&&a.platform===e.platform&&String(a.buildProfile||a.buildType||"production").toLowerCase()===i);if(!l?.buildId)throw new Error(`No successful ${e.platform} build found for profile ${i}.`);return r.stop(`Latest build resolved: ${l.buildId}`),Qr(l.buildId,e.platform)}catch(o){r.stop("Could not resolve latest build");let s=o.response?.data?.message||o.message||"Unknown error";return B.error(W.red(`Latest build lookup failed: ${s}`)),null}}async function Nl(e){let t=e.platform||yi(e.url);if(!t)return B.error(W.red("Could not infer platform for local install. Pass --platform android or --platform ios.")),!1;let n=M.mkdtempSync(Y.join(_t.tmpdir(),"mach-maestro-")),i=e.name||io(e.url)||(t==="android"?"app.apk":"app.zip"),r=Y.join(n,i),o=Ft();o.start(`Downloading ${i}...`);try{await ui(e.url,r),o.stop("Artifact downloaded")}catch(s){return o.stop("Artifact download failed"),B.error(W.red(s.message||"Failed to download artifact")),!1}return t==="android"?ql(r):Xl(r,n)}async function ui(e,t){let n=await Ut.get(e,{responseType:"stream"});await yl(n.data,M.createWriteStream(t))}function Tl(e,t=12e3){try{return M.readFileSync(e,"utf-8").slice(-t)}catch{return""}}function jr(e){if(!Number.isFinite(e)||e<0)return"unknown size";if(e<1024)return`${e} B`;let t=["KB","MB","GB"],n=e/1024,i=t[0];for(let r=1;n>=1024&&r<t.length;r+=1)n/=1024,i=t[r];return`${n.toFixed(n>=10?1:2)} ${i}`}function kl(e){return Object.entries(e||{}).filter(([t,n])=>!!t&&n!==void 0).sort(([t],[n])=>t.localeCompare(n)).flatMap(([t,n])=>["-e",`${t}=${n}`])}function xl(e,t){let n=Y.resolve(e,t||".maestro"),i=Y.relative(e,n);if(i.startsWith("..")||Y.isAbsolute(i))throw new Error("Maestro flow path must stay inside the build source.");return n}function eo(e,t){let n=[e];for(let i=0;i<t.length;i+=1){let r=t[i],o=t[i-1];(o==="-e"||o==="--env")&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(r)?n.push(`${r.slice(0,r.indexOf("="))}=<redacted>`):n.push(r)}return n.join(" ")}function Ml(e){return/\[Failed\]\s+/.test(e)}function Ll(e){if(!e.killed){try{e.kill("SIGTERM")}catch{}setTimeout(()=>{try{e.kill("SIGKILL")}catch{}},5e3).unref()}}function to(e,t,n={}){let{cwd:i,env:r=process.env,logPath:o,echoOutput:s=!1,fastFailOnFlowFailure:l=!1}=n;return o&&M.appendFileSync(o,`
|
|
1250
|
-
$ ${
|
|
1251
|
-
`),new Promise(a=>{let c=!1,u=!1,d="",
|
|
1346
|
+
`}`)},f=async(p,g)=>{try{await zt.post(`${r}/internal/tests/${encodeURIComponent(n)}/runner`,{projectId:t,runnerToken:i,status:p,error:g,logPreview:fd(l),junitUrl:a?.urls?.junitDownloadUrl,logsUrl:a?.urls?.logsDownloadUrl,artifactsUrl:a?.urls?.artifactsDownloadUrl})}catch(y){d(`[WARN] Could not post runner update: ${y.message||y}`)}};try{d(`Mach Maestro local runner starting for ${n}`);let p=await zt.post(`${r}/internal/tests/${encodeURIComponent(n)}/runner-payload`,{projectId:t,runnerToken:i});if(p.data?.status!=="success"||!p.data?.payload)throw new Error(p.data?.message||"Runner payload was not returned.");a=p.data.payload;let g=Object.keys(a.env||{});d(`Using Maestro env vars: ${g.length>0?g.join(", "):"none"}`);let y={...process.env,...a.env||{}},_=md(a.env);_.length>0&&d(`Passing Maestro env vars to test command: ${g.sort().join(", ")}`),await f("running");let D=a.platform==="android"?"app.apk":"app.zip",b=Y.join(o,D),x=Y.join(o,"source.zip"),A=Y.join(o,"source");L.mkdirSync(A,{recursive:!0}),d("Downloading app artifact..."),await bi(a.artifactUrl,b),d(`Downloaded app artifact: ${D} (${so(L.statSync(b).size)})`),d("Downloading Maestro source..."),await bi(a.urls.sourceUrl,x),d(`Downloaded Maestro source: source.zip (${so(L.statSync(x).size)})`),new En(x).extractAllTo(A,!0);let B=gd(A,a.flowPath||".maestro");if(!L.existsSync(B))throw new Error(`Maestro flow path not found: ${a.flowPath||".maestro"}`);if(d(`Resolved Maestro flow path: ${Y.relative(A,B)||"."}`),a.platform==="ios"){await Ad(a.device||"iphone_15",l);let C=Id(b,o),h=Ao(C,l);d(`Resolved iOS app bundle: ${C}`),d(`Resolved iOS bundle id: ${h||"unknown"}`),_d(C,l),Ei("xcrun",["simctl","install","booted",C],l),h&&(u={platform:a.platform,appId:h}),h&&ot("xcrun",["simctl","get_app_container","booted",h,"app"],l),gi(s,l,"ios-before-maestro.png"),a.record&&(c=wd(s,l))}else{let C=vd(b,l),h=$d(a.device,l),M=h?["-s",h]:[];d(`Resolved Android application id: ${C||"unknown"}`),Ei("adb",[...M,"install","-r",b],l),C&&(u={platform:a.platform,appId:C,deviceId:h||void 0})}let P=Math.max(0,Math.min(10,Number(a.retries??1)))+1,I=Y.join(s,"report.xml"),T=bd(l);if(!T)throw new Error("Maestro CLI not found on this runner. Install Maestro or set MAESTRO_BIN to the full maestro path.");let w=1;for(let C=1;C<=P;C+=1){d(`Running Maestro attempt ${C}/${P}...`);let h=["test","--platform",a.platform,..._,B,"--format","junit","--output",I,"--test-output-dir",s];if(go&&C<P?w=(await Eo(T,h,{logPath:l,env:y,fastFailOnFlowFailure:!0})).exitCode:w=ot(T,h,l,void 0,y),w===0)break}return a.platform==="ios"&&gi(s,l,"ios-after-maestro.png"),await ao(c,l),c=null,await uo(a.urls,o,s,l),w===0?(await f("passed"),F.success(K.green(`Managed Maestro run passed: ${n}`)),{status:"passed",exitCode:0,attempts:P,flows:a.flowPath,platform:a.platform}):(await f("failed",`Maestro exited with code ${w}`),F.error(K.red(`Managed Maestro run failed with exit code ${w}`)),{status:"failed",exitCode:w,attempts:P,flows:a.flowPath,platform:a.platform})}catch(p){let g=p.message||String(p);return d(`MACH_MAESTRO_RUN_FAILED: ${g}`),a?.platform==="ios"&&gi(s,l,"ios-after-failure.png"),await ao(c,l),a?.urls&&await uo(a.urls,o,s,l),await f("failed",g),F.error(K.red(`Managed Maestro runner failed: ${g}`)),{status:"failed",exitCode:1,attempts:0,flows:a?.flowPath||".maestro",platform:a?.platform||e.platform}}finally{Rd(u,l)}}async function rd(e){let t=e.maestroFlows||".maestro",n=So(e.maestroRetries);if(n===null)return null;let i=Y.resolve(t);if(!L.existsSync(i))return F.error(K.red(`Maestro flows not found: ${t}`)),{status:"failed",exitCode:1,attempts:0,flows:t,platform:e.platform};let r=await cd(e);if(r?.url){if(!await pd(r))return{status:"failed",exitCode:1,attempts:0,flows:t,platform:r.platform||e.platform}}else if(e.buildId||e.buildUrl||e.artifactUrl||e.latest)return{status:"failed",exitCode:1,attempts:0,flows:t,platform:e.platform};e.maestroRecord&&F.warn(K.yellow("--maestro-record is managed-runner only and is ignored in --local mode."));let o=r?.platform||e.platform,s=["test"];o&&s.push("--platform",o),e.maestroDevice&&s.push("--device",String(e.maestroDevice));let l=nd(e.maestroEnv),a=Object.keys(l);if(a.length>0){F.info(K.dim(`Passing Maestro env vars to local run: ${a.join(", ")}`));for(let[p,g]of Object.entries(l))s.push("-e",`${p}=${g}`)}s.push(t);let c=n+1,u=1;for(let p=1;p<=c;p+=1){if(F.info(K.dim(`Running local Maestro attempt ${p}/${c}...`)),go&&p<c){let g=await Eo("maestro",s,{cwd:process.cwd(),env:process.env,echoOutput:!0,fastFailOnFlowFailure:!0});if(g.error){let y=g.error.message||"Failed to run Maestro";F.error(K.red(`Local Maestro failed to start: ${y}`)),F.info(K.dim("Install Maestro locally, then retry: https://maestro.mobile.dev/getting-started/installing-maestro")),u=1;break}u=g.exitCode}else{let g=Ge("maestro",s,{cwd:process.cwd(),stdio:"inherit",env:process.env});if(g.error){let y=g.error.message||"Failed to run Maestro";F.error(K.red(`Local Maestro failed to start: ${y}`)),F.info(K.dim("Install Maestro locally, then retry: https://maestro.mobile.dev/getting-started/installing-maestro")),u=1;break}u=typeof g.status=="number"?g.status:1}if(u===0)break}let d=u===0?"passed":"failed",f={status:d,exitCode:u,attempts:c,flows:t,platform:o};return kd(e,f),d==="passed"?F.success(K.green("Local Maestro run passed")):F.error(K.red(`Local Maestro run failed with exit code ${u}`)),f}async function Ii(e){let t=$e(`./${m.configFileName}`),n=e.projectId||t?.projectId,i=String(e.profile||e.buildProfile||"production").toLowerCase();if(!n)return F.error(`No projectId found. Run \`${m.nameLower} link\` first or pass an internal project id.`),null;let r=e.platform;if(!r&&e.latest){let d=await fo({message:"Select platform for the latest build:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"}]});if(yi(d))return null;r=d}let o=await dd(e);if(!o)return null;if(o.kind==="latest"&&!r)return F.error("Pass --platform when using --latest."),null;if(o.kind==="artifact-url"&&!r)return F.error("Pass --platform when using --artifact-url."),null;let s=So(e.maestroRetries);if(s===null)return null;let l=Ai(e.maestroEnv),a=td(e.maestroEnv);!e.quiet&&l.length>0&&F.info(K.dim(`Forwarding Maestro env vars by name: ${l.join(", ")}`));let c=await sd(e,n);if(c===null)return null;let u=Wt();e.quiet||u.start("Queuing Maestro run...");try{let d=await k.post("/tests/maestro",{projectId:n,platform:r,profile:i,latest:o.kind==="latest",buildId:o.kind==="build-id"?o.value:e.buildId,buildUrl:o.kind==="build-url"?o.value:e.buildUrl,artifactUrl:o.kind==="artifact-url"?o.value:e.artifactUrl,flowSourceKey:c,flows:e.maestroFlows||".maestro",device:e.maestroDevice||(r==="ios"?"iphone_15":"pixel_6"),retries:s,record:!!e.maestroRecord,...l.length>0?{envNames:l}:{},...a?{env:a}:{}});if(d.data.status!=="success")throw new Error(d.data.message||"Failed to queue Maestro run");let f=d.data.testRun,p={testRunId:f.testRunId,status:f.status,projectId:n,buildId:f.buildId,platform:f.platform,dashboardUrl:f.dashboardUrl||`${Je}/tests/${f.testRunId}`,launchDeferredReason:f.launchDeferredReason};return wo(e,p),e.quiet||u.stop("Maestro run queued"),p}catch(d){e.quiet||u.stop("Could not queue Maestro run");let f=d.response?.data?.message||d.message||"Unknown error";return F.error(K.red(`Maestro queue failed: ${f}`)),null}}async function od(e,t){let n=oo(e.waitTimeout,60,"--wait-timeout"),i=oo(e.waitInterval,15,"--wait-interval");if(n===null||i===null)return null;let r=n*60*1e3,o=Math.max(5,i)*1e3,s=Date.now(),l=t.status||"queued";for(F.info(K.dim(`Waiting for Maestro run ${t.testRunId} to finish...`));Date.now()-s<=r;){let a=await ld(t.projectId,t.testRunId);if(!a)return null;if(a.status&&a.status!==l&&(l=a.status,F.info(K.dim(`Maestro status: ${l}`))),Ql.has(String(a.status)))return wo(e,a),a.status==="passed"?F.success(K.green(`Maestro run passed: ${a.testRunId}`)):(F.error(K.red(`Maestro run ${a.status}: ${a.testRunId}`)),a.error&&F.error(K.red(String(a.error)))),a;await wi(o)}return F.error(K.red(`Timed out waiting for Maestro run ${t.testRunId} after ${n} minute(s).`)),{...t,status:"timeout"}}async function sd(e,t){if(e.maestroUseBuildSource)return;let n=e.maestroFlows||".maestro",i=Y.resolve(n);if(!L.existsSync(i))return e.maestroFlows?(F.error(K.red(`Maestro flows not found: ${n}`)),null):void 0;let r=Y.relative(process.cwd(),i);if(!r||r.startsWith("..")||Y.isAbsolute(r))return F.error(K.red("Managed Maestro flow uploads must be inside the current project directory.")),null;let o=Wt();e.quiet||o.start(`Uploading Maestro flows from ${r}...`);try{let s=await k.post("/tests/maestro/source-upload-url",{projectId:t,uploadId:Xl()});if(s.data.status!=="success"||!s.data.uploadUrl||!s.data.key)throw new Error(s.data.message||"Failed to get Maestro flow upload URL");let l=new En;if(L.statSync(i).isDirectory())l.addLocalFolder(i,r);else{let u=Y.dirname(r);l.addLocalFile(i,u==="."?void 0:u,Y.basename(r))}let c=l.toBuffer();return await ad(s.data.uploadUrl,c,"application/zip","Maestro flow upload",u=>{e.quiet||o.message(u)}),e.quiet||o.stop("Maestro flows uploaded"),s.data.key}catch(s){e.quiet||o.stop("Could not upload Maestro flows");let l=s.response?.data?.message||s.message||"Unknown error";return F.error(K.red(`Maestro flow upload failed: ${l}`)),null}}function ho(e){let t=e.response?.status,n=e.code||"",i=e.message||"";return t&&![408,409,425,429].includes(t)&&t<500?!1:/ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|ECONNABORTED|socket hang up|network|timeout/i.test(`${n} ${i}`)||!t}async function ad(e,t,n,i,r){let o;for(let s=1;s<=ro;s+=1)try{await zt.put(e,t,{headers:{"Content-Type":n},maxBodyLength:1/0,maxContentLength:1/0,timeout:ed});return}catch(l){if(o=l,!ho(l)||s>=ro)break;let a=Math.min(2e4,2e3*s),c=l.code||l.response?.status||l.message||"network error";r?.(`${i} attempt ${s} failed (${c}), retrying...`),await wi(a)}throw o}async function ld(e,t){try{let n=await k.get(`/tests/${encodeURIComponent(t)}`,{params:{projectId:e}});if(n.data.status!=="success")throw new Error(n.data.message||"Failed to fetch Maestro run");let i=n.data.testRun;return{testRunId:i.testRunId,status:i.status,projectId:e,buildId:i.buildId,platform:i.platform,dashboardUrl:i.dashboardUrl||`${Je}/tests/${i.testRunId}`,launchDeferredReason:i.launchDeferredReason,...i.error?{error:i.error}:{}}}catch(n){let i=n.response?.data?.message||n.message||"Unknown error";return F.error(K.red(`Could not fetch Maestro run status: ${i}`)),null}}async function dd(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 fo({message:"Select app artifact source for Maestro:",options:[{value:"latest",label:"Latest successful build"},{value:"build-id",label:"Build ID"},{value:"build-url",label:`${m.name} build URL`},{value:"artifact-url",label:"Direct artifact URL"}]});if(yi(t))return null;if(t==="latest")return{kind:"latest"};let n=await Zl({message:t==="build-id"?"Enter build ID:":t==="build-url"?`Enter ${m.name} build URL:`:"Enter artifact URL:",validate:i=>{let r=String(i||"").trim();if(!r)return"Value is required";if((t==="build-url"||t==="artifact-url")&&!r.startsWith("http"))return"Must be a URL"}});return yi(n)?null:{kind:t,value:String(n).trim()}}function oo(e,t,n){if(e==null||e==="")return t;let i=Number(e);return!Number.isFinite(i)||i<=0?(F.error(`${n} must be a positive number.`),null):i}function wi(e){return new Promise(t=>setTimeout(t,e))}function So(e){if(e==null||e==="")return 1;let t=Number(e);return!Number.isInteger(t)||t<0||t>10?(F.error("--maestro-retries must be an integer between 0 and 10."),null):t}async function cd(e){if(e.artifactUrl)return{url:e.artifactUrl,platform:e.platform||Ri(e.artifactUrl),name:Io(e.artifactUrl)};let t=e.buildId||Td(e.buildUrl);return t?yo(t,e.platform):e.latest?ud(e):null}async function yo(e,t){let n=Wt();n.start(`Resolving build ${e}...`);try{let i=await k.get(`/public/builds/${encodeURIComponent(e)}`);if(i.data.status!=="success")throw new Error(i.data.message||"Build lookup failed");let r=t||i.data.build?.platform,o=Nd(i.data.artifacts||[],r);if(!o?.downloadUrl)throw new Error("No installable APK or simulator app artifact found for this build.");return n.stop("Build artifact resolved"),{url:o.downloadUrl,platform:r||Ri(o.name||o.downloadUrl),name:o.name}}catch(i){n.stop("Could not resolve build artifact");let r=i.response?.data?.message||i.message||"Unknown error";return F.error(K.red(`Local Maestro artifact lookup failed: ${r}`)),null}}async function ud(e){let t=$e(`./${m.configFileName}`),n=e.projectId||t?.projectId,i=String(e.profile||e.buildProfile||"production").toLowerCase();if(!n)return F.error(`No projectId found. Run \`${m.nameLower} link\` first or pass --build-id/--artifact-url.`),null;if(!e.platform)return F.error("Pass --platform when using --latest with --local."),null;let r=Wt();r.start("Resolving latest build...");try{let o=await k.get(`/builds/${n}`,{params:{limit:100}}),l=(Array.isArray(o.data.builds)?o.data.builds:[]).find(a=>a.status==="success"&&a.platform===e.platform&&String(a.buildProfile||a.buildType||"production").toLowerCase()===i);if(!l?.buildId)throw new Error(`No successful ${e.platform} build found for profile ${i}.`);return r.stop(`Latest build resolved: ${l.buildId}`),yo(l.buildId,e.platform)}catch(o){r.stop("Could not resolve latest build");let s=o.response?.data?.message||o.message||"Unknown error";return F.error(K.red(`Latest build lookup failed: ${s}`)),null}}async function pd(e){let t=e.platform||Ri(e.url);if(!t)return F.error(K.red("Could not infer platform for local install. Pass --platform android or --platform ios.")),!1;let n=L.mkdtempSync(Y.join(Tt.tmpdir(),"mach-maestro-")),i=e.name||Io(e.url)||(t==="android"?"app.apk":"app.zip"),r=Y.join(n,i),o=Wt();o.start(`Downloading ${i}...`);try{await bi(e.url,r),o.stop("Artifact downloaded")}catch(s){return o.stop("Artifact download failed"),F.error(K.red(s.message||"Failed to download artifact")),!1}return t==="android"?Dd(r):Cd(r,n)}async function bi(e,t){let n=await zt.get(e,{responseType:"stream"});await ql(n.data,L.createWriteStream(t))}function fd(e,t=12e3){try{return L.readFileSync(e,"utf-8").slice(-t)}catch{return""}}function so(e){if(!Number.isFinite(e)||e<0)return"unknown size";if(e<1024)return`${e} B`;let t=["KB","MB","GB"],n=e/1024,i=t[0];for(let r=1;n>=1024&&r<t.length;r+=1)n/=1024,i=t[r];return`${n.toFixed(n>=10?1:2)} ${i}`}function md(e){return Object.entries(e||{}).filter(([t,n])=>!!t&&n!==void 0).sort(([t],[n])=>t.localeCompare(n)).flatMap(([t,n])=>["-e",`${t}=${n}`])}function gd(e,t){let n=Y.resolve(e,t||".maestro"),i=Y.relative(e,n);if(i.startsWith("..")||Y.isAbsolute(i))throw new Error("Maestro flow path must stay inside the build source.");return n}function bo(e,t){let n=[e];for(let i=0;i<t.length;i+=1){let r=t[i],o=t[i-1];(o==="-e"||o==="--env")&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(r)?n.push(`${r.slice(0,r.indexOf("="))}=<redacted>`):n.push(r)}return n.join(" ")}function hd(e){return/\[Failed\]\s+/.test(e)}function Sd(e){if(!e.killed){try{e.kill("SIGTERM")}catch{}setTimeout(()=>{try{e.kill("SIGKILL")}catch{}},5e3).unref()}}function Eo(e,t,n={}){let{cwd:i,env:r=process.env,logPath:o,echoOutput:s=!1,fastFailOnFlowFailure:l=!1}=n;return o&&L.appendFileSync(o,`
|
|
1347
|
+
$ ${bo(e,t)}
|
|
1348
|
+
`),new Promise(a=>{let c=!1,u=!1,d="",f=y=>{u||(u=!0,a(y))},p=po(e,t,{cwd:i,env:r,stdio:["ignore","pipe","pipe"]}),g=y=>{d+=y;let _=d.split(/\r?\n/);d=_.pop()||"";for(let D of _)if(l&&hd(D)&&!c){c=!0;let b="Mach fast-fail: detected failed Maestro flow; stopping this attempt early to retry...";o&&L.appendFileSync(o,`
|
|
1252
1349
|
${b}
|
|
1253
1350
|
`),s&&process.stderr.write(`${b}
|
|
1254
|
-
`),
|
|
1255
|
-
`),
|
|
1256
|
-
`),
|
|
1257
|
-
$ ${
|
|
1258
|
-
`);let o=
|
|
1259
|
-
`),1):typeof o.status=="number"?o.status:1}function
|
|
1260
|
-
`)[0]?.trim():"";i&&t.unshift(i);for(let r of t)if(r&&
|
|
1261
|
-
`),r;return e&&
|
|
1262
|
-
`),null}function
|
|
1263
|
-
`);return}let i=
|
|
1264
|
-
`),
|
|
1265
|
-
`),
|
|
1266
|
-
`),null;let i=
|
|
1267
|
-
`),null):r}function
|
|
1268
|
-
`)}function
|
|
1269
|
-
`);let i=
|
|
1270
|
-
`)}),i}async function
|
|
1271
|
-
`),e.kill("SIGINT")),setTimeout(()=>{!i&&!e.killed&&(
|
|
1272
|
-
`),e.kill("SIGKILL")),r()},5e3).unref?.()})}function
|
|
1273
|
-
`),
|
|
1274
|
-
`)}function
|
|
1275
|
-
`),e.platform==="ios"){let r=
|
|
1276
|
-
`):
|
|
1277
|
-
`);return}let n=e.deviceId?["-s",e.deviceId]:[],i=
|
|
1278
|
-
`):
|
|
1279
|
-
`)}function
|
|
1351
|
+
`),Sd(p)}};p.stdout?.on("data",y=>{let _=y.toString();o&&L.appendFileSync(o,_),s&&process.stdout.write(_),g(_)}),p.stderr?.on("data",y=>{let _=y.toString();o&&L.appendFileSync(o,_),s&&process.stderr.write(_),g(_)}),p.on("error",y=>{o&&L.appendFileSync(o,`${y.message}
|
|
1352
|
+
`),f({exitCode:1,fastFailed:c,error:y})}),p.on("close",(y,_)=>{c&&o&&L.appendFileSync(o,`Maestro attempt stopped after first failed flow${_?` (${_})`:""}.
|
|
1353
|
+
`),f({exitCode:typeof y=="number"?y:1,fastFailed:c})})})}function ot(e,t,n,i,r=process.env){L.appendFileSync(n,`
|
|
1354
|
+
$ ${bo(e,t)}
|
|
1355
|
+
`);let o=Ge(e,t,{cwd:i,encoding:"utf-8",env:r});return o.stdout&&L.appendFileSync(n,o.stdout),o.stderr&&L.appendFileSync(n,o.stderr),o.error?(L.appendFileSync(n,`${o.error.message}
|
|
1356
|
+
`),1):typeof o.status=="number"?o.status:1}function Ei(e,t,n,i){let r=ot(e,t,n,i);if(r!==0)throw new Error(`${e} ${t.join(" ")} failed with exit code ${r}`)}function yd(e){try{return L.accessSync(e,L.constants.X_OK),!0}catch{return!1}}function bd(e){let t=[process.env.MAESTRO_BIN,Y.join(Tt.homedir(),".maestro","bin","maestro"),"/opt/homebrew/bin/maestro","/usr/local/bin/maestro"].filter(Boolean),n=Ge("/usr/bin/env",["which","maestro"],{encoding:"utf-8",env:process.env}),i=n.status===0?String(n.stdout||"").split(`
|
|
1357
|
+
`)[0]?.trim():"";i&&t.unshift(i);for(let r of t)if(r&&yd(r))return e&&L.appendFileSync(e,`Using Maestro CLI at ${r}
|
|
1358
|
+
`),r;return e&&L.appendFileSync(e,`Maestro CLI not found. Checked: ${t.join(", ")}
|
|
1359
|
+
`),null}function Ed(e){let t=String(e||"").trim();return t?t.replace(/_/g," ").replace(/\bios\b/gi,"").replace(/\biphone\b/i,"iPhone").replace(/\s+/g," ").trim():"iPhone 15"}async function Ad(e,t){if((Ge("xcrun",["simctl","list","devices","booted"],{encoding:"utf-8"}).stdout||"").includes("(Booted)")){L.appendFileSync(t,`Using already booted iOS Simulator.
|
|
1360
|
+
`);return}let i=Ed(e),r=Ge("xcrun",["simctl","list","devices","--json"],{encoding:"utf-8"});if(r.status!==0||!r.stdout)throw new Error("Could not list iOS simulators.");let o=JSON.parse(r.stdout),s=Object.values(o.devices||{}).flatMap(c=>Array.isArray(c)?c:[]).filter(c=>c?.isAvailable),l=s.find(c=>c.name===i)||s.find(c=>String(c.name||"").toLowerCase().includes(i.toLowerCase()))||s.find(c=>String(c.name||"").startsWith("iPhone"));if(!l?.udid)throw new Error(`No available iOS Simulator found for ${i}.`);L.appendFileSync(t,`Booting iOS Simulator ${l.name} (${l.udid})...
|
|
1361
|
+
`),ot("xcrun",["simctl","boot",l.udid],t)!==0&&L.appendFileSync(t,`simctl boot returned non-zero; continuing to bootstatus in case it was already booting.
|
|
1362
|
+
`),Ei("xcrun",["simctl","bootstatus",l.udid,"-b"],t)}function Id(e,t){if(e.endsWith(".ipa"))throw new Error("iOS Maestro runs need a simulator .app.zip artifact, not an App Store .ipa.");if(e.endsWith(".zip")){let n=Y.join(t,"ios-app");L.mkdirSync(n,{recursive:!0}),new En(e).extractAllTo(n,!0);let i=_i(n);if(!i)throw new Error("Could not find a .app bundle inside the iOS artifact zip.");return i}if(e.endsWith(".app"))return e;throw new Error("iOS Maestro runs need a .app bundle or .app.zip artifact.")}function Ao(e,t){let n=Y.join(e,"Info.plist");if(!L.existsSync(n))return L.appendFileSync(t,`Could not find Info.plist in ${e}; skipping uninstall.
|
|
1363
|
+
`),null;let i=Ge("/usr/bin/plutil",["-extract","CFBundleIdentifier","raw","-o","-",n],{encoding:"utf-8",env:process.env}),r=String(i.stdout||"").trim();return i.status!==0||!r?(L.appendFileSync(t,`Could not read CFBundleIdentifier from Info.plist; skipping uninstall.
|
|
1364
|
+
`),null):r}function gi(e,t,n){let i=Y.join(e,n);ot("xcrun",["simctl","io","booted","screenshot",i],t)!==0&&L.appendFileSync(t,`[WARN] Could not capture iOS simulator screenshot: ${n}
|
|
1365
|
+
`)}function wd(e,t){let n=Y.join(e,"ios-simulator-recording.mp4");L.appendFileSync(t,`Starting iOS simulator recording: ${n}
|
|
1366
|
+
`);let i=po("xcrun",["simctl","io","booted","recordVideo",n],{stdio:["ignore","pipe","pipe"],env:process.env});return i.stdout?.on("data",r=>{L.appendFileSync(t,r)}),i.stderr?.on("data",r=>{L.appendFileSync(t,r)}),i.on("error",r=>{L.appendFileSync(t,`[WARN] Could not start iOS simulator recording: ${r.message}
|
|
1367
|
+
`)}),i}async function ao(e,t){e&&await new Promise(n=>{let i=!1,r=()=>{i||(i=!0,n())};e.once("exit",r),e.once("close",r),e.killed||(L.appendFileSync(t,`Stopping iOS simulator recording...
|
|
1368
|
+
`),e.kill("SIGINT")),setTimeout(()=>{!i&&!e.killed&&(L.appendFileSync(t,`[WARN] iOS simulator recording did not stop after SIGINT; sending SIGKILL.
|
|
1369
|
+
`),e.kill("SIGKILL")),r()},5e3).unref?.()})}function _d(e,t){let n=Ao(e,t);if(!n)return;L.appendFileSync(t,`Uninstalling existing iOS app data for ${n} if present...
|
|
1370
|
+
`),ot("xcrun",["simctl","uninstall","booted",n],t)!==0&&L.appendFileSync(t,`No existing app install removed for ${n}; continuing.
|
|
1371
|
+
`)}function Rd(e,t){if(!e?.appId)return;if(L.appendFileSync(t,`Cleaning up installed app after Maestro run...
|
|
1372
|
+
`),e.platform==="ios"){let r=ot("xcrun",["simctl","uninstall","booted",e.appId],t);r===0?L.appendFileSync(t,`Uninstalled iOS app ${e.appId} after Maestro run.
|
|
1373
|
+
`):L.appendFileSync(t,`Warning: failed to uninstall iOS app ${e.appId} after Maestro run: xcrun simctl uninstall exited with code ${r}
|
|
1374
|
+
`);return}let n=e.deviceId?["-s",e.deviceId]:[],i=ot("adb",[...n,"uninstall",e.appId],t);i===0?L.appendFileSync(t,`Uninstalled Android app ${e.appId} after Maestro run.
|
|
1375
|
+
`):L.appendFileSync(t,`Warning: failed to uninstall Android app ${e.appId} after Maestro run: adb uninstall exited with code ${i}
|
|
1376
|
+
`)}function $d(e,t){let n=Ge("adb",["devices"],{encoding:"utf-8",env:process.env});if(n.status!==0||n.error)return L.appendFileSync(t,`[WARN] Could not list Android devices before install; using adb default target.
|
|
1280
1377
|
`),null;let i=String(n.stdout||"").split(`
|
|
1281
|
-
`).map(r=>r.trim().split(/\s+/)).filter(r=>r.length>=2&&r[1]==="device").map(r=>r[0]).filter(Boolean);return e&&i.includes(e)?(
|
|
1282
|
-
`),e):i.length===1?(
|
|
1283
|
-
`),i[0]):(i.length>1&&
|
|
1284
|
-
`),null)}function
|
|
1285
|
-
`),null)}function
|
|
1286
|
-
`)[0]?.trim()||null}async function
|
|
1287
|
-
`)}try{await
|
|
1288
|
-
`)}try{
|
|
1289
|
-
`)}}function ql(e){if(!e.endsWith(".apk"))return B.error(W.red("Local Android Maestro runs need an APK artifact.")),!1;B.info(W.dim("Installing APK on local Android device/emulator..."));let t=He("adb",["install","-r",e],{stdio:"inherit",env:process.env});return t.error?(B.error(W.red(`adb failed to start: ${t.error.message}`)),!1):t.status!==0?(B.error(W.red(`adb install failed with exit code ${t.status??1}`)),!1):!0}function Xl(e,t){if(e.endsWith(".ipa"))return B.error(W.red("Local iOS Maestro runs need an iOS Simulator .app.zip artifact, not an App Store .ipa.")),!1;let n=e;if(e.endsWith(".zip")){let r=Y.join(t,"ios-app");M.mkdirSync(r,{recursive:!0}),new gn(e).extractAllTo(r,!0);let o=hi(r);if(!o)return B.error(W.red("Could not find a .app bundle inside the downloaded zip.")),!1;n=o}if(!n.endsWith(".app"))return B.error(W.red("Local iOS Maestro runs need an iOS Simulator .app bundle or .app.zip artifact.")),!1;B.info(W.dim("Installing app on booted iOS Simulator..."));let i=He("xcrun",["simctl","install","booted",n],{stdio:"inherit",env:process.env});return i.error?(B.error(W.red(`xcrun failed to start: ${i.error.message}`)),!1):i.status!==0?(B.error(W.red(`iOS Simulator install failed with exit code ${i.status??1}`)),!1):!0}function hi(e){let t=M.readdirSync(e,{withFileTypes:!0});for(let n of t){let i=Y.join(e,n.name);if(n.isDirectory()&&n.name.endsWith(".app"))return i;if(n.isDirectory()){let r=hi(i);if(r)return r}}return null}function Zl(e,t){let n=String(t||"").toLowerCase();return n==="android"?e.find(i=>wt(i,".apk")):n==="ios"?e.find(i=>wt(i,".app.zip"))||e.find(i=>wt(i,".zip")):e.find(i=>wt(i,".apk"))||e.find(i=>wt(i,".app.zip"))||e.find(i=>wt(i,".zip"))}function wt(e,t){return String(e?.name||e?.downloadUrl||e?.url||"").toLowerCase().endsWith(t)}function yi(e){let t=String(e||"").toLowerCase();if(t.includes(".apk"))return"android";if(t.includes(".app.zip")||t.endsWith(".app")||t.includes(".ipa"))return"ios"}function io(e){if(e)try{return Y.basename(new URL(e).pathname)||void 0}catch{return Y.basename(e)||void 0}}function Ql(e){return e?e.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i)?.[0]:void 0}function ro(e,t){if(!e.jsonOutput)return;let n=Y.resolve(e.jsonOutput),i={...t,updatedAt:new Date().toISOString()};try{let r=Y.dirname(n);r&&r!=="."&&M.mkdirSync(r,{recursive:!0}),M.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){B.warn(W.yellow(`Could not write Maestro metadata JSON: ${r.message}`))}}function ed(e,t){if(!e.jsonOutput)return;let n=Y.resolve(e.jsonOutput),i={mode:"local",...t,updatedAt:new Date().toISOString()};try{let r=Y.dirname(n);r&&r!=="."&&M.mkdirSync(r,{recursive:!0}),M.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){B.warn(W.yellow(`Could not write Maestro metadata JSON: ${r.message}`))}}import{spinner as st,text as Bt,select as Ii,isCancel as rt,cancel as wi,log as fo}from"@clack/prompts";import ne from"chalk";import se from"fs";import Ie from"path";import{spawn as td,spawnSync as mt}from"child_process";import po from"axios";import ht from"os";import vi from"crypto";var nd=5e3,id=12,mo=100,Si=24,oo=8e3,rd={completed:"completed",draft:"draft",halted:"halted",inprogress:"inProgress","in-progress":"inProgress"},od=e=>e?.type==="google_service_account",yn=e=>e?.bundleId||e?.packageName||e?.meta?.packageName||e?.meta?.bundleId,go=e=>e.submitArgs||process.argv.slice(3).join(" ");async function Sn(e){let t=st(),n=Pe(),i=sd(e);if(!i){process.exitCode=1;return}let r=e.projectId||i.projectId,o=e.profile||e.buildProfile||"production";if(!r){le(`${m.configFileName} is missing projectId. Pass --project-id in runner mode.`),process.exitCode=1;return}i.projectId=r,fe(ne.dim(`Submit for project: ${i.name||r} | Profile: ${o}`));let s=e.platform;if(!s){let g=await Ii({message:"Select platform to submit:",options:[{value:"ios",label:"iOS (App Store Connect / TestFlight)"},{value:"android",label:"Android (Google Play Console)"}]});if(rt(g)){wi("Operation cancelled");return}s=g}if(s=String(s).toLowerCase(),s!=="ios"&&s!=="android"){le(`Platform ${s} is not supported. Use 'ios' or 'android'.`),process.exitCode=1;return}let l=s==="ios"&&!e.local&&e.sshHost?Id(i,o,e):null;if(s==="ios"&&!e.local&&!l){await ad(i,o,e);return}let a=e.submitId,c=!!(e.local&&a),u=a||null,d=async(g,k={})=>{u&&await ud(r,u,{status:g,...k})},p=s==="android"?e.packageName||e.androidPackage||bd(i,o):void 0,f=s==="ios"?e.bundleId||e.iosBundleIdentifier||Ed(i,o):void 0,h,S,L,x=!1;try{s==="android"&&(h=e.track||i.submit?.[o]?.android?.track||i.submit?.production?.android?.track||"internal",S=wd(i,o,e.releaseStatus),L=$d(i,o,e.rollout),x=vd(i,o,e.changesNotSentForReview),Rd(S,L))}catch(g){le(g.message),process.exitCode=1;return}if(s==="android"&&!c&&(u=await ld(i,r,s,o,e,{packageName:p,track:h,releaseStatus:S,rollout:L,changesNotSentForReview:x}),!u)){le("Could not create submission tracking record. Submission was not started."),process.exitCode=1;return}await d("running",{platform:s,profile:o,packageName:p,track:h,releaseStatus:S,rollout:L,startTime:Date.now(),...c?pd():{}});let b=null,U=null;try{U=await Pd(r,s,e,n?.token),b=U?.filePath||null}catch(g){await d("failed",{error:`Failed to resolve submission artifact: ${g.message}`,endTime:Date.now()}),le(`Failed to resolve submission artifact: ${g.message}`),process.exitCode=1;return}if(!b){let g=Dd(s,e);await d("failed",{error:g,endTime:Date.now()}),le(g),process.exitCode=1;return}await d("running",{buildId:U?.buildId,artifactName:U?.artifactName,artifactSource:U?.source}),fe(`Using artifact: ${ne.green(Ie.basename(b))} `),t.start("Fetching submission credentials from Dashboard...");let w;try{let k=(await N.get(`/credentials/${r}`)).data.credentials||[];if(s==="android"&&!p){t.stop("Package name missing"),le("Could not resolve Android package name. Set android.package in mach.config.json/app.json."),await d("failed",{error:"Could not resolve Android package name.",endTime:Date.now()}),process.exitCode=1;return}let F=k.filter(od),V=s==="ios"?k.filter(J=>J.type==="asc_api_key"):Ad(F,p);if(V.length===0){if(t.stop("Credentials missing"),le(s==="android"?`No Google Play service credential found for package ${p}.`:`No Service Credentials found for ${s}.`),s==="android"){let J=F.map(yn).filter(Boolean).join(", ");J&&fe(`Found Google Play service credential(s) for: ${J}`),fe(`Use '${m.nameLower} credentials:service --platform android --package-name ${p}' or upload it under that package in the Dashboard.`)}else fe(`Use '${m.nameLower} credentials:service --platform ${s}' or use the Dashboard to upload them.`);await d("failed",{error:`No submission credentials found for ${s}.`,endTime:Date.now()}),process.exitCode=1;return}if(w=gd(V,e.credentialId),!w&&s==="ios"&&f&&(w=hd(V,f)),w||V.length===1)w=w||V[0],t.stop(`Using: ${w.name}`),s==="android"&&yn(w)==="*"&&fe(ne.yellow(`Using legacy wildcard Google Play credential for ${p}. Upload a package-scoped credential when possible.`));else{if(t.stop("Multiple credentials found"),yd()){let H=V.map(P=>`${P.name||"credential"} (${P.credentialId||P.id||"no-id"})`).join(", ");le(`Multiple ${s==="ios"?"App Store Connect":"Google Play"} credentials found. Use --credential-id in CI. Available: ${H}`),await d("failed",{error:"Multiple submission credentials found; --credential-id is required in CI.",endTime:Date.now()}),process.exitCode=1;return}let J=await Ii({message:`Choose a ${s==="ios"?"App Store Connect":"Google Play"} credential:`,options:V.map(H=>({value:H.credentialId,label:H.name,hint:`${H.keyId?`ID: ${H.keyId}`:""} ${H.issuerId?`(Issuer: ${H.issuerId.substring(0,8)}...)`:""}`}))});if(rt(J)){wi("Submission cancelled"),await d("failed",{error:"Submission cancelled while selecting credential.",endTime:Date.now()}),process.exitCode=1;return}w=V.find(H=>H.credentialId===J),fe(`Using selected: ${ne.green(w.name)}`)}}catch(g){t.stop("Failed to fetch credentials"),le(`API Error: ${g.message} `),await d("failed",{error:`Failed to fetch credentials: ${g.message}`,endTime:Date.now()}),process.exitCode=1;return}let z=se.mkdtempSync(Ie.join(ht.tmpdir(),`${m.nameLower}-submit-`)),Q=w.keyId||w.meta?.keyId,O=w.issuerId||w.meta?.issuerId,E=w.type==="asc_api_key"?`AuthKey_${Q}.p8`:"service-account.json",D=Ie.join(z,E);t.start("Downloading secure key...");try{let g=await N.get(`/credentials/${w.credentialId}/download`,{params:{projectId:r,format:"raw"}});if(g.data.status!=="success"||!g.data.downloadUrl)throw new Error("Failed to get secure download URL");let k=await po.get(g.data.downloadUrl,{responseType:"arraybuffer"});se.writeFileSync(D,Buffer.from(k.data)),t.stop("Key downloaded to secure temp storage")}catch(g){t.stop("Download failed"),le(`Failed to download key: ${g.message}`);try{se.rmSync(z,{recursive:!0,force:!0})}catch{}await d("failed",{error:`Failed to download credential key: ${g.message}`,endTime:Date.now()}),process.exitCode=1;return}fe(ne.blue(`Initiating ${s==="ios"?"TestFlight":"Google Play"} submission...`));let $=!1,C;try{if(s==="ios"){if(!Q){let k=await Bt({message:"Enter App Store Connect Key ID (e.g. 2X948D...):",validate:F=>F.length>0?void 0:"Key ID is required"});if(rt(k)){await d("failed",{error:"Submission cancelled while entering ASC Key ID.",endTime:Date.now()}),process.exitCode=1;return}Q=k}if(!O||O==="undefined"){let k=await Bt({message:"Enter App Store Connect Issuer ID (Found on ASC Keys page):",validate:F=>F.length>0?void 0:"Issuer ID is required"});if(rt(k)){await d("failed",{error:"Submission cancelled while entering ASC Issuer ID.",endTime:Date.now()}),process.exitCode=1;return}O=k}fe(`Using ASC Key ID: ${Q}`),fe(`Using ASC Issuer ID: ${O}`);let g=l?await Nd(b,D,O,Q,f,l):await Cd(b,D,O,Q,f);$i(`${s==="ios"?"App Store":"Google Play"} submission successful!`),$=!0}else C=await Ld(b,D,h||"internal",p,S||"completed",L,x,o),$i("Google Play submission successful!"),$=!0}catch(g){le(`Submission failed: ${g.message}`),await d("failed",{error:g.message,endTime:Date.now()}),ot(e,{status:"failed",projectId:r,submitId:u,platform:s,profile:o,buildId:U?.buildId||e.buildId,artifactName:U?.artifactName,error:g.message,dashboardUrl:u?gt(u,r):void 0}),process.exitCode=1}finally{$&&(await d("success",{endTime:Date.now(),versionCode:C?.versionCode,track:h,releaseStatus:S}),ot(e,{status:"success",projectId:r,submitId:u,platform:s,profile:o,buildId:U?.buildId||e.buildId,artifactName:U?.artifactName,versionCode:C?.versionCode,track:h,releaseStatus:S,dashboardUrl:u?gt(u,r):void 0})),Zd(z),b&&b.includes(`${m.nameLower}-artifact-`)}}function sd(e){let t=`./${m.configFileName}`;if(se.existsSync(t))try{return JSON.parse(se.readFileSync(t,"utf-8"))}catch(n){return le(`Failed to read ${m.configFileName}: ${n.message}`),null}return e.projectId?{projectId:e.projectId}:(le(`No ${m.configFileName} found. Run \`${m.nameLower} init\` or \`${m.nameLower} link\` first.`),null)}async function ad(e,t,n){let i=n.projectId||e.projectId;if(!i){le(`${m.configFileName} is missing projectId.`),process.exitCode=1;return}let r=n.submitId||vi.randomUUID(),o=!!n.latest||!n.buildId,s=dd({...n,latest:o,profile:t,projectId:i,submitId:r}),l={projectId:i,submitId:r,platform:"ios",profile:t,latest:o,buildId:n.buildId,credentialId:n.credentialId,status:"pending",source:"cli",submitArgs:go(n),runnerArgs:s,runnerCommand:[m.nameLower,"submit",...s].map(Sd).join(" "),appName:e.name,startTime:Date.now()},a=st();a.start("Queuing iOS submit on macOS runner...");try{let c=await N.post("/submissions",l),u=c.data?.submission||c.data?.submit||{},d=c.data?.dashboardUrl||gt(r,i);a.stop("iOS submit queued"),fe(`Submission ID: ${ne.cyan(r)}`),fe(`Dashboard: ${ne.blue.underline(d)}`),ot(n,{status:"pending",projectId:i,submitId:r,platform:"ios",profile:t,latest:o,buildId:n.buildId,dashboardUrl:d}),await cd(i,r,n)}catch(c){a.stop("Could not queue iOS submit"),le(md(c)),process.exitCode=1}}async function ld(e,t,n,i,r,o={}){let s=r.submitId||vi.randomUUID(),l=!!r.latest||!r.buildId,a={projectId:t,submitId:s,platform:n,profile:i,latest:l,buildId:r.buildId,credentialId:r.credentialId,status:"running",source:"cli-direct",submitArgs:go(r),appName:e.name,startTime:Date.now(),...o};try{let c=await N.post("/submissions",a),u=c.data?.submission||c.data?.submit||{},d=c.data?.dashboardUrl||u.dashboardUrl||gt(s,t);return fe(`Submission ID: ${ne.cyan(s)}`),fe(`Dashboard: ${ne.blue.underline(d)}`),ot(r,{status:"running",projectId:t,submitId:s,platform:n,profile:i,latest:l,buildId:r.buildId,dashboardUrl:d}),s}catch(c){let u=c.response?.data?.message||c.response?.data?.error||c.message;return fe(ne.yellow(`Could not create submission tracking record: ${u}`)),null}}function dd(e){let t=["--local","--submit-id",e.submitId,"--project-id",e.projectId,"--platform","ios","--profile",e.profile||"production"];return e.buildId?t.push("--build-id",e.buildId):t.push("--latest"),e.credentialId&&t.push("--credential-id",e.credentialId),e.bundleId&&t.push("--bundle-id",e.bundleId),e.packageName&&t.push("--package-name",e.packageName),e.quiet&&t.push("--quiet"),e.jsonOutput&&t.push("--json-output",e.jsonOutput),t.filter(n=>n!=null&&n!=="")}async function cd(e,t,n){let i=st(),r=0,o=0;for(n.quiet||i.start("Waiting for iOS submit runner...");;)try{let s=await N.get(`/submissions/${e}/${t}`),l=s.data?.submission||s.data?.submit||s.data,a=String(l?.status||"pending").toLowerCase();r=0;let c=Array.isArray(l?.logs)?l.logs:[];for(let u=o;u<c.length;u++){let d=c[u];d&&console.log(ne.dim(String(d)))}if(o=c.length,["success","completed","succeeded"].includes(a)){n.quiet||i.stop("iOS submit completed"),$i("App Store submission successful!"),ot(n,{status:"success",projectId:e,submitId:t,platform:"ios",profile:l?.profile||n.profile||"production",buildId:l?.buildId||n.buildId,artifactName:l?.artifactName,dashboardUrl:l?.dashboardUrl||gt(t,e)});return}if(["failed","error","cancelled","canceled"].includes(a)){n.quiet||i.stop("iOS submit failed");let u=l?.error||l?.message||"Unknown iOS submit failure.";le(u),ot(n,{status:"failed",projectId:e,submitId:t,platform:"ios",profile:l?.profile||n.profile||"production",buildId:l?.buildId||n.buildId,artifactName:l?.artifactName,error:u,dashboardUrl:l?.dashboardUrl||gt(t,e)}),process.exitCode=1;return}n.quiet||i.message(`iOS submit ${a}...`),await _i(nd)}catch(s){if(r++,r>=id){n.quiet||i.stop("Lost connection to iOS submit status"),le(`Could not fetch iOS submit status after ${r} attempts: ${s.message}`),process.exitCode=1;return}await _i(Math.min(2e3*r,15e3))}}async function ud(e,t,n){let i;for(let r=1;r<=3;r++)try{await N.patch(`/submissions/${e}/${t}`,n);return}catch(o){if(i=o,r>=3||!fd(o))break;await _i(1e3*r)}fo.warn(ne.dim(`Could not report submission status: ${i?.message||i}`))}function fd(e){let t=e.response?.status;return!t||t===408||t===409||t===425||t===429||t>=500}function pd(){let e={gitlabJobId:process.env.CI_JOB_ID,gitlabJobUrl:process.env.CI_JOB_URL,gitlabPipelineId:process.env.CI_PIPELINE_ID,gitlabProjectId:process.env.CI_PROJECT_ID,gitlabProjectPath:process.env.CI_PROJECT_PATH};return Object.fromEntries(Object.entries(e).filter(([,t])=>!!t))}function md(e){let t=e.response?.status,n=e.response?.data?.message||e.response?.data?.error;return t===404||t===405?["Managed iOS submit is not enabled on this Mach API yet.","Deploy the API/dashboard submission orchestration endpoint, then retry the same command.","Expected API: POST /submissions and GET/PATCH /submissions/:projectId/:submitId."].join(`
|
|
1290
|
-
`):n||e.message||String(e)}function gt(e,t){if(!e)return We;let n=t?`?projectId=${encodeURIComponent(t)}`:"";return`${We}/submissions/${e}${n}`}function ot(e,t){if(!e.jsonOutput)return;let n=Ie.resolve(e.jsonOutput),i={...t,url:t.url||t.dashboardUrl||gt(t.submitId,t.projectId),updatedAt:new Date().toISOString()};try{let r=Ie.dirname(n);r&&r!=="."&&se.mkdirSync(r,{recursive:!0}),se.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){fo.warn(ne.yellow(`Could not write submission metadata JSON: ${r.message}`))}}function gd(e,t){return t&&e.find(n=>n.credentialId===t||n.id===t||n.keyId===t||n.meta?.keyId===t)||null}function hd(e,t){let n=e.filter(i=>[i.bundleId,i.bundleIdentifier,i.appIdentifier,i.meta?.bundleId,i.meta?.bundleIdentifier,i.meta?.appIdentifier].filter(Boolean).map(String).includes(t));return n.length===1?n[0]:null}function yd(){return process.env.CI==="true"||process.env.CI==="1"||!process.stdin.isTTY}function _i(e){return new Promise(t=>setTimeout(t,e))}function Sd(e){return/^[a-zA-Z0-9_./:=@-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function bd(e,t){if(e.submit?.[t]?.android?.package)return e.submit[t].android.package;let n=sr(e,t);if(n)return n;let i=Ie.join(process.cwd(),"app.json");if(se.existsSync(i))try{return JSON.parse(se.readFileSync(i,"utf-8")).expo?.android?.package}catch{}let r=Ie.join(process.cwd(),"app.config.json");if(se.existsSync(r))try{let o=JSON.parse(se.readFileSync(r,"utf-8"));return o.expo?.android?.package||o.android?.package}catch{}}function Ad(e,t){let n=e.filter(o=>yn(o)===t);if(n.length>0)return n;let i=e.filter(o=>{let s=yn(o);return!s||s==="*"});return e.length>0&&e.length===i.length?i:[]}function Ed(e,t){return e.submit?.[t]?.ios?.bundleIdentifier?e.submit[t].ios.bundleIdentifier:e.submit?.[t]?.ios?.bundleId?e.submit[t].ios.bundleId:ar(e,t)}function Id(e,t,n){let i=e.submit?.[t]?.ios||{},r=e.submit?.production?.ios||{},o=n.sshHost||i.sshHost||r.sshHost||process.env.MACH_IOS_SUBMIT_SSH_HOST;return o?{sshHost:o,sshUser:n.sshUser||i.sshUser||r.sshUser||process.env.MACH_IOS_SUBMIT_SSH_USER||process.env.USER||"ubuntu",sshKey:n.sshKey||i.sshKey||r.sshKey||process.env.MACH_IOS_SUBMIT_SSH_KEY}:null}function wd(e,t,n){let i=n||e.submit?.[t]?.android?.releaseStatus||e.submit?.production?.android?.releaseStatus||"completed";return _d(i)}function _d(e){let t=rd[String(e).trim().toLowerCase()];if(!t)throw new Error(`Invalid Android release status "${e}". Use completed, draft, halted, or inProgress.`);return t}function $d(e,t,n){let i=n??e.submit?.[t]?.android?.rollout??e.submit?.[t]?.android?.userFraction??e.submit?.[t]?.android?.rolloutFraction??e.submit?.production?.android?.rollout??e.submit?.production?.android?.userFraction??e.submit?.production?.android?.rolloutFraction;if(i==null||i==="")return;let r=Number(i);if(!Number.isFinite(r)||r<=0||r>=1)throw new Error(`Invalid Android rollout fraction "${i}". Use a number greater than 0 and less than 1, for example 0.1.`);return r}function vd(e,t,n){let i=n??e.submit?.[t]?.android?.changesNotSentForReview??e.submit?.[t]?.android?.changes_not_sent_for_review??e.submit?.production?.android?.changesNotSentForReview??e.submit?.production?.android?.changes_not_sent_for_review??!1;return i===!0||i==="true"||i==="1"}function Rd(e,t){if(e==="inProgress"&&t===void 0)throw new Error("Google Play staged rollout requires --rollout <fraction> when --release-status inProgress is used.");if(e!=="inProgress"&&e!=="halted"&&t!==void 0)throw new Error("Android rollout fraction can only be used with --release-status inProgress or halted.")}async function Pd(e,t,n,i){let r=n.buildId?"id":n.latest?"latest":null;if(!r){let s=await Ii({message:"Select artifact source:",options:[{value:"latest",label:`Latest Production Build (${m.name})`},{value:"id",label:`Input Build ID (${m.name})`},{value:"url",label:"Remote URL"},{value:"local",label:"Local File Path"}]});if(rt(s))return wi("Operation cancelled"),null;r=s}if(r==="local"){let s=await Bt({message:"Enter path to artifact (.ipa/.aab):",validate:l=>{if(!se.existsSync(l))return"File not found";if(t==="ios"&&!l.endsWith(".ipa"))return"Must be an .ipa file";if(t==="android"&&!l.endsWith(".aab"))return"Must be an .aab file"}});return rt(s)?null:{filePath:s,source:"local"}}let o=st();if(r==="latest"){let s=n.profile||n.buildProfile;o.start(`Fetching latest${s?` ${s}`:""} build...`);try{let l=await N.get(`/builds/${e}`,{params:{limit:50}});if(l.data.status!=="success")throw new Error(l.data.message);let a=l.data.builds||[],c=s?.toLowerCase(),u=w=>w.platform?.toLowerCase()===t.toLowerCase()&&w.status?.toLowerCase()==="success",d=w=>c?[w.buildProfile,w.profile,w.profileName,w.buildType].filter(Boolean).some(z=>String(z).toLowerCase()===c):!0,p=a.filter(w=>u(w)&&d(w)),f=p.find(w=>w.buildType?.toLowerCase()==="store"||w.distribution?.toLowerCase()==="store")||p[0],h=a.some(w=>w.platform?.toLowerCase()===t.toLowerCase()&&w.status?.toLowerCase()==="success");if(!f)return o.stop("No suitable build found"),le(s&&h?`No successful ${t} builds found for profile "${s}".`:"No successful builds found for this platform."),null;o.stop(`Found build: ${f.buildId}`);let S=f.artifacts||[];if(S.length===0||S.every(w=>!(w.url||w.downloadUrl)))try{let w=await N.get(`/builds/${e}/${f.buildId}/artifacts`);w.data.status==="success"&&w.data.artifacts?.length>0?(S=w.data.artifacts.map(z=>({...z,url:z.url||z.downloadUrl})),console.log(ne.cyan(` [RECOVERY] Fetched ${S.length} artifact(s) with download URLs.`))):console.log(ne.yellow(" [RECOVERY] /artifacts endpoint returned 0 artifacts."))}catch(w){console.log(ne.red(` [RECOVERY] /artifacts fetch failed: ${w.message}`))}let x=t==="ios",b=S.find(w=>{let z=(w.type||"").toLowerCase(),Q=(w.name||"").toLowerCase();if(console.log(ne.dim(` - Checking: ${w.name} (Type: ${w.type}, HasLink: ${!!(w.url||w.downloadUrl)})`)),z)return z===(x?"ipa":"aab");let O=x?".ipa":".aab",E=(w.url||w.downloadUrl||"").toLowerCase();return Q.endsWith(O)||E.includes(O)});if(!b||!(b.url||b.downloadUrl))return le("Build found but artifact URL is missing."),null;let U=b.url||b.downloadUrl;return{filePath:await bi(U,x?"ios":"android"),buildId:f.buildId,artifactName:b.name,source:"latest"}}catch(l){return o.stop("Fetch failed"),le(`API Error: ${l.message}`),null}}if(r==="id"){let s=n.buildId||await Bt({message:"Enter Build ID:",validate:a=>a.length<5?"Invalid ID":void 0});if(rt(s))return null;let l=String(s);o.start("Fetching build...");try{let a=null;try{let f=await N.get(`/builds/${e}/${l}`);f.data.status==="success"&&(a=f.data.build)}catch(f){f.response?.status!==404&&console.log(ne.dim(` [RECOVERY] Project build lookup skipped: ${f.message}`))}if(!a){let f=await N.get(`/build/${l}`);if(f.data.status!=="success")throw new Error(f.data.message);a=f.data.build}if(!a)throw new Error(`Build ${l} was not found.`);let c=t==="ios",u=hn(a.artifacts);Od(u)||(u=await ao(e,l,u));let d=so(u,t);if(d||(u=await ao(e,l,u),d=so(u,t)),!d)throw new Error(`No ${c?".ipa":".aab"} artifact found for build ${l}. The build exists, but its artifact list does not contain a downloadable submission artifact.`);let p=d.url||d.downloadUrl;if(!p)throw new Error(`Artifact ${d.name||"(unnamed)"} for build ${l} has no download URL. Retry after the build artifact upload is visible in the Installation Hub.`);return o.stop(`Found build: ${a.buildId||l}`),{filePath:await bi(p,c?"ios":"android"),buildId:a.buildId||l,artifactName:d.name,source:"id"}}catch(a){throw o.stop("Fetch failed"),a}}if(r==="url"){let s=await Bt({message:"Enter Artifact URL:",validate:l=>l.startsWith("http")?void 0:"Must be a valid URL"});return rt(s)?null:{filePath:await bi(s,t),source:"url"}}return null}function hn(e){return(e||[]).map(t=>({...t,url:t.url||t.downloadUrl}))}function Od(e){return e.some(t=>!!(t.url||t.downloadUrl))}function so(e,t){let n=t==="ios",i=n?"ipa":"aab",r=n?".ipa":".aab";return e.find(o=>{let s=String(o.type||"").toLowerCase(),l=String(o.name||"").toLowerCase(),a=String(o.url||o.downloadUrl||"").toLowerCase();return s?s===i:l.endsWith(r)||a.includes(r)})||null}function Dd(e,t){let n=e==="ios"?".ipa":".aab";if(t.buildId)return`No downloadable ${n} artifact found for build ${t.buildId}. Check that the build finished artifact upload before submitting.`;if(t.latest){let i=t.profile||t.buildProfile;return`No latest successful ${e}${i?` ${i}`:""} build has a downloadable ${n} artifact.`}return`No downloadable ${n} artifact was selected for submission.`}async function ao(e,t,n){try{let i=await N.get(`/builds/${e}/${t}/artifacts`);if(i.data.status==="success"&&i.data.artifacts?.length>0){let r=hn(i.data.artifacts);return console.log(ne.cyan(` [RECOVERY] Fetched ${r.length} artifact(s) with download URLs.`)),r}}catch(i){console.log(ne.dim(` [RECOVERY] Project artifact lookup skipped: ${i.message}`))}try{let i=await N.get(`/public/builds/${t}`);if(i.data.status==="success"&&i.data.artifacts?.length>0){let r=hn(i.data.artifacts);return console.log(ne.cyan(` [RECOVERY] Fetched ${r.length} public artifact(s) with download URLs.`)),r}}catch(i){console.log(ne.dim(` [RECOVERY] Public artifact lookup skipped: ${i.message}`))}return hn(n)}async function bi(e,t,n=3){let i=st();i.start("Downloading artifact...");let r=se.mkdtempSync(Ie.join(ht.tmpdir(),`${m.nameLower}-artifact-`)),o=`app.${t==="ios"?"ipa":"aab"}`,s=Ie.join(r,o);for(let l=1;l<=n;l++)try{l>1&&(i.message(`Downloading artifact (Retry ${l}/${n})...`),await new Promise(u=>setTimeout(u,2e3*l)));let a=se.createWriteStream(s),c=await po({url:e,method:"GET",responseType:"stream",timeout:6e4});return await new Promise((u,d)=>{c.data.pipe(a);let p=!1;c.data.on("error",f=>{p||(p=!0,a.close(),d(f))}),a.on("finish",()=>{p||u()}),a.on("error",f=>{p||(p=!0,d(f))})}),i.stop("Download complete"),s}catch(a){if(l===n)throw i.stop("Download failed"),a}throw new Error("Download failed after retries")}async function Cd(e,t,n,i,r){let o=st();if(r&&fe(`Bundle ID: ${ne.green(r)}`),!n||!i)throw le(`Missing credentials: issuerId=${n}, keyId=${i}. Check your Dashboard.`),new Error("Missing ASC API Key Metadata (IssuerID or KeyID)");let s=ho(t,n,i),l=Fd();return o.start("Uploading to TestFlight (pilot)..."),new Promise((a,c)=>{let u=Hd(),d=td(l.command,["pilot","upload","--ipa",e,"--api_key_path",s,"--skip_submission","true","--skip_waiting_for_build_processing","true"],{stdio:["ignore","pipe","pipe"],env:l.env});d.stdout?.on("data",p=>u.append(p,process.stdout)),d.stderr?.on("data",p=>u.append(p,process.stderr)),d.on("close",p=>{if(u.flush(),p!==0){o.stop("Pilot failed");try{se.unlinkSync(s)}catch{}c(jd(p,u.lines()))}else{o.stop("IPA uploaded to TestFlight");try{se.unlinkSync(s)}catch{}a({})}}),d.on("error",p=>{u.flush();try{se.unlinkSync(s)}catch{}o.stop("Pilot execution error");let f=qd(p);f.logs=u.lines(),c(f)})})}async function Nd(e,t,n,i,r,o){let s=st();if(r&&fe(`Bundle ID: ${ne.green(r)}`),!n||!i)throw le(`Missing credentials: issuerId=${n}, keyId=${i}. Check your Dashboard.`),new Error("Missing ASC API Key Metadata (IssuerID or KeyID)");let l=ho(t,n,i),a=`${o.sshUser}@${o.sshHost}`,c=Td(o),u=kd(o),d="",p="";try{if(s.start(`Preparing remote iOS submit runner (${a})...`),d=xd("ssh",[...c,"mktemp -d /tmp/mach-submit.XXXXXX"]).trim(),!d)throw new Error("Remote runner did not return a temp directory.");s.stop(`Remote runner ready: ${a}`),s.start("Uploading IPA and App Store Connect key to remote runner..."),Ai("scp",[...u,e,`${a}:${d}/app.ipa`],"IPA upload to remote runner"),Ai("scp",[...u,l,`${a}:${d}/api_key.json`],"ASC key upload to remote runner"),p=Ie.join(ht.tmpdir(),`${m.nameLower}-ios-submit-${Date.now()}.sh`),se.writeFileSync(p,Md(d)),Ai("scp",[...u,p,`${a}:${d}/submit.sh`],"submit script upload to remote runner"),s.stop("Remote submit inputs uploaded"),s.start("Uploading to TestFlight on remote runner...");let f=`chmod +x ${Ht(`${d}/submit.sh`)} && bash ${Ht(`${d}/submit.sh`)}`,h=mt("ssh",[...c,f],{stdio:"inherit"});if(h.error)throw Ri("ssh",h.error);if(h.status!==0)throw new Error(`Remote iOS submit failed with exit code ${h.status}.`);return s.stop("IPA uploaded to TestFlight"),{apiKeyJsonPath:null}}catch(f){throw s.stop("Remote iOS submit failed"),f}finally{try{se.unlinkSync(l)}catch{}if(p)try{se.unlinkSync(p)}catch{}if(d)try{mt("ssh",[...c,`rm -rf ${Ht(d)}`],{stdio:"ignore"})}catch{}}}function ho(e,t,n){let i=se.readFileSync(e,"utf8"),r;try{r=vi.createPrivateKey(i).export({type:"pkcs8",format:"pem"})}catch{fe("Key normalization failed, falling back to manual re-wrapping..."),r=`-----BEGIN PRIVATE KEY-----
|
|
1378
|
+
`).map(r=>r.trim().split(/\s+/)).filter(r=>r.length>=2&&r[1]==="device").map(r=>r[0]).filter(Boolean);return e&&i.includes(e)?(L.appendFileSync(t,`Using Android device ${e} for install and cleanup.
|
|
1379
|
+
`),e):i.length===1?(L.appendFileSync(t,`Using Android device ${i[0]} for install and cleanup.
|
|
1380
|
+
`),i[0]):(i.length>1&&L.appendFileSync(t,`[WARN] Multiple Android devices are connected; using adb default target for install and cleanup.
|
|
1381
|
+
`),null)}function vd(e,t){let i=(hi("aapt",["dump","badging",e])||hi("aapt2",["dump","badging",e]))?.match(/package:\s+name='([^']+)'/);if(i?.[1])return i[1];let o=hi("apkanalyzer",["manifest","application-id",e])?.split(/\s+/).find(Boolean);return o||(L.appendFileSync(t,`[WARN] Could not determine Android application id from APK; post-run uninstall will be skipped.
|
|
1382
|
+
`),null)}function hi(e,t){for(let n of Pd(e)){let i=Ge(n,t,{encoding:"utf-8",env:process.env,maxBuffer:10485760});if(i.status===0&&i.stdout)return String(i.stdout).trim()}return null}function Pd(e){let t=process.platform==="win32"&&!e.endsWith(".exe")?`${e}.exe`:e,n=[];if(e==="aapt"||e==="aapt2")for(let r of lo()){let o=Y.join(r,"build-tools");for(let s of co(o))n.push(Y.join(o,s,t))}if(e==="apkanalyzer")for(let r of lo()){n.push(Y.join(r,"cmdline-tools","latest","bin",t));let o=Y.join(r,"cmdline-tools");for(let s of co(o))n.push(Y.join(o,s,"bin",t));n.push(Y.join(r,"tools","bin",t))}let i=Od(e);return i&&n.unshift(i),n.push(t),[...new Set(n)]}function lo(){let e=[process.env.ANDROID_HOME,process.env.ANDROID_SDK_ROOT];return process.platform==="darwin"?e.push(Y.join(Tt.homedir(),"Library","Android","sdk")):process.platform==="linux"&&e.push(Y.join(Tt.homedir(),"Android","Sdk"),Y.join(Tt.homedir(),"Android","sdk"),"/opt/android-sdk","/usr/lib/android-sdk"),[...new Set(e.filter(t=>!!t))]}function co(e){try{return L.readdirSync(e,{withFileTypes:!0}).filter(t=>t.isDirectory()).map(t=>t.name).sort((t,n)=>n.localeCompare(t,void 0,{numeric:!0}))}catch{return[]}}function Od(e){let t=process.platform==="win32"?"where":"/usr/bin/env",n=process.platform==="win32"?[e]:["which",e],i=Ge(t,n,{encoding:"utf-8",env:process.env});return i.status!==0||!i.stdout?null:String(i.stdout).split(`
|
|
1383
|
+
`)[0]?.trim()||null}async function Si(e,t,n){if(!L.existsSync(e))return;let i=L.readFileSync(e),r;for(let o=1;o<=3;o+=1)try{await zt.put(t,i,{headers:{"Content-Type":n,"Content-Length":String(i.length)},maxBodyLength:1/0,maxContentLength:1/0,timeout:12e4});return}catch(s){if(r=s,!ho(s)||o>=3)break;await wi(2e3*o)}throw r}async function uo(e,t,n,i){let r=Y.join(n,"report.xml"),o=Y.join(t,"artifacts.tar.gz");try{await Si(r,e.junitUploadUrl,"application/xml")}catch(s){L.appendFileSync(i,`[WARN] Failed to upload JUnit report: ${s.message||s}
|
|
1384
|
+
`)}try{await Si(i,e.logUploadUrl,"text/plain")}catch(s){L.appendFileSync(i,`[WARN] Failed to upload runner log: ${s.message||s}
|
|
1385
|
+
`)}try{ot("tar",["-czf",o,"-C",t,Y.basename(n)],i),await Si(o,e.artifactsUploadUrl,"application/gzip")}catch(s){L.appendFileSync(i,`[WARN] Failed to upload Maestro artifacts: ${s.message||s}
|
|
1386
|
+
`)}}function Dd(e){if(!e.endsWith(".apk"))return F.error(K.red("Local Android Maestro runs need an APK artifact.")),!1;F.info(K.dim("Installing APK on local Android device/emulator..."));let t=Ge("adb",["install","-r",e],{stdio:"inherit",env:process.env});return t.error?(F.error(K.red(`adb failed to start: ${t.error.message}`)),!1):t.status!==0?(F.error(K.red(`adb install failed with exit code ${t.status??1}`)),!1):!0}function Cd(e,t){if(e.endsWith(".ipa"))return F.error(K.red("Local iOS Maestro runs need an iOS Simulator .app.zip artifact, not an App Store .ipa.")),!1;let n=e;if(e.endsWith(".zip")){let r=Y.join(t,"ios-app");L.mkdirSync(r,{recursive:!0}),new En(e).extractAllTo(r,!0);let o=_i(r);if(!o)return F.error(K.red("Could not find a .app bundle inside the downloaded zip.")),!1;n=o}if(!n.endsWith(".app"))return F.error(K.red("Local iOS Maestro runs need an iOS Simulator .app bundle or .app.zip artifact.")),!1;F.info(K.dim("Installing app on booted iOS Simulator..."));let i=Ge("xcrun",["simctl","install","booted",n],{stdio:"inherit",env:process.env});return i.error?(F.error(K.red(`xcrun failed to start: ${i.error.message}`)),!1):i.status!==0?(F.error(K.red(`iOS Simulator install failed with exit code ${i.status??1}`)),!1):!0}function _i(e){let t=L.readdirSync(e,{withFileTypes:!0});for(let n of t){let i=Y.join(e,n.name);if(n.isDirectory()&&n.name.endsWith(".app"))return i;if(n.isDirectory()){let r=_i(i);if(r)return r}}return null}function Nd(e,t){let n=String(t||"").toLowerCase();return n==="android"?e.find(i=>Nt(i,".apk")):n==="ios"?e.find(i=>Nt(i,".app.zip"))||e.find(i=>Nt(i,".zip")):e.find(i=>Nt(i,".apk"))||e.find(i=>Nt(i,".app.zip"))||e.find(i=>Nt(i,".zip"))}function Nt(e,t){return String(e?.name||e?.downloadUrl||e?.url||"").toLowerCase().endsWith(t)}function Ri(e){let t=String(e||"").toLowerCase();if(t.includes(".apk"))return"android";if(t.includes(".app.zip")||t.endsWith(".app")||t.includes(".ipa"))return"ios"}function Io(e){if(e)try{return Y.basename(new URL(e).pathname)||void 0}catch{return Y.basename(e)||void 0}}function Td(e){return e?e.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i)?.[0]:void 0}function wo(e,t){if(!e.jsonOutput)return;let n=Y.resolve(e.jsonOutput),i={...t,updatedAt:new Date().toISOString()};try{let r=Y.dirname(n);r&&r!=="."&&L.mkdirSync(r,{recursive:!0}),L.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){F.warn(K.yellow(`Could not write Maestro metadata JSON: ${r.message}`))}}function kd(e,t){if(!e.jsonOutput)return;let n=Y.resolve(e.jsonOutput),i={mode:"local",...t,updatedAt:new Date().toISOString()};try{let r=Y.dirname(n);r&&r!=="."&&L.mkdirSync(r,{recursive:!0}),L.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){F.warn(K.yellow(`Could not write Maestro metadata JSON: ${r.message}`))}}import{spinner as ut,text as Yt,select as Di,isCancel as dt,cancel as Ci,log as Do}from"@clack/prompts";import ne from"chalk";import oe from"fs";import Ie from"path";import{spawn as xd,spawnSync as It}from"child_process";import Co from"axios";import _t from"os";import ki from"crypto";var Ld=5e3,Md=12,No=100,$i=24,_o=8e3,Ud={completed:"completed",draft:"draft",halted:"halted",inprogress:"inProgress","in-progress":"inProgress"},Fd=e=>e?.type==="google_service_account",In=e=>e?.bundleId||e?.packageName||e?.meta?.packageName||e?.meta?.bundleId,To=e=>e.submitArgs||process.argv.slice(3).join(" ");async function wn(e){let t=ut(),n=Pe(),i=Bd(e);if(!i){process.exitCode=1;return}let r=e.projectId||i.projectId,o=e.profile||e.buildProfile||"production";if(!r){le(`${m.configFileName} is missing projectId. Pass --project-id in runner mode.`),process.exitCode=1;return}i.projectId=r,me(ne.dim(`Submit for project: ${i.name||r} | Profile: ${o}`));let s=e.platform;if(!s){let h=await Di({message:"Select platform to submit:",options:[{value:"ios",label:"iOS (App Store Connect / TestFlight)"},{value:"android",label:"Android (Google Play Console)"}]});if(dt(h)){Ci("Operation cancelled");return}s=h}if(s=String(s).toLowerCase(),s!=="ios"&&s!=="android"){le(`Platform ${s} is not supported. Use 'ios' or 'android'.`),process.exitCode=1;return}let l=s==="ios"&&!e.local&&e.sshHost?nc(i,o,e):null;if(s==="ios"&&!e.local&&!l){await Hd(i,o,e);return}let a=e.submitId,c=!!(e.local&&a),u=a||null,d=async(h,M={})=>{u&&await Vd(r,u,{status:h,...M})},f=s==="android"?e.packageName||e.androidPackage||Qd(i,o):void 0,p=s==="ios"?e.bundleId||e.iosBundleIdentifier||tc(i,o):void 0,g,y,_,D=!1;try{s==="android"&&(g=e.track||i.submit?.[o]?.android?.track||i.submit?.production?.android?.track||"internal",y=ic(i,o,e.releaseStatus),_=oc(i,o,e.rollout),D=sc(i,o,e.changesNotSentForReview),ac(y,_))}catch(h){le(h.message),process.exitCode=1;return}if(s==="android"&&!c&&(u=await jd(i,r,s,o,e,{packageName:f,track:g,releaseStatus:y,rollout:_,changesNotSentForReview:D}),!u)){le("Could not create submission tracking record. Submission was not started."),process.exitCode=1;return}await d("running",{platform:s,profile:o,packageName:f,track:g,releaseStatus:y,rollout:_,startTime:Date.now(),...c?Wd():{}});let b=null,x=null;try{x=await lc(r,s,e,n?.token),b=x?.filePath||null}catch(h){await d("failed",{error:`Failed to resolve submission artifact: ${h.message}`,endTime:Date.now()}),le(`Failed to resolve submission artifact: ${h.message}`),process.exitCode=1;return}if(!b){let h=cc(s,e);await d("failed",{error:h,endTime:Date.now()}),le(h),process.exitCode=1;return}await d("running",{buildId:x?.buildId,artifactName:x?.artifactName,artifactSource:x?.source}),me(`Using artifact: ${ne.green(Ie.basename(b))} `),t.start("Fetching submission credentials from Dashboard...");let A;try{let M=(await k.get(`/credentials/${r}`)).data.credentials||[];if(s==="android"&&!f){t.stop("Package name missing"),le("Could not resolve Android package name. Set android.package in mach.config.json/app.json."),await d("failed",{error:"Could not resolve Android package name.",endTime:Date.now()}),process.exitCode=1;return}let U=M.filter(Fd),j=s==="ios"?M.filter(X=>X.type==="asc_api_key"):ec(U,f);if(j.length===0){if(t.stop("Credentials missing"),le(s==="android"?`No Google Play service credential found for package ${f}.`:`No Service Credentials found for ${s}.`),s==="android"){let X=U.map(In).filter(Boolean).join(", ");X&&me(`Found Google Play service credential(s) for: ${X}`),me(`Use '${m.nameLower} credentials:service --platform android --package-name ${f}' or upload it under that package in the Dashboard.`)}else me(`Use '${m.nameLower} credentials:service --platform ${s}' or use the Dashboard to upload them.`);await d("failed",{error:`No submission credentials found for ${s}.`,endTime:Date.now()}),process.exitCode=1;return}if(A=Jd(j,e.credentialId),!A&&s==="ios"&&p&&(A=Xd(j,p)),A||j.length===1)A=A||j[0],t.stop(`Using: ${A.name}`),s==="android"&&In(A)==="*"&&me(ne.yellow(`Using legacy wildcard Google Play credential for ${f}. Upload a package-scoped credential when possible.`));else{if(t.stop("Multiple credentials found"),qd()){let H=j.map(N=>`${N.name||"credential"} (${N.credentialId||N.id||"no-id"})`).join(", ");le(`Multiple ${s==="ios"?"App Store Connect":"Google Play"} credentials found. Use --credential-id in CI. Available: ${H}`),await d("failed",{error:"Multiple submission credentials found; --credential-id is required in CI.",endTime:Date.now()}),process.exitCode=1;return}let X=await Di({message:`Choose a ${s==="ios"?"App Store Connect":"Google Play"} credential:`,options:j.map(H=>({value:H.credentialId,label:H.name,hint:`${H.keyId?`ID: ${H.keyId}`:""} ${H.issuerId?`(Issuer: ${H.issuerId.substring(0,8)}...)`:""}`}))});if(dt(X)){Ci("Submission cancelled"),await d("failed",{error:"Submission cancelled while selecting credential.",endTime:Date.now()}),process.exitCode=1;return}A=j.find(H=>H.credentialId===X),me(`Using selected: ${ne.green(A.name)}`)}}catch(h){t.stop("Failed to fetch credentials"),le(`API Error: ${h.message} `),await d("failed",{error:`Failed to fetch credentials: ${h.message}`,endTime:Date.now()}),process.exitCode=1;return}let B=oe.mkdtempSync(Ie.join(_t.tmpdir(),`${m.nameLower}-submit-`)),q=A.keyId||A.meta?.keyId,P=A.issuerId||A.meta?.issuerId,I=A.type==="asc_api_key"?`AuthKey_${q}.p8`:"service-account.json",T=Ie.join(B,I);t.start("Downloading secure key...");try{let h=await k.get(`/credentials/${A.credentialId}/download`,{params:{projectId:r,format:"raw"}});if(h.data.status!=="success"||!h.data.downloadUrl)throw new Error("Failed to get secure download URL");let M=await Co.get(h.data.downloadUrl,{responseType:"arraybuffer"});oe.writeFileSync(T,Buffer.from(M.data)),t.stop("Key downloaded to secure temp storage")}catch(h){t.stop("Download failed"),le(`Failed to download key: ${h.message}`);try{oe.rmSync(B,{recursive:!0,force:!0})}catch{}await d("failed",{error:`Failed to download credential key: ${h.message}`,endTime:Date.now()}),process.exitCode=1;return}me(ne.blue(`Initiating ${s==="ios"?"TestFlight":"Google Play"} submission...`));let w=!1,C;try{if(s==="ios"){if(!q){let M=await Yt({message:"Enter App Store Connect Key ID (e.g. 2X948D...):",validate:U=>U.length>0?void 0:"Key ID is required"});if(dt(M)){await d("failed",{error:"Submission cancelled while entering ASC Key ID.",endTime:Date.now()}),process.exitCode=1;return}q=M}if(!P||P==="undefined"){let M=await Yt({message:"Enter App Store Connect Issuer ID (Found on ASC Keys page):",validate:U=>U.length>0?void 0:"Issuer ID is required"});if(dt(M)){await d("failed",{error:"Submission cancelled while entering ASC Issuer ID.",endTime:Date.now()}),process.exitCode=1;return}P=M}me(`Using ASC Key ID: ${q}`),me(`Using ASC Issuer ID: ${P}`);let h=l?await pc(b,T,P,q,p,l):await uc(b,T,P,q,p);Ti(`${s==="ios"?"App Store":"Google Play"} submission successful!`),w=!0}else C=await Sc(b,T,g||"internal",f,y||"completed",_,D,o),Ti("Google Play submission successful!"),w=!0}catch(h){le(`Submission failed: ${h.message}`),await d("failed",{error:h.message,endTime:Date.now()}),ct(e,{status:"failed",projectId:r,submitId:u,platform:s,profile:o,buildId:x?.buildId||e.buildId,artifactName:x?.artifactName,error:h.message,dashboardUrl:u?wt(u,r):void 0}),process.exitCode=1}finally{w&&(await d("success",{endTime:Date.now(),versionCode:C?.versionCode,track:g,releaseStatus:y}),ct(e,{status:"success",projectId:r,submitId:u,platform:s,profile:o,buildId:x?.buildId||e.buildId,artifactName:x?.artifactName,versionCode:C?.versionCode,track:g,releaseStatus:y,dashboardUrl:u?wt(u,r):void 0})),Nc(B),b&&b.includes(`${m.nameLower}-artifact-`)}}function Bd(e){let t=`./${m.configFileName}`;if(oe.existsSync(t))try{return JSON.parse(oe.readFileSync(t,"utf-8"))}catch(n){return le(`Failed to read ${m.configFileName}: ${n.message}`),null}return e.projectId?{projectId:e.projectId}:(le(`No ${m.configFileName} found. Run \`${m.nameLower} init\` or \`${m.nameLower} link\` first.`),null)}async function Hd(e,t,n){let i=n.projectId||e.projectId;if(!i){le(`${m.configFileName} is missing projectId.`),process.exitCode=1;return}let r=n.submitId||ki.randomUUID(),o=!!n.latest||!n.buildId,s=Gd({...n,latest:o,profile:t,projectId:i,submitId:r}),l={projectId:i,submitId:r,platform:"ios",profile:t,latest:o,buildId:n.buildId,credentialId:n.credentialId,status:"pending",source:"cli",submitArgs:To(n),runnerArgs:s,runnerCommand:[m.nameLower,"submit",...s].map(Zd).join(" "),appName:e.name,startTime:Date.now()},a=ut();a.start("Queuing iOS submit on macOS runner...");try{let c=await k.post("/submissions",l),u=c.data?.submission||c.data?.submit||{},d=c.data?.dashboardUrl||wt(r,i);a.stop("iOS submit queued"),me(`Submission ID: ${ne.cyan(r)}`),me(`Dashboard: ${ne.blue.underline(d)}`),ct(n,{status:"pending",projectId:i,submitId:r,platform:"ios",profile:t,latest:o,buildId:n.buildId,dashboardUrl:d}),await Kd(i,r,n)}catch(c){a.stop("Could not queue iOS submit"),le(Yd(c)),process.exitCode=1}}async function jd(e,t,n,i,r,o={}){let s=r.submitId||ki.randomUUID(),l=!!r.latest||!r.buildId,a={projectId:t,submitId:s,platform:n,profile:i,latest:l,buildId:r.buildId,credentialId:r.credentialId,status:"running",source:"cli-direct",submitArgs:To(r),appName:e.name,startTime:Date.now(),...o};try{let c=await k.post("/submissions",a),u=c.data?.submission||c.data?.submit||{},d=c.data?.dashboardUrl||u.dashboardUrl||wt(s,t);return me(`Submission ID: ${ne.cyan(s)}`),me(`Dashboard: ${ne.blue.underline(d)}`),ct(r,{status:"running",projectId:t,submitId:s,platform:n,profile:i,latest:l,buildId:r.buildId,dashboardUrl:d}),s}catch(c){let u=c.response?.data?.message||c.response?.data?.error||c.message;return me(ne.yellow(`Could not create submission tracking record: ${u}`)),null}}function Gd(e){let t=["--local","--submit-id",e.submitId,"--project-id",e.projectId,"--platform","ios","--profile",e.profile||"production"];return e.buildId?t.push("--build-id",e.buildId):t.push("--latest"),e.credentialId&&t.push("--credential-id",e.credentialId),e.bundleId&&t.push("--bundle-id",e.bundleId),e.packageName&&t.push("--package-name",e.packageName),e.quiet&&t.push("--quiet"),e.jsonOutput&&t.push("--json-output",e.jsonOutput),t.filter(n=>n!=null&&n!=="")}async function Kd(e,t,n){let i=ut(),r=0,o=0;for(n.quiet||i.start("Waiting for iOS submit runner...");;)try{let s=await k.get(`/submissions/${e}/${t}`),l=s.data?.submission||s.data?.submit||s.data,a=String(l?.status||"pending").toLowerCase();r=0;let c=Array.isArray(l?.logs)?l.logs:[];for(let u=o;u<c.length;u++){let d=c[u];d&&console.log(ne.dim(String(d)))}if(o=c.length,["success","completed","succeeded"].includes(a)){n.quiet||i.stop("iOS submit completed"),Ti("App Store submission successful!"),ct(n,{status:"success",projectId:e,submitId:t,platform:"ios",profile:l?.profile||n.profile||"production",buildId:l?.buildId||n.buildId,artifactName:l?.artifactName,dashboardUrl:l?.dashboardUrl||wt(t,e)});return}if(["failed","error","cancelled","canceled"].includes(a)){n.quiet||i.stop("iOS submit failed");let u=l?.error||l?.message||"Unknown iOS submit failure.";le(u),ct(n,{status:"failed",projectId:e,submitId:t,platform:"ios",profile:l?.profile||n.profile||"production",buildId:l?.buildId||n.buildId,artifactName:l?.artifactName,error:u,dashboardUrl:l?.dashboardUrl||wt(t,e)}),process.exitCode=1;return}n.quiet||i.message(`iOS submit ${a}...`),await Ni(Ld)}catch(s){if(r++,r>=Md){n.quiet||i.stop("Lost connection to iOS submit status"),le(`Could not fetch iOS submit status after ${r} attempts: ${s.message}`),process.exitCode=1;return}await Ni(Math.min(2e3*r,15e3))}}async function Vd(e,t,n){let i;for(let r=1;r<=3;r++)try{await k.patch(`/submissions/${e}/${t}`,n);return}catch(o){if(i=o,r>=3||!zd(o))break;await Ni(1e3*r)}Do.warn(ne.dim(`Could not report submission status: ${i?.message||i}`))}function zd(e){let t=e.response?.status;return!t||t===408||t===409||t===425||t===429||t>=500}function Wd(){let e={gitlabJobId:process.env.CI_JOB_ID,gitlabJobUrl:process.env.CI_JOB_URL,gitlabPipelineId:process.env.CI_PIPELINE_ID,gitlabProjectId:process.env.CI_PROJECT_ID,gitlabProjectPath:process.env.CI_PROJECT_PATH};return Object.fromEntries(Object.entries(e).filter(([,t])=>!!t))}function Yd(e){let t=e.response?.status,n=e.response?.data?.message||e.response?.data?.error;return t===404||t===405?["Managed iOS submit is not enabled on this Mach API yet.","Deploy the API/dashboard submission orchestration endpoint, then retry the same command.","Expected API: POST /submissions and GET/PATCH /submissions/:projectId/:submitId."].join(`
|
|
1387
|
+
`):n||e.message||String(e)}function wt(e,t){if(!e)return Je;let n=t?`?projectId=${encodeURIComponent(t)}`:"";return`${Je}/submissions/${e}${n}`}function ct(e,t){if(!e.jsonOutput)return;let n=Ie.resolve(e.jsonOutput),i={...t,url:t.url||t.dashboardUrl||wt(t.submitId,t.projectId),updatedAt:new Date().toISOString()};try{let r=Ie.dirname(n);r&&r!=="."&&oe.mkdirSync(r,{recursive:!0}),oe.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){Do.warn(ne.yellow(`Could not write submission metadata JSON: ${r.message}`))}}function Jd(e,t){return t&&e.find(n=>n.credentialId===t||n.id===t||n.keyId===t||n.meta?.keyId===t)||null}function Xd(e,t){let n=e.filter(i=>[i.bundleId,i.bundleIdentifier,i.appIdentifier,i.meta?.bundleId,i.meta?.bundleIdentifier,i.meta?.appIdentifier].filter(Boolean).map(String).includes(t));return n.length===1?n[0]:null}function qd(){return process.env.CI==="true"||process.env.CI==="1"||!process.stdin.isTTY}function Ni(e){return new Promise(t=>setTimeout(t,e))}function Zd(e){return/^[a-zA-Z0-9_./:=@-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function Qd(e,t){if(e.submit?.[t]?.android?.package)return e.submit[t].android.package;let n=hr(e,t);if(n)return n;let i=Ie.join(process.cwd(),"app.json");if(oe.existsSync(i))try{return JSON.parse(oe.readFileSync(i,"utf-8")).expo?.android?.package}catch{}let r=Ie.join(process.cwd(),"app.config.json");if(oe.existsSync(r))try{let o=JSON.parse(oe.readFileSync(r,"utf-8"));return o.expo?.android?.package||o.android?.package}catch{}}function ec(e,t){let n=e.filter(o=>In(o)===t);if(n.length>0)return n;let i=e.filter(o=>{let s=In(o);return!s||s==="*"});return e.length>0&&e.length===i.length?i:[]}function tc(e,t){return e.submit?.[t]?.ios?.bundleIdentifier?e.submit[t].ios.bundleIdentifier:e.submit?.[t]?.ios?.bundleId?e.submit[t].ios.bundleId:Sr(e,t)}function nc(e,t,n){let i=e.submit?.[t]?.ios||{},r=e.submit?.production?.ios||{},o=n.sshHost||i.sshHost||r.sshHost||process.env.MACH_IOS_SUBMIT_SSH_HOST;return o?{sshHost:o,sshUser:n.sshUser||i.sshUser||r.sshUser||process.env.MACH_IOS_SUBMIT_SSH_USER||process.env.USER||"ubuntu",sshKey:n.sshKey||i.sshKey||r.sshKey||process.env.MACH_IOS_SUBMIT_SSH_KEY}:null}function ic(e,t,n){let i=n||e.submit?.[t]?.android?.releaseStatus||e.submit?.production?.android?.releaseStatus||"completed";return rc(i)}function rc(e){let t=Ud[String(e).trim().toLowerCase()];if(!t)throw new Error(`Invalid Android release status "${e}". Use completed, draft, halted, or inProgress.`);return t}function oc(e,t,n){let i=n??e.submit?.[t]?.android?.rollout??e.submit?.[t]?.android?.userFraction??e.submit?.[t]?.android?.rolloutFraction??e.submit?.production?.android?.rollout??e.submit?.production?.android?.userFraction??e.submit?.production?.android?.rolloutFraction;if(i==null||i==="")return;let r=Number(i);if(!Number.isFinite(r)||r<=0||r>=1)throw new Error(`Invalid Android rollout fraction "${i}". Use a number greater than 0 and less than 1, for example 0.1.`);return r}function sc(e,t,n){let i=n??e.submit?.[t]?.android?.changesNotSentForReview??e.submit?.[t]?.android?.changes_not_sent_for_review??e.submit?.production?.android?.changesNotSentForReview??e.submit?.production?.android?.changes_not_sent_for_review??!1;return i===!0||i==="true"||i==="1"}function ac(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 lc(e,t,n,i){let r=n.buildId?"id":n.latest?"latest":null;if(!r){let s=await Di({message:"Select artifact source:",options:[{value:"latest",label:`Latest Production Build (${m.name})`},{value:"id",label:`Input Build ID (${m.name})`},{value:"url",label:"Remote URL"},{value:"local",label:"Local File Path"}]});if(dt(s))return Ci("Operation cancelled"),null;r=s}if(r==="local"){let s=await Yt({message:"Enter path to artifact (.ipa/.aab):",validate:l=>{if(!oe.existsSync(l))return"File not found";if(t==="ios"&&!l.endsWith(".ipa"))return"Must be an .ipa file";if(t==="android"&&!l.endsWith(".aab"))return"Must be an .aab file"}});return dt(s)?null:{filePath:s,source:"local"}}let o=ut();if(r==="latest"){let s=n.profile||n.buildProfile;o.start(`Fetching latest${s?` ${s}`:""} build...`);try{let l=await k.get(`/builds/${e}`,{params:{limit:50}});if(l.data.status!=="success")throw new Error(l.data.message);let a=l.data.builds||[],c=s?.toLowerCase(),u=A=>A.platform?.toLowerCase()===t.toLowerCase()&&A.status?.toLowerCase()==="success",d=A=>c?[A.buildProfile,A.profile,A.profileName,A.buildType].filter(Boolean).some(B=>String(B).toLowerCase()===c):!0,f=a.filter(A=>u(A)&&d(A)),p=f.find(A=>A.buildType?.toLowerCase()==="store"||A.distribution?.toLowerCase()==="store")||f[0],g=a.some(A=>A.platform?.toLowerCase()===t.toLowerCase()&&A.status?.toLowerCase()==="success");if(!p)return o.stop("No suitable build found"),le(s&&g?`No successful ${t} builds found for profile "${s}".`:"No successful builds found for this platform."),null;o.stop(`Found build: ${p.buildId}`);let y=p.artifacts||[];if(y.length===0||y.every(A=>!(A.url||A.downloadUrl)))try{let A=await k.get(`/builds/${e}/${p.buildId}/artifacts`);A.data.status==="success"&&A.data.artifacts?.length>0?(y=A.data.artifacts.map(B=>({...B,url:B.url||B.downloadUrl})),console.log(ne.cyan(` [RECOVERY] Fetched ${y.length} artifact(s) with download URLs.`))):console.log(ne.yellow(" [RECOVERY] /artifacts endpoint returned 0 artifacts."))}catch(A){console.log(ne.red(` [RECOVERY] /artifacts fetch failed: ${A.message}`))}let D=t==="ios",b=y.find(A=>{let B=(A.type||"").toLowerCase(),q=(A.name||"").toLowerCase();if(console.log(ne.dim(` - Checking: ${A.name} (Type: ${A.type}, HasLink: ${!!(A.url||A.downloadUrl)})`)),B)return B===(D?"ipa":"aab");let P=D?".ipa":".aab",I=(A.url||A.downloadUrl||"").toLowerCase();return q.endsWith(P)||I.includes(P)});if(!b||!(b.url||b.downloadUrl))return le("Build found but artifact URL is missing."),null;let x=b.url||b.downloadUrl;return{filePath:await vi(x,D?"ios":"android"),buildId:p.buildId,artifactName:b.name,source:"latest"}}catch(l){return o.stop("Fetch failed"),le(`API Error: ${l.message}`),null}}if(r==="id"){let s=n.buildId||await Yt({message:"Enter Build ID:",validate:a=>a.length<5?"Invalid ID":void 0});if(dt(s))return null;let l=String(s);o.start("Fetching build...");try{let a=null;try{let p=await k.get(`/builds/${e}/${l}`);p.data.status==="success"&&(a=p.data.build)}catch(p){p.response?.status!==404&&console.log(ne.dim(` [RECOVERY] Project build lookup skipped: ${p.message}`))}if(!a){let p=await k.get(`/build/${l}`);if(p.data.status!=="success")throw new Error(p.data.message);a=p.data.build}if(!a)throw new Error(`Build ${l} was not found.`);let c=t==="ios",u=An(a.artifacts);dc(u)||(u=await $o(e,l,u));let d=Ro(u,t);if(d||(u=await $o(e,l,u),d=Ro(u,t)),!d)throw new Error(`No ${c?".ipa":".aab"} artifact found for build ${l}. The build exists, but its artifact list does not contain a downloadable submission artifact.`);let f=d.url||d.downloadUrl;if(!f)throw new Error(`Artifact ${d.name||"(unnamed)"} for build ${l} has no download URL. Retry after the build artifact upload is visible in the Installation Hub.`);return o.stop(`Found build: ${a.buildId||l}`),{filePath:await vi(f,c?"ios":"android"),buildId:a.buildId||l,artifactName:d.name,source:"id"}}catch(a){throw o.stop("Fetch failed"),a}}if(r==="url"){let s=await Yt({message:"Enter Artifact URL:",validate:l=>l.startsWith("http")?void 0:"Must be a valid URL"});return dt(s)?null:{filePath:await vi(s,t),source:"url"}}return null}function An(e){return(e||[]).map(t=>({...t,url:t.url||t.downloadUrl}))}function dc(e){return e.some(t=>!!(t.url||t.downloadUrl))}function Ro(e,t){let n=t==="ios",i=n?"ipa":"aab",r=n?".ipa":".aab";return e.find(o=>{let s=String(o.type||"").toLowerCase(),l=String(o.name||"").toLowerCase(),a=String(o.url||o.downloadUrl||"").toLowerCase();return s?s===i:l.endsWith(r)||a.includes(r)})||null}function cc(e,t){let n=e==="ios"?".ipa":".aab";if(t.buildId)return`No downloadable ${n} artifact found for build ${t.buildId}. Check that the build finished artifact upload before submitting.`;if(t.latest){let i=t.profile||t.buildProfile;return`No latest successful ${e}${i?` ${i}`:""} build has a downloadable ${n} artifact.`}return`No downloadable ${n} artifact was selected for submission.`}async function $o(e,t,n){try{let i=await k.get(`/builds/${e}/${t}/artifacts`);if(i.data.status==="success"&&i.data.artifacts?.length>0){let r=An(i.data.artifacts);return console.log(ne.cyan(` [RECOVERY] Fetched ${r.length} artifact(s) with download URLs.`)),r}}catch(i){console.log(ne.dim(` [RECOVERY] Project artifact lookup skipped: ${i.message}`))}try{let i=await k.get(`/public/builds/${t}`);if(i.data.status==="success"&&i.data.artifacts?.length>0){let r=An(i.data.artifacts);return console.log(ne.cyan(` [RECOVERY] Fetched ${r.length} public artifact(s) with download URLs.`)),r}}catch(i){console.log(ne.dim(` [RECOVERY] Public artifact lookup skipped: ${i.message}`))}return An(n)}async function vi(e,t,n=3){let i=ut();i.start("Downloading artifact...");let r=oe.mkdtempSync(Ie.join(_t.tmpdir(),`${m.nameLower}-artifact-`)),o=`app.${t==="ios"?"ipa":"aab"}`,s=Ie.join(r,o);for(let l=1;l<=n;l++)try{l>1&&(i.message(`Downloading artifact (Retry ${l}/${n})...`),await new Promise(u=>setTimeout(u,2e3*l)));let a=oe.createWriteStream(s),c=await Co({url:e,method:"GET",responseType:"stream",timeout:6e4});return await new Promise((u,d)=>{c.data.pipe(a);let f=!1;c.data.on("error",p=>{f||(f=!0,a.close(),d(p))}),a.on("finish",()=>{f||u()}),a.on("error",p=>{f||(f=!0,d(p))})}),i.stop("Download complete"),s}catch(a){if(l===n)throw i.stop("Download failed"),a}throw new Error("Download failed after retries")}async function uc(e,t,n,i,r){let o=ut();if(r&&me(`Bundle ID: ${ne.green(r)}`),!n||!i)throw le(`Missing credentials: issuerId=${n}, keyId=${i}. Check your Dashboard.`),new Error("Missing ASC API Key Metadata (IssuerID or KeyID)");let s=ko(t,n,i),l=bc();return o.start("Uploading to TestFlight (pilot)..."),new Promise((a,c)=>{let u=Ac(),d=xd(l.command,["pilot","upload","--ipa",e,"--api_key_path",s,"--skip_submission","true","--skip_waiting_for_build_processing","true"],{stdio:["ignore","pipe","pipe"],env:l.env});d.stdout?.on("data",f=>u.append(f,process.stdout)),d.stderr?.on("data",f=>u.append(f,process.stderr)),d.on("close",f=>{if(u.flush(),f!==0){o.stop("Pilot failed");try{oe.unlinkSync(s)}catch{}c(Ic(f,u.lines()))}else{o.stop("IPA uploaded to TestFlight");try{oe.unlinkSync(s)}catch{}a({})}}),d.on("error",f=>{u.flush();try{oe.unlinkSync(s)}catch{}o.stop("Pilot execution error");let p=Dc(f);p.logs=u.lines(),c(p)})})}async function pc(e,t,n,i,r,o){let s=ut();if(r&&me(`Bundle ID: ${ne.green(r)}`),!n||!i)throw le(`Missing credentials: issuerId=${n}, keyId=${i}. Check your Dashboard.`),new Error("Missing ASC API Key Metadata (IssuerID or KeyID)");let l=ko(t,n,i),a=`${o.sshUser}@${o.sshHost}`,c=fc(o),u=mc(o),d="",f="";try{if(s.start(`Preparing remote iOS submit runner (${a})...`),d=gc("ssh",[...c,"mktemp -d /tmp/mach-submit.XXXXXX"]).trim(),!d)throw new Error("Remote runner did not return a temp directory.");s.stop(`Remote runner ready: ${a}`),s.start("Uploading IPA and App Store Connect key to remote runner..."),Pi("scp",[...u,e,`${a}:${d}/app.ipa`],"IPA upload to remote runner"),Pi("scp",[...u,l,`${a}:${d}/api_key.json`],"ASC key upload to remote runner"),f=Ie.join(_t.tmpdir(),`${m.nameLower}-ios-submit-${Date.now()}.sh`),oe.writeFileSync(f,hc(d)),Pi("scp",[...u,f,`${a}:${d}/submit.sh`],"submit script upload to remote runner"),s.stop("Remote submit inputs uploaded"),s.start("Uploading to TestFlight on remote runner...");let p=`chmod +x ${Jt(`${d}/submit.sh`)} && bash ${Jt(`${d}/submit.sh`)}`,g=It("ssh",[...c,p],{stdio:"inherit"});if(g.error)throw xi("ssh",g.error);if(g.status!==0)throw new Error(`Remote iOS submit failed with exit code ${g.status}.`);return s.stop("IPA uploaded to TestFlight"),{apiKeyJsonPath:null}}catch(p){throw s.stop("Remote iOS submit failed"),p}finally{try{oe.unlinkSync(l)}catch{}if(f)try{oe.unlinkSync(f)}catch{}if(d)try{It("ssh",[...c,`rm -rf ${Jt(d)}`],{stdio:"ignore"})}catch{}}}function ko(e,t,n){let i=oe.readFileSync(e,"utf8"),r;try{r=ki.createPrivateKey(i).export({type:"pkcs8",format:"pem"})}catch{me("Key normalization failed, falling back to manual re-wrapping..."),r=`-----BEGIN PRIVATE KEY-----
|
|
1291
1388
|
${(i.replace(/-----BEGIN[^-]*-----/g,"").replace(/-----END[^-]*-----/g,"").replace(/\s+/g,"").match(/.{1,64}/g)||[]).join(`
|
|
1292
1389
|
`)}
|
|
1293
|
-
-----END PRIVATE KEY-----`}let o=Ie.join(
|
|
1390
|
+
-----END PRIVATE KEY-----`}let o=Ie.join(_t.tmpdir(),`api_key_${n}_${Date.now()}.json`),s={key_id:n,issuer_id:t,key:r,in_house:!1};return oe.writeFileSync(o,JSON.stringify(s,null,2)),o}function fc(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 mc(e){let t=["-o","StrictHostKeyChecking=no","-o","ServerAliveInterval=30"];return e.sshKey&&t.push("-i",e.sshKey),t}function gc(e,t){let n=It(e,t,{encoding:"utf-8",stdio:["ignore","pipe","inherit"]});if(n.error)throw xi(e,n.error);if(n.status!==0)throw new Error(`${e} failed with exit code ${n.status}.`);return n.stdout||""}function Pi(e,t,n){let i=It(e,t,{stdio:"inherit"});if(i.error)throw xi(e,i.error);if(i.status!==0)throw new Error(`${n} failed with exit code ${i.status}.`)}function xi(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 Jt(e){return`'${e.replace(/'/g,"'\\''")}'`}function hc(e){let t=Jt(`${e}/app.ipa`),n=Jt(`${e}/api_key.json`);return`#!/bin/bash
|
|
1294
1391
|
set -euo pipefail
|
|
1295
1392
|
|
|
1296
1393
|
export PATH="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:$HOME/.local/share/fastlane/3.4.0/bin:$PATH"
|
|
@@ -1318,39 +1415,39 @@ fastlane pilot upload \\
|
|
|
1318
1415
|
--api_key_path ${n} \\
|
|
1319
1416
|
--skip_submission true \\
|
|
1320
1417
|
--skip_waiting_for_build_processing true
|
|
1321
|
-
`}async function
|
|
1418
|
+
`}async function Sc(e,t,n="internal",i,r="completed",o,s=!1,l="production"){let a=ut();if(!i||i==="*")throw new Error("Android package name is required for Google Play submission.");let c=o!==void 0?` (${o} rollout)`:"";a.start(`Uploading to Google Play ${n} track with ${r} release status${c}...`);try{let u=JSON.parse(oe.readFileSync(t,"utf-8"));yc(u);let d=await Mr({packageName:i,serviceAccount:u,aabPath:e,track:n,releaseStatus:r,userFraction:o,changesNotSentForReview:s});return a.stop(`AAB uploaded to ${n} track (versionCode ${d.versionCode})`),d}catch(u){throw a.stop("Google Play upload failed"),new Error(Cc(u,n,i,l))}}function yc(e){if(!e?.client_email||!e?.private_key)throw new Error("Invalid Google service account JSON: missing client_email or private_key.")}function Oi(){let e=process.env.HOME||_t.homedir(),t=process.env.FASTLANE_GEM_HOME||Ie.join(e,".local/share/fastlane/3.4.0"),n=[process.env.FASTLANE_BIN_DIR,"/usr/local/opt/ruby/bin","/opt/homebrew/opt/ruby/bin","/usr/local/bin","/opt/homebrew/bin","/usr/local/Cellar/fastlane/2.227.0/libexec/bin",Ie.join(t,"bin"),process.env.PATH].filter(Boolean).join(":");return{...process.env,PATH:n,GEM_HOME:t,GEM_PATH:[t,"/usr/local/Cellar/fastlane/2.227.0/libexec",process.env.GEM_PATH].filter(Boolean).join(":"),FASTLANE_INSTALLED_VIA_HOMEBREW:"true",FASTLANE_SKIP_UPDATE_CHECK:"1",FASTLANE_HIDE_CHANGELOG:"1",LANG:process.env.LANG||"en_US.UTF-8",LC_ALL:process.env.LC_ALL||"en_US.UTF-8",CI:process.env.CI||"1"}}function bc(){let e=Oi(),t=vo(e);if(t)return t;if(process.env.MACH_SKIP_FASTLANE_INSTALL!=="1"){Ec(e);let n=vo(Oi());if(n)return n}return{command:"fastlane",env:Oi()}}function vo(e){let t=process.env.HOME||_t.homedir(),n=[process.env.FASTLANE_BINARY,"/usr/local/bin/fastlane","/opt/homebrew/bin/fastlane","/usr/local/Cellar/fastlane/2.227.0/libexec/bin/fastlane",Ie.join(process.env.FASTLANE_GEM_HOME||Ie.join(t,".local/share/fastlane/3.4.0"),"bin/fastlane"),"fastlane"].filter(Boolean);for(let i of n){if(i.includes("/")&&!oe.existsSync(i))continue;if(!It(i,["--version"],{env:e,stdio:"ignore"}).error)return{command:i,env:e}}return null}function Ec(e){let t=It("gem",["--version"],{env:e,stdio:"ignore"});if(t.error||t.status!==0)return;let n=process.env.HOME||_t.homedir(),i=process.env.FASTLANE_GEM_HOME||Ie.join(n,".local/share/fastlane/3.4.0"),r=Ie.join(i,"bin");oe.mkdirSync(r,{recursive:!0}),me(ne.dim("fastlane not found. Installing fastlane into the local Mach runner cache..."));let o=It("gem",["install","fastlane","-NV","--install-dir",i,"--bindir",r],{env:{...e,GEM_HOME:i,GEM_PATH:[i,e.GEM_PATH].filter(Boolean).join(":")},stdio:"inherit"});(o.error||o.status!==0)&&me(ne.yellow("Automatic fastlane install failed; Mach will try PATH resolution once more."))}function Ac(e=No){let t=[],n="",i=r=>{let o=Lo(r);if(o)for(t.push(o);t.length>e;)t.shift()};return{append(r,o){let s=Buffer.isBuffer(r)?r.toString("utf8"):String(r);o.write(s),n+=s;let l=n.split(/\r?\n/);n=l.pop()||"";for(let a of l)i(a)},flush(){n.trim()&&i(n),n=""},lines(){return t.slice()}}}function Ic(e,t){let n=new Error(wc(e,t));return n.logs=xo(t),n.exitCode=e,n}function wc(e,t){let n=`fastlane pilot failed with exit code ${e??"unknown"}.`,i=_c(t);return i.length===0?n:`${n}
|
|
1322
1419
|
|
|
1323
1420
|
Fastlane output:
|
|
1324
1421
|
${i.join(`
|
|
1325
|
-
`)}`}function
|
|
1326
|
-
`),n=t.match(/CFBundleShortVersionString\s*\[([^\]]+)\]/i)?.[1]||t.match(/train version ['"]([^'"]+)['"]/i)?.[1];if(/Invalid Pre-Release Train/i.test(t)||/CFBundleShortVersionString[\s\S]*must contain a higher version/i.test(t))return[`App Store Connect rejected CFBundleShortVersionString${n?` ${n}`:""}: this App Store version train is closed or not higher than the approved version.`,'ios.buildNumber="auto" only changes CFBundleVersion; bump the marketing version (Expo app.json "expo.version" / iOS MARKETING_VERSION), rebuild, then submit the new build.'].join(" ");if(!/bundle version must be higher than the previously uploaded version/i.test(t))return null;let i=t.match(/previous(?:ly)?BundleVersion\s*:\s*([0-9.]+)/i)?.[1]||t.match(/previously uploaded version:\s*[‘'"]?([0-9.]+)/i)?.[1];return`App Store Connect rejected CFBundleVersion: the bundle version must be higher than the previously uploaded version.${i?` Previous uploaded build: ${i}.`:""}`}function
|
|
1327
|
-
`))}function
|
|
1422
|
+
`)}`}function _c(e){let t=xo(e);if(t.length===0)return[];let n=Po(t.filter($c)),i=Rc(t);if(i)return[i,...Oo(n,$i-1,_o)];let r=n.length>0?n:t.slice(-$i);return Oo(Po(r),$i,_o)}function Rc(e){let t=e.join(`
|
|
1423
|
+
`),n=t.match(/CFBundleShortVersionString\s*\[([^\]]+)\]/i)?.[1]||t.match(/train version ['"]([^'"]+)['"]/i)?.[1];if(/Invalid Pre-Release Train/i.test(t)||/CFBundleShortVersionString[\s\S]*must contain a higher version/i.test(t))return[`App Store Connect rejected CFBundleShortVersionString${n?` ${n}`:""}: this App Store version train is closed or not higher than the approved version.`,'ios.buildNumber="auto" only changes CFBundleVersion; bump the marketing version (Expo app.json "expo.version" / iOS MARKETING_VERSION), rebuild, then submit the new build.'].join(" ");if(!/bundle version must be higher than the previously uploaded version/i.test(t))return null;let i=t.match(/previous(?:ly)?BundleVersion\s*:\s*([0-9.]+)/i)?.[1]||t.match(/previously uploaded version:\s*[‘'"]?([0-9.]+)/i)?.[1];return`App Store Connect rejected CFBundleVersion: the bundle version must be higher than the previously uploaded version.${i?` Previous uploaded build: ${i}.`:""}`}function $c(e){return/\[!\]|ERROR ITMS-\d+|ITMS-\d+|ENTITY_ERROR|previousBundleVersion|CFBundleVersion|Application Loader Error Output|Transporter Error|Transporter transfer failed|Asset validation failed|Validation failed|Error Domain=|The request could not be completed|No suitable application records|Could not|authentication|unauthori[sz]ed|invalid|failed|exception/i.test(e)}function Po(e){let t=new Set,n=[];for(let i of e){let r=i.trim();!r||t.has(r)||(t.add(r),n.push(i))}return n}function Oo(e,t,n){let i=[],r=0;for(let o=e.length-1;o>=0&&i.length<t;o--){let s=e[o],l=r+s.length+1;if(l>n&&i.length>0)break;i.unshift(s.length>n?`${s.slice(0,n-18)}... [truncated]`:s),r=l}return i}function xo(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let i=String(n).split(/\r?\n/);for(let r of i){let o=Lo(r);o&&t.push(o)}}return t.slice(-No)}function Lo(e){return Pc(vc(e).trimEnd()).trim()}function vc(e){return e.replace(/[\u001b\u009b][[\]()#;?]*(?:(?:(?:[a-zA-Z\d]*(?:;[a-zA-Z\d]*)*)?\u0007)|(?:(?:\d{1,4}(?:;\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]))/g,"")}function Pc(e){let t=e.replace(/-----BEGIN [^-]+-----[\s\S]*?-----END [^-]+-----/g,"[REDACTED_PRIVATE_KEY]").replace(/(authorization:\s*bearer\s+)[A-Za-z0-9._-]+/ig,"$1[REDACTED]").replace(/((?:password|token|secret|private[_-]?key)\s*[:=]\s*)("[^"]+"|'[^']+'|[^\s,]+)/ig,"$1[REDACTED]");for(let[n,i]of Object.entries(process.env))!i||i.length<8||/(TOKEN|SECRET|PASSWORD|PASS|PRIVATE|CREDENTIAL)/i.test(n)&&(t=t.replace(new RegExp(Oc(i),"g"),"[REDACTED]"));return t}function Oc(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Dc(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(`
|
|
1424
|
+
`))}function Cc(e,t,n,i="production"){let r=e?.message||String(e);if(/changesNotSentForReview/i.test(r))return["Google Play rejected the commit because this change may need explicit review handling.",`Package: ${n||"unknown"} | Track: ${t}`,`Retry with: ${m.nameLower} submit --latest --platform android --profile ${i} --track ${t} --changes-not-sent-for-review`,"Then send the change for review from Google Play Console if required."].join(`
|
|
1328
1425
|
`);if(/caller does not have permission|permission denied|insufficient permissions|not authorized/i.test(r))return["Google Play rejected the service account permissions.",`Package: ${n||"unknown"} | Track: ${t}`,"Grant this service account access to the app in Play Console with release permissions, then retry."].join(`
|
|
1329
1426
|
`);if(/package.*not found|application.*not found|no application was found/i.test(r))return["Google Play could not find this package for the selected service account.",`Package: ${n||"unknown"} | Track: ${t}`,"Check android.package / submit.<profile>.android.package and make sure the app exists in this Play Console account."].join(`
|
|
1330
1427
|
`);if(/only releases with status draft|draft app/i.test(r))return["Google Play requires a draft release for this app state.",`Package: ${n||"unknown"} | Track: ${t}`,`Retry with: ${m.nameLower} submit --latest --platform android --profile ${i} --track ${t} --release-status draft`].join(`
|
|
1331
1428
|
`);if(r.includes("does not allow any existing users to upgrade"))return["Google Play rejected this release because the uploaded AAB is not an upgrade for existing users.",`Package: ${n||"unknown"} | Track: ${t}`,"Build a new Android artifact with a higher versionCode, then submit that build.",`Recommended: ${m.nameLower} build --platform android --profile ${i} --auto-version`,`Then: ${m.nameLower} submit --latest --platform android --profile ${i} --track ${t}`].join(`
|
|
1332
1429
|
`);if(/version code \d+ has already been used/i.test(r))return[r.match(/version code \d+ has already been used[^\n]*/i)?.[0]||"Version code has already been used.",`Package: ${n||"unknown"} | Track: ${t}`,"Build a new Android artifact with a higher versionCode, then submit that build.",`Recommended: ${m.nameLower} build --platform android --profile ${i} --auto-version`].join(`
|
|
1333
|
-
`);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 Zd(e){try{se.existsSync(e)&&se.rmSync(e,{recursive:!0,force:!0})}catch{}}function le(e){console.log(ne.red(`\u274C ${e}`))}function fe(e){console.log(ne.gray(`\u2022 ${e}`))}function $i(e){console.log(ne.green(`\u2713 ${e}`))}var Pi=8,tc=6,_o=Number(process.env.MACH_ARTIFACT_UPLOAD_MAX_ATTEMPTS||2),Oi=Number(process.env.MACH_ARTIFACT_UPLOAD_TIMEOUT_MS||12e4),nc=[{value:"production",label:"production",hint:"Store / release build"},{value:"staging",label:"staging",hint:"Internal testing build"},{value:"development",label:"development",hint:"Development build"}],Lo=e=>new Promise(t=>setTimeout(t,e)),ic=e=>!e.yes&&!e.failOnly&&!e.buildId&&process.stdin.isTTY&&process.stdout.isTTY,rc=e=>{if(!e||typeof e!="object")return;let t=[e.distribution?`distribution: ${e.distribution}`:void 0,e.environment?`env: ${e.environment}`:void 0,e.developmentClient?"development client":void 0,e.simulator?"simulator":void 0].filter(Boolean);return t.length>0?t.join(", "):void 0},oc=()=>{let e=$e(`./${m.configFileName}`),t=e?.build&&typeof e.build=="object"?e.build:{},n=Object.keys(t);return n.length===0?nc:n.map(i=>({value:i,label:i,hint:rc(t[i])}))},sc=async e=>{let t=ic(e);if(!e.platform&&t){let n=await bo({message:"Select platform",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"}]});In(n)&&(Eo("Build cancelled."),process.exit(0)),e.platform=n}if(!e.buildProfile&&t){let n=oc(),i=await bo({message:"Select build profile",options:n,initialValue:n.find(r=>r.value==="production")?.value||n[0]?.value});In(i)&&(Eo("Build cancelled."),process.exit(0)),e.buildProfile=i}e.buildProfile||(e.buildProfile="production")},$o=e=>{if(e===!0||e===!1)return e;if(e===1||e==="1")return!0;if(e===0||e==="0")return!1;if(typeof e!="string")return;let t=e.trim().toLowerCase();if(["true","yes","on"].includes(t))return!0;if(["false","no","off"].includes(t))return!1},Uo=(e,t)=>{if(e)for(let n of t){let i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=e.match(new RegExp(`(?:^|\\s)${i}(?:=|\\s+)([^\\s]+)`));if(r?.[1])return r[1].replace(/^["']|["']$/g,"")}},ac=(e,t)=>!!e&&t.some(n=>new RegExp(`(?:^|\\s)${n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:\\s|$)`).test(e)),lc=e=>{let n=Uo(e,["--platform"])||e?.split(/\s+/).find(i=>i==="ios"||i==="android");return n==="ios"||n==="android"?n:void 0},dc=async e=>{if(!(!e.projectId||!e.buildId))try{let t=await N.get(`/builds/${e.projectId}/${e.buildId}`),n=t.data?.build||t.data;if(!n||typeof n!="object")return;let i=typeof n.buildArgs=="string"?n.buildArgs:void 0;if(!e.platform){let r=n.platform||lc(i);(r==="ios"||r==="android")&&(e.platform=r)}if(e.buildProfile||(e.buildProfile=n.buildProfile||n.profile||n.profileName||Uo(i,["--profile","--build-profile","-p"])),e.simulator===void 0){let r=$o(n.simulator??n.isSimulator);r!==void 0?e.simulator=r:ac(i,["--simulator"])&&(e.simulator=!0)}if(e.developmentClient===void 0){let r=$o(n.developmentClient??n.devClient);r!==void 0&&(e.developmentClient=r)}}catch(t){v.warn(R.yellow(`Could not load saved build options for runner: ${t.message}`))}},cc=e=>{if(!Number.isFinite(e)||e<=0)return"0 B";let t=["B","KB","MB","GB"],n=Math.min(Math.floor(Math.log(e)/Math.log(1024)),t.length-1);return`${(e/Math.pow(1024,n)).toFixed(n===0?0:1)} ${t[n]}`},uc=e=>{let t=e.response?.status,n=e.code||"",i=e.message||"";return t?t===408||t===409||t===425||t===429||t>=500||/ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|ECONNABORTED|socket hang up|network|timeout/i.test(`${n} ${i}`):!0},bn=async(e,t,n=tc)=>{let i;for(let r=1;r<=n;r++)try{return await t()}catch(o){if(i=o,!uc(o)||r>=n)break;let s=Math.min(6e4,2e3*Math.pow(2,r-1)),l=o.response?.status||o.code||o.message||"network error";v.warn(R.yellow(`${e} failed transiently (${l}). Retrying in ${Math.round(s/1e3)}s... (${r}/${n})`)),await Lo(s)}throw i},fc=async(e,t,n)=>{let i=ve.basename(e),r=de.statSync(e).size,o=Math.round(Oi/1e3);try{await bn(`Upload artifact ${i}`,async()=>{let s=new AbortController,l=de.createReadStream(e),a=setTimeout(()=>{l.destroy(new Error(`Artifact upload timed out after ${o}s`)),s.abort()},Oi);try{await En.put(t,l,{headers:{"Content-Type":n,"Content-Length":r,Connection:"close"},maxBodyLength:1/0,maxContentLength:1/0,timeout:Oi,timeoutErrorMessage:`Artifact upload timed out after ${o}s`,signal:s.signal})}finally{clearTimeout(a)}},_o)}catch(s){throw new Error(`${i} (${cc(r)}) failed after ${_o} upload attempt(s): ${s.message||s}`)}return r},pc=e=>{let t=e.response?.status;return t?t===408||t===429||t>=500:!0},jt=e=>e.credentialId||e.id,mc=async(e,t)=>{let n=jt(e);if(!n)return e.downloadUrl;let i=await N.get(`/credentials/${n}/download`,{params:{projectId:t,format:"raw"}});return i.data?.status==="success"&&i.data?.downloadUrl?i.data.downloadUrl:e.downloadUrl},Fo=async(e,t)=>{let n=e.downloadUrl;for(let i=1;i<=Pi;i++)try{if((!n||i>1)&&(n=await mc(e,t)),!n)throw new Error(`Credential ${e.name||jt(e)||"unknown"} has no download URL.`);let r=await En.get(n,{responseType:"arraybuffer",timeout:6e4,maxContentLength:1/0,maxBodyLength:1/0,headers:{Connection:"close"}});return Buffer.from(r.data).toString("base64")}catch(r){if(i>=Pi||!pc(r))throw r;let o=Math.min(1500*i*i,15e3);v.warn(R.dim(` - Temporary network error downloading ${e.name}. Retrying... (${i}/${Pi})`)),await Lo(o)}throw new Error(`Failed to download credential ${e.name||jt(e)||"unknown"}.`)},vo=async(e,t)=>{let n=await Fo(e,t);return Buffer.from(n,"base64").toString("utf8")},gc=(e,t)=>{try{return JSON.parse(e)}catch{throw new Error(`${t} is not valid JSON.`)}},hc=e=>/ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|ECONNABORTED|socket hang up|network|timeout/i.test(e),yc=(e,t)=>t?.ios?.buildNumber??t?.iosBuildNumber??e?.ios?.buildNumber??e?.expo?.ios?.buildNumber,Sc=(e,t,n)=>t?.ios?.ascAppId??t?.ascAppId??e?.ios?.ascAppId??e?.submit?.[n]?.ios?.ascAppId??e?.submit?.production?.ios?.ascAppId,Ro=e=>e.bundleId||e.bundleIdentifier||e.meta?.bundleId||e.meta?.bundleIdentifier,Po=(e,t)=>{let n=e.filter(i=>i.type==="asc_api_key");if(n.length!==0){if(t){let i=n.find(o=>Ro(o)===t);if(i)return i;let r=n.find(o=>Ro(o)==="*");if(r)return r}return n[0]}},bc=e=>typeof e=="string"&&e.trim().toLowerCase()==="auto",Bo=(e,t,n=[])=>{if(!de.existsSync(e))return n;let i;try{i=de.readdirSync(e,{withFileTypes:!0})}catch{return n}for(let r of i){if(r.name==="Pods"||r.name==="build"||r.name==="DerivedData")continue;let o=ve.join(e,r.name);r.isDirectory()?Bo(o,t,n):r.name===t&&n.push(o)}return n},Ac=(e,t,n)=>{let i=`${n} ${t.environment||""}`.toLowerCase(),r=e.toLowerCase(),o=0;return(i.includes("development")||i.includes("dev"))&&/(^|[.-])dev(elopment)?($|[.-])/.test(r)&&(o+=20),(i.includes("staging")||i.includes("stage"))&&/(^|[.-])stag(e|ing)?($|[.-])/.test(r)&&(o+=20),(i.includes("production")||i.includes("prod"))&&(/(^|[.-])(dev|development|stag|stage|staging)($|[.-])/.test(r)||(o+=20)),o},Ec=(e,t)=>{let n=ve.resolve(process.cwd(),de.existsSync("ios")?"ios":"."),i=Bo(n,"project.pbxproj"),r=[];for(let o of i)try{let l=de.readFileSync(o,"utf8").matchAll(/PRODUCT_BUNDLE_IDENTIFIER\s*=\s*"?([^";\s]+)"?;/g);for(let a of l){let c=a[1]?.trim();c&&!c.includes("$")&&!c.startsWith("com.apple.")&&!r.includes(c)&&r.push(c)}}catch{}if(r.length!==0)return r.length===1?r[0]:r.map(o=>({bundleId:o,score:Ac(o,e,t)})).sort((o,s)=>s.score-o.score)[0]?.bundleId},An=e=>String(e||"").trim().toLowerCase().replace(/_/g,"-"),wn=(e,t)=>{let n=An(e);return t==="ios"&&(n==="internal"||n==="ad-hoc")?"adhoc":t==="android"&&["internal","adhoc","ad-hoc","development","dev","staging","stage"].includes(n)?"internal":n},Oo=(e,t,n)=>{let i=wn(e.distributionType||e.meta?.distributionType,n);return i?i===wn(t,n):!0},Do=(e,t,n)=>{let i=wn(e.distributionType||e.meta?.distributionType,n),r=wn(t,n);return i?i===r?3:n==="android"&&r!=="store"&&i!=="store"?2:0:1},Ic=e=>{let t=e.toLowerCase();return t==="development"||t==="dev"||t.startsWith("development-")||t.startsWith("dev-")||t.endsWith("-development")||t.endsWith("-dev")},wc=e=>{let t=e.toLowerCase();return t.includes("staging")||t.includes("stage")||t.includes("preview")||t.includes("adhoc")||t.includes("ad-hoc")},_c=(e,t)=>{let n=An(e.distribution),i=An(e.iosExportMethod),r=An(e.environment);return e.platform!=="ios"?n==="store"?"store":"internal":e.developmentClient||e.simulator?"development":i==="app-store"||n==="store"?"store":i==="development"||n==="development"?"development":i==="ad-hoc"||i==="adhoc"||n==="ad-hoc"||n==="adhoc"||n==="internal"?"adhoc":r==="production"||r==="store"?"store":r==="development"||r==="dev"?"development":r==="staging"||r==="stage"||r==="preview"?"adhoc":t.toLowerCase()==="production"||t.toLowerCase().includes("store")?"store":Ic(t)?"development":(wc(t),"adhoc")},Ho=e=>e.bundleId||e.bundleIdentifier||e.packageName||e.meta?.bundleId||e.meta?.bundleIdentifier||e.meta?.packageName,Co=(e,t)=>{if(!t)return!0;let n=Ho(e);return!n||n==="*"||n===t},No=(e,t)=>{let n=Ho(e);return!t||!n?0:n===t?2:n==="*"?1:-1},jo=e=>{try{let t=Buffer.from(e,"base64").toString("utf8"),n=t.match(/<key>application-identifier<\/key>\s*<string>([^<]+)<\/string>/)?.[1]?.trim();if(!n)return;let i=t.match(/<key>TeamIdentifier<\/key>\s*<array>\s*<string>([^<]+)<\/string>/)?.[1]?.trim();if(i&&n.startsWith(`${i}.`))return n.slice(i.length+1);let r=n.indexOf(".");return r>=0?n.slice(r+1):n}catch{return}},$c=(e,t)=>{if(e===t||e==="*")return!0;if(e.endsWith(".*")){let n=e.slice(0,-2);return t.startsWith(`${n}.`)}return!1},vc=(e,t)=>{if(!t)return!0;let n=jo(e);if(n)return $c(n,t);try{return Buffer.from(e,"base64").toString("latin1").includes(t)}catch{return!0}},_n=async e=>{if(e.failOnly){(!e.projectId||!e.buildId)&&(v.error(R.red("--project-id and --build-id are required with --fail-only.")),process.exit(1));let l=e.error||"Build runner failed before it could report a final status.";try{await N.patch(`/builds/${e.projectId}/${e.buildId}`,{status:"failed",error:l,endTime:Date.now()}),v.info(R.yellow(`Marked build ${e.buildId} as failed.`));return}catch(a){v.error(R.red(`Could not mark build failed: ${a.message}`)),process.exit(1)}}await dc(e),await sc(e),e.platform!=="android"&&e.platform!=="ios"&&(v.error(`Platform ${e.platform} is not supported. Use 'android' or 'ios'.`),process.exit(1)),e.autoSubmit&&e.platform==="ios"&&e.simulator&&(v.error(R.red("--auto-submit cannot be used with --simulator because simulator builds are not App Store artifacts.")),process.exit(1)),e.autoSubmit&&e.dryRun&&v.warn(R.yellow("--auto-submit is ignored during --dry-run."));let t=Ci(),n=e.buildId||Qd(),i=e.projectId,r=Date.now(),o=!!i,s=async l=>{if(i)try{await N.patch(`/builds/${i}/${n}`,{status:"failed",error:l})}catch{}};if(e.local&&e.buildId){e.quiet||t.start(`Preparing isolated workspace for build: ${e.buildId}`);try{let l=await N.get(`/builds/${i}/${e.buildId}/source-url`);if(l.data.status!=="success")throw new Error("Failed to get source download URL from API");let a=await En.get(l.data.downloadUrl,{responseType:"stream"}),c=(i||e.projectId||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),u=ve.join(ec.homedir(),m.workspacesDir,c);de.mkdirSync(u,{recursive:!0});let d=new Set(["node_modules",`.${m.nameLower}-cache-meta`]),p=new Set(["Pods"]);if(de.existsSync(u)){let x=de.readdirSync(u);for(let b of x){if(d.has(b))continue;if(b==="ios"){let w=ve.join(u,"ios");try{let z=de.readdirSync(w);for(let Q of z)if(!p.has(Q))try{de.rmSync(ve.join(w,Q),{recursive:!0,force:!0})}catch{}}catch{}continue}let U=ve.join(u,b);try{de.rmSync(U,{recursive:!0,force:!0})}catch{}}}let f=ve.join(u,"source.zip"),h=a.data,S=de.createWriteStream(f);await new Promise((x,b)=>{h.pipe(S),h.on("error",U=>b(U)),S.on("finish",()=>x())}),new wo(f).extractAllTo(u,!0);try{de.unlinkSync(f)}catch{}process.chdir(u),v.info(R.green(`\u2713 Persistent workspace ready: ${u}`)),v.info(R.dim(` \u{1F4E6} Cached dirs preserved: node_modules=${de.existsSync(ve.join(u,"node_modules"))?"\u2705":"\u274C"}, Pods=${de.existsSync(ve.join(u,"ios","Pods"))?"\u2705":"\u274C"}`)),t.stop()}catch(l){t.stop(`Failed to prepare isolated workspace: ${l.message}`),i&&await s(`Setup Error: ${l.message}`),process.exit(1)}}try{let l=e.repo;if(!l)try{l=Io("git config --get remote.origin.url").toString().trim()}catch{v.warn("Could not detect git repository URL.")}!l&&e.dryRun,l||(l="https://github.com/placeholder/repo.git"),v.info(`Build ID: ${R.cyan(n)}`);let a={},c={},u=null,d=$e(`./${m.configFileName}`);if(d||(v.error(R.red(`${m.configFileName} not found. Run \`${m.nameLower} init\` or \`${m.nameLower} link\` first.`)),process.exit(1)),d){u=d;let O=rr(d);e.framework=O,i=d.projectId;let E=e.buildProfile||"production",D=nt(d,E);!D&&e.buildProfile&&(v.error(`Build profile '${E}' not found in ${m.configFileName}`),process.exit(1));let $=D||{};process.env.MACH_DEBUG&&v.info(R.dim(`Framework: ${O} | Build profile: ${E} | Platform: ${e.platform} | Distribution: ${$.distribution||"store"} | Environment: ${$.environment||E}`)),$.env&&(c=$.env,v.info(R.blue(`Use Build Profile: ${E}`)));let C=e.platform,g=$[C]||{},k=["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 F=H=>H==="androidPackage"?g.androidPackage??g.package??$.androidPackage??$.android?.package:H==="iosBundleIdentifier"?g.iosBundleIdentifier??g.bundleIdentifier??$.iosBundleIdentifier??$.ios?.bundleIdentifier:g[H]!==void 0?g[H]:$[H];for(let H of k){let P=F(H),q=H==="androidPackage"||H==="iosBundleIdentifier";P!==void 0&&(e[H]===void 0||q)&&(e[H]=P)}if(e.platform==="ios"&&!(g.iosBundleIdentifier??g.bundleIdentifier??$.iosBundleIdentifier??$.ios?.bundleIdentifier)){let P=Ec(e,E);P&&P!==e.iosBundleIdentifier&&(v.warn(R.yellow(`Detected native iOS bundle identifier ${P}; using it for credential lookup. Set build.${E}.ios.bundleIdentifier to make this explicit.`)),e.iosBundleIdentifier=P)}e.branch=e.branch||"main",e.iosConfiguration=e.iosConfiguration||(e.developmentClient?"Debug":"Release"),e.sshUser=e.sshUser||process.env.USER||"ubuntu",e.simulator===void 0&&(e.simulator=!1),e.local===void 0&&(e.local=!1),e.verbose===void 0&&(e.verbose=!1);let V=H=>{if(!H)return H;if(H.startsWith("scripts.")){let P=H.split(".")[1],q=d.scripts?.[P];if(q)return q;v.warn(`Script reference not found: ${H}`)}return H};e.buildCommand=V(e.buildCommand),e.preBuild=V(e.preBuild),e.postBuild=V(e.postBuild),!e.scheme&&d.scheme&&(e.scheme=d.scheme);let J={...At(d,m.envPrefix),...At($,`${m.envPrefix}PROFILE_`)};a={...a,...c,...J},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&&$.ios?.appleTeamId&&(e.iosTeamId=$.ios.appleTeamId),!e.iosTeamId&&d.submit?.[E]?.ios?.appleTeamId&&(e.iosTeamId=d.submit[E].ios.appleTeamId),!e.iosTeamId&&d.submit?.production?.ios?.appleTeamId&&(v.warn(R.yellow(`Check: Using 'production' Team ID for '${E}' build.`)),e.iosTeamId=d.submit.production.ios.appleTeamId),e.iosTeamId?v.info(R.magenta(`\u2713 Injected iOS Team ID from config: ${e.iosTeamId}`)):e.simulator||v.warn(R.yellow("\u26A0\uFE0F No iOS Team ID found. Device or archive signing may fail unless managed iOS credentials provide the team automatically.")))}let p="unknown";try{p=Io("git rev-parse --abbrev-ref HEAD").toString().trim()}catch{v.warn("Failed to detect git branch.")}let f="1.0.0";try{de.existsSync("./package.json")&&(f=JSON.parse(de.readFileSync("./package.json","utf-8")).version||"1.0.0")}catch{}let h=e.buildProfile||"production",S="Internal";e.developmentClient?S="DevelopmentClient":h.toLowerCase().includes("store")||h.toLowerCase()==="production"?S="Store":h.toLowerCase().includes("preview")||h.toLowerCase().includes("staging")?S="Staging":(h.toLowerCase().includes("development")||h.toLowerCase().includes("dev"))&&(S="Development");let L=e.platform==="ios"?"iOS":"Android",x=e.platform==="ios"&&e.simulator?" (Simulator)":"",b=`${L}${x} v${f} (${S})`;if($n(e,{status:"created",projectId:i,buildId:n,platform:e.platform,profile:h,branch:p,version:f,buildType:S,developmentClient:!!e.developmentClient,summary:b}),i){try{let O=e.buildProfile||"production",E=e.environment||O;v.info(R.blue(`Fetching managed secrets for profile: ${O} (environment: ${E})...`));let $=(await N.get(`/projects/${i}/secrets/export?env=${E}`)).data;$.status==="success"&&$.secrets&&(a={...a,...$.secrets},Object.keys($.secrets).length>0&&v.info(R.magenta(`\u2713 Injected ${Object.keys($.secrets).length} secrets from Dashboard.`)))}catch(O){v.warn(`Failed to load managed secrets from Dashboard: ${O.message}`)}if(e.platform==="ios"&&e.simulator)v.info(R.dim("Skipping managed iOS signing credentials for simulator build."));else try{v.info(R.blue("Fetching managed credentials..."));let O=_c(e,h),E=e.platform==="ios"?e.iosBundleIdentifier:e.androidPackage,D=e.platform==="ios"?"bundle":"package";v.info(R.dim(` Credential target: ${D} ${E||"not set"} (${O})`));let $=await N.get("/credentials/resolve",{params:{projectId:i,platform:e.platform,bundleId:E,distributionType:O,teamId:e.platform==="ios"?e.iosTeamId:void 0}});if($.data.status==="success"&&$.data.credentials){let C=$.data.credentials;v.info(R.magenta(`\u2713 Found ${C.length} relevant credentials.`));let g=C.filter(P=>e.platform==="ios"&&P.type==="ios_profile"?Oo(P,O,e.platform)?Co(P,E):!1:e.platform==="android"&&P.type==="android_keystore"?Co(P,E):!!Oo(P,O,e.platform)).sort((P,q)=>No(q,E)*10+Do(q,O,e.platform)-(No(P,E)*10+Do(P,O,e.platform)));v.info(R.dim(` Filtered to ${g.length} credentials for distributionType: ${O}`));let k=!1,F=!1,V=!1,J=[];for(let P of g)if(!(P.type==="ios_cert"&&k||P.type==="ios_profile"&&F||P.type==="android_keystore"&&V)&&["ios_cert","ios_profile","android_keystore"].includes(P.type)&&(P.downloadUrl||jt(P)))try{let ye=await Fo(P,i);if(P.type==="ios_cert"&&!k)a.IOS_DIST_P12=ye,P.password?(a.IOS_P12_PASSWORD=P.password,v.info(R.dim(` - Injected ${P.name} as IOS_DIST_P12 with password from credential record`))):v.info(R.dim(` - Injected ${P.name} as IOS_DIST_P12`)),k=!0;else if(P.type==="ios_profile"&&!F){if(!vc(ye,E)){let Ae=jo(ye)||"unknown";throw new Error(`Provisioning profile ${P.name||jt(P)||"unknown"} is for a different bundle ID. Expected ${E}, found ${Ae}. Upload a ${O} profile for ${E}.`)}a.IOS_PROVISIONING_PROFILE=ye,v.info(R.dim(` - Injected ${P.name} as IOS_PROVISIONING_PROFILE`)),F=!0}else if(P.type==="android_keystore"&&!V){a.ANDROID_KEYSTORE_BASE64=ye;let Ae=P.keystorePassword||P.password,G=P.keyPassword||P.keystorePassword||P.password,j=P.alias||P.meta?.alias;if(Ae)a.ANDROID_STORE_PASSWORD=Ae,v.info(R.dim(" - Injected keystore password from credential record"));else{let K=["ANDROID_STORE_PASSWORD",...[O==="store"?"PRODUCTION":O==="internal"||O==="adhoc"?"STAGING":"DEVELOPMENT",O.toUpperCase(),"PRODUCTION","STORE","INTERNAL","STAGING","RELEASE","DEBUG"].map(Z=>`KEYSTORE_PASSWORD_${Z}`),"KEYSTORE_PASSWORD"].find(Z=>!!a[Z]);K&&a[K]&&(a.ANDROID_STORE_PASSWORD=a[K])}if(G?(a.ANDROID_KEY_PASSWORD=G,v.info(R.dim(" - Injected key password from credential record"))):a.ANDROID_KEY_PASSWORD=a.ANDROID_STORE_PASSWORD||"",j)a.ANDROID_KEY_ALIAS=j;else{let X=["ANDROID_KEY_ALIAS","KEYSTORE_ALIAS"].find(T=>!!a[T]);X&&(a.ANDROID_KEY_ALIAS=a[X])}v.info(R.dim(` - Injected ${P.name} as ANDROID_KEYSTORE_BASE64`)),V=!0}}catch(ye){J.push(`${P.name||P.type}: ${ye.message}`)}let H=e.platform==="ios"?e.simulator||k&&F:V||!g.some(P=>P.type==="android_keystore");if(J.length>0&&!H)throw new Error(`Credential setup failed:
|
|
1334
|
-
${
|
|
1335
|
-
`)}`);
|
|
1336
|
-
\u{1F517} Download Links:`));for(let C of
|
|
1337
|
-
\u2713 Build completed and reported to dashboard.`)),e.maestro&&!
|
|
1338
|
-
${
|
|
1339
|
-
\u{1F3BC} Queuing managed Maestro test...`)),await
|
|
1340
|
-
Auto-submit: submitting the successful build...`));try{let r=await
|
|
1341
|
-
\u2717 Build failed: ${a.error||"Unknown error"}`)),process.exit(1);else if(r==="completed"||r==="success"){n.quiet||i.stop("Build successful!")
|
|
1342
|
-
\u2713 Build completed successfully!`));try{n.quiet||(
|
|
1343
|
-
\u{1F4F1} Installation Hub:`))
|
|
1344
|
-
`);if(d.length>o){for(let
|
|
1345
|
-
\u2717 Lost connection to Dashboard API.`)),process.exit(1))}await new Promise(l=>setTimeout(l,3e3))}}import*as
|
|
1430
|
+
`);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 Nc(e){try{oe.existsSync(e)&&oe.rmSync(e,{recursive:!0,force:!0})}catch{}}function le(e){console.log(ne.red(`\u274C ${e}`))}function me(e){console.log(ne.gray(`\u2022 ${e}`))}function Ti(e){console.log(ne.green(`\u2713 ${e}`))}var Li=8,xc=6,jo=Number(process.env.MACH_ARTIFACT_UPLOAD_MAX_ATTEMPTS||2),Mi=Number(process.env.MACH_ARTIFACT_UPLOAD_TIMEOUT_MS||12e4),Go=new Set([".git",".gradle",".idea",".mach-cache",".expo",".turbo",".yarn/cache","build","builds","coverage","dist","node_modules",`${m.nameLower}_cli`,`.${m.nameLower}_cli`]),Lc=new Set(["android/.gradle","android/.cxx","android/app/.cxx","android/app/build","android/build","ios/Pods","ios/build","ios/DerivedData"]),Mc=[{value:"production",label:"production",hint:"Store / release build"},{value:"staging",label:"staging",hint:"Internal testing build"},{value:"development",label:"development",hint:"Development build"}],ns=e=>new Promise(t=>setTimeout(t,e)),is=e=>e.split(ge.sep).filter(Boolean).join("/"),Uc=(e,t)=>{let n=is(e),i=n.split("/")[0];return n?!!(Go.has(n)||Go.has(i)||Lc.has(n)||t==="ios"&&i==="android"||t==="android"&&i==="ios"):!1},Fc=(e,t,n)=>{let i=0,r=new Set,o=(s,l)=>{let a=is(l);if(Uc(a,n)){r.add(a.split("/")[0]||a);return}let c=de.lstatSync(s);if(!c.isSymbolicLink()){if(c.isDirectory()){for(let u of de.readdirSync(s))o(ge.join(s,u),ge.join(l,u));return}if(c.isFile()){let u=ge.dirname(a);e.addLocalFile(s,u==="."?void 0:u,ge.basename(a)),i++}}};for(let s of de.readdirSync(t))o(ge.join(t,s),s);return{files:i,skipped:Array.from(r).sort()}},Bc=e=>!e.yes&&!e.failOnly&&!e.buildId&&process.stdin.isTTY&&process.stdout.isTTY,Hc=e=>{if(!e||typeof e!="object")return;let t=[e.distribution?`distribution: ${e.distribution}`:void 0,e.environment?`env: ${e.environment}`:void 0,e.developmentClient?"development client":void 0,e.simulator?"simulator":void 0].filter(Boolean);return t.length>0?t.join(", "):void 0},jc=()=>{let e=$e(`./${m.configFileName}`),t=e?.build&&typeof e.build=="object"?e.build:{},n=Object.keys(t);return n.length===0?Mc:n.map(i=>({value:i,label:i,hint:Hc(t[i])}))},Gc=async e=>{let t=Bc(e);if(!e.platform&&t){let n=await Mo({message:"Select platform",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"}]});vn(n)&&(Fo("Build cancelled."),process.exit(0)),e.platform=n}if(!e.buildProfile&&t){let n=jc(),i=await Mo({message:"Select build profile",options:n,initialValue:n.find(r=>r.value==="production")?.value||n[0]?.value});vn(i)&&(Fo("Build cancelled."),process.exit(0)),e.buildProfile=i}e.buildProfile||(e.buildProfile="production")},Ko=e=>{if(e===!0||e===!1)return e;if(e===1||e==="1")return!0;if(e===0||e==="0")return!1;if(typeof e!="string")return;let t=e.trim().toLowerCase();if(["true","yes","on"].includes(t))return!0;if(["false","no","off"].includes(t))return!1},rs=(e,t)=>{if(e)for(let n of t){let i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=e.match(new RegExp(`(?:^|\\s)${i}(?:=|\\s+)([^\\s]+)`));if(r?.[1])return r[1].replace(/^["']|["']$/g,"")}},Kc=(e,t)=>!!e&&t.some(n=>new RegExp(`(?:^|\\s)${n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:\\s|$)`).test(e)),Vc=e=>{let n=rs(e,["--platform"])||e?.split(/\s+/).find(i=>i==="ios"||i==="android");return n==="ios"||n==="android"?n:void 0},zc=async e=>{if(!(!e.projectId||!e.buildId))try{let t=await k.get(`/builds/${e.projectId}/${e.buildId}`),n=t.data?.build||t.data;if(!n||typeof n!="object")return;let i=typeof n.buildArgs=="string"?n.buildArgs:void 0;if(!e.platform){let r=n.platform||Vc(i);(r==="ios"||r==="android")&&(e.platform=r)}if(e.buildProfile||(e.buildProfile=n.buildProfile||n.profile||n.profileName||rs(i,["--profile","--build-profile","-p"])),e.simulator===void 0){let r=Ko(n.simulator??n.isSimulator);r!==void 0?e.simulator=r:Kc(i,["--simulator"])&&(e.simulator=!0)}if(e.developmentClient===void 0){let r=Ko(n.developmentClient??n.devClient);r!==void 0&&(e.developmentClient=r)}}catch(t){$.warn(v.yellow(`Could not load saved build options for runner: ${t.message}`))}},Wc=e=>{if(!Number.isFinite(e)||e<=0)return"0 B";let t=["B","KB","MB","GB"],n=Math.min(Math.floor(Math.log(e)/Math.log(1024)),t.length-1);return`${(e/Math.pow(1024,n)).toFixed(n===0?0:1)} ${t[n]}`},Yc=e=>{let t=e.response?.status,n=e.code||"",i=e.message||"";return t?t===408||t===409||t===425||t===429||t>=500||/ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|ECONNABORTED|socket hang up|network|timeout/i.test(`${n} ${i}`):!0},_n=async(e,t,n=xc)=>{let i;for(let r=1;r<=n;r++)try{return await t()}catch(o){if(i=o,!Yc(o)||r>=n)break;let s=Math.min(6e4,2e3*Math.pow(2,r-1)),l=o.response?.status||o.code||o.message||"network error";$.warn(v.yellow(`${e} failed transiently (${l}). Retrying in ${Math.round(s/1e3)}s... (${r}/${n})`)),await ns(s)}throw i},Jc=async(e,t,n)=>{let i=ge.basename(e),r=de.statSync(e).size,o=Math.round(Mi/1e3);try{await _n(`Upload artifact ${i}`,async()=>{let s=new AbortController,l=de.createReadStream(e),a=setTimeout(()=>{l.destroy(new Error(`Artifact upload timed out after ${o}s`)),s.abort()},Mi);try{await $n.put(t,l,{headers:{"Content-Type":n,"Content-Length":r,Connection:"close"},maxBodyLength:1/0,maxContentLength:1/0,timeout:Mi,timeoutErrorMessage:`Artifact upload timed out after ${o}s`,signal:s.signal})}finally{clearTimeout(a)}},jo)}catch(s){throw new Error(`${i} (${Wc(r)}) failed after ${jo} upload attempt(s): ${s.message||s}`)}return r},Xc=e=>{let t=e.response?.status;return t?t===408||t===429||t>=500:!0},Xt=e=>e.credentialId||e.id,qc=async(e,t)=>{let n=Xt(e);if(!n)return e.downloadUrl;let i=await k.get(`/credentials/${n}/download`,{params:{projectId:t,format:"raw"}});return i.data?.status==="success"&&i.data?.downloadUrl?i.data.downloadUrl:e.downloadUrl},os=async(e,t)=>{let n=e.downloadUrl;for(let i=1;i<=Li;i++)try{if((!n||i>1)&&(n=await qc(e,t)),!n)throw new Error(`Credential ${e.name||Xt(e)||"unknown"} has no download URL.`);let r=await $n.get(n,{responseType:"arraybuffer",timeout:6e4,maxContentLength:1/0,maxBodyLength:1/0,headers:{Connection:"close"}});return Buffer.from(r.data).toString("base64")}catch(r){if(i>=Li||!Xc(r))throw r;let o=Math.min(1500*i*i,15e3);$.warn(v.dim(` - Temporary network error downloading ${e.name}. Retrying... (${i}/${Li})`)),await ns(o)}throw new Error(`Failed to download credential ${e.name||Xt(e)||"unknown"}.`)},Vo=async(e,t)=>{let n=await os(e,t);return Buffer.from(n,"base64").toString("utf8")},Zc=(e,t)=>{try{return JSON.parse(e)}catch{throw new Error(`${t} is not valid JSON.`)}},Qc=e=>/ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|ECONNABORTED|socket hang up|network|timeout/i.test(e),eu=(e,t)=>t?.ios?.buildNumber??t?.iosBuildNumber??e?.ios?.buildNumber??e?.expo?.ios?.buildNumber,tu=(e,t,n)=>t?.ios?.ascAppId??t?.ascAppId??e?.ios?.ascAppId??e?.submit?.[n]?.ios?.ascAppId??e?.submit?.production?.ios?.ascAppId,zo=e=>e.bundleId||e.bundleIdentifier||e.meta?.bundleId||e.meta?.bundleIdentifier,Wo=(e,t)=>{let n=e.filter(i=>i.type==="asc_api_key");if(n.length!==0){if(t){let i=n.find(o=>zo(o)===t);if(i)return i;let r=n.find(o=>zo(o)==="*");if(r)return r}return n[0]}},nu=e=>typeof e=="string"&&e.trim().toLowerCase()==="auto",ss=(e,t,n=[])=>{if(!de.existsSync(e))return n;let i;try{i=de.readdirSync(e,{withFileTypes:!0})}catch{return n}for(let r of i){if(r.name==="Pods"||r.name==="build"||r.name==="DerivedData")continue;let o=ge.join(e,r.name);r.isDirectory()?ss(o,t,n):r.name===t&&n.push(o)}return n},iu=(e,t,n)=>{let i=`${n} ${t.environment||""}`.toLowerCase(),r=e.toLowerCase(),o=0;return(i.includes("development")||i.includes("dev"))&&/(^|[.-])dev(elopment)?($|[.-])/.test(r)&&(o+=20),(i.includes("staging")||i.includes("stage"))&&/(^|[.-])stag(e|ing)?($|[.-])/.test(r)&&(o+=20),(i.includes("production")||i.includes("prod"))&&(/(^|[.-])(dev|development|stag|stage|staging)($|[.-])/.test(r)||(o+=20)),o},ru=(e,t)=>{let n=ge.resolve(process.cwd(),de.existsSync("ios")?"ios":"."),i=ss(n,"project.pbxproj"),r=[];for(let o of i)try{let l=de.readFileSync(o,"utf8").matchAll(/PRODUCT_BUNDLE_IDENTIFIER\s*=\s*"?([^";\s]+)"?;/g);for(let a of l){let c=a[1]?.trim();c&&!c.includes("$")&&!c.startsWith("com.apple.")&&!r.includes(c)&&r.push(c)}}catch{}if(r.length!==0)return r.length===1?r[0]:r.map(o=>({bundleId:o,score:iu(o,e,t)})).sort((o,s)=>s.score-o.score)[0]?.bundleId},Rn=e=>String(e||"").trim().toLowerCase().replace(/_/g,"-"),Pn=(e,t)=>{let n=Rn(e);return t==="ios"&&(n==="internal"||n==="ad-hoc")?"adhoc":t==="android"&&["internal","adhoc","ad-hoc","development","dev","staging","stage"].includes(n)?"internal":n},Yo=(e,t,n)=>{let i=Pn(e.distributionType||e.meta?.distributionType,n);return i?i===Pn(t,n):!0},Jo=(e,t,n)=>{let i=Pn(e.distributionType||e.meta?.distributionType,n),r=Pn(t,n);return i?i===r?3:n==="android"&&r!=="store"&&i!=="store"?2:0:1},ou=e=>{let t=e.toLowerCase();return t==="development"||t==="dev"||t.startsWith("development-")||t.startsWith("dev-")||t.endsWith("-development")||t.endsWith("-dev")},su=e=>{let t=e.toLowerCase();return t.includes("staging")||t.includes("stage")||t.includes("preview")||t.includes("adhoc")||t.includes("ad-hoc")},au=(e,t)=>{let n=Rn(e.distribution),i=Rn(e.iosExportMethod),r=Rn(e.environment);return e.platform!=="ios"?n==="store"?"store":"internal":e.developmentClient||e.simulator?"development":i==="app-store"||n==="store"?"store":i==="development"||n==="development"?"development":i==="ad-hoc"||i==="adhoc"||n==="ad-hoc"||n==="adhoc"||n==="internal"?"adhoc":r==="production"||r==="store"?"store":r==="development"||r==="dev"?"development":r==="staging"||r==="stage"||r==="preview"?"adhoc":t.toLowerCase()==="production"||t.toLowerCase().includes("store")?"store":ou(t)?"development":(su(t),"adhoc")},as=e=>e.bundleId||e.bundleIdentifier||e.packageName||e.meta?.bundleId||e.meta?.bundleIdentifier||e.meta?.packageName,Xo=(e,t)=>{if(!t)return!0;let n=as(e);return!n||n==="*"||n===t},qo=(e,t)=>{let n=as(e);return!t||!n?0:n===t?2:n==="*"?1:-1},ls=e=>{try{let t=Buffer.from(e,"base64").toString("utf8"),n=t.match(/<key>application-identifier<\/key>\s*<string>([^<]+)<\/string>/)?.[1]?.trim();if(!n)return;let i=t.match(/<key>TeamIdentifier<\/key>\s*<array>\s*<string>([^<]+)<\/string>/)?.[1]?.trim();if(i&&n.startsWith(`${i}.`))return n.slice(i.length+1);let r=n.indexOf(".");return r>=0?n.slice(r+1):n}catch{return}},lu=(e,t)=>{if(e===t||e==="*")return!0;if(e.endsWith(".*")){let n=e.slice(0,-2);return t.startsWith(`${n}.`)}return!1},du=(e,t)=>{if(!t)return!0;let n=ls(e);if(n)return lu(n,t);try{return Buffer.from(e,"base64").toString("latin1").includes(t)}catch{return!0}},On=async e=>{if(e.failOnly){(!e.projectId||!e.buildId)&&($.error(v.red("--project-id and --build-id are required with --fail-only.")),process.exit(1));let l=e.error||"Build runner failed before it could report a final status.";try{await k.patch(`/builds/${e.projectId}/${e.buildId}`,{status:"failed",error:l,endTime:Date.now()}),$.info(v.yellow(`Marked build ${e.buildId} as failed.`));return}catch(a){$.error(v.red(`Could not mark build failed: ${a.message}`)),process.exit(1)}}await zc(e),await Gc(e),e.platform!=="android"&&e.platform!=="ios"&&($.error(`Platform ${e.platform} is not supported. Use 'android' or 'ios'.`),process.exit(1)),e.autoSubmit&&e.platform==="ios"&&e.simulator&&($.error(v.red("--auto-submit cannot be used with --simulator because simulator builds are not App Store artifacts.")),process.exit(1)),e.autoSubmit&&e.dryRun&&$.warn(v.yellow("--auto-submit is ignored during --dry-run."));let t=Fi(),n=e.buildId||Tc(),i=e.projectId,r=Date.now(),o=!!i,s=async l=>{if(i)try{await k.patch(`/builds/${i}/${n}`,{status:"failed",error:l,endTime:Date.now()})}catch{}};if(e.local&&e.buildId){e.quiet||t.start(`Preparing isolated workspace for build: ${e.buildId}`);try{let l=await k.get(`/builds/${i}/${e.buildId}/source-url`);if(l.data.status!=="success")throw new Error("Failed to get source download URL from API");let a=await $n.get(l.data.downloadUrl,{responseType:"stream"}),c=(i||e.projectId||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),u=ge.join(kc.homedir(),m.workspacesDir,c);de.mkdirSync(u,{recursive:!0});let d=new Set(["node_modules",`.${m.nameLower}-cache-meta`]),f=new Set(["Pods"]);if(de.existsSync(u)){let D=de.readdirSync(u);for(let b of D){if(d.has(b))continue;if(b==="ios"){let A=ge.join(u,"ios");try{let B=de.readdirSync(A);for(let q of B)if(!f.has(q))try{de.rmSync(ge.join(A,q),{recursive:!0,force:!0})}catch{}}catch{}continue}let x=ge.join(u,b);try{de.rmSync(x,{recursive:!0,force:!0})}catch{}}}let p=ge.join(u,"source.zip"),g=a.data,y=de.createWriteStream(p);await new Promise((D,b)=>{g.pipe(y),g.on("error",x=>b(x)),y.on("finish",()=>D())}),new Ho(p).extractAllTo(u,!0);try{de.unlinkSync(p)}catch{}process.chdir(u),$.info(v.green(`\u2713 Persistent workspace ready: ${u}`)),$.info(v.dim(` \u{1F4E6} Cached dirs preserved: node_modules=${de.existsSync(ge.join(u,"node_modules"))?"\u2705":"\u274C"}, Pods=${de.existsSync(ge.join(u,"ios","Pods"))?"\u2705":"\u274C"}`)),t.stop()}catch(l){t.stop(`Failed to prepare isolated workspace: ${l.message}`),i&&await s(`Setup Error: ${l.message}`),process.exit(1)}}try{let l=e.repo;if(!l)try{l=Bo("git config --get remote.origin.url").toString().trim()}catch{$.warn("Could not detect git repository URL.")}!l&&e.dryRun,l||(l="https://github.com/placeholder/repo.git"),$.info(`Build ID: ${v.cyan(n)}`);let a={},c={},u=null,d=$e(`./${m.configFileName}`);if(d||($.error(v.red(`${m.configFileName} not found. Run \`${m.nameLower} init\` or \`${m.nameLower} link\` first.`)),process.exit(1)),d){u=d;let P=mr(d);e.framework=P,i=d.projectId;let I=e.buildProfile||"production",T=lt(d,I);!T&&e.buildProfile&&($.error(`Build profile '${I}' not found in ${m.configFileName}`),process.exit(1));let w=T||{};process.env.MACH_DEBUG&&$.info(v.dim(`Framework: ${P} | Build profile: ${I} | Platform: ${e.platform} | Distribution: ${w.distribution||"store"} | Environment: ${w.environment||I}`)),w.env&&(c=w.env,$.info(v.blue(`Use Build Profile: ${I}`)));let C=e.platform,h=w[C]||{},M=["developmentClient","simulator","distribution","buildCommand","apk","iosScheme","preBuild","postBuild","scheme","environment","androidPackage","iosBundleIdentifier","name","iosDeploymentTarget","iosApiKeyId","iosApiKeyIssuer","iosApiKeyPath","iosTeamId","iosConfiguration","iosExportMethod","branch","repo","instanceType","ami","bucket","region","nodeVersion"];e.name=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 U=H=>H==="androidPackage"?h.androidPackage??h.package??w.androidPackage??w.android?.package:H==="iosBundleIdentifier"?h.iosBundleIdentifier??h.bundleIdentifier??w.iosBundleIdentifier??w.ios?.bundleIdentifier:h[H]!==void 0?h[H]:w[H];for(let H of M){let N=U(H),W=H==="androidPackage"||H==="iosBundleIdentifier";N!==void 0&&(e[H]===void 0||W)&&(e[H]=N)}if(e.platform==="ios"&&!(h.iosBundleIdentifier??h.bundleIdentifier??w.iosBundleIdentifier??w.ios?.bundleIdentifier)){let N=ru(e,I);N&&N!==e.iosBundleIdentifier&&($.warn(v.yellow(`Detected native iOS bundle identifier ${N}; using it for credential lookup. Set build.${I}.ios.bundleIdentifier to make this explicit.`)),e.iosBundleIdentifier=N)}e.branch=e.branch||"main",e.iosConfiguration=e.iosConfiguration||(e.developmentClient?"Debug":"Release"),e.sshUser=e.sshUser||process.env.USER||"ubuntu",e.simulator===void 0&&(e.simulator=!1),e.local===void 0&&(e.local=!1),e.verbose===void 0&&(e.verbose=!1),$.info(v.dim(`Resolved build config: framework=${P}, profile=${I}, platform=${e.platform}, simulator=${e.platform==="ios"?String(!!e.simulator):"n/a"}, developmentClient=${String(!!e.developmentClient)}, distribution=${e.distribution||w.distribution||"store"}, iosConfiguration=${e.platform==="ios"?e.iosConfiguration||"Release":"n/a"}`));let j=H=>{if(!H)return H;if(H.startsWith("scripts.")){let N=H.split(".")[1],W=d.scripts?.[N];if(W)return W;$.warn(`Script reference not found: ${H}`)}return H};e.buildCommand=j(e.buildCommand),e.preBuild=j(e.preBuild),e.postBuild=j(e.postBuild),!e.scheme&&d.scheme&&(e.scheme=d.scheme);let X={...Pt(d,m.envPrefix),...Pt(w,`${m.envPrefix}PROFILE_`)};a={...a,...c,...X},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?.[I]?.ios?.appleTeamId&&(e.iosTeamId=d.submit[I].ios.appleTeamId),!e.iosTeamId&&d.submit?.production?.ios?.appleTeamId&&($.warn(v.yellow(`Check: Using 'production' Team ID for '${I}' build.`)),e.iosTeamId=d.submit.production.ios.appleTeamId),e.iosTeamId?$.info(v.magenta(`\u2713 Injected iOS Team ID from config: ${e.iosTeamId}`)):e.simulator||$.warn(v.yellow("\u26A0\uFE0F No iOS Team ID found. Device or archive signing may fail unless managed iOS credentials provide the team automatically.")))}let f="unknown";try{f=Bo("git rev-parse --abbrev-ref HEAD").toString().trim()}catch{$.warn("Failed to detect git branch.")}let p="1.0.0";try{de.existsSync("./package.json")&&(p=JSON.parse(de.readFileSync("./package.json","utf-8")).version||"1.0.0")}catch{}let g=e.buildProfile||"production",y="Internal";e.developmentClient?y="DevelopmentClient":g.toLowerCase().includes("store")||g.toLowerCase()==="production"?y="Store":g.toLowerCase().includes("preview")||g.toLowerCase().includes("staging")?y="Staging":(g.toLowerCase().includes("development")||g.toLowerCase().includes("dev"))&&(y="Development");let _=e.platform==="ios"?"iOS":"Android",D=e.platform==="ios"&&e.simulator?" (Simulator)":"",b=`${_}${D} v${p} (${y})`;if(Dn(e,{status:"created",projectId:i,buildId:n,platform:e.platform,profile:g,branch:f,version:p,buildType:y,developmentClient:!!e.developmentClient,summary:b}),i){try{let P=e.buildProfile||"production",I=e.environment||P;$.info(v.blue(`Fetching managed secrets for profile: ${P} (environment: ${I})...`));let w=(await k.get(`/projects/${i}/secrets/export?env=${I}`)).data;w.status==="success"&&w.secrets&&(a={...a,...w.secrets},Object.keys(w.secrets).length>0&&$.info(v.magenta(`\u2713 Injected ${Object.keys(w.secrets).length} secrets from Dashboard.`)))}catch(P){$.warn(`Failed to load managed secrets from Dashboard: ${P.message}`)}if(e.platform==="ios"&&e.simulator)$.info(v.dim("Skipping managed iOS signing credentials for simulator build."));else try{$.info(v.blue("Fetching managed credentials..."));let P=au(e,g),I=e.platform==="ios"?e.iosBundleIdentifier:e.androidPackage,T=e.platform==="ios"?"bundle":"package";$.info(v.dim(` Credential target: ${T} ${I||"not set"} (${P})`));let w=await k.get("/credentials/resolve",{params:{projectId:i,platform:e.platform,bundleId:I,distributionType:P,teamId:e.platform==="ios"?e.iosTeamId:void 0}});if(w.data.status==="success"&&w.data.credentials){let C=w.data.credentials;$.info(v.magenta(`\u2713 Found ${C.length} relevant credentials.`));let h=C.filter(N=>e.platform==="ios"&&N.type==="ios_profile"?Yo(N,P,e.platform)?Xo(N,I):!1:e.platform==="android"&&N.type==="android_keystore"?Xo(N,I):!!Yo(N,P,e.platform)).sort((N,W)=>qo(W,I)*10+Jo(W,P,e.platform)-(qo(N,I)*10+Jo(N,P,e.platform)));$.info(v.dim(` Filtered to ${h.length} credentials for distributionType: ${P}`));let M=!1,U=!1,j=!1,X=[];for(let N of h)if(!(N.type==="ios_cert"&&M||N.type==="ios_profile"&&U||N.type==="android_keystore"&&j)&&["ios_cert","ios_profile","android_keystore"].includes(N.type)&&(N.downloadUrl||Xt(N)))try{let ce=await os(N,i);if(N.type==="ios_cert"&&!M)a.IOS_DIST_P12=ce,N.password?(a.IOS_P12_PASSWORD=N.password,$.info(v.dim(` - Injected ${N.name} as IOS_DIST_P12 with password from credential record`))):$.info(v.dim(` - Injected ${N.name} as IOS_DIST_P12`)),M=!0;else if(N.type==="ios_profile"&&!U){if(!du(ce,I)){let ue=ls(ce)||"unknown";throw new Error(`Provisioning profile ${N.name||Xt(N)||"unknown"} is for a different bundle ID. Expected ${I}, found ${ue}. Upload a ${P} profile for ${I}.`)}a.IOS_PROVISIONING_PROFILE=ce,$.info(v.dim(` - Injected ${N.name} as IOS_PROVISIONING_PROFILE`)),U=!0}else if(N.type==="android_keystore"&&!j){a.ANDROID_KEYSTORE_BASE64=ce;let ue=N.keystorePassword||N.password,V=N.keyPassword||N.keystorePassword||N.password,G=N.alias||N.meta?.alias;if(ue)a.ANDROID_STORE_PASSWORD=ue,$.info(v.dim(" - Injected keystore password from credential record"));else{let J=["ANDROID_STORE_PASSWORD",...[P==="store"?"PRODUCTION":P==="internal"||P==="adhoc"?"STAGING":"DEVELOPMENT",P.toUpperCase(),"PRODUCTION","STORE","INTERNAL","STAGING","RELEASE","DEBUG"].map(ae=>`KEYSTORE_PASSWORD_${ae}`),"KEYSTORE_PASSWORD"].find(ae=>!!a[ae]);J&&a[J]&&(a.ANDROID_STORE_PASSWORD=a[J])}if(V?(a.ANDROID_KEY_PASSWORD=V,$.info(v.dim(" - Injected key password from credential record"))):a.ANDROID_KEY_PASSWORD=a.ANDROID_STORE_PASSWORD||"",G)a.ANDROID_KEY_ALIAS=G;else{let Q=["ANDROID_KEY_ALIAS","KEYSTORE_ALIAS"].find(z=>!!a[z]);Q&&(a.ANDROID_KEY_ALIAS=a[Q])}$.info(v.dim(` - Injected ${N.name} as ANDROID_KEYSTORE_BASE64`)),j=!0}}catch(ce){X.push(`${N.name||N.type}: ${ce.message}`)}let H=e.platform==="ios"?e.simulator||M&&U:j||!h.some(N=>N.type==="android_keystore");if(X.length>0&&!H)throw new Error(`Credential setup failed:
|
|
1431
|
+
${X.map(N=>`- ${N}`).join(`
|
|
1432
|
+
`)}`);X.length>0&&$.warn(v.dim(` Skipped ${X.length} stale or unusable credential(s).`))}if(e.platform==="ios"&&!e.simulator){let C=e.buildProfile||"production",h=lt(d,C)||{},M=eu(d,h),U=nu(M),j=e.distribution!==void 0?e.distribution==="store":y==="Store",X=M===void 0&&j,H=e.autoVersion||U&&j||X,N=e.autoVersion||U&&j;if(U&&!j&&$.info(v.dim(` Skipping App Store Connect buildNumber lookup for ${e.distribution||"non-store"} build. Pass --auto-version to force it.`)),H){let W=e.iosBundleIdentifier||d.ios?.bundleIdentifier||d.expo?.ios?.bundleIdentifier,ce=tu(d,h,C),ue=w.data.credentials||[],V=Wo(ue,W);if(!V&&(N||X)){let G=await k.get(`/credentials/${i}`);V=Wo(G.data.credentials||[],W)}if(V){t.start("Resolving latest iOS buildNumber from App Store Connect...");try{let G=V.keyId||V.meta?.keyId,Q=V.issuerId||V.meta?.issuerId;if(!G||!Q)throw new Error("App Store Connect credential is missing keyId or issuerId.");let z=await Vo(V,i),J=await jr({keyId:G,issuerId:Q,privateKey:z,ascAppId:ce,bundleId:W}),ae=/^\d+$/.test(J.latestBuildNumber);ae?(a.BUILD_NUMBER=J.nextBuildNumber,delete a.MACH_IOS_BUILD_NUMBER_LOCKED):(a.BUILD_NUMBER=J.nextBuildNumber,a.CURRENT_PROJECT_VERSION=J.nextBuildNumber,a.MACH_IOS_BUILD_NUMBER_LOCKED="1"),t.stop(ae?`\u2713 Latest iOS buildNumber on App Store Connect: ${v.green(J.latestBuildNumber)} (Mach will assign >= ${J.nextBuildNumber})`:`\u2713 Resolved iOS buildNumber: ${v.green(J.nextBuildNumber)} (Latest on App Store Connect: ${J.latestBuildNumber})`)}catch(G){t.stop("iOS buildNumber lookup failed");let Q=G.response?.data?.error?.message||G.message;if(N)throw new Error(`Auto-versioning failed: ${Q}. Fix App Store Connect API key permissions or remove ios.buildNumber="auto".`);$.warn(v.yellow(`Could not check App Store Connect buildNumber: ${Q}. Falling back to Mach counter.`))}}else if(N)throw new Error(`Auto-versioning failed: App Store Connect API key not found. Upload it with '${m.nameLower} credentials:service --platform ios'.`)}}if(e.platform==="android"){let C=e.buildProfile||"production",h=lt(d,C)||{},j=((h.android||{}).versionCode??h.androidVersionCode??d.android?.versionCode??d.expo?.android?.versionCode)==="auto",X=e.distribution!==void 0?e.distribution==="store":y==="Store",H=e.autoVersion||j&&X;if(j&&!H&&$.info(v.dim(` Skipping Google Play versionCode lookup for ${e.distribution||"non-store"} build. Pass --auto-version to force it.`)),H){t.start("Resolving latest versionCode from Google Play...");try{let N=e.androidPackage||d.android?.package||d.expo?.android?.package||d.name,W=(w.data.credentials||[]).find(Q=>Q.type==="google_service_account"&&(!Q.bundleId||Q.bundleId===N));if(!W){let z=((await k.get(`/credentials/${i}`)).data.credentials||[]).filter(J=>J.type==="google_service_account");if(W=z.find(J=>J.type==="google_service_account"&&J.bundleId===N),!W&&z.length>0){let J=z.map(ae=>ae.bundleId).filter(Boolean).join(", ");throw new Error(`Google Service Account not found for package ${N}. Found service credential(s) for: ${J}.`)}}if(!W)throw new Error(`Google Service Account not found for package ${N}. Upload it under this package in Dashboard or run '${m.nameLower} credentials:service --platform android --package-name ${N}'.`);let ce=await Vo(W,i),ue=Zc(ce,"Google Play service account");if(!ue.client_email||!ue.private_key)throw new Error("Google Play service account JSON is missing client_email or private_key.");let V=await Lr(N,ue);if(V==null)throw new Error("Could not retrieve any version information from Google Play.");let G=V+1;a.ANDROID_VERSION_CODE=G.toString(),t.stop(`\u2713 Resolved versionCode: ${v.green(G)} (Latest on Play Store: ${V})`)}catch(N){t.stop("Version resolution failed");let W=N.response?.data?.error?.message||N.message,ce=Qc(W)?"This looks like a temporary network error while contacting Mach or Google Play. Retry the command, or build and submit as separate steps if it continues.":'Fix Google Play service account permissions or remove android.versionCode="auto".';throw new Error(`Auto-versioning failed: ${W}. ${ce}`)}}}if(e.platform==="ios"&&!e.simulator){let C=!!a.IOS_DIST_P12,h=!!a.IOS_PROVISIONING_PROFILE;if(!C||!h){let M=[...C?[]:["Distribution Certificate"],...h?[]:["Provisioning Profile"]].join(" and ");if(e.local&&e.buildId)throw new Error(`Missing iOS credentials: ${M}. Expected ${P} credentials for ${I||"the selected bundle ID"}. Run \`${m.nameLower} credentials --platform ios --profile ${g}\` and select ${I||"the correct bundle ID"}.`);$.error(v.red(`Missing iOS credentials: ${M}`)),e.quiet&&process.exit(1);let U=e.yes||await Uo({message:"Would you like to generate these credentials now?",initialValue:!0});if(U&&!vn(U))return await Ht({platform:"ios",profile:g}),e.quiet||$.info(v.green("\u2713 Credentials setup complete! Restarting build phase...")),On(e);e.quiet||$.info(v.yellow(`Run \`${m.nameLower} credentials\` to set up signing credentials manually.`)),process.exit(1)}}if(e.platform==="android"&&!e.developmentClient&&(e.distribution==="internal"||e.distribution==="store")&&!(!!a.ANDROID_KEYSTORE_BASE64||!!a.ANDROID_KEYSTORE)){$.error(v.red("Missing Android credentials: Signing Keystore")),e.quiet&&process.exit(1);let h=e.yes||await Uo({message:"Would you like to automatically create and upload an Android Keystore for this profile now?",initialValue:!0});if(h&&!vn(h))return await Ht({platform:"android",profile:g}),e.quiet||$.info(v.green("\u2713 Android Keystore setup complete! Restarting build phase...")),On(e);e.quiet||$.info(v.yellow(`Run \`${m.nameLower} credentials --platform android\` to set up a signing keystore manually.`)),process.exit(1)}}catch(P){(String(P.message||"").startsWith("Credential download failed")||String(P.message||"").startsWith("Credential setup failed")||String(P.message||"").startsWith("Missing iOS credentials")||String(P.message||"").startsWith("Auto-versioning failed"))&&($.error(v.red(P.message)),process.exit(1)),e.platform==="ios"&&e.local&&e.buildId&&($.error(v.red(`Failed to resolve iOS credentials: ${P.message}`)),process.exit(1)),$.warn(`Failed to resolve credentials: ${P.message}`)}}let x=!!(e.local&&e.buildId),A=!!(e.local||e.sshHost),B=!A&&!x;if(x){$.info(v.magenta("\u{1F3D7}\uFE0F Runner Mode: Executing isolated build task..."));let P=await mi({...e,interactive:!1},n,a,i,{branch:f,version:p,summary:b,buildType:y});await q(P),process.exit(0)}async function q(P){let I=async T=>{if(i)try{await _n("Report failed build status",()=>k.patch(`/builds/${i}/${n}`,{status:"failed",error:T,endTime:Date.now()}),3)}catch(w){$.warn(v.yellow(`Could not report failed build status: ${w.message}`))}};if(i&&P.length>0){let T=Fi(),w=[];e.quiet||T.start("Uploading artifacts to Dashboard...");try{for(let C of P){let h=ge.basename(C),M=de.statSync(C).size,U=ge.extname(h).toLowerCase(),j="application/octet-stream",X=await _n(`Create artifact upload URL for ${h}`,()=>k.post(`/builds/${i}/${n}/artifact-upload-url`,{fileName:h,fileType:j}));if(X.data.status!=="success")throw new Error(`Failed to get upload URL for ${h}`);await Jc(C,X.data.uploadUrl,j),w.push({name:h,url:X.data.downloadUrl,size:M,type:U.substring(1)})}e.quiet||T.stop("Artifacts uploaded.")}catch(C){e.quiet||T.stop("Failed to upload artifacts.");let h=`Artifact upload failed: ${C.message}`;throw $.error(v.red(h)),await I(h),new Error(h)}if(i&&w.length>0)try{$.info(v.cyan(`
|
|
1433
|
+
\u{1F517} Download Links:`));for(let C of w)$.info(v.dim(` - ${C.name}: `)+v.blue.underline(C.url));await _n("Finalize build in dashboard",()=>k.patch(`/builds/${i}/${n}`,{status:"success",artifacts:w,endTime:Date.now()})),Dn(e,{status:"success",projectId:i,buildId:n,platform:e.platform,profile:g,branch:f,version:p,buildType:y,developmentClient:!!e.developmentClient,summary:b,artifacts:w}),$.success(v.green(`
|
|
1434
|
+
\u2713 Build completed and reported to dashboard.`)),e.maestro&&!x&&await Zo(i,n,e,g),e.autoSubmit&&!x&&await Ui(i,n,e,g)}catch(C){let h=`Build artifact uploaded but dashboard finalization failed: ${C.message}`;throw $.error(v.red(`
|
|
1435
|
+
${h}`)),await I(h),new Error(h)}}else if(i){let T="Build completed but produced no uploadable artifacts.";throw $.error(v.red(T)),await I(T),new Error(T)}}if(A){if($.info(v.cyan(`\u{1F680} Direct Build Mode: Executing on ${e.sshHost||"local"}...`)),i&&!o){let P=process.argv.slice(3).join(" ");await k.post("/builds",{projectId:i,buildId:n,platform:e.platform,status:"building",branch:f,version:p,summary:b,startTime:r,buildType:y,buildProfile:g,buildArgs:P,framework:e.framework,simulator:!!e.simulator,developmentClient:!!e.developmentClient,...Qo(e,n,g,u)}),es(e)}if(e.sshHost&&e.platform==="ios")await kr(e,n,a,i),e.autoSubmit&&await Ui(i,n,e,g);else{let P=await mi({...e,interactive:!!e.local},n,a,i,{branch:f,version:p,summary:b,buildType:y});await q(P)}return}if(B&&($.info(v.blue("\u{1F6F0}\uFE0F Cloud Initiator Mode: Preparing orchestration...")),!e.dryRun)){e.quiet||t.start("Zipping and uploading local source...");let P=await k.post("/builds/source-upload-url",{projectId:i,buildId:n});if(P.data.status!=="success")throw t.stop("Failed to get upload URL."),new Error("Failed to get source upload URL from API");let I=new Ho,T=Fc(I,process.cwd(),e.platform),w=I.toBuffer();if(!e.quiet){let h=T.skipped.length>0?` Skipped: ${T.skipped.join(", ")}.`:"";t.message(`Prepared source (${T.files} files).${h}`)}e.quiet||t.message(`Uploading source (${(w.length/1024/1024).toFixed(1)} MB)...`);let C=!1;for(let h=1;h<=3;h++)try{await $n.put(P.data.uploadUrl,w,{headers:{"Content-Type":"application/zip"},maxBodyLength:1/0,maxContentLength:1/0,timeout:12e4}),C=!0;break}catch(M){if(h<3)t.message(`Upload attempt ${h} failed (${M.code||M.message}), retrying...`),await new Promise(U=>setTimeout(U,2e3*h));else throw M}if(e.quiet||t.stop("Source uploaded"),i){let h=process.argv.slice(3).join(" ");await k.post("/builds",{projectId:i,buildId:n,platform:e.platform,status:"pending",branch:f,version:p,summary:b,startTime:r,buildType:y,buildProfile:g,buildArgs:h,framework:e.framework,simulator:!!e.simulator,developmentClient:!!e.developmentClient,...Qo(e,n,g,u)}),$.info(v.green("\u2713 Cloud build registered.")),es(e)}e.platform==="android"&&await Cr(e,n,a,i,e.preBuild),e.quiet||$.info(v.cyan("\u{1F4E1} Connecting to build stream...")),await pu(i,n,e),e.maestro&&await Zo(i,n,e,g),e.autoSubmit&&await Ui(i,n,e,g);return}}catch(l){let a=l.message||"Build failed";l.response?.data?.message?a=l.response.data.message:l.message.includes("status code 402")?a="Insufficient wallet balance. Please add credits in the Dashboard.":l.message.includes("status code 403")&&(a="Monthly build quota exceeded. Upgrade your plan in the Dashboard."),i&&await s(a),$.error(v.red(`\u2717 Build failed: ${a}`)),process.exit(1)}};async function Zo(e,t,n,i){$.info(v.cyan(`
|
|
1436
|
+
\u{1F3BC} Queuing managed Maestro test...`)),await Ii({projectId:e,buildId:t,platform:n.platform,profile:i,maestroFlows:n.maestroFlows,maestroDevice:n.maestroDevice,maestroRetries:n.maestroRetries,maestroRecord:n.maestroRecord,maestroUseBuildSource:n.maestroUseBuildSource,maestroEnv:n.maestroEnv,quiet:n.quiet})}async function Ui(e,t,n,i){if(!e){$.error(v.red("Auto-submit requires a linked Mach project. Run `mach link` or pass --project-id.")),process.exitCode=1;return}$.info(v.cyan(`
|
|
1437
|
+
Auto-submit: submitting the successful build...`));try{let r=await cu(e,t);if(r?.autoSubmit){let o=r.submissionId?`${Je}/submissions/${r.submissionId}?projectId=${encodeURIComponent(e)}`:void 0,s=String(r.status||"").toLowerCase(),l=String(r.autoSubmitStatus||"").toLowerCase(),a=r.submissionId||["success","completed","succeeded"].includes(s)||["starting","submitted","failed","skipped"].includes(l);if(r.submissionId?($.info(v.green(`Auto-submit is already queued by Mach backend: ${r.submissionId}`)),$.info(v.dim(`Dashboard: ${o}`))):r.autoSubmitStatus==="failed"?$.warn(v.yellow(`Backend auto-submit failed: ${r.autoSubmitError||"Unknown error"}`)):a&&$.info(v.green("Auto-submit is registered with Mach backend; skipping local duplicate submit.")),a){ct(n,{status:r.autoSubmitStatus||"pending",projectId:e,submitId:r.submissionId,platform:n.platform,profile:i,buildId:t,dashboardUrl:o});return}}await wn({platform:n.platform,profile:i,buildProfile:i,buildId:t,projectId:e,yes:n.yes,quiet:n.quiet,track:n.submitTrack,releaseStatus:n.submitReleaseStatus,rollout:n.submitRollout,changesNotSentForReview:n.submitChangesNotSentForReview,credentialId:n.submitCredentialId,packageName:n.androidPackage,jsonOutput:n.submitJsonOutput,submitArgs:ds(n,t,i)})}catch(r){$.error(v.red(`Auto-submit failed: ${r.message||r}`)),process.exitCode=1}}function ds(e,t,n){let i=["--platform",e.platform,"--profile",n,"--build-id",t];return e.submitTrack&&i.push("--track",String(e.submitTrack)),e.submitReleaseStatus&&i.push("--release-status",String(e.submitReleaseStatus)),e.submitRollout!==void 0&&i.push("--rollout",String(e.submitRollout)),e.submitChangesNotSentForReview&&i.push("--changes-not-sent-for-review"),e.submitCredentialId&&i.push("--credential-id",e.submitCredentialId),e.platform==="android"&&e.androidPackage&&i.push("--package-name",e.androidPackage),e.platform==="ios"&&e.iosBundleIdentifier&&i.push("--bundle-id",e.iosBundleIdentifier),e.submitJsonOutput&&i.push("--json-output",e.submitJsonOutput),i.join(" ")}async function cu(e,t){try{let i=(await k.get(`/builds/${e}/${t}`)).data?.build;if(i?.autoSubmit)return i}catch(n){$.warn(v.dim(`Could not check backend auto-submit status: ${n.message}`))}return null}function cs(e){for(let t of Object.keys(e))e[t]===void 0&&delete e[t];return e}function uu(e,t,n){let i=n?.submit?.[t]?.android||{},r=n?.submit?.production?.android||{},o=e.submitTrack||i.track||r.track,s=e.submitReleaseStatus||i.releaseStatus||r.releaseStatus,l=e.submitRollout??i.rollout??i.userFraction??i.rolloutFraction??r.rollout??r.userFraction??r.rolloutFraction,a=e.submitChangesNotSentForReview??i.changesNotSentForReview??i.changes_not_sent_for_review??r.changesNotSentForReview??r.changes_not_sent_for_review;return cs({track:o,releaseStatus:s,rollout:l,changesNotSentForReview:a===void 0?!1:a===!0||a==="true"||a==="1"})}function Qo(e,t,n,i){if(!e.autoSubmit||e.dryRun)return{};let r=e.platform==="android"?uu(e,n,i):{};return{autoSubmit:!0,autoSubmitStatus:"pending",autoSubmitOptions:cs({platform:e.platform,profile:n,buildId:t,latest:!1,...r,credentialId:e.submitCredentialId,packageName:e.platform==="android"?e.androidPackage:void 0,bundleId:e.platform==="ios"?e.iosBundleIdentifier:void 0,submitArgs:ds(e,t,n)})}}function es(e){!e.autoSubmit||e.dryRun||e.quiet||($.info(v.green("\u2713 Auto-submit has been registered with the build.")),$.info(v.dim(" You can close this terminal; submission will start after build success.")))}function ts(e){return`${Je}/build/${e}`}function Dn(e,t){if(!e.jsonOutput)return;let n=ge.resolve(e.jsonOutput),i={...t,url:t.url||ts(t.buildId),dashboardUrl:t.dashboardUrl||ts(t.buildId),updatedAt:new Date().toISOString()};try{let r=ge.dirname(n);r&&r!=="."&&de.mkdirSync(r,{recursive:!0}),de.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){$.warn(v.yellow(`Could not write build metadata JSON: ${r.message}`))}}async function pu(e,t,n){let i=Fi(),r="pending",o=0,s=0;for(n.quiet||i.start("Connecting to build stream...");;){try{let a=(await k.get(`/builds/${e}/${t}`)).data.build;if(a){if(r=a.status,r==="building")n.quiet||i.message("Build in progress...");else if(r==="failed")n.quiet||i.stop("Build failed."),Dn(n,{status:"failed",projectId:e,buildId:t,platform:n.platform,profile:a.buildProfile,buildType:a.buildType,developmentClient:!!a.developmentClient,version:a.version,summary:a.summary,error:a.error||"Unknown error",artifacts:a.artifacts||[]}),$.error(v.red(`
|
|
1438
|
+
\u2717 Build failed: ${a.error||"Unknown error"}`)),process.exit(1);else if(r==="completed"||r==="success"){n.quiet||i.stop("Build successful!"),Dn(n,{status:r,projectId:e,buildId:t,platform:n.platform,profile:a.buildProfile,buildType:a.buildType,developmentClient:!!a.developmentClient,version:a.version,summary:a.summary,artifacts:a.artifacts||[]}),$.success(v.green(`
|
|
1439
|
+
\u2713 Build completed successfully!`));try{n.quiet||($.info(v.magenta(`
|
|
1440
|
+
\u{1F4F1} Installation Hub:`)),$.info(v.dim(" - View & Install Build: ")+v.white.underline(`${Je}/build/${t}`)))}catch{}return}else if(r!=="pending"){n.quiet||i.stop(`Build status: ${r}`);return}}try{let u=(await k.get(`/builds/${e}/${t}/logs`)).data;if(u&&typeof u=="string"&&!n.quiet){let d=u.split(`
|
|
1441
|
+
`);if(d.length>o){for(let f=o;f<d.length;f++)d[f].trim()&&console.log(v.dim(` ${d[f]}`));o=d.length}}}catch{}s=0}catch{s++,s>10&&(i.stop("Connection lost."),$.error(v.red(`
|
|
1442
|
+
\u2717 Lost connection to Dashboard API.`)),process.exit(1))}await new Promise(l=>setTimeout(l,3e3))}}import*as Ln from"http";import*as Ss from"net";import{execFile as fu,execFileSync as mt,execSync as Tn,spawn as us}from"child_process";import pe from"chalk";import{log as ee}from"@clack/prompts";import mu from"axios";import se from"fs";import Ke from"os";import Z from"path";var st=7070,Zt=`http://127.0.0.1:${st}`,xt="com.radhya.mach.agent",kt="Mach Agent",Lt=`${xt}.service`,gu=5e3,hu=3e3,Cn=null,Nn=null,Ve=()=>Z.join(Ke.homedir(),m.configDir),ys=()=>Z.join(Ke.homedir(),"Library","LaunchAgents"),kn=()=>Z.join(ys(),`${xt}.plist`),bs=()=>Z.join(Ke.homedir(),".config","systemd","user"),Hi=()=>Z.join(bs(),Lt),ji=()=>Z.join(Ve(),"agent.cmd");function Gi(){return`gui/${process.getuid?.()||Number(Tn("id -u").toString().trim())}`}function Es(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function qt(e){return`<string>${Es(e)}</string>`}function Ki(){let e=process.argv[1]?se.realpathSync(process.argv[1]):"";if(!e||!se.existsSync(e))throw new Error("Could not resolve the current Mach CLI entrypoint.");return[process.execPath,e,"agent","run"]}function Vi(){let e=As(),t=process.platform==="win32"?[process.env.SystemRoot?Z.join(process.env.SystemRoot,"System32"):void 0,process.env.SystemRoot]:["/opt/homebrew/bin","/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"],n={HOME:Ke.homedir(),PATH:[process.env.PATH,...e.flatMap(i=>[Z.join(i,"platform-tools"),Z.join(i,"emulator"),Z.join(i,"cmdline-tools","latest","bin"),Z.join(i,"tools","bin")]),...t].filter(Boolean).join(Z.delimiter)};for(let i of["ANDROID_HOME","ANDROID_SDK_ROOT","JAVA_HOME","SHELL"])process.env[i]&&(n[i]=process.env[i]);return n}function As(){let e=[process.env.ANDROID_HOME,process.env.ANDROID_SDK_ROOT];if(process.platform==="darwin")e.push(Z.join(Ke.homedir(),"Library","Android","sdk"));else if(process.platform==="linux")e.push(Z.join(Ke.homedir(),"Android","Sdk"),Z.join(Ke.homedir(),"Android","sdk"),"/opt/android-sdk","/usr/lib/android-sdk");else if(process.platform==="win32"){let t=process.env.LOCALAPPDATA,n=process.env.USERPROFILE||Ke.homedir();e.push(t?Z.join(t,"Android","Sdk"):void 0,Z.join(n,"AppData","Local","Android","Sdk"))}return Array.from(new Set(e.filter(t=>!!t)))}function Su(e){return process.platform==="win32"&&!e.toLowerCase().endsWith(".exe")?`${e}.exe`:e}function Is(e,t){let n=Su(e);for(let i of As()){let r=Z.join(i,t,n);if(se.existsSync(r))return r}return n}function ws(){return Is("adb","platform-tools")}function _s(){return Is("emulator","emulator")}function Bi(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}"`}function yu(){if(process.platform!=="linux")throw new Error("Linux service install requires Linux.");se.mkdirSync(Ve(),{recursive:!0}),se.mkdirSync(bs(),{recursive:!0});let e=Ki(),t=Vi(),n=Object.entries(t).map(([r,o])=>`Environment=${Bi(`${r}=${o}`)}`).join(`
|
|
1346
1443
|
`),i=`[Unit]
|
|
1347
1444
|
Description=Mach local device agent
|
|
1348
1445
|
After=default.target
|
|
1349
1446
|
|
|
1350
1447
|
[Service]
|
|
1351
1448
|
Type=simple
|
|
1352
|
-
ExecStart=${e.map(
|
|
1353
|
-
WorkingDirectory=${
|
|
1449
|
+
ExecStart=${e.map(Bi).join(" ")}
|
|
1450
|
+
WorkingDirectory=${Bi(Ke.homedir())}
|
|
1354
1451
|
${n}
|
|
1355
1452
|
Restart=on-failure
|
|
1356
1453
|
RestartSec=5
|
|
@@ -1359,20 +1456,20 @@ StandardError=append:%h/${m.configDir}/agent.error.log
|
|
|
1359
1456
|
|
|
1360
1457
|
[Install]
|
|
1361
1458
|
WantedBy=default.target
|
|
1362
|
-
`;return
|
|
1459
|
+
`;return se.writeFileSync(Hi(),i),Hi()}function ft(e,t={}){try{return mt("systemctl",["--user",...e],{stdio:t.ignoreError?"ignore":"pipe"}),!0}catch(n){if(t.ignoreError)return!1;throw n}}function bu(){if(process.platform!=="win32")throw new Error("Windows agent script requires Windows.");se.mkdirSync(Ve(),{recursive:!0});let e=Vi(),[t,n,...i]=Ki(),r=Z.join(Ve(),"agent.log"),o=Z.join(Ve(),"agent.error.log"),s=Object.entries(e).map(([c,u])=>`set "${c}=${u}"`).join(`\r
|
|
1363
1460
|
`),l=i.map(c=>`"${c.replace(/"/g,'\\"')}"`).join(" "),a=`@echo off\r
|
|
1364
1461
|
${s}\r
|
|
1365
|
-
cd /d "${
|
|
1462
|
+
cd /d "${Ke.homedir()}"\r
|
|
1366
1463
|
"${t}" "${n}" ${l} >> "${r}" 2>> "${o}"\r
|
|
1367
|
-
`;return
|
|
1368
|
-
${
|
|
1369
|
-
`),o=e.map(l=>` ${
|
|
1464
|
+
`;return se.writeFileSync(ji(),a),ji()}function Qt(e,t={}){try{return mt("schtasks.exe",e,{stdio:t.ignoreError?"ignore":"pipe"}),!0}catch(n){if(t.ignoreError)return!1;throw n}}function Eu(){if(process.platform!=="darwin")throw new Error("Background agent install currently supports macOS only.");se.mkdirSync(Ve(),{recursive:!0}),se.mkdirSync(ys(),{recursive:!0});let e=Ki(),t=Vi(),n=Z.join(Ve(),"agent.log"),i=Z.join(Ve(),"agent.error.log"),r=Object.entries(t).map(([l,a])=>` <key>${Es(l)}</key>
|
|
1465
|
+
${qt(a)}`).join(`
|
|
1466
|
+
`),o=e.map(l=>` ${qt(l)}`).join(`
|
|
1370
1467
|
`),s=`<?xml version="1.0" encoding="UTF-8"?>
|
|
1371
1468
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
1372
1469
|
<plist version="1.0">
|
|
1373
1470
|
<dict>
|
|
1374
1471
|
<key>Label</key>
|
|
1375
|
-
${
|
|
1472
|
+
${qt(xt)}
|
|
1376
1473
|
<key>ProgramArguments</key>
|
|
1377
1474
|
<array>
|
|
1378
1475
|
${o}
|
|
@@ -1384,28 +1481,28 @@ ${r}
|
|
|
1384
1481
|
<key>RunAtLoad</key>
|
|
1385
1482
|
<true/>
|
|
1386
1483
|
<key>StandardOutPath</key>
|
|
1387
|
-
${
|
|
1484
|
+
${qt(n)}
|
|
1388
1485
|
<key>StandardErrorPath</key>
|
|
1389
|
-
${
|
|
1486
|
+
${qt(i)}
|
|
1390
1487
|
</dict>
|
|
1391
1488
|
</plist>
|
|
1392
|
-
`;return
|
|
1393
|
-
`).forEach(n=>{if(n.includes("List of devices")||!n.trim())return;let i=n.split(/\s+/);if(i.length<2||i[1]!=="device")return;let r=i[0],o=n.match(/model:([^\s]+)/);e.push({id:r,platform:"android",type:r.startsWith("emulator-")?"emulator":"physical",name:o?o[1].replace(/_/g," "):r,status:"online",details:n.trim()})})}catch{}try{let n=(await
|
|
1394
|
-
`).filter(r=>!!r.trim()),i=e.some(r=>r.platform==="android"&&r.id.startsWith("emulator-"));n.forEach(r=>{i||e.push({id:r,platform:"android",type:"emulator",name:r.replace(/_/g," "),status:"offline",details:`Android Virtual Device: ${r}`})})}catch{}return e}async function qc(){if(process.platform!=="darwin")return[];try{let e=await On("/usr/bin/xcrun",["simctl","list","devices","--json"]),t=JSON.parse(e),n=[];return Object.entries(t.devices||{}).forEach(([i,r])=>{r.forEach(o=>{o.isAvailable&&n.push({id:o.udid,platform:"ios",type:"simulator",name:o.name,status:o.state?.toLowerCase()==="booted"?"online":"offline",runtime:i,details:`${o.name} (${i})`})})}),n}catch{return[]}}async function Xc(){if(process.platform!=="darwin")return[];try{let e=await On("/usr/bin/xcrun",["devicectl","list","devices","--json-output","-"]);return(JSON.parse(e).result?.devices||[]).filter(n=>{let i=n.connectionProperties?.transportType;return i==="wired"||i==="localNetwork"}).map(n=>{let i=n.connectionProperties?.transportType,r=n.deviceProperties?.name||"iPhone";return{id:n.identifier,platform:"ios",type:"physical",name:r,status:"online",details:`${r} (${n.model?.name||n.hardwareModel||""}) - ${i}`}})}catch{return[]}}async function Zc(){let[e,t,n]=await Promise.all([Jc(),qc(),Xc()]);return[...e,...t,...n]}async function Qc(){let e=Date.now();return vn&&e-vn.updatedAt<Tc?vn.targets:(Rn||(Rn=Zc().then(t=>(vn={targets:t,updatedAt:Date.now()},t)).finally(()=>{Rn=null})),Rn)}async function Yo(e){let t=[];for await(let n of e)t.push(Buffer.isBuffer(n)?n:Buffer.from(n));return t.length===0?{}:JSON.parse(Buffer.concat(t).toString("utf-8"))}async function eu(e,t){let n=await Cc({method:"GET",url:e,responseType:"stream",timeout:12e4}),i=pe.createWriteStream(t);n.data.pipe(i),await new Promise((r,o)=>{i.on("finish",r),i.on("error",o)})}async function tu(e,t,n){let i=n||(t.toLowerCase().includes(".apk")?"android":"ios"),r=t.toLowerCase().includes(".ipa"),o=pe.mkdtempSync(ie.join(je.tmpdir(),`${et}-install-`)),s=ie.join(o,i==="android"?"install.apk":r?"install.ipa":"install.zip");try{if(await eu(t,s),i==="android"){Cn(ts(),["-s",e,"install","-r",s],{stdio:"pipe"});return}if(process.platform!=="darwin")throw new Error("iOS local install requires macOS.");yt(`unzip -o ${JSON.stringify(s)} -d ${JSON.stringify(o)}`,{stdio:"pipe"});let l="";try{l=yt(`find ${JSON.stringify(ie.join(o,"Payload"))} -maxdepth 1 -name "*.app" 2>/dev/null | head -n 1`,{stdio:"pipe"}).toString().trim()}catch{}if(l||(l=yt(`find ${JSON.stringify(o)} -name "*.app" -type d | head -n 1`,{stdio:"pipe"}).toString().trim()),!l)throw new Error(`No .app bundle found inside the ${r?"IPA":"archive"}.`);try{yt(`/usr/bin/xcrun devicectl device install app --device ${JSON.stringify(e)} ${JSON.stringify(l)}`,{stdio:"pipe"})}catch(a){try{yt(`/usr/bin/xcrun simctl install ${JSON.stringify(e)} ${JSON.stringify(l)}`,{stdio:"pipe"})}catch{throw new Error(a.stderr?.toString().trim()||a.message||"iOS install failed.")}}}finally{pe.rmSync(o,{recursive:!0,force:!0})}}function nu(e,t){if(!e)throw new Error("Device id is required.");if(t==="ios"){if(process.platform!=="darwin")throw new Error("iOS Simulator launch requires macOS.");return yt(`/usr/bin/xcrun simctl boot ${JSON.stringify(e)}`,{stdio:"pipe"}),Vo("open",["-a","Simulator"],{detached:!0,stdio:"ignore"}).unref(),"Simulator booting..."}if(t==="android")return Vo(ns(),["-avd",e],{detached:!0,stdio:"ignore",windowsHide:!0}).unref(),"Emulator booting in background...";throw new Error("Invalid platform.")}async function iu(){process.platform!=="darwin"&&ee.warn("Running on non-macOS \u2014 iOS discovery unavailable, Android only.");let e=Dn.createServer((i,r)=>{if(r.setHeader("Access-Control-Allow-Origin","*"),r.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),r.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),i.method==="OPTIONS"){r.writeHead(204),r.end();return}let o=new URL(i.url||"/",`http://localhost:${et}`);if(i.method==="GET"&&o.pathname==="/local/devices"){Qc().then(s=>{r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"success",targets:s}))}).catch(s=>{r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"error",message:s.message}))});return}if(i.method==="GET"&&o.pathname==="/health"){r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"success",service:"mach-agent",port:et,platform:process.platform}));return}if(i.method==="POST"&&o.pathname==="/install-local"){t(i,r);return}if(i.method==="POST"&&o.pathname==="/local/boot"){n(i,r);return}r.writeHead(404),r.end()}),t=async(i,r)=>{try{let{deviceId:o,artifactUrl:s,platform:l}=await Yo(i);if(!o||!s){r.writeHead(400,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"error",message:"deviceId and artifactUrl are required"}));return}await tu(o,s,l),r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"success",message:`Installed on ${o}`}))}catch(o){r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"error",message:o.message||"Local install failed"}))}},n=async(i,r)=>{try{let{id:o,platform:s}=await Yo(i),l=nu(o,s);r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"success",message:l}))}catch(o){r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"error",message:o.message||"Local device launch failed"}))}};e.listen(et,"127.0.0.1",()=>{ee.success(ce.green(`Local device agent running on http://localhost:${et}`)),ee.info(ce.dim("Keep this running while using the Install Hub on the dashboard.")),ee.info(ce.dim("Press Ctrl+C to stop."))}),e.on("error",i=>{i.code==="EADDRINUSE"?ee.error(`Port ${et} is already in use \u2014 agent may already be running.`):ee.error(`Agent error: ${i.message}`),process.exit(1)}),await new Promise(()=>{})}async function as(e="start"){let t=String(e||"start").toLowerCase();if(t==="start"||t==="run"){await iu();return}if(t==="install"){await zo();return}if(t==="status"){await Yc();return}if(t==="stop"){await Wo();return}if(t==="uninstall"){await Wc();return}if(t==="restart"){await Wo(),await zo();return}ee.error(`Unknown agent action: ${e}`),ee.info(ce.dim(`Use: ${m.nameLower} agent start | install | status | restart | stop | uninstall`)),process.exit(1)}import{createRequire as kf}from"module";import{text as ou,password as su,spinner as au,isCancel as cs}from"@clack/prompts";import ji from"chalk";import zt from"fs";import ls from"path";import ru from"os";var Fi=ls.join(ru.homedir(),m.configDir),Bi=ls.join(Fi,"config.json");function Hi(){if(!zt.existsSync(Bi))return{};try{return JSON.parse(zt.readFileSync(Bi,"utf-8"))}catch{return{}}}function ds(e){zt.existsSync(Fi)||zt.mkdirSync(Fi,{recursive:!0});let n={...Hi(),...e};zt.writeFileSync(Bi,JSON.stringify(n,null,2))}async function us(){let e=Hi(),t=await ou({message:"Enter your email:",placeholder:"user@example.com",initialValue:e.lastLoginEmail,validate(r){if(r.length===0)return"Email is required!"}});if(cs(t))return;let n=await su({message:"Enter your password:",validate(r){if(r.length===0)return"Password is required!"}});if(cs(n))return;let i=au();i.start("Authenticating...");try{let o=await(await fetch(`${bt}/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:t,password:n})})).json();o.status==="success"&&o.user.token?(er({id:o.user.id,email:t,token:o.user.token,refreshToken:o.user.refreshToken}),ds({lastLoginEmail:t}),i.stop(ji.green("Login successful!"))):i.stop(ji.red("Login failed: "+(o.message||"Unknown error")))}catch(r){i.stop(ji.red("Network error: "+r.message))}}import{log as Nn,outro as lu}from"@clack/prompts";import Wt from"chalk";async function fs(){let e=tr(),t=`${m.envPrefix}TOKEN`;e?Nn.success(Wt.green(`Logged out. Removed saved credentials from ~/${m.configDir}/credentials.json.`)):Nn.warn(Wt.yellow(`No saved ${m.name} credentials found.`)),process.env[t]&&(Nn.warn(Wt.yellow(`${t} is still set in this shell. Commands will continue to authenticate with that token until you unset it.`)),Nn.info(Wt.dim(`Run: unset ${t}`))),lu(Wt.blue("---"))}import{outro as du,select as cu,spinner as uu,isCancel as fu}from"@clack/prompts";import Tn from"chalk";import Gi from"fs";import pu from"path";var ps=e=>e==="1234567890"||e==="ABC123DEFG"||e==="XXXXXXXXXX"?"":typeof e=="string"?e:"",mu=()=>process.versions.node.split(".")[0]||"24";async function ms(){if(!Pe()){console.log(Tn.red(`You are not logged in. Run \`${m.nameLower} login\` first.`));return}let t=uu();t.start("Fetching projects...");try{let{data:n}=await N.get("/projects");if(t.stop("Projects loaded."),n.status!=="success"||!n.projects||n.projects.length===0){console.log(Tn.yellow(`No projects found. Run \`${m.nameLower} init\` to create one.`));return}let i=n.projects.map(h=>({value:h.projectId,label:`${h.name} (${h.slug})`})),r=await cu({message:"Select a project to link:",options:i});if(fu(r))return;let o=pu.join(process.cwd(),m.configFileName),s={};if(Gi.existsSync(o))try{s=JSON.parse(Gi.readFileSync(o,"utf-8"))}catch{}let l=n.projects.find(h=>h.projectId===r),a=s.android?.package||Ze("android"),c=s.ios?.bundleIdentifier||Ze("ios"),u=s.android||{},d=s.submit?.production?.android||{},p=s.submit?.production?.ios||{},f={projectId:r,framework:ir(s.framework)||ln,name:l?.name,slug:l?.slug,nodeVersion:s.nodeVersion||mu(),scheme:l?.slug?.toLowerCase()||"app",android:{...u,package:a||"",versionCode:u.versionCode||"auto"},ios:{bundleIdentifier:c||"",buildNumber:s.ios?.buildNumber||"auto"},build:{development:{environment:"development",distribution:"development"},staging:{environment:"staging",distribution:"internal"},production:{environment:"production",distribution:"store"}},submit:{production:{android:{...d,track:d.track||"internal",releaseStatus:d.releaseStatus||"completed"},ios:{ascAppId:ps(p.ascAppId),appleTeamId:ps(p.appleTeamId)}}}};Gi.writeFileSync(o,JSON.stringify(f,null,2)),du(Tn.green(`Linked to project ${f.name} (${f.slug})`))}catch(n){t.stop(Tn.red("Error fetching projects: "+n.message))}}import{outro as gu,text as kn,select as hu,spinner as yu,isCancel as Yt}from"@clack/prompts";import Jt from"chalk";import Su from"fs";import bu from"path";import{randomUUID as Au}from"crypto";var Eu=()=>process.versions.node.split(".")[0]||"24";async function gs(){if(!Pe()){console.log(Jt.red(`You are not logged in. Run \`${m.nameLower} login\` first.`));return}let t=await kn({message:"Project Name:",placeholder:"My Awesome App",validate(l){if(l.length===0)return"Name is required!"}});if(Yt(t))return;let n=await kn({message:"Project Slug (URL friendly):",placeholder:"my-awesome-app",validate(l){if(l.length===0)return"Slug is required!";if(!/^[a-z0-9-]+$/.test(l))return"Slug must be lowercase alphanumeric with dashes."}});if(Yt(n))return;let i=await hu({message:"Platform:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"},{value:"web",label:"Web"},{value:"all",label:"All Platforms"}]});if(Yt(i))return;let r="";if(i==="android"||i==="all"){let l=Ze("android");if(r=await kn({message:"Android Package Name:",initialValue:l||"",placeholder:"com.example.app",validate(a){if(a.length===0)return"Package name is required for Android!"}}),Yt(r))return}let o="";if(i==="ios"||i==="all"){let l=Ze("ios");if(o=await kn({message:"iOS Bundle Identifier:",initialValue:l||"",placeholder:"com.example.app",validate(a){if(a.length===0)return"Bundle ID is required for iOS!"}}),Yt(o))return}let s=yu();s.start("Creating project...");try{let l=Au(),c={projectId:l,name:t,slug:n,storageType:"managed",platforms:i==="all"?["android","ios","web"]:[i]},{data:u}=await N.post("/projects",c);if(u.status==="success"){s.stop(Jt.green("Project created successfully!"));let d=bu.join(process.cwd(),m.configFileName);Su.writeFileSync(d,JSON.stringify({projectId:l,framework:ln,name:t,slug:n,nodeVersion:Eu(),...r?{android:{package:r,versionCode:"auto"}}:{},...o?{ios:{bundleIdentifier:o,buildNumber:"auto"}}:{},build:{development:{environment:"development",distribution:"development"},staging:{environment:"staging",distribution:"internal"},production:{environment:"production",distribution:"store"}},submit:{production:{android:{track:"internal",releaseStatus:"completed"},ios:{ascAppId:"",appleTeamId:""}}}},null,2)),gu(Jt.green(`Initialized project ${t} and linked locally!`))}else s.stop(Jt.red("creation failed: "+u.message))}catch(l){s.stop(Jt.red("Network error: "+l.message))}}import{spinner as Ki,log as Re}from"@clack/prompts";import qt from"chalk";import xn from"fs";import hs from"path";function Vi(e,t,n,i){let r=e?.response?.status,o=e?.response?.data?.message||e?.response?.data?.error,s=i?` ${i}`:"";return r===401?`Not logged in or token expired while trying to ${n}${s}. Run \`${m.nameLower} login\` and try again.`:r===403?[`Permission denied while trying to ${n}${s}.`,o?`API says: ${o}.`:void 0,`Current Mach account/token does not have access to project ${t}.`,`Run \`${m.nameLower} login\` with the correct account, or ask a project owner to grant access.`].filter(Boolean).join(" "):r===404?[`Project or environment endpoint was not found while trying to ${n}${s}.`,`Project ID: ${t}.`,o?`API says: ${o}.`:void 0].filter(Boolean).join(" "):r?`Failed to ${n}${s}: ${o||`API returned HTTP ${r}`}`:`Network error while trying to ${n}${s}: ${e?.message||"Unknown error"}`}function Iu(e){let t=String(e??"");return t===""?'""':/^[A-Za-z0-9_./:@%+-]+$/.test(t)?t:JSON.stringify(t)}function wu(e,t){return`${[`# Generated by ${m.nameLower} env pull --environment ${t}`,"# Do not commit this file.","",...Object.keys(e).sort((i,r)=>i.localeCompare(r)).map(i=>`${i}=${Iu(e[i])}`)].join(`
|
|
1489
|
+
`;return se.writeFileSync(kn(),s),kn()}function pt(e,t={}){try{return mt("launchctl",e,{stdio:t.ignoreError?"ignore":"pipe"}),!0}catch(n){if(t.ignoreError)return!1;throw n}}function Au(e){return new Promise(t=>setTimeout(t,e))}function xn(e,t,n=gu){return new Promise((i,r)=>{fu(e,t,{timeout:n,maxBuffer:10*1024*1024,windowsHide:!0},(o,s,l)=>{if(o){let a=l?.toString().trim();r(new Error(a||o.message));return}i(s?.toString()||"")})})}async function Rs(){if(typeof fetch=="function"){let e=new AbortController,t=setTimeout(()=>e.abort(),3e3);try{return(await fetch(`${Zt}/health`,{signal:e.signal})).ok}catch{return!1}finally{clearTimeout(t)}}return new Promise(e=>{let t=!1,n=r=>{t||(t=!0,e(r))},i=Ln.get(`${Zt}/health`,r=>{r.resume(),n(r.statusCode===200)});i.setTimeout(3e3,()=>{i.destroy(),n(!1)}),i.on("error",()=>n(!1))})}async function Iu(e=8e3){let t=Date.now()+e;for(;Date.now()<t;){if(await Rs())return!0;await Au(250)}return!1}async function $s(){return new Promise(e=>{let t=!1,n=Ss.createConnection({host:"127.0.0.1",port:st}),i=r=>{t||(t=!0,n.destroy(),e(r))};n.setTimeout(1e3),n.once("connect",()=>i(!0)),n.once("timeout",()=>i(!1)),n.once("error",()=>i(!1))})}async function zi(){if(await Iu()){ee.success(pe.green("Mach agent installed and started."));return}if(await $s()){ee.warn(`Mach agent service is installed, but port ${st} is held by a process that is not answering /health.`),ee.info(pe.dim(`Run \`${m.nameLower} agent stop\`, close any foreground \`${m.nameLower} agent\` terminal, then run \`${m.nameLower} agent install\` again.`));return}ee.warn(`Mach agent service is installed, but it did not start listening on ${Zt}.`)}async function wu(){let e=Eu(),t=Gi();pt(["bootout",t,e],{ignoreError:!0}),pt(["bootstrap",t,e],{ignoreError:!0})||pt(["load","-w",e]),pt(["enable",`${t}/${xt}`],{ignoreError:!0}),pt(["kickstart","-k",`${t}/${xt}`],{ignoreError:!0}),await zi(),ee.info(pe.dim(`It will start automatically when you log in. Plist: ${e}`)),ee.info(pe.dim(`Logs: ${Z.join(Ve(),"agent.log")}`))}async function vs(){let e=kn(),t=Gi();pt(["bootout",t,e],{ignoreError:!0})||pt(["unload","-w",e],{ignoreError:!0})?ee.success(pe.green("Mach agent service stopped.")):ee.warn("Mach agent service was not loaded.")}async function _u(){await vs();let e=kn();se.existsSync(e)&&se.unlinkSync(e),ee.success(pe.green("Mach agent service uninstalled."))}async function Ru(){let e=yu();ft(["daemon-reload"]),ft(["enable","--now",Lt]),await zi(),ee.info(pe.dim(`It will start automatically when you log in. Service: ${e}`)),ee.info(pe.dim(`Logs: ${Z.join(Ve(),"agent.log")}`))}async function $u(){ft(["stop",Lt],{ignoreError:!0})?ee.success(pe.green("Mach agent service stopped.")):ee.warn("Mach agent service was not running.")}async function vu(){ft(["disable","--now",Lt],{ignoreError:!0}),ft(["daemon-reload"],{ignoreError:!0});let e=Hi();se.existsSync(e)&&se.unlinkSync(e),ft(["daemon-reload"],{ignoreError:!0}),ee.success(pe.green("Mach agent service uninstalled."))}async function Pu(){let e=bu();Qt(["/Create","/TN",kt,"/SC","ONLOGON","/TR",`"${e}"`,"/RL","LIMITED","/F"]),Qt(["/Run","/TN",kt],{ignoreError:!0}),await zi(),ee.info(pe.dim(`It will start automatically when you log in. Task: ${kt}`)),ee.info(pe.dim(`Logs: ${Z.join(Ve(),"agent.log")}`))}async function Ps(){Qt(["/End","/TN",kt],{ignoreError:!0})?ee.success(pe.green("Mach agent task stopped.")):ee.warn("Mach agent task was not running.")}async function Ou(){await Ps(),Qt(["/Delete","/TN",kt,"/F"],{ignoreError:!0});let e=ji();se.existsSync(e)&&se.unlinkSync(e),ee.success(pe.green("Mach agent task uninstalled."))}async function ps(){if(process.platform==="darwin")return wu();if(process.platform==="linux")return Ru();if(process.platform==="win32")return Pu();throw new Error(`Background agent install is not supported on ${process.platform}.`)}async function fs(){if(process.platform==="darwin")return vs();if(process.platform==="linux")return $u();if(process.platform==="win32")return Ps();ee.warn(`Background agent service control is not supported on ${process.platform}.`)}async function Du(){if(process.platform==="darwin")return _u();if(process.platform==="linux")return vu();if(process.platform==="win32")return Ou();ee.warn(`Background agent uninstall is not supported on ${process.platform}.`)}async function Cu(){let e=await Rs(),t=e?!0:await $s();if(e?ee.success(pe.green(`Mach agent is online at ${Zt}`)):t?ee.warn(`Mach agent port is open, but /health did not respond. Run \`${m.nameLower} agent restart\` if the dashboard still shows offline.`):ee.warn(`Mach agent is not responding at ${Zt}`),process.platform==="darwin"){let n=pt(["print",`${Gi()}/${xt}`],{ignoreError:!0});ee.info(pe.dim(`Login service: ${n?"installed/loaded":"not loaded"}`))}else if(process.platform==="linux"){let n=ft(["is-enabled",Lt],{ignoreError:!0}),i=ft(["is-active",Lt],{ignoreError:!0});ee.info(pe.dim(`Login service: ${n?"enabled":"not enabled"} / ${i?"active":"inactive"}`))}else if(process.platform==="win32"){let n=Qt(["/Query","/TN",kt],{ignoreError:!0});ee.info(pe.dim(`Login task: ${n?"installed":"not installed"}`))}}async function Nu(){let e=[];try{(await xn(ws(),["devices","-l"])).split(`
|
|
1490
|
+
`).forEach(n=>{if(n.includes("List of devices")||!n.trim())return;let i=n.split(/\s+/);if(i.length<2||i[1]!=="device")return;let r=i[0],o=n.match(/model:([^\s]+)/);e.push({id:r,platform:"android",type:r.startsWith("emulator-")?"emulator":"physical",name:o?o[1].replace(/_/g," "):r,status:"online",details:n.trim()})})}catch{}try{let n=(await xn(_s(),["-list-avds"])).split(`
|
|
1491
|
+
`).filter(r=>!!r.trim()),i=e.some(r=>r.platform==="android"&&r.id.startsWith("emulator-"));n.forEach(r=>{i||e.push({id:r,platform:"android",type:"emulator",name:r.replace(/_/g," "),status:"offline",details:`Android Virtual Device: ${r}`})})}catch{}return e}async function Os(){if(process.platform!=="darwin")return[];try{let e=await xn("/usr/bin/xcrun",["simctl","list","devices","--json"]),t=JSON.parse(e),n=[];return Object.entries(t.devices||{}).forEach(([i,r])=>{r.forEach(o=>{o.isAvailable&&n.push({id:o.udid,platform:"ios",type:"simulator",name:o.name,status:o.state?.toLowerCase()==="booted"?"online":"offline",runtime:i,details:`${o.name} (${i})`})})}),n}catch{return[]}}async function Tu(){if(process.platform!=="darwin")return[];try{let e=await xn("/usr/bin/xcrun",["devicectl","list","devices","--json-output","-"]);return(JSON.parse(e).result?.devices||[]).filter(n=>{let i=n.connectionProperties?.transportType;return i==="wired"||i==="localNetwork"}).map(n=>{let i=n.connectionProperties?.transportType,r=n.deviceProperties?.name||"iPhone";return{id:n.identifier,platform:"ios",type:"physical",name:r,status:"online",details:`${r} (${n.model?.name||n.hardwareModel||""}) - ${i}`}})}catch{return[]}}async function ku(e){let t=await Os(),n=t.find(r=>r.id===e);if(n)return n;let i=t.filter(r=>r.status==="online");return i.length===1?i[0]:null}async function xu(){let[e,t,n]=await Promise.all([Nu(),Os(),Tu()]);return[...e,...t,...n]}async function Lu(){let e=Date.now();return Cn&&e-Cn.updatedAt<hu?Cn.targets:(Nn||(Nn=xu().then(t=>(Cn={targets:t,updatedAt:Date.now()},t)).finally(()=>{Nn=null})),Nn)}async function ms(e){let t=[];for await(let n of e)t.push(Buffer.isBuffer(n)?n:Buffer.from(n));return t.length===0?{}:JSON.parse(Buffer.concat(t).toString("utf-8"))}async function Mu(e,t){let n=await mu({method:"GET",url:e,responseType:"stream",timeout:12e4}),i=se.createWriteStream(t);n.data.pipe(i),await new Promise((r,o)=>{i.on("finish",r),i.on("error",o)})}function gs(e,t){let n=e?.stderr?.toString?.().trim();if(n)return n;let i=e?.stdout?.toString?.().trim();return i||e?.message||t}function Uu(e,t){return mt("/usr/libexec/PlistBuddy",["-c",`Print :${t}`,e],{encoding:"utf-8"}).trim()}function Fu(e){let t=Z.join(e,"Info.plist");if(!se.existsSync(t))throw new Error(`Could not validate iOS app executable: ${t} not found.`);let n=Uu(t,"CFBundleExecutable"),i=Z.join(e,n);if(!se.existsSync(i))throw new Error(`Could not validate iOS app executable: ${i} not found.`);return i}function Bu(){return process.arch==="arm64"?"arm64":"x86_64"}function Hu(e){return se.existsSync(e)?se.readdirSync(e).map(t=>Z.join(e,t)).filter(t=>t.endsWith(".app")&&se.statSync(t).isDirectory()):[]}function hs(e,t){let n=Hu(e);if(n.length===1)return n[0];if(n.length>1)throw new Error(`Multiple .app bundles found in ${t}: ${n.map(i=>Z.basename(i)).join(", ")}. Mach cannot safely choose which app to install.`);return""}function ju(e){let t=Fu(e),n=Bu(),i="",r="";try{i=mt("lipo",["-info",t],{encoding:"utf-8"}).trim()}catch(o){throw new Error(`Could not inspect iOS simulator app architecture for ${Z.basename(e)}: ${o.message}`)}if(!new RegExp(`\\b${n}\\b`).test(i))throw new Error(`This iOS simulator artifact cannot be installed because ${Z.basename(e)} does not include the ${n} simulator architecture. lipo output: ${i}. Rebuild the app with the latest Mach CLI and make sure the profile is a simulator build.`);try{r=mt("/usr/bin/xcrun",["vtool","-show-build",t],{encoding:"utf-8"}).trim()}catch(o){throw new Error(`Could not inspect iOS simulator app platform for ${Z.basename(e)}: ${o.message}`)}if(!/\bplatform\s+IOSSIMULATOR\b/i.test(r))throw new Error(`This iOS simulator artifact cannot be installed because ${Z.basename(e)} was built for the wrong Apple platform. A simulator artifact must contain platform IOSSIMULATOR. vtool output: ${r}. Rebuild the app with the latest Mach CLI.`)}async function Gu(e,t,n){let i=n||(t.toLowerCase().includes(".apk")?"android":"ios"),r=t.toLowerCase().includes(".ipa"),o=se.mkdtempSync(Z.join(Ke.tmpdir(),`${st}-install-`)),s=Z.join(o,i==="android"?"install.apk":r?"install.ipa":"install.zip");try{if(await Mu(t,s),i==="android"){mt(ws(),["-s",e,"install","-r",s],{stdio:"pipe"});return}if(process.platform!=="darwin")throw new Error("iOS local install requires macOS.");Tn(`unzip -o ${JSON.stringify(s)} -d ${JSON.stringify(o)}`,{stdio:"pipe"});let l=Z.join(o,"Payload"),a=se.existsSync(l),c=r||a,u="";if(c?u=hs(l,"Payload"):u=hs(o,"the simulator artifact"),!u)throw new Error(`No .app bundle found inside the ${r?"IPA":"archive"}.`);let d=c?null:await ku(e);if(d){try{ju(u),mt("/usr/bin/xcrun",["simctl","install",d.id,u],{stdio:"pipe"})}catch(f){throw new Error(gs(f,"iOS Simulator install failed."))}return}if(!c)throw new Error("Selected iOS Simulator was not found. Refresh Install Hub devices or boot one simulator and try again.");try{Tn(`/usr/bin/xcrun devicectl device install app --device ${JSON.stringify(e)} ${JSON.stringify(u)}`,{stdio:"pipe"})}catch(f){throw new Error(gs(f,"iOS device install failed."))}}finally{se.rmSync(o,{recursive:!0,force:!0})}}function Ku(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 Tn(`/usr/bin/xcrun simctl boot ${JSON.stringify(e)}`,{stdio:"pipe"}),us("open",["-a","Simulator"],{detached:!0,stdio:"ignore"}).unref(),"Simulator booting..."}if(t==="android")return us(_s(),["-avd",e],{detached:!0,stdio:"ignore",windowsHide:!0}).unref(),"Emulator booting in background...";throw new Error("Invalid platform.")}async function Vu(){process.platform!=="darwin"&&ee.warn("Running on non-macOS \u2014 iOS discovery unavailable, Android only.");let e=Ln.createServer((i,r)=>{if(r.setHeader("Access-Control-Allow-Origin","*"),r.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),r.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),i.method==="OPTIONS"){r.writeHead(204),r.end();return}let o=new URL(i.url||"/",`http://localhost:${st}`);if(i.method==="GET"&&o.pathname==="/local/devices"){Lu().then(s=>{r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"success",targets:s}))}).catch(s=>{r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"error",message:s.message}))});return}if(i.method==="GET"&&o.pathname==="/health"){r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"success",service:"mach-agent",port:st,platform:process.platform}));return}if(i.method==="POST"&&o.pathname==="/install-local"){t(i,r);return}if(i.method==="POST"&&o.pathname==="/local/boot"){n(i,r);return}r.writeHead(404),r.end()}),t=async(i,r)=>{try{let{deviceId:o,artifactUrl:s,platform:l}=await ms(i);if(!o||!s){r.writeHead(400,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"error",message:"deviceId and artifactUrl are required"}));return}await Gu(o,s,l),r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"success",message:`Installed on ${o}`}))}catch(o){r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"error",message:o.message||"Local install failed"}))}},n=async(i,r)=>{try{let{id:o,platform:s}=await ms(i),l=Ku(o,s);r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"success",message:l}))}catch(o){r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"error",message:o.message||"Local device launch failed"}))}};e.listen(st,"127.0.0.1",()=>{ee.success(pe.green(`Local device agent running on http://localhost:${st}`)),ee.info(pe.dim("Keep this running while using the Install Hub on the dashboard.")),ee.info(pe.dim("Press Ctrl+C to stop."))}),e.on("error",i=>{i.code==="EADDRINUSE"?ee.error(`Port ${st} is already in use \u2014 agent may already be running.`):ee.error(`Agent error: ${i.message}`),process.exit(1)}),await new Promise(()=>{})}async function Ds(e="start"){let t=String(e||"start").toLowerCase();if(t==="start"||t==="run"){await Vu();return}if(t==="install"){await ps();return}if(t==="status"){await Cu();return}if(t==="stop"){await fs();return}if(t==="uninstall"){await Du();return}if(t==="restart"){await fs(),await ps();return}ee.error(`Unknown agent action: ${e}`),ee.info(pe.dim(`Use: ${m.nameLower} agent start | install | status | restart | stop | uninstall`)),process.exit(1)}import{createRequire as If}from"module";import{text as Wu,password as Yu,spinner as Ju,isCancel as Ts}from"@clack/prompts";import Xi from"chalk";import en from"fs";import Cs from"path";import zu from"os";var Wi=Cs.join(zu.homedir(),m.configDir),Yi=Cs.join(Wi,"config.json");function Ji(){if(!en.existsSync(Yi))return{};try{return JSON.parse(en.readFileSync(Yi,"utf-8"))}catch{return{}}}function Ns(e){en.existsSync(Wi)||en.mkdirSync(Wi,{recursive:!0});let n={...Ji(),...e};en.writeFileSync(Yi,JSON.stringify(n,null,2))}async function ks(){let e=Ji(),t=await Wu({message:"Enter your email:",placeholder:"user@example.com",initialValue:e.lastLoginEmail,validate(r){if(r.length===0)return"Email is required!"}});if(Ts(t))return;let n=await Yu({message:"Enter your password:",validate(r){if(r.length===0)return"Password is required!"}});if(Ts(n))return;let i=Ju();i.start("Authenticating...");try{let o=await(await fetch(`${vt}/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:t,password:n})})).json();o.status==="success"&&o.user.token?(cr({id:o.user.id,email:t,token:o.user.token,refreshToken:o.user.refreshToken}),Ns({lastLoginEmail:t}),i.stop(Xi.green("Login successful!"))):i.stop(Xi.red("Login failed: "+(o.message||"Unknown error")))}catch(r){i.stop(Xi.red("Network error: "+r.message))}}import{log as Mn,outro as Xu}from"@clack/prompts";import tn from"chalk";async function xs(){let e=ur(),t=`${m.envPrefix}TOKEN`;e?Mn.success(tn.green(`Logged out. Removed saved credentials from ~/${m.configDir}/credentials.json.`)):Mn.warn(tn.yellow(`No saved ${m.name} credentials found.`)),process.env[t]&&(Mn.warn(tn.yellow(`${t} is still set in this shell. Commands will continue to authenticate with that token until you unset it.`)),Mn.info(tn.dim(`Run: unset ${t}`))),Xu(tn.blue("---"))}import{outro as qu,select as Zu,spinner as Qu,isCancel as ep}from"@clack/prompts";import Un from"chalk";import qi from"fs";import tp from"path";var Ls=e=>e==="1234567890"||e==="ABC123DEFG"||e==="XXXXXXXXXX"?"":typeof e=="string"?e:"",np=()=>process.versions.node.split(".")[0]||"24";async function Ms(){if(!Pe()){console.log(Un.red(`You are not logged in. Run \`${m.nameLower} login\` first.`));return}let t=Qu();t.start("Fetching projects...");try{let{data:n}=await k.get("/projects");if(t.stop("Projects loaded."),n.status!=="success"||!n.projects||n.projects.length===0){console.log(Un.yellow(`No projects found. Run \`${m.nameLower} init\` to create one.`));return}let i=n.projects.map(g=>({value:g.projectId,label:`${g.name} (${g.slug})`})),r=await Zu({message:"Select a project to link:",options:i});if(ep(r))return;let o=tp.join(process.cwd(),m.configFileName),s={};if(qi.existsSync(o))try{s=JSON.parse(qi.readFileSync(o,"utf-8"))}catch{}let l=n.projects.find(g=>g.projectId===r),a=s.android?.package||rt("android"),c=s.ios?.bundleIdentifier||rt("ios"),u=s.android||{},d=s.submit?.production?.android||{},f=s.submit?.production?.ios||{},p={projectId:r,framework:fr(s.framework)||fn,name:l?.name,slug:l?.slug,nodeVersion:s.nodeVersion||np(),scheme:l?.slug?.toLowerCase()||"app",android:{...u,package:a||"",versionCode:u.versionCode||"auto"},ios:{bundleIdentifier:c||"",buildNumber:s.ios?.buildNumber||"auto"},build:{development:{environment:"development",distribution:"development"},staging:{environment:"staging",distribution:"internal"},production:{environment:"production",distribution:"store"}},submit:{production:{android:{...d,track:d.track||"internal",releaseStatus:d.releaseStatus||"completed"},ios:{ascAppId:Ls(f.ascAppId),appleTeamId:Ls(f.appleTeamId)}}}};qi.writeFileSync(o,JSON.stringify(p,null,2)),qu(Un.green(`Linked to project ${p.name} (${p.slug})`))}catch(n){t.stop(Un.red("Error fetching projects: "+n.message))}}import{outro as ip,text as Fn,select as rp,spinner as op,isCancel as nn}from"@clack/prompts";import rn from"chalk";import sp from"fs";import ap from"path";import{randomUUID as lp}from"crypto";var dp=()=>process.versions.node.split(".")[0]||"24";async function Us(){if(!Pe()){console.log(rn.red(`You are not logged in. Run \`${m.nameLower} login\` first.`));return}let t=await Fn({message:"Project Name:",placeholder:"My Awesome App",validate(l){if(l.length===0)return"Name is required!"}});if(nn(t))return;let n=await Fn({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(nn(n))return;let i=await rp({message:"Platform:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"},{value:"web",label:"Web"},{value:"all",label:"All Platforms"}]});if(nn(i))return;let r="";if(i==="android"||i==="all"){let l=rt("android");if(r=await Fn({message:"Android Package Name:",initialValue:l||"",placeholder:"com.example.app",validate(a){if(a.length===0)return"Package name is required for Android!"}}),nn(r))return}let o="";if(i==="ios"||i==="all"){let l=rt("ios");if(o=await Fn({message:"iOS Bundle Identifier:",initialValue:l||"",placeholder:"com.example.app",validate(a){if(a.length===0)return"Bundle ID is required for iOS!"}}),nn(o))return}let s=op();s.start("Creating project...");try{let l=lp(),c={projectId:l,name:t,slug:n,storageType:"managed",platforms:i==="all"?["android","ios","web"]:[i]},{data:u}=await k.post("/projects",c);if(u.status==="success"){s.stop(rn.green("Project created successfully!"));let d=ap.join(process.cwd(),m.configFileName);sp.writeFileSync(d,JSON.stringify({projectId:l,framework:fn,name:t,slug:n,nodeVersion:dp(),...r?{android:{package:r,versionCode:"auto"}}:{},...o?{ios:{bundleIdentifier:o,buildNumber:"auto"}}:{},build:{development:{environment:"development",distribution:"development"},staging:{environment:"staging",distribution:"internal"},production:{environment:"production",distribution:"store"}},submit:{production:{android:{track:"internal",releaseStatus:"completed"},ios:{ascAppId:"",appleTeamId:""}}}},null,2)),ip(rn.green(`Initialized project ${t} and linked locally!`))}else s.stop(rn.red("creation failed: "+u.message))}catch(l){s.stop(rn.red("Network error: "+l.message))}}import{spinner as Zi,log as ve}from"@clack/prompts";import on from"chalk";import Bn from"fs";import Fs from"path";function Qi(e,t,n,i){let r=e?.response?.status,o=e?.response?.data?.message||e?.response?.data?.error,s=i?` ${i}`:"";return r===401?`Not logged in or token expired while trying to ${n}${s}. Run \`${m.nameLower} login\` and try again.`:r===403?[`Permission denied while trying to ${n}${s}.`,o?`API says: ${o}.`:void 0,`Current Mach account/token does not have access to project ${t}.`,`Run \`${m.nameLower} login\` with the correct account, or ask a project owner to grant access.`].filter(Boolean).join(" "):r===404?[`Project or environment endpoint was not found while trying to ${n}${s}.`,`Project ID: ${t}.`,o?`API says: ${o}.`:void 0].filter(Boolean).join(" "):r?`Failed to ${n}${s}: ${o||`API returned HTTP ${r}`}`:`Network error while trying to ${n}${s}: ${e?.message||"Unknown error"}`}function cp(e){let t=String(e??"");return t===""?'""':/^[A-Za-z0-9_./:@%+-]+$/.test(t)?t:JSON.stringify(t)}function up(e,t){return`${[`# Generated by ${m.nameLower} env pull --environment ${t}`,"# Do not commit this file.","",...Object.keys(e).sort((i,r)=>i.localeCompare(r)).map(i=>`${i}=${cp(e[i])}`)].join(`
|
|
1395
1492
|
`)}
|
|
1396
|
-
`}async function
|
|
1397
|
-
`))}else
|
|
1398
|
-
Profile Settings:`)),
|
|
1399
|
-
Environment Variables:`)),Object.entries(i.env).forEach(([r,o])=>{
|
|
1493
|
+
`}async function Bs(e,t,n={}){let i=Pe();if(!i){ve.error(`You are not logged in. Run \`${m.nameLower} login\` first.`);return}let r=Fs.join(process.cwd(),m.configFileName);if(!Bn.existsSync(r)){ve.error(`No ${m.configFileName} found. Run \`${m.nameLower} init\` or \`${m.nameLower} link\` first.`);return}let o;try{o=JSON.parse(Bn.readFileSync(r,"utf-8"))}catch{ve.error(`Failed to parse ${m.configFileName}`);return}let{projectId:s}=o;if(!s){ve.error(`${m.configFileName} is missing projectId.`);return}e==="set"?await pp(s,t,i):e==="list"?await fp(s,i):e==="pull"||e==="download"||e==="export"?await mp(s,n):ve.error(`Unknown env action: ${e}. Use 'set', 'list', or 'pull'.`)}async function pp(e,t,n){if(t.length===0){ve.error(`Usage: ${m.nameLower} env set KEY=VALUE [KEY2=VALUE2 ...]`);return}let i=Zi();i.start("Setting environment variables...");let r=0,o=0;for(let s of t){let[l,...a]=s.split("="),c=a.join("=");if(!l||c===void 0){ve.warn(`Invalid format for argument: ${s}. Expected KEY=VALUE.`),o++;continue}try{let u={key:l.trim(),value:c,type:"env",environment:"global",visibility:"secret"},{data:d}=await k.post(`/projects/${e}/secrets`,u);d.status==="success"?r++:(ve.error(`Failed to set ${l}: ${d.message}`),o++)}catch(u){ve.error(Qi(u,e,"set",l)),o++}}i.stop(`Set ${r} variable(s). ${o>0?`${o} failed.`:""}`)}async function fp(e,t){let n=Zi();n.start("Fetching environment variables...");try{let{data:i}=await k.get(`/projects/${e}/secrets`);if(i.status==="success"){n.stop("Fetched variables.");let r=i.secrets||[];r.length===0?ve.info("No environment variables found for this project."):(ve.info(on.bold("Environment Variables (Global & Scoped):")),r.forEach(o=>{let s=o.visibility==="plain"?o.value:"********";console.log(` ${on.cyan(o.key)} = ${s} ${on.gray(`[${o.environment}]`)}`)}))}else n.stop(on.red(`Failed to fetch variables: ${i.message}`))}catch(i){n.stop("Failed to fetch variables."),ve.error(Qi(i,e,"list"))}}async function mp(e,t){let n=(t.environment||"development").trim(),i=t.out||".env.local",r=Fs.resolve(process.cwd(),i);if(Bn.existsSync(r)&&!t.overwrite){ve.error(`${i} already exists. Re-run with \`--overwrite\` to replace it.`);return}let o=Zi();o.start(`Downloading ${n} environment variables...`);try{let{data:s}=await k.get(`/projects/${e}/secrets/export?env=${encodeURIComponent(n)}`);if(s.status!=="success"){o.stop(on.red(`Failed to download variables: ${s.message||"Unknown API error"}`));return}let l=s.secrets||{},a=up(l,n);Bn.writeFileSync(r,a,{encoding:"utf-8",mode:384}),o.stop(`Wrote ${Object.keys(l).length} variable(s) to ${i}.`)}catch(s){o.stop("Failed to download variables."),ve.error(Qi(s,e,"pull"))}}import{spinner as gp,log as Rt,outro as hp}from"@clack/prompts";import er from"chalk";import Hs from"fs";import Sp from"path";import{execSync as yp}from"child_process";import bp from"adm-zip";import Ep from"axios";import{randomUUID as Ap}from"crypto";async function js(e){Rt.info(er.magenta("\u{1F680} Starting Over-The-Air (OTA) Update via Mach..."));let t=$e();(!t||!t.projectId)&&(Rt.error(`No ${m.configFileName} found or missing projectId. Run \`mach link\` first.`),process.exit(1));let n=t.projectId,i=e.branch||"production",r="1.0.0";try{r=JSON.parse(Hs.readFileSync("./package.json","utf-8")).version||"1.0.0"}catch{Rt.warn("Could not read package.json version. Defaulting to 1.0.0")}let o=gp();o.start(`Compiling JavaScript bundles for OTA (Channel: ${i}, Runtime: ${r})...`);try{yp("npx expo export --platform all",{stdio:"ignore"})}catch(c){o.stop("Compilation failed."),Rt.error(`Failed to export JS bundles using Expo: ${c.message}`),process.exit(1)}o.message("Zipping artifact payload...");let s=Sp.join(process.cwd(),"dist");Hs.existsSync(s)||(o.stop("Missing dist folder."),Rt.error("The `dist` directory was not created. Export failed."),process.exit(1));let l=new bp;l.addLocalFolder(s,"dist");let a=l.toBuffer();o.message("Uploading payload to Mach Cloud...");try{let c=Ap(),u=await k.post("/builds/source-upload-url",{projectId:n,buildId:c});if(u.data.status!=="success")throw new Error("Could not secure upload bucket URL");let{uploadUrl:d,key:f}=u.data;await Ep.put(d,a,{headers:{"Content-Type":"application/zip"},maxBodyLength:1/0,maxContentLength:1/0}),o.message(`Promoting Update to ${i}...`),await k.post("/updates/publish",{projectId:n,channelName:i,runtimeVersion:r,platform:"android",updateId:`${c}-android`,manifestKey:f}),await k.post("/updates/publish",{projectId:n,channelName:i,runtimeVersion:r,platform:"ios",updateId:`${c}-ios`,manifestKey:f}),o.stop("Update Live!"),hp(er.green(`\u2713 OTA Update natively shipped to the '${i}' channel.`)),Rt.info(er.dim(`Any app running runtime '${r}' will download this bundle smoothly.`))}catch(c){o.stop("Update failed during Cloud Sync."),Rt.error(`Upload error: ${c.message}`),process.exit(1)}}import{intro as Ip,outro as Gs,log as Mt}from"@clack/prompts";import qe from"chalk";async function Ks(){Ip(qe.blue(`${m.name} CLI - User Profile`));let e=Pe();if(!e){Mt.warn(qe.yellow("You are not logged in.")),Mt.info(`Run \`${m.nameLower} login\` to authenticate.`),Gs();return}Mt.info(`${qe.bold("Logged in as:")} ${qe.green(e.email)}`);try{await k.get("/projects");let n=Pe().token.split(".");if(n.length===3){let i=JSON.parse(Buffer.from(n[1],"base64").toString());if(i.exp){let r=new Date(i.exp*1e3),o=new Date,s=r.getTime()-o.getTime();if(s>0){let l=Math.round(s/6e4),a=(l/60).toFixed(1);Mt.info(`${qe.bold("Token status:")} Valid (Expires in ~${a}h / ${l}m)`)}else Mt.warn(`${qe.bold("Token status:")} ${qe.red("Expired")} (Auto-refresh failed)`)}}}catch{Mt.warn(`${qe.bold("Token status:")} ${qe.red("Unreachable")} (Session might be truly expired)${vt}`)}Gs(qe.blue("---"))}import{spawn as Rp}from"child_process";import{log as gt}from"@clack/prompts";import xe from"chalk";import $p from"fs";import wp from"net";async function _p(e){return new Promise(t=>{let n=wp.createServer();n.once("error",i=>{i.code==="EADDRINUSE"?t(!0):t(!1)}),n.once("listening",()=>{n.close(),t(!1)}),n.listen(e,"0.0.0.0")})}async function Vs(e,t=20){let n=e;for(;n<e+t;){if(!await _p(n))return n;n++}throw new Error(`Could not find an available port after ${t} attempts starting from ${e}.`)}var zs=async e=>{gt.info(xe.blue(`Starting ${m.name} Dev Orchestrator...`));let t=$e(),n=e.buildProfile||"development",i=t?lt(t,n):null,r={...process.env};if(t?.projectId)try{gt.info(xe.dim(`Fetching managed secrets for profile: ${n}...`));let d=await k.get(`/projects/${t.projectId}/secrets/export?env=${n}`);d.data?.status==="success"&&d.data.secrets&&(Object.assign(r,d.data.secrets),gt.info(xe.magenta(`\u2713 Injected secrets from ${m.name} Dashboard.`)))}catch{gt.warn("Could not fetch managed secrets. Running with local env only.")}t&&Object.assign(r,Pt(t,m.envPrefix)),i&&(Object.assign(r,Pt(i,`${m.envPrefix}PROFILE_`)),i.env&&Object.assign(r,i.env));let o=!1;try{let d=JSON.parse($p.readFileSync("package.json","utf-8"));o=!!(d.dependencies?.expo||d.devDependencies?.expo)}catch{gt.warn("Could not parse package.json. Defaulting to Bare React Native mode.")}let s=Number(e.port||i?.port||8081),l=await Vs(s);l!==s&>.info(xe.yellow(`Port ${s} is busy. ${m.name} is using ${l} instead.`));let a=process.platform==="win32"?"npx.cmd":"npx",c=[];if(o?(c=["expo","start","--port",String(l)],e.clear&&c.push("--clear"),e.tunnel&&c.push("--tunnel"),e.lan&&c.push("--lan"),e.localhost&&c.push("--localhost"),e.ios&&c.push("--ios"),e.android&&c.push("--android"),e.web&&c.push("--web")):(c=["react-native","start","--port",String(l)],e.clear&&c.push("--clear")),o){let d=[`${xe.cyan("i")} open iOS simulator`,`${xe.cyan("a")} open Android emulator/device`,`${xe.cyan("w")} open web`,`${xe.cyan("r")} reload app`];gt.info([xe.bold("Launch controls"),...d.map(f=>` ${f}`),"",xe.dim("Direct launch: mach start --ios | --android | --web"),xe.dim(`Metro URL: http://localhost:${l}`)].join(`
|
|
1494
|
+
`))}else gt.info(xe.dim(`Metro URL: http://localhost:${l}`));let u=Rp(a,c,{stdio:"inherit",env:r});return new Promise((d,f)=>{u.on("exit",p=>{p===0?d():f(new Error(`Dev server exited with code ${p}`))}),u.on("error",p=>{f(p)})})};import{log as Ne}from"@clack/prompts";import ze from"chalk";var Ws=async e=>{let t=$e();t||(Ne.error(ze.red(`No ${m.configFileName} found in the current directory.`)),process.exit(1));let n=e.profile||"development",i=lt(t,n);if(e.json){console.log(JSON.stringify({project:t,resolved:i},null,2));return}Ne.info(ze.bgBlue.white(` Resolved ${m.name} Config [${n}] `)),Ne.info(ze.dim("----------------------------------------")),Ne.info(`${ze.blue("Project ID:")} ${t.projectId}`),Ne.info(`${ze.blue("Name:")} ${t.name}`),Ne.info(`${ze.blue("Scheme:")} ${t.scheme}`),i?(Ne.info(ze.dim(`
|
|
1495
|
+
Profile Settings:`)),Ne.info(`${ze.cyan("Distribution:")} ${i.distribution||"none"}`),Ne.info(`${ze.cyan("Development Client:")} ${i.developmentClient||"false"}`),i.env&&Object.keys(i.env).length>0&&(Ne.info(ze.dim(`
|
|
1496
|
+
Environment Variables:`)),Object.entries(i.env).forEach(([r,o])=>{Ne.info(` ${r}=${o}`)}))):Ne.warn(`Profile '${n}' not found.`),Ne.info(ze.dim("----------------------------------------"))};import{log as Le,spinner as ln,text as Ys,select as Js,confirm as vp,isCancel as sn,cancel as an,outro as dn,note as Pp}from"@clack/prompts";import ie from"chalk";import{execSync as Op}from"child_process";async function Dp(){try{let e=Op("xcrun devicectl list devices --json-output -",{stdio:["pipe","pipe","pipe"]}).toString();return(JSON.parse(e).result?.devices||[]).filter(i=>i.connectionProperties?.transportType==="wired"||i.connectionProperties?.transportType==="localNetwork").map(i=>({udid:i.identifier,name:i.deviceProperties?.name||"Unknown Device",model:i.hardwareProperties?.marketingName||"iPhone"}))}catch{return[]}}var Xs=e=>e?.trim().toUpperCase()||void 0;function qs(e){let t=$e(),n=t?gr(t):{},i=Xs(e.teamId),r=i||n.teamId;return{...n,teamId:r,developerTeamId:i||n.developerTeamId||r}}async function Cp(e){let t=e.udid,n=e.name,i=qs(e),r=i.teamId;if(!t){let s=ln();s.start("Scanning for connected iOS devices...");let l=await Dp();if(s.stop(l.length>0?`Found ${l.length} device(s)`:"No devices detected"),l.length===1)t=l[0].udid,n=n||l[0].name,Le.info(`Detected: ${ie.bold(n)} (${ie.dim(t.substring(0,12)+"...")})`);else if(l.length>1){let a=await Js({message:"Select a device to register:",options:l.map(u=>({value:u.udid,label:`${u.name} (${u.model})`,hint:u.udid.substring(0,12)+"..."}))});if(sn(a)){an("Cancelled");return}t=a;let c=l.find(u=>u.udid===t);n=n||c.name}else{Le.info(ie.dim("No connected devices found. Enter UDID manually."));let a=await Ys({message:"Device UDID:",placeholder:"00008101-XXXXXXXXXXXX",validate(c){if(c.length<10)return"UDID seems too short"}});if(sn(a)){an("Cancelled");return}t=a}}if(!n){let s=await Ys({message:"Device name:",placeholder:"Nitesh's iPhone",validate(l){if(l.length===0)return"Name is required"}});if(sn(s)){an("Cancelled");return}n=s}let o=ln();o.start("Registering device...");try{await k.post("/devices",{udid:t,name:n,platform:"ios",addedVia:"cli",teamId:r,teamName:i.teamName,developerTeamId:i.developerTeamId,appStoreConnectTeamId:i.appStoreConnectTeamId,providerId:i.providerId,providerName:i.providerName}),o.stop(ie.green("Device registered!")),Le.info(` ${ie.bold("Name:")} ${n}`),Le.info(` ${ie.bold("UDID:")} ${ie.dim(t)}`),r&&Le.info(` ${ie.bold("Team:")} ${ie.dim(r)}`)}catch(s){o.stop(ie.red("Failed to register device")),Le.error(s.response?.data?.message||s.message)}dn(ie.blue("---"))}async function Np(e={}){let t=Xs(e.teamId),n=ln();n.start("Fetching registered devices...");try{let r=(await k.get("/devices",t?{params:{teamId:t}}:void 0)).data.devices||[];if(n.stop(`${r.length} device(s) registered${t?` for team ${t}`:""}`),r.length===0){Le.info(ie.dim(`No devices registered yet. Run \`${m.nameLower} device register\` to add one.`)),dn(ie.blue("---"));return}let o=r.map(s=>{let l=new Date(s.createdAt).toLocaleDateString();return` ${ie.bold(s.name.padEnd(24))} ${ie.dim(s.udid.padEnd(28))} ${ie.dim((s.teamId||"-").padEnd(12))} ${ie.cyan((s.addedVia||"-").padEnd(10))} ${ie.dim(l)}`});Pp(` ${ie.bold("Name".padEnd(24))} ${"UDID".padEnd(28)} ${"Team".padEnd(12)} ${"Via".padEnd(10)} Date
|
|
1400
1497
|
`+o.join(`
|
|
1401
|
-
`),"Registered Devices")}catch(i){n.stop(
|
|
1402
|
-
`),c=
|
|
1403
|
-
`),u=
|
|
1404
|
-
`),u=
|
|
1405
|
-
`),u=
|
|
1406
|
-
`);/__DEV__/.test(
|
|
1407
|
-
Running expo prebuild for deeper analysis...`));try{
|
|
1408
|
-
Skipping manifest/plist checks \u2014 no android/ios dirs. Use --prebuild to generate them.`)),o;for(let c of r){let u=
|
|
1409
|
-
`)),s.length>0){
|
|
1410
|
-
`));for(let a of s)ge.error(ue.red(`${ue.bold(a.name)} ${ue.dim(`(${a.arch})`)}`)),ge.info(ue.dim(` PT_LOAD alignment: 2**${Math.log2(a.align)} (${a.align} bytes, needs 2**14 = ${Qs})`))}return l.length>0&&(console.log(""),ge.success(ue.green(`${l.length} librar${l.length===1?"y":"ies"} correctly aligned (2**14 or higher).`))),console.log(""),s.length===0?(ge.success(ue.green.bold("ELF Verification Successful. APK is 16KB compatible.")),!0):(ge.error(ue.red.bold(`Found ${s.length} unaligned lib${s.length===1?"":"s"} (arm64-v8a/x86_64 libs need to be aligned).`)),console.log(""),ge.info(ue.yellow("To fix this:")),ge.info(ue.dim(" 1. Rebuild with NDK r28+ which defaults to 16KB page alignment")),ge.info(ue.dim(" 2. Or set -DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON in CMake")),ge.info(ue.dim(" 3. Update third-party libraries that ship prebuilt .so files")),ge.info(ue.dim(" 4. After rebuilding: zipalign -p -f -v 16 input.apk output.apk")),console.log(""),ge.info(ue.dim("Reference: https://developer.android.com/guide/practices/page-sizes")),!1)}catch(r){return n.stop("Analysis failed."),ge.error(ue.red(`Failed to analyze APK: ${r.message}`)),!1}finally{try{tt.rmSync(i,{recursive:!0,force:!0})}catch{}}}function _f(e){let t=tt.openSync(e,"r");try{let n=Buffer.alloc(64);if(tt.readSync(t,n,0,64,0),!n.subarray(0,4).equals(wf))return null;let i=n[4]===2,r=n[5]===1,o=(p,f)=>r?p.readUInt16LE(f):p.readUInt16BE(f),s=(p,f)=>r?p.readUInt32LE(f):p.readUInt32BE(f),l=(p,f)=>Number(r?p.readBigUInt64LE(f):p.readBigUInt64BE(f)),a,c,u;i?(a=l(n,32),c=o(n,54),u=o(n,56)):(a=s(n,28),c=o(n,42),u=o(n,44));let d=null;for(let p=0;p<u;p++){let f=Buffer.alloc(c);if(tt.readSync(t,f,0,c,a+p*c),s(f,0)!==If)continue;let S;i?S=l(f,48):S=s(f,28),S>0&&(d===null||S<d)&&(d=S)}return d??0}catch{return null}finally{tt.closeSync(t)}}function ta(e){let t=[];if(!tt.existsSync(e))return t;let n=tt.readdirSync(e,{withFileTypes:!0});for(let i of n){let r=Dt.join(e,i.name);i.isDirectory()?t.push(...ta(r)):i.name.endsWith(".so")&&t.push(r)}return t}function $f(e){return e.includes("arm64-v8a")?"arm64-v8a":e.includes("x86_64")?"x86_64":"unknown"}var ra=async e=>{if(Pe()||(ke.error(ze.red(`You are not logged in. Run \`${m.nameLower} login\` first.`)),process.exit(1)),e.apk){await Pf(e);return}let n=process.cwd(),i=zn.join(n,"package.json");rn.existsSync(i)||(ke.error(ze.red("No package.json found. Run this command from a project root.")),process.exit(1));let r=JSON.parse(rn.readFileSync(i,"utf-8")),o=!!(r.dependencies?.expo||r.devDependencies?.expo);e.json||(ke.info(ze.dim(`Project: ${r.name||"unknown"} v${r.version||"0.0.0"}`)),ke.info(ze.dim(`Type: ${o?"Expo":"Bare React Native"}`)),ke.info(""));let s={json:e.json,fix:e.fix,category:e.category,severity:e.severity,prebuild:e.prebuild},l=await qs(n,s);e.json?console.log(JSON.stringify(Zs(l,r),null,2)):Xs(l,e.severity);let a=l.some(u=>u.findings.some(d=>d.severity==="critical")),c=l.some(u=>u.findings.some(d=>d.severity==="high"));(a||c)&&process.exit(1)},na=["16kb"];async function Pf(e){let t=e.category?.toLowerCase();t&&!na.includes(t)&&(ke.error(ze.red(`Unknown APK check category: "${t}"`)),ke.info(ze.dim(`Available APK checks: ${na.join(", ")}`)),process.exit(1));let n=await Of(e.apk);n||process.exit(1);let i=!t,r=!1;(i||t==="16kb")&&(await ea(n)||(r=!0)),r&&process.exit(1)}async function Of(e){if(e.startsWith("build:")){let n=e.slice(6);return await Df(n)}if(e.startsWith("http://")||e.startsWith("https://"))return await oa(e);let t=zn.resolve(e);return rn.existsSync(t)?t:(ke.error(ze.red(`APK file not found: ${t}`)),null)}async function Df(e){let t=ia();t.start(`Fetching APK from build ${e}...`);try{let n=await N.get(`/build/${e}`);if(n.data.status!=="success")throw new Error(n.data.message);let i=n.data.build;if(!i)throw new Error("Build not found");let r=i.artifacts?.find(o=>o.type?o.type==="apk":o.name?.endsWith(".apk")||o.url?.includes(".apk"));return!r||!r.url?(t.stop("No APK artifact found"),ke.error(ze.red("This build does not have an APK artifact.")),ke.info(ze.dim("Make sure the build produced an APK (not just an AAB).")),null):(t.stop(`Found build: ${i.buildId||e}`),await oa(r.url))}catch(n){return t.stop("Failed to fetch build"),ke.error(ze.red(n.message)),null}}async function oa(e){let t=ia();t.start("Downloading APK...");try{let n=rn.mkdtempSync(zn.join(vf.tmpdir(),`${m.nameLower}-audit-`)),i=zn.join(n,"app.apk"),r=await Rf.get(e,{responseType:"arraybuffer"});rn.writeFileSync(i,r.data);let o=(r.data.length/(1024*1024)).toFixed(1);return t.stop(`Downloaded APK (${o} MB)`),i}catch(n){return t.stop("Download failed"),ke.error(ze.red(`Failed to download APK: ${n.message}`)),null}}var Tf=console.log;console.log=()=>{};Nf();console.log=Tf;we(be.bgCyan.black(m.cliTag("Production Build Orchestrator")));var xf=kf(import.meta.url),Mf=xf("../package.json"),aa=(e,t=[])=>t.concat(e),oe=new Cf;oe.name(m.nameLower).description(`${m.name} CLI: Powerful Cloud Infrastructure Tools`).version(Mf.version).option("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1);oe.command("agent").description("Manage local device discovery agent for the Install Hub (port 7070)").argument("[action]","start, run, install, status, restart, stop, or uninstall","start").action(async e=>{await as(e)});oe.command("host").description("Setup AWS S3 static hosting and CloudFront").action(async()=>{we(be.bgCyan.black(m.cliTag("Hosting"))),await cr()});oe.command("sitemap").description("Generate sitemap.xml from Expo Router app structure").option("-o, --output <path>","Output path for sitemap.xml","./public/sitemap.xml").action(async e=>{we(be.bgCyan.black(m.cliTag("Sitemap Generator"))),await mr(e)});oe.command("build").description("Run a build on a cloud provider (AWS Spot Instances)").argument("[platform]","Target platform (android, ios)").option("--platform <os>","Target platform alias (android, ios) [Optional]").option("--repo <url>","Git Repository URL").option("--branch <name>","Git Branch").option("--ami <id>","AMI ID").option("--bucket <name>","S3 Bucket for artifacts").option("--region <region>","AWS Region").option("--aws-profile <name>","AWS Credentials Profile").option("-p, --build-profile <name>","Build Profile (e.g. production, staging)").option("--profile <name>","Build Profile (alias for --build-profile)").option("--dry-run","Generate User Data script without launching").option("--keep-instance","Do not terminate the instance after build").option("--subnet <id>","VPC Subnet ID to launch the instance in").option("--security-group <id>","VPC Security Group ID to use").option("--ssh-host <host>","Remote host for iOS build (SSH)").option("--ssh-user <user>","SSH username for remote host").option("--ssh-key <path>","Path to private SSH key for remote host").option("--ios-scheme <scheme>","iOS Scheme to build").option("--ios-team-id <id>","Apple Development Team ID").option("--ios-configuration <config>","Xcode configuration (Release/Debug)").option("--ios-export-method <method>","Export method (ad-hoc, app-store, development, enterprise)").option("--ios-api-key-id <id>","App Store Connect API Key ID").option("--ios-api-key-issuer <id>","App Store Connect API Key Issuer ID").option("--ios-api-key-path <path>","Path to App Store Connect API Key (.p8) file").option("--simulator","Build for iOS Simulator (no signing required)").addOption(new xe("--build-id <id>","Internal build ID").hideHelp()).addOption(new xe("--project-id <id>","Internal project ID").hideHelp()).addOption(new xe("--fail-only","Internal: mark an existing build failed").hideHelp()).addOption(new xe("--error <message>","Internal failure message").hideHelp()).option("--local","Run build on local machine").option("--auto-version","Automatically fetch and increment Android versionCode or iOS buildNumber from the store").option("--auto-submit","Submit this build after it completes successfully").option("--submit-track <track>","Google Play track to use with --auto-submit").option("--submit-release-status <status>","Google Play release status to use with --auto-submit").option("--submit-rollout <fraction>","Google Play staged rollout fraction to use with --auto-submit").option("--submit-changes-not-sent-for-review","Commit Google Play changes without automatically sending them for review when using --auto-submit").option("--submit-credential-id <id>","Service credential ID to use with --auto-submit").option("--submit-json-output <path>","Write auto-submit metadata JSON to a file for CI/CD").option("--verbose","Enable verbose logging").option("--json-output <path>","Write build metadata JSON to a file for CI/CD").option("--maestro","Queue a managed Maestro test run after a successful build").option("--maestro-flows <path>","Maestro flow file or directory (default: .maestro)").option("--maestro-device <device>","Managed Maestro device profile").option("--maestro-retries <n>","Retries for the Maestro run","1").option("--maestro-record","Enable screen recording where supported").option("--maestro-use-build-source","Use Maestro flows from the build source snapshot instead of uploading local flows").option("--maestro-env <name>","Forward an environment variable to the managed Maestro runner; repeat or comma-separate names",aa,[]).option("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1).action(async(e,t)=>{let n=oe.opts();t.yes=t.yes||n.yes,t.quiet=t.quiet||n.quiet,t.platform=e||t.platform,t.buildProfile=t.profile||t.buildProfile,t.quiet||we(be.bgCyan.black(m.cliTag("Cloud Build"))),await _n(t)});oe.command("maestro").description("Run Maestro tests locally or with the managed Mach runner").option("--platform <os>","Target platform (android/ios)").option("-p, --profile <name>","Build profile to resolve when using --latest","production").option("--latest","Use the latest successful build for the platform/profile").option("--build-id <id>","Use a specific Mach build ID").option("--build-url <url>","Use a Mach build URL").option("--artifact-url <url>","Use a direct APK or iOS simulator app artifact URL").option("--local","Run Maestro on a connected local emulator/device instead of the managed runner").option("--maestro-flows <path>","Maestro flow file or directory (default: .maestro)").option("--maestro-device <device>","Managed Maestro device profile").option("--maestro-retries <n>","Retries for the Maestro run","1").option("--maestro-record","Enable screen recording where supported").option("--maestro-use-build-source","Use Maestro flows from the build source snapshot instead of uploading local flows").option("--maestro-env <name>","Forward an environment variable to the managed Maestro runner; repeat or comma-separate names",aa,[]).option("--wait","Wait for managed Maestro completion and exit non-zero on failure").option("--wait-timeout <minutes>","Maximum minutes to wait for managed Maestro completion","60").option("--wait-interval <seconds>","Polling interval while waiting for managed Maestro completion","15").option("--json-output <path>","Write test run metadata JSON to a file for CI/CD").addOption(new xe("--local-runner","Internal: execute a managed Maestro run on this machine").hideHelp()).addOption(new xe("--test-run-id <id>","Internal test run ID").hideHelp()).addOption(new xe("--project-id <id>","Internal project ID").hideHelp()).addOption(new xe("--runner-token <token>","Internal runner token").hideHelp()).action(async e=>{we(be.bgCyan.black(m.cliTag("Maestro Testing"))),await Jr(e)});oe.command("update").description("Deploy an Over-The-Air (OTA) update to your live channel").option("--branch <name>","Channel or Branch to deploy to (e.g., production)","production").action(async e=>{we(be.bgCyan.black(m.cliTag("OTA Update"))),await bs(e)});oe.command("submit").description("Automated Store Submission (App Store / Google Play)").option("--platform <os>","Target platform (ios/android)").option("-p, --profile <name>","Build/submission profile to submit from (e.g. production, preprod)").option("--track <track>","Google Play Track (internal, alpha, beta, production)").option("--release-status <status>","Google Play release status (completed, draft, halted, inProgress)").option("--rollout <fraction>","Google Play staged rollout fraction for inProgress releases (example: 0.1)").option("--changes-not-sent-for-review","Commit Google Play changes without automatically sending them for review").option("--ssh-host <host>","Remote macOS host for iOS submission").option("--ssh-user <user>","SSH username for remote iOS submission").option("--ssh-key <path>","Path to private SSH key for remote iOS submission").option("--credential-id <id>","Service credential ID to use when multiple submission credentials exist").option("--local","Run submission on this machine (internal runner mode for iOS)").addOption(new xe("--submit-id <id>","Internal submission ID").hideHelp()).addOption(new xe("--project-id <id>","Internal project ID").hideHelp()).addOption(new xe("--package-name <name>","Internal Android package name").hideHelp()).addOption(new xe("--bundle-id <id>","Internal iOS bundle identifier").hideHelp()).option("--json-output <path>","Write submission metadata JSON to a file for CI/CD").option("--latest","Use the latest successful build for submission").option("--build-id <id>","Use a specific build ID for submission").action(async e=>{let t=oe.opts();e.quiet=e.quiet||t.quiet,e.yes=e.yes||t.yes,we(be.bgCyan.black(m.cliTag("Store Submission"))),await Sn(e)});oe.command("login").description(`Login to ${m.name} Dashboard`).action(async()=>{we(be.bgCyan.black(m.cliTag("Login"))),await us()});oe.command("logout").description(`Logout from ${m.name} on this machine`).action(async()=>{we(be.bgCyan.black(m.cliTag("Logout"))),await fs()});oe.command("link").description(`Link local directory to a ${m.name} Project`).action(async()=>{we(be.bgCyan.black(m.cliTag("Link Project"))),await ms()});oe.command("me").description("Display currently logged in user details").action(async()=>{await Es()});oe.command("init").description(`Create a new ${m.name} Project`).action(async()=>{we(be.bgCyan.black(m.cliTag("Init Project"))),await gs()});oe.command("env").description("Manage Environment Variables").argument("<action>","Action to perform: set, list, pull, download, or export").argument("[args...]","Key=Value pairs for set action").option("-e, --environment <name>","Environment to pull/download","development").option("-o, --out <file>","Output file for pull/download",".env.local").option("--overwrite","Overwrite output file if it already exists").action(async(e,t,n)=>{we(be.bgCyan.black(m.cliTag("Env Manager"))),await ys(e,t,n)});oe.command("start").description("Start the development server (Metro)").option("-p, --build-profile <name>","Build profile (e.g. development, staging)","development").option("--tunnel","Use ngrok tunnel").option("--lan","Use LAN IP").option("--localhost","Use localhost").option("-c, --clear","Clear Metro cache").option("--port <number>","Port to listen on").option("--ios","Start on iOS").option("--android","Start on Android").option("--web","Start on Web").action(async e=>{we(be.bgCyan.black(m.cliTag("Dev Server"))),await ws(e)});oe.command("config").description("Show resolved configuration for a profile").option("-p, --profile <name>","Build profile to resolve","development").option("--json","Output as JSON").action(async e=>{await _s(e)});oe.command("credentials").description("Unified, interactive credential management (iOS/Android)").option("-p, --profile <name>","Build profile (production, staging, development)").option("--force","Force recreate certificates (nuke existing on Apple Portal)",!1).action(async e=>{let{credentialsMainCommand:t}=await import("./credentials-3MYGMYJK.js");await t(e)});oe.command("credentials:setup").description("Automated credential provisioning (iOS/Android) [Legacy]").requiredOption("--platform <os>","Platform: ios or android").option("--profile <name>","Build profile (production, staging, development)").option("--bundle-id <id>","Bundle ID / Package Name (optional, auto-detected)").option("--team-id <id>","Apple Team ID (iOS only)").option("--key-alias <alias>","Android keystore alias (optional, auto-generated)").option("--aws-profile <name>","AWS Credentials Profile (for S3 storage)").option("--force","Force recreate certificates (nuke existing on Apple Portal)",!1).action(async e=>{we(be.bgCyan.black(m.cliTag("Credentials Setup"))),await Tt(e),sa(be.green("Done!"))});oe.command("credentials:service").description("Upload Service Credentials (ASC API Key / Google Service JSON) [Legacy]").requiredOption("--platform <os>","Platform: ios or android").option("--file <path>","Path to credential file (.p8 or .json)").option("--issuer-id <id>","ASC API Key Issuer ID (iOS only)").option("--key-id <id>","ASC API Key ID (iOS only)").option("--bundle-id <id>","Bundle identifier / Android package name to attach this service credential to").option("--package-name <name>","Android package name to attach this service credential to").option("-p, --profile <name>","Build profile to resolve package/bundle identifier from config").action(async e=>{we(be.bgCyan.black(m.cliTag("Service Credentials"))),await lr(e),sa(be.green("Done!"))});var qi=oe.command("device").description("Manage registered iOS test devices");qi.command("register").description("Register a connected iOS device or enter UDID manually").option("--udid <udid>","Device UDID (skip auto-detection)").option("--name <name>","Device name").option("--team-id <id>","Apple Developer Team ID for this device").action(async e=>{await Mn("register",e)});qi.command("list").description("List all registered devices").option("--team-id <id>","Filter by Apple Developer Team ID").action(async e=>{await Mn("list",e)});qi.command("remove").description("Remove a registered device").option("--udid <udid>","Device UDID to remove").option("--team-id <id>","Apple Developer Team ID for this device").action(async e=>{await Mn("remove",e)});oe.command("audit").description("Run automated security audit on the project or APK").option("--apk <path>","Path to APK file (runs APK diagnostics like 16KB alignment)").option("--json","Output results as JSON (for CI/CD)").option("--fix","Auto-apply fixes where possible").option("--category <name>","Run only a specific check category (e.g. 16kb, permissions, secrets)").option("--severity <level>","Minimum severity to display (critical, high, medium, low, info)").option("--prebuild","Run expo prebuild for deeper manifest/plist analysis").action(async e=>{we(be.bgCyan.black(m.cliTag(e.apk?"APK Audit":"Security Audit"))),await ra(e)});var Lf=new Set(["login","logout","agent"]);oe.hook("preAction",(e,t)=>{let n=t.name(),i=t.opts?.()||{};n==="maestro"&&(i.local||i.localRunner)||Lf.has(n)||nr()});oe.on("command:*",()=>{console.error(`Invalid command: %s
|
|
1411
|
-
See --help for a list of available commands.`,
|
|
1498
|
+
`),"Registered Devices")}catch(i){n.stop(ie.red("Failed to fetch devices")),Le.error(i.response?.data?.message||i.message)}dn(ie.blue("---"))}async function Tp(e){let t=e.udid,n=qs(e).teamId;if(!t){let o=ln();o.start("Fetching registered devices...");try{let l=(await k.get("/devices",n?{params:{teamId:n}}:void 0)).data.devices||[];if(o.stop(`${l.length} device(s) found`),l.length===0){Le.info(ie.dim("No devices to remove.")),dn(ie.blue("---"));return}let a=await Js({message:"Select device to remove:",options:l.map(u=>({value:u.deviceKey||u.udid,label:u.name,hint:`${u.udid.substring(0,12)}...${u.teamId?` \xB7 ${u.teamId}`:""}`}))});if(sn(a)){an("Cancelled");return}let c=l.find(u=>(u.deviceKey||u.udid)===a);t=c?.udid||a,n=c?.teamId||n}catch(s){o.stop(ie.red("Failed to fetch devices")),Le.error(s.response?.data?.message||s.message);return}}let i=await vp({message:`Remove device ${ie.dim(t.substring(0,12)+"...")}?`});if(sn(i)||!i){an("Cancelled");return}let r=ln();r.start("Removing device...");try{await k.delete(`/devices/${encodeURIComponent(t)}`,n?{params:{teamId:n}}:void 0),r.stop(ie.green("Device removed"))}catch(o){r.stop(ie.red("Failed to remove device")),Le.error(o.response?.data?.message||o.message)}dn(ie.blue("---"))}async function Hn(e,t){switch(e){case"register":await Cp(t);break;case"list":await Np(t);break;case"remove":await Tp(t);break;default:Le.error(`Unknown action: ${e}`)}}import{log as Ue,spinner as $a}from"@clack/prompts";import Ye from"chalk";import qn from"path";import pn from"fs";import mf from"os";import gf from"axios";var Me=(o=>(o.CRITICAL="critical",o.HIGH="high",o.MEDIUM="medium",o.LOW="low",o.INFO="info",o))(Me||{}),We=(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))(We||{});import{spinner as ha,log as un}from"@clack/prompts";import Te from"chalk";import{execSync as rf}from"child_process";import Sa from"fs";import ya from"path";import ht from"fs";import cn from"path";import{execSync as kp}from"child_process";var Zs={"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"}},xp={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 Lp(e){try{let n=kp("npx expo config --type introspect --json 2>/dev/null",{cwd:e,encoding:"utf-8",timeout:3e4});return JSON.parse(n)}catch{}let t=cn.join(e,"app.json");if(ht.existsSync(t))try{let n=JSON.parse(ht.readFileSync(t,"utf-8"));return n.expo||n}catch{}return null}function Mp(e){let t=[],n=cn.join(e,"node_modules");if(!ht.existsSync(n))return t;let i=/<uses-permission\s+android:name="([^"]+)"/g;function r(o,s){let l=cn.join(o,"android","src","main","AndroidManifest.xml");if(!ht.existsSync(l))return;let a=ht.readFileSync(l,"utf-8"),c;for(;(c=i.exec(a))!==null;)t.push({pkg:s,permission:c[1]});i.lastIndex=0}for(let o of ht.readdirSync(n)){if(o.startsWith("."))continue;let s=cn.join(n,o);if(o.startsWith("@")){if(!ht.statSync(s).isDirectory())continue;for(let l of ht.readdirSync(s))r(cn.join(s,l),`${o}/${l}`)}else r(s,o)}return t}async function Qs(e,t){let n=[],i=1,r=Lp(e),o=r?.android?.permissions||[],s=r?.android?.blockedPermissions||[];for(let c of o){let u=Zs[c];u&&n.push({id:`PERM-${String(i++).padStart(3,"0")}`,title:`${c.split(".").pop()} declared`,description:u.description,severity:u.severity,category:"permissions",file:"app.config.ts",recommendation:"Remove from permissions if not needed, or add justification."})}let l=Mp(e);for(let{pkg:c,permission:u}of l){let d=Zs[u];d&&(s.includes(u)||o.includes(u)||n.push({id:`PERM-${String(i++).padStart(3,"0")}`,title:`${u.split(".").pop()} injected by ${c}`,description:`${d.description}. Auto-injected via ${c} AndroidManifest.xml`,severity:d.severity,category:"permissions",file:`node_modules/${c}/android/src/main/AndroidManifest.xml`,recommendation:`Add "${u}" to blockedPermissions if not needed.`,autoFixable:!0}))}let a=r?.ios?.infoPlist||{};for(let[c,u]of Object.entries(xp))c in a&&n.push({id:`PERM-${String(i++).padStart(3,"0")}`,title:`iOS: ${c} declared`,description:u.description,severity:u.severity,category:"permissions",file:"app.config.ts",recommendation:`Remove ${c} from infoPlist if the app does not use this capability.`});return{category:"permissions",label:"Permission Audit",findings:n,durationMs:0}}import tr from"fs";import jn from"path";var Up=[{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"}],Fp=new Set([".ts",".tsx",".js",".jsx"]),Bp=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function ea(e){let t=[],n=tr.readdirSync(e,{withFileTypes:!0});for(let i of n){if(Bp.has(i.name))continue;let r=jn.join(e,i.name);i.isDirectory()?t.push(...ea(r)):Fp.has(jn.extname(i.name))&&t.push(r)}return t}function Hp(e){let t=e.trim();return t.startsWith("//")||t.startsWith("*")||t.startsWith("/*")}function jp(e){return/process\.env\./i.test(e)||/import\.meta\.env/i.test(e)}async function ta(e,t){let n=[],i=jn.join(e,"src"),r=tr.existsSync(i)?i:e,o=ea(r);for(let s of o){let a=tr.readFileSync(s,"utf-8").split(`
|
|
1499
|
+
`),c=jn.relative(e,s);for(let u=0;u<a.length;u++){let d=a[u];if(!Hp(d)&&!jp(d))for(let{id:f,pattern:p,severity:g,label:y}of Up)p.lastIndex=0,p.test(d)&&n.push({id:f,title:y,description:`Potential ${y.toLowerCase()} found in source code`,severity:g,category:"secrets",file:c,line:u+1,recommendation:`Move to environment variables or a secrets manager. Use \`${m.nameLower} env set\` for managed secrets.`})}}return{category:"secrets",label:"Secrets Detection",findings:n,durationMs:0}}import{execSync as Gp}from"child_process";var Kp={critical:"critical",high:"high",moderate:"medium",low:"low",info:"info"};async function na(e,t){let n=[],i=1,r;try{r=Gp("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=Kp[a.severity]||"info",u=Array.isArray(a.via)?a.via.map(d=>typeof d=="string"?d:d.title||d.name).join(", "):String(a.via);n.push({id:`DEP-${String(i++).padStart(3,"0")}`,title:`${l} \u2014 ${a.severity}`,description:`Via: ${u}. Range: ${a.range||"unknown"}`,severity:c,category:"dependencies",recommendation:a.fixAvailable?`Run \`npm audit fix\` or update ${l} to a patched version.`:"No fix available yet. Monitor for updates or evaluate alternatives.",autoFixable:!!a.fixAvailable})}return{category:"dependencies",label:"Dependency CVEs",findings:n,durationMs:0}}import Gn from"fs";import Kn from"path";var Vp=/(?:token|password|credential|secret|apiKey|api_key|session|auth|jwt|refresh_token|access_token|private_key|pin|otp)/i,ia=/AsyncStorage\s*\.\s*(?:setItem|mergeItem)\s*\(\s*['"`]([^'"`]+)['"`]/g,zp=/from\s+['"]@react-native-async-storage\/async-storage['"]|from\s+['"]react-native['"].*AsyncStorage/,Wp=new Set([".ts",".tsx",".js",".jsx"]),Yp=new Set(["node_modules",".expo",".git","android","ios","dist","build"]);function ra(e){let t=[];if(!Gn.existsSync(e))return t;let n=Gn.readdirSync(e,{withFileTypes:!0});for(let i of n){if(Yp.has(i.name))continue;let r=Kn.join(e,i.name);i.isDirectory()?t.push(...ra(r)):Wp.has(Kn.extname(i.name))&&t.push(r)}return t}async function oa(e,t){let n=[],i=1,r=Kn.join(e,"src"),o=Gn.existsSync(r)?r:e,s=ra(o);for(let l of s){let a=Gn.readFileSync(l,"utf-8");if(!zp.test(a))continue;let c=a.split(`
|
|
1500
|
+
`),u=Kn.relative(e,l);for(let d=0;d<c.length;d++){let f=c[d];ia.lastIndex=0;let p;for(;(p=ia.exec(f))!==null;){let g=p[1];Vp.test(g)&&n.push({id:`STOR-${String(i++).padStart(3,"0")}`,title:`AsyncStorage used for "${g}"`,description:`Sensitive data key "${g}" stored in AsyncStorage (unencrypted).`,severity:"high",category:"storage",file:u,line:d+1,recommendation:"Use expo-secure-store (SecureStore) for sensitive data instead of AsyncStorage."})}}}return{category:"storage",label:"Insecure Storage",findings:n,durationMs:0}}import Vn from"fs";import zn from"path";var sa=/['"`](http:\/\/(?!localhost|127\.0\.0\.1|10\.|192\.168\.|0\.0\.0\.0|172\.(?:1[6-9]|2\d|3[01])\.)[^'"`\s]+)['"`]/g,Jp=/\/api\/|\/v[0-9]+\/|\/graphql|\/rest\//i,Xp=new Set([".ts",".tsx",".js",".jsx"]),qp=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function aa(e){let t=[];if(!Vn.existsSync(e))return t;let n=Vn.readdirSync(e,{withFileTypes:!0});for(let i of n){if(qp.has(i.name))continue;let r=zn.join(e,i.name);i.isDirectory()?t.push(...aa(r)):Xp.has(zn.extname(i.name))&&t.push(r)}return t}async function la(e,t){let n=[],i=1,r=zn.join(e,"src"),o=Vn.existsSync(r)?r:e,s=aa(o);for(let l of s){let c=Vn.readFileSync(l,"utf-8").split(`
|
|
1501
|
+
`),u=zn.relative(e,l);for(let d=0;d<c.length;d++){let f=c[d],p=f.trim();if(p.startsWith("//")||p.startsWith("*"))continue;sa.lastIndex=0;let g;for(;(g=sa.exec(f))!==null;){let y=g[1],_=Jp.test(y);n.push({id:`NET-${String(i++).padStart(3,"0")}`,title:`Insecure HTTP URL${_?" (API endpoint)":""}`,description:`Plain HTTP URL found: ${y}`,severity:_?"high":"medium",category:"network",file:u,line:d+1,recommendation:"Use HTTPS instead of HTTP for all network requests."})}}}return{category:"network",label:"HTTP URLs",findings:n,durationMs:0}}import Wn from"fs";import Yn from"path";var da=/(?:debug|debugMode|devMode|enableDebug)\s*[:=]\s*true/gi,ca=/console\.(?:log|warn|info|debug)\s*\([^)]*(?:token|password|secret|credential|key|auth)/gi,Zp=new Set([".ts",".tsx",".js",".jsx"]),Qp=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function ua(e){let t=[];if(!Wn.existsSync(e))return t;let n=Wn.readdirSync(e,{withFileTypes:!0});for(let i of n){if(Qp.has(i.name))continue;let r=Yn.join(e,i.name);i.isDirectory()?t.push(...ua(r)):Zp.has(Yn.extname(i.name))&&t.push(r)}return t}async function pa(e,t){let n=[],i=1,r=Yn.join(e,"src"),o=Wn.existsSync(r)?r:e,s=ua(o);for(let l of s){let c=Wn.readFileSync(l,"utf-8").split(`
|
|
1502
|
+
`),u=Yn.relative(e,l);for(let d=0;d<c.length;d++){let f=c[d],p=f.trim();if(!(p.startsWith("//")||p.startsWith("*"))&&(da.lastIndex=0,da.test(f)&&n.push({id:`DBG-${String(i++).padStart(3,"0")}`,title:"Hardcoded debug flag",description:"Debug/dev mode enabled in source code",severity:"medium",category:"debug",file:u,line:d+1,recommendation:"Use __DEV__ or environment variables instead of hardcoded debug flags."}),ca.lastIndex=0,ca.test(f))){let g=c.slice(Math.max(0,d-3),d).join(`
|
|
1503
|
+
`);/__DEV__/.test(g)||n.push({id:`DBG-${String(i++).padStart(3,"0")}`,title:"Sensitive data in console log",description:"Console log may expose sensitive data (token, password, etc.) in production",severity:"medium",category:"debug",file:u,line:d+1,recommendation:"Wrap in __DEV__ check or remove sensitive data from console output."})}}}return{category:"debug",label:"Debug/Dev Flags",findings:n,durationMs:0}}import fa from"fs";import nr from"path";var ef=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 tf(e){let t=[nr.join(e,"android","app","src","main","AndroidManifest.xml"),nr.join(e,"android","AndroidManifest.xml")];for(let n of t)if(fa.existsSync(n))return n;return null}async function ma(e,t){let n=[],i=1,r=tf(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=fa.readFileSync(r,"utf-8"),s=nr.relative(e,r),l=/<(activity|service|receiver|provider)\s+([^>]*?)(?:\/>|>)/gs,a;for(;(a=l.exec(o))!==null;){let c=a[1],u=a[2],f=u.match(/android:name="([^"]+)"/)?.[1]||"unknown";if(ef.has(f))continue;let p=/android:exported="true"/.test(u),g=/android:permission="/.test(u);p&&!g&&n.push({id:`MAN-${String(i++).padStart(3,"0")}`,title:`Exported ${c}: ${f.split(".").pop()}`,description:`${f} is exported=true without android:permission protection`,severity:"medium",category:"manifest",file:s,recommendation:'Set android:exported="false" or add an android:permission attribute.'})}return/android:allowBackup="true"/.test(o)&&n.push({id:`MAN-${String(i++).padStart(3,"0")}`,title:"allowBackup is enabled",description:'android:allowBackup="true" allows data extraction via ADB backup',severity:"medium",category:"manifest",file:s,recommendation:'Set android:allowBackup="false" via expo-build-properties plugin.',autoFixable:!0}),/android:debuggable="true"/.test(o)&&n.push({id:`MAN-${String(i++).padStart(3,"0")}`,title:"App is debuggable",description:'android:debuggable="true" allows attaching a debugger in production',severity:"critical",category:"manifest",file:s,recommendation:"Ensure debuggable is false for production builds. This is usually set automatically for release builds."}),{category:"manifest",label:"Android Manifest",findings:n,durationMs:0}}import Jn from"fs";import ir from"path";function nf(e){let t=ir.join(e,"ios");if(!Jn.existsSync(t))return null;let n=Jn.readdirSync(t,{withFileTypes:!0});for(let i of n){if(!i.isDirectory()||i.name==="Pods"||i.name.startsWith("."))continue;let r=ir.join(t,i.name,"Info.plist");if(Jn.existsSync(r))return r}return null}async function ga(e,t){let n=[],i=1,r=nf(e);if(!r)return{category:"ats",label:"iOS ATS Config",findings:[],durationMs:0,error:"No Info.plist found. Run with --prebuild or run `expo prebuild` first."};let o=Jn.readFileSync(r,"utf-8"),s=ir.relative(e,r),l=o.match(/<key>NSAppTransportSecurity<\/key>\s*<dict>([\s\S]*?)<\/dict>/);if(l){let a=l[1];/<key>NSAllowsArbitraryLoads<\/key>\s*<true\s*\/>/.test(a)&&n.push({id:`ATS-${String(i++).padStart(3,"0")}`,title:"ATS disabled \u2014 NSAllowsArbitraryLoads",description:"App Transport Security is completely disabled. All HTTP connections are allowed.",severity:"critical",category:"ats",file:s,recommendation:"Remove NSAllowsArbitraryLoads or set to false. Use domain-specific exceptions only if absolutely necessary."});let c=a.match(/<key>NSExceptionDomains<\/key>\s*<dict>([\s\S]*?)<\/dict>/);if(c){let u=c[1].match(/<key>([^<]+)<\/key>/g);if(u)for(let d of u){let f=d.replace(/<\/?key>/g,"");f!=="NSExceptionDomains"&&n.push({id:`ATS-${String(i++).padStart(3,"0")}`,title:`ATS exception: ${f}`,description:`ATS exception configured for ${f}`,severity:"low",category:"ats",file:s,recommendation:`Verify that the ATS exception for ${f} is necessary. Use HTTPS where possible.`})}}}return{category:"ats",label:"iOS ATS Config",findings:n,durationMs:0}}var of=[{category:"permissions",label:"Permission Audit",fn:Qs,requiresPrebuild:!1},{category:"secrets",label:"Secrets Detection",fn:ta,requiresPrebuild:!1},{category:"dependencies",label:"Dependency CVEs",fn:na,requiresPrebuild:!1},{category:"storage",label:"Insecure Storage",fn:oa,requiresPrebuild:!1},{category:"network",label:"HTTP URLs",fn:la,requiresPrebuild:!1},{category:"debug",label:"Debug/Dev Flags",fn:pa,requiresPrebuild:!1},{category:"manifest",label:"Android Manifest",fn:ma,requiresPrebuild:!0},{category:"ats",label:"iOS ATS Config",fn:ga,requiresPrebuild:!0}];async function ba(e,t){let n=of;t.category&&(n=n.filter(s=>s.category===t.category),n.length===0&&(un.error(Te.red(`Unknown category: ${t.category}`)),un.info(Te.dim(`Available: ${Object.values(We).join(", ")}`)),process.exit(1)));let i=n.filter(s=>!s.requiresPrebuild),r=n.filter(s=>s.requiresPrebuild),o=[];for(let s of i){let l=ha();l.start(Te.dim(`Running ${s.label}...`));try{let a=Date.now(),c=await s.fn(e,t);c.durationMs=Date.now()-a,o.push(c);let u=c.findings.length;l.stop(u>0?Te.yellow(`${s.label} \u2014 ${u} finding(s)`):Te.green(`${s.label} \u2014 clean`))}catch(a){l.stop(Te.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=ya.join(e,"android"),l=ya.join(e,"ios"),a=Sa.existsSync(s)||Sa.existsSync(l);if(!a&&t.prebuild){t.json||un.info(Te.dim(`
|
|
1504
|
+
Running expo prebuild for deeper analysis...`));try{rf("npx expo prebuild --no-install",{cwd:e,stdio:"pipe"})}catch{return un.warn(Te.yellow("Prebuild failed \u2014 skipping manifest/plist checks.")),o}}else if(!a)return t.json||un.info(Te.dim(`
|
|
1505
|
+
Skipping manifest/plist checks \u2014 no android/ios dirs. Use --prebuild to generate them.`)),o;for(let c of r){let u=ha();u.start(Te.dim(`Running ${c.label}...`));try{let d=Date.now(),f=await c.fn(e,t);f.durationMs=Date.now()-d,o.push(f);let p=f.findings.length;u.stop(p>0?Te.yellow(`${c.label} \u2014 ${p} finding(s)`):Te.green(`${c.label} \u2014 clean`))}catch(d){u.stop(Te.red(`${c.label} \u2014 error`)),o.push({category:c.category,label:c.label,findings:[],durationMs:0,error:d.message})}}}return o}import be from"chalk";import{log as he}from"@clack/prompts";var Ut={critical:be.bgRed.white.bold,high:be.red.bold,medium:be.yellow.bold,low:be.blue,info:be.dim},Xn={critical:0,high:1,medium:2,low:3,info:4};function sf(e,t){if(!t)return!0;let n=Xn[t];return n===void 0?!0:Xn[e]<=n}function Ea(e,t){let n=0,i={critical:0,high:0,medium:0,low:0,info:0};for(let s of e){let l=s.findings.filter(c=>sf(c.severity,t));if(l.length===0&&!s.error)continue;if(he.info(""),he.info(be.bold(` ${s.label}`)+be.dim(` ${l.length} finding(s)`)),he.info(be.dim(" "+"\u2500".repeat(60))),s.error){he.error(be.red(` Error: ${s.error}`));continue}let a=[...l].sort((c,u)=>Xn[c.severity]-Xn[u.severity]);for(let c of a){let u=Ut[c.severity](` ${c.severity.toUpperCase()} `);he.info(` ${u} ${be.bold(c.id)} ${c.title}`),he.info(be.dim(` ${c.description}`)),c.file&&he.info(be.dim(` File: ${c.file}${c.line?`:${c.line}`:""}`)),he.info(be.cyan(` Fix: ${c.recommendation}`)),he.info(""),i[c.severity]++,n++}}he.info(""),he.info(be.bold(" Summary")),he.info(be.dim(" "+"\u2500".repeat(60))),he.info(` Total: ${be.bold(String(n))} finding(s)`),he.info(` ${Ut.critical(` ${i.critical} Critical `)} ${Ut.high(` ${i.high} High `)} ${Ut.medium(` ${i.medium} Medium `)} ${Ut.low(` ${i.low} Low `)} ${Ut.info(` ${i.info} Info `)}`);let r=i.critical>0,o=i.high>0;r||o?(he.info(""),he.error(be.red.bold(` FAIL \u2014 ${i.critical} critical, ${i.high} high issue(s) found`))):n>0?(he.info(""),he.warn(be.yellow(" PASS (with warnings) \u2014 no critical or high issues"))):(he.info(""),he.success(be.green.bold(" PASS \u2014 no issues found")))}function Aa(e,t){let n=e.flatMap(r=>r.findings),i={};for(let r of Object.values(Me))i[r]=n.filter(o=>o.severity===r).length;return{version:"1.0.0",timestamp:new Date().toISOString(),project:t.name||"unknown",projectVersion:t.version||"0.0.0",summary:{total:n.length,...i},passed:i.critical===0&&i.high===0,checks:e.map(r=>({category:r.category,label:r.label,findingCount:r.findings.length,durationMs:r.durationMs,error:r.error||null})),findings:n}}import{log as Se,spinner as af}from"@clack/prompts";import fe from"chalk";import at from"fs";import lf from"os";import Ft from"path";import{execSync as df}from"child_process";var Ia=16384,cf=1,uf=Buffer.from([127,69,76,70]);async function wa(e){Se.info(fe.bold.underline("16KB Page Alignment Check")),console.log("");let t=Ft.resolve(e);if(!at.existsSync(t))return Se.error(fe.red(`APK file not found: ${t}`)),!1;if(!t.endsWith(".apk"))return Se.error(fe.red("The provided file is not an APK file.")),!1;let n=af();n.start("Extracting and analyzing native libraries...");let i=at.mkdtempSync(Ft.join(lf.tmpdir(),"mach-16kb-"));try{try{df(`unzip -o -q "${t}" "lib/arm64-v8a/*.so" "lib/x86_64/*.so" -d "${i}" 2>/dev/null`,{encoding:"utf-8",maxBuffer:50*1024*1024})}catch{}let r=_a(Ft.join(i,"lib"));if(r.length===0)return n.stop("Analysis complete."),Se.info(fe.yellow("No arm64-v8a or x86_64 native libraries found in the APK.")),Se.info(fe.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(i,a),u=ff(c),d=Ft.basename(a),f=pf(a);f!==null&&o.push({name:d,filePath:c,arch:u,align:f,compatible:f>=Ia})}if(n.stop("Analysis complete."),o.length===0)return Se.info(fe.yellow("No valid ELF shared libraries found.")),!0;let s=o.filter(a=>!a.compatible),l=o.filter(a=>a.compatible);if(Se.info(fe.dim(`Checked ${o.length} native librar${o.length===1?"y":"ies"}
|
|
1506
|
+
`)),s.length>0){Se.info(fe.red.bold(`Incompatible libraries:
|
|
1507
|
+
`));for(let a of s)Se.error(fe.red(`${fe.bold(a.name)} ${fe.dim(`(${a.arch})`)}`)),Se.info(fe.dim(` PT_LOAD alignment: 2**${Math.log2(a.align)} (${a.align} bytes, needs 2**14 = ${Ia})`))}return l.length>0&&(console.log(""),Se.success(fe.green(`${l.length} librar${l.length===1?"y":"ies"} correctly aligned (2**14 or higher).`))),console.log(""),s.length===0?(Se.success(fe.green.bold("ELF Verification Successful. APK is 16KB compatible.")),!0):(Se.error(fe.red.bold(`Found ${s.length} unaligned lib${s.length===1?"":"s"} (arm64-v8a/x86_64 libs need to be aligned).`)),console.log(""),Se.info(fe.yellow("To fix this:")),Se.info(fe.dim(" 1. Rebuild with NDK r28+ which defaults to 16KB page alignment")),Se.info(fe.dim(" 2. Or set -DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON in CMake")),Se.info(fe.dim(" 3. Update third-party libraries that ship prebuilt .so files")),Se.info(fe.dim(" 4. After rebuilding: zipalign -p -f -v 16 input.apk output.apk")),console.log(""),Se.info(fe.dim("Reference: https://developer.android.com/guide/practices/page-sizes")),!1)}catch(r){return n.stop("Analysis failed."),Se.error(fe.red(`Failed to analyze APK: ${r.message}`)),!1}finally{try{at.rmSync(i,{recursive:!0,force:!0})}catch{}}}function pf(e){let t=at.openSync(e,"r");try{let n=Buffer.alloc(64);if(at.readSync(t,n,0,64,0),!n.subarray(0,4).equals(uf))return null;let i=n[4]===2,r=n[5]===1,o=(f,p)=>r?f.readUInt16LE(p):f.readUInt16BE(p),s=(f,p)=>r?f.readUInt32LE(p):f.readUInt32BE(p),l=(f,p)=>Number(r?f.readBigUInt64LE(p):f.readBigUInt64BE(p)),a,c,u;i?(a=l(n,32),c=o(n,54),u=o(n,56)):(a=s(n,28),c=o(n,42),u=o(n,44));let d=null;for(let f=0;f<u;f++){let p=Buffer.alloc(c);if(at.readSync(t,p,0,c,a+f*c),s(p,0)!==cf)continue;let y;i?y=l(p,48):y=s(p,28),y>0&&(d===null||y<d)&&(d=y)}return d??0}catch{return null}finally{at.closeSync(t)}}function _a(e){let t=[];if(!at.existsSync(e))return t;let n=at.readdirSync(e,{withFileTypes:!0});for(let i of n){let r=Ft.join(e,i.name);i.isDirectory()?t.push(..._a(r)):i.name.endsWith(".so")&&t.push(r)}return t}function ff(e){return e.includes("arm64-v8a")?"arm64-v8a":e.includes("x86_64")?"x86_64":"unknown"}var va=async e=>{if(Pe()||(Ue.error(Ye.red(`You are not logged in. Run \`${m.nameLower} login\` first.`)),process.exit(1)),e.apk){await hf(e);return}let n=process.cwd(),i=qn.join(n,"package.json");pn.existsSync(i)||(Ue.error(Ye.red("No package.json found. Run this command from a project root.")),process.exit(1));let r=JSON.parse(pn.readFileSync(i,"utf-8")),o=!!(r.dependencies?.expo||r.devDependencies?.expo);e.json||(Ue.info(Ye.dim(`Project: ${r.name||"unknown"} v${r.version||"0.0.0"}`)),Ue.info(Ye.dim(`Type: ${o?"Expo":"Bare React Native"}`)),Ue.info(""));let s={json:e.json,fix:e.fix,category:e.category,severity:e.severity,prebuild:e.prebuild},l=await ba(n,s);e.json?console.log(JSON.stringify(Aa(l,r),null,2)):Ea(l,e.severity);let a=l.some(u=>u.findings.some(d=>d.severity==="critical")),c=l.some(u=>u.findings.some(d=>d.severity==="high"));(a||c)&&process.exit(1)},Ra=["16kb"];async function hf(e){let t=e.category?.toLowerCase();t&&!Ra.includes(t)&&(Ue.error(Ye.red(`Unknown APK check category: "${t}"`)),Ue.info(Ye.dim(`Available APK checks: ${Ra.join(", ")}`)),process.exit(1));let n=await Sf(e.apk);n||process.exit(1);let i=!t,r=!1;(i||t==="16kb")&&(await wa(n)||(r=!0)),r&&process.exit(1)}async function Sf(e){if(e.startsWith("build:")){let n=e.slice(6);return await yf(n)}if(e.startsWith("http://")||e.startsWith("https://"))return await Pa(e);let t=qn.resolve(e);return pn.existsSync(t)?t:(Ue.error(Ye.red(`APK file not found: ${t}`)),null)}async function yf(e){let t=$a();t.start(`Fetching APK from build ${e}...`);try{let n=await k.get(`/build/${e}`);if(n.data.status!=="success")throw new Error(n.data.message);let i=n.data.build;if(!i)throw new Error("Build not found");let r=i.artifacts?.find(o=>o.type?o.type==="apk":o.name?.endsWith(".apk")||o.url?.includes(".apk"));return!r||!r.url?(t.stop("No APK artifact found"),Ue.error(Ye.red("This build does not have an APK artifact.")),Ue.info(Ye.dim("Make sure the build produced an APK (not just an AAB).")),null):(t.stop(`Found build: ${i.buildId||e}`),await Pa(r.url))}catch(n){return t.stop("Failed to fetch build"),Ue.error(Ye.red(n.message)),null}}async function Pa(e){let t=$a();t.start("Downloading APK...");try{let n=pn.mkdtempSync(qn.join(mf.tmpdir(),`${m.nameLower}-audit-`)),i=qn.join(n,"app.apk"),r=await gf.get(e,{responseType:"arraybuffer"});pn.writeFileSync(i,r.data);let o=(r.data.length/(1024*1024)).toFixed(1);return t.stop(`Downloaded APK (${o} MB)`),i}catch(n){return t.stop("Download failed"),Ue.error(Ye.red(`Failed to download APK: ${n.message}`)),null}}var Af=console.log;console.log=()=>{};Ef();console.log=Af;we(Ee.bgCyan.black(m.cliTag("Production Build Orchestrator")));var wf=If(import.meta.url),_f=wf("../package.json"),Da=(e,t=[])=>t.concat(e),re=new bf;re.name(m.nameLower).description(`${m.name} CLI: Powerful Cloud Infrastructure Tools`).version(_f.version).option("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1);re.command("agent").description("Manage local device discovery agent for the Install Hub (port 7070)").argument("[action]","start, run, install, status, restart, stop, or uninstall","start").action(async e=>{await Ds(e)});re.command("host").description("Setup AWS S3 static hosting and CloudFront").action(async()=>{we(Ee.bgCyan.black(m.cliTag("Hosting"))),await Er()});re.command("sitemap").description("Generate sitemap.xml from Expo Router app structure").option("-o, --output <path>","Output path for sitemap.xml","./public/sitemap.xml").action(async e=>{we(Ee.bgCyan.black(m.cliTag("Sitemap Generator"))),await _r(e)});re.command("build").description("Run a build on a cloud provider (AWS Spot Instances)").argument("[platform]","Target platform (android, ios)").option("--platform <os>","Target platform alias (android, ios) [Optional]").option("--repo <url>","Git Repository URL").option("--branch <name>","Git Branch").option("--ami <id>","AMI ID").option("--bucket <name>","S3 Bucket for artifacts").option("--region <region>","AWS Region").option("--aws-profile <name>","AWS Credentials Profile").option("-p, --build-profile <name>","Build Profile (e.g. production, staging)").option("--profile <name>","Build Profile (alias for --build-profile)").option("--dry-run","Generate User Data script without launching").option("--keep-instance","Do not terminate the instance after build").option("--subnet <id>","VPC Subnet ID to launch the instance in").option("--security-group <id>","VPC Security Group ID to use").option("--ssh-host <host>","Remote host for iOS build (SSH)").option("--ssh-user <user>","SSH username for remote host").option("--ssh-key <path>","Path to private SSH key for remote host").option("--ios-scheme <scheme>","iOS Scheme to build").option("--ios-team-id <id>","Apple Development Team ID").option("--ios-configuration <config>","Xcode configuration (Release/Debug)").option("--ios-export-method <method>","Export method (ad-hoc, app-store, development, enterprise)").option("--ios-api-key-id <id>","App Store Connect API Key ID").option("--ios-api-key-issuer <id>","App Store Connect API Key Issuer ID").option("--ios-api-key-path <path>","Path to App Store Connect API Key (.p8) file").option("--simulator","Build for iOS Simulator (no signing required)").addOption(new Fe("--build-id <id>","Internal build ID").hideHelp()).addOption(new Fe("--project-id <id>","Internal project ID").hideHelp()).addOption(new Fe("--fail-only","Internal: mark an existing build failed").hideHelp()).addOption(new Fe("--error <message>","Internal failure message").hideHelp()).option("--local","Run build on local machine").option("--auto-version","Automatically fetch and increment Android versionCode or iOS buildNumber from the store").option("--auto-submit","Submit this build after it completes successfully").option("--submit-track <track>","Google Play track to use with --auto-submit").option("--submit-release-status <status>","Google Play release status to use with --auto-submit").option("--submit-rollout <fraction>","Google Play staged rollout fraction to use with --auto-submit").option("--submit-changes-not-sent-for-review","Commit Google Play changes without automatically sending them for review when using --auto-submit").option("--submit-credential-id <id>","Service credential ID to use with --auto-submit").option("--submit-json-output <path>","Write auto-submit metadata JSON to a file for CI/CD").option("--verbose","Enable verbose logging").option("--json-output <path>","Write build metadata JSON to a file for CI/CD").option("--maestro","Queue a managed Maestro test run after a successful build").option("--maestro-flows <path>","Maestro flow file or directory (default: .maestro)").option("--maestro-device <device>","Managed Maestro device profile").option("--maestro-retries <n>","Retries for the Maestro run","1").option("--maestro-record","Enable screen recording where supported").option("--maestro-use-build-source","Use Maestro flows from the build source snapshot instead of uploading local flows").option("--maestro-env <name>","Forward an environment variable to the managed Maestro runner; repeat or comma-separate names",Da,[]).option("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1).action(async(e,t)=>{let n=re.opts();t.yes=t.yes||n.yes,t.quiet=t.quiet||n.quiet,t.platform=e||t.platform,t.buildProfile=t.profile||t.buildProfile,t.quiet||we(Ee.bgCyan.black(m.cliTag("Cloud Build"))),await On(t)});re.command("maestro").description("Run Maestro tests locally or with the managed Mach runner").option("--platform <os>","Target platform (android/ios)").option("-p, --profile <name>","Build profile to resolve when using --latest","production").option("--latest","Use the latest successful build for the platform/profile").option("--build-id <id>","Use a specific Mach build ID").option("--build-url <url>","Use a Mach build URL").option("--artifact-url <url>","Use a direct APK or iOS simulator app artifact URL").option("--local","Run Maestro on a connected local emulator/device instead of the managed runner").option("--maestro-flows <path>","Maestro flow file or directory (default: .maestro)").option("--maestro-device <device>","Managed Maestro device profile").option("--maestro-retries <n>","Retries for the Maestro run","1").option("--maestro-record","Enable screen recording where supported").option("--maestro-use-build-source","Use Maestro flows from the build source snapshot instead of uploading local flows").option("--maestro-env <name>","Forward an environment variable to the managed Maestro runner; repeat or comma-separate names",Da,[]).option("--wait","Wait for managed Maestro completion and exit non-zero on failure").option("--wait-timeout <minutes>","Maximum minutes to wait for managed Maestro completion","60").option("--wait-interval <seconds>","Polling interval while waiting for managed Maestro completion","15").option("--json-output <path>","Write test run metadata JSON to a file for CI/CD").addOption(new Fe("--local-runner","Internal: execute a managed Maestro run on this machine").hideHelp()).addOption(new Fe("--test-run-id <id>","Internal test run ID").hideHelp()).addOption(new Fe("--project-id <id>","Internal project ID").hideHelp()).addOption(new Fe("--runner-token <token>","Internal runner token").hideHelp()).action(async e=>{we(Ee.bgCyan.black(m.cliTag("Maestro Testing"))),await mo(e)});re.command("update").description("Deploy an Over-The-Air (OTA) update to your live channel").option("--branch <name>","Channel or Branch to deploy to (e.g., production)","production").action(async e=>{we(Ee.bgCyan.black(m.cliTag("OTA Update"))),await js(e)});re.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 Fe("--submit-id <id>","Internal submission ID").hideHelp()).addOption(new Fe("--project-id <id>","Internal project ID").hideHelp()).addOption(new Fe("--package-name <name>","Internal Android package name").hideHelp()).addOption(new Fe("--bundle-id <id>","Internal iOS bundle identifier").hideHelp()).option("--json-output <path>","Write submission metadata JSON to a file for CI/CD").option("--latest","Use the latest successful build for submission").option("--build-id <id>","Use a specific build ID for submission").action(async e=>{let t=re.opts();e.quiet=e.quiet||t.quiet,e.yes=e.yes||t.yes,we(Ee.bgCyan.black(m.cliTag("Store Submission"))),await wn(e)});re.command("login").description(`Login to ${m.name} Dashboard`).action(async()=>{we(Ee.bgCyan.black(m.cliTag("Login"))),await ks()});re.command("logout").description(`Logout from ${m.name} on this machine`).action(async()=>{we(Ee.bgCyan.black(m.cliTag("Logout"))),await xs()});re.command("link").description(`Link local directory to a ${m.name} Project`).action(async()=>{we(Ee.bgCyan.black(m.cliTag("Link Project"))),await Ms()});re.command("me").description("Display currently logged in user details").action(async()=>{await Ks()});re.command("init").description(`Create a new ${m.name} Project`).action(async()=>{we(Ee.bgCyan.black(m.cliTag("Init Project"))),await Us()});re.command("env").description("Manage Environment Variables").argument("<action>","Action to perform: set, list, pull, download, or export").argument("[args...]","Key=Value pairs for set action").option("-e, --environment <name>","Environment to pull/download","development").option("-o, --out <file>","Output file for pull/download",".env.local").option("--overwrite","Overwrite output file if it already exists").action(async(e,t,n)=>{we(Ee.bgCyan.black(m.cliTag("Env Manager"))),await Bs(e,t,n)});re.command("start").description("Start the development server (Metro)").option("-p, --build-profile <name>","Build profile (e.g. development, staging)","development").option("--tunnel","Use ngrok tunnel").option("--lan","Use LAN IP").option("--localhost","Use localhost").option("-c, --clear","Clear Metro cache").option("--port <number>","Port to listen on").option("--ios","Start on iOS").option("--android","Start on Android").option("--web","Start on Web").action(async e=>{we(Ee.bgCyan.black(m.cliTag("Dev Server"))),await zs(e)});re.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 Ws(e)});re.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-3MYGMYJK.js");await t(e)});re.command("credentials:setup").description("Automated credential provisioning (iOS/Android) [Legacy]").requiredOption("--platform <os>","Platform: ios or android").option("--profile <name>","Build profile (production, staging, development)").option("--bundle-id <id>","Bundle ID / Package Name (optional, auto-detected)").option("--team-id <id>","Apple Team ID (iOS only)").option("--key-alias <alias>","Android keystore alias (optional, auto-generated)").option("--aws-profile <name>","AWS Credentials Profile (for S3 storage)").option("--force","Force recreate certificates (nuke existing on Apple Portal)",!1).action(async e=>{we(Ee.bgCyan.black(m.cliTag("Credentials Setup"))),await Ht(e),Oa(Ee.green("Done!"))});re.command("credentials:service").description("Upload Service Credentials (ASC API Key / Google Service JSON) [Legacy]").requiredOption("--platform <os>","Platform: ios or android").option("--file <path>","Path to credential file (.p8 or .json)").option("--issuer-id <id>","ASC API Key Issuer ID (iOS only)").option("--key-id <id>","ASC API Key ID (iOS only)").option("--bundle-id <id>","Bundle identifier / Android package name to attach this service credential to").option("--package-name <name>","Android package name to attach this service credential to").option("-p, --profile <name>","Build profile to resolve package/bundle identifier from config").action(async e=>{we(Ee.bgCyan.black(m.cliTag("Service Credentials"))),await yr(e),Oa(Ee.green("Done!"))});var rr=re.command("device").description("Manage registered iOS test devices");rr.command("register").description("Register a connected iOS device or enter UDID manually").option("--udid <udid>","Device UDID (skip auto-detection)").option("--name <name>","Device name").option("--team-id <id>","Apple Developer Team ID for this device").action(async e=>{await Hn("register",e)});rr.command("list").description("List all registered devices").option("--team-id <id>","Filter by Apple Developer Team ID").action(async e=>{await Hn("list",e)});rr.command("remove").description("Remove a registered device").option("--udid <udid>","Device UDID to remove").option("--team-id <id>","Apple Developer Team ID for this device").action(async e=>{await Hn("remove",e)});re.command("audit").description("Run automated security audit on the project or APK").option("--apk <path>","Path to APK file (runs APK diagnostics like 16KB alignment)").option("--json","Output results as JSON (for CI/CD)").option("--fix","Auto-apply fixes where possible").option("--category <name>","Run only a specific check category (e.g. 16kb, permissions, secrets)").option("--severity <level>","Minimum severity to display (critical, high, medium, low, info)").option("--prebuild","Run expo prebuild for deeper manifest/plist analysis").action(async e=>{we(Ee.bgCyan.black(m.cliTag(e.apk?"APK Audit":"Security Audit"))),await va(e)});var Rf=new Set(["login","logout","agent"]);re.hook("preAction",(e,t)=>{let n=t.name(),i=t.opts?.()||{};n==="maestro"&&(i.local||i.localRunner)||Rf.has(n)||pr()});re.on("command:*",()=>{console.error(`Invalid command: %s
|
|
1508
|
+
See --help for a list of available commands.`,re.args.join(" ")),process.exit(1)});process.argv.slice(2).length||re.help();re.parse(process.argv);
|