@radhya/mach 1.4.28 → 1.5.0
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 +119 -2
- package/dist/chunk-K4B4LODJ.js +54 -0
- package/dist/commands/isolated-upload.js +1 -1
- package/dist/{credentials-RNU5D7E7.js → credentials-XU7FSPK4.js} +1 -1
- package/dist/index.js +361 -146
- package/package.json +1 -1
- package/dist/chunk-IBDTJ42P.js +0 -54
package/dist/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as
|
|
3
|
-
`;
|
|
4
|
-
`,
|
|
5
|
-
|
|
6
|
-
CloudFront ID: ${Ze.cyan(r.cloudFrontId)}`,
|
|
7
|
-
CloudFront URL: ${Ze.blue(r.cloudFrontUrl)}`),
|
|
8
|
-
${
|
|
9
|
-
`)}`,"Sitemap Summary"),
|
|
2
|
+
import{a as di,c as qe}from"./chunk-K4B4LODJ.js";import{a as f,b as ci,c as pe,d as li,e as ht,f as Ft,g as D}from"./chunk-YZYFEHP5.js";import{Command as es,Option as Un}from"commander";import{configDotenv as ts}from"dotenv";import{intro as ue,outro as Mn}from"@clack/prompts";import ae from"chalk";import{text as ui,confirm as Fn,spinner as Hn,isCancel as Ht,cancel as Xe,note as Bn,outro as Gn}from"@clack/prompts";import Ze from"chalk";async function pi(){try{let e=await ui({message:"Enter Bucket Name:",placeholder:"e.g. my-app-dev",validate(o){if(o.length===0)return"Bucket name is required"}});Ht(e)&&(Xe("Operation cancelled."),process.exit(0));let n=await ui({message:"Enter Region:",initialValue:"ap-south-1"});Ht(n)&&(Xe("Operation cancelled."),process.exit(0));let t=await Fn({message:"Do you want to create a CloudFront Distribution for this bucket?",initialValue:!0});Ht(t)&&(Xe("Operation cancelled."),process.exit(0));let i=Hn();i.start("Setting up hosting infrastructure...");try{let o=await D.post("/hosting/setup",{bucketName:e,region:n,createCloudFront:t});if(o.data.status!=="success")throw new Error(o.data.message||"Hosting setup failed");i.stop("Hosting setup complete!");let r=o.data,c=`Bucket Name: ${Ze.cyan(r.bucketName)}
|
|
3
|
+
`;c+=`Region: ${Ze.cyan(r.region)}
|
|
4
|
+
`,c+=`S3 Website URL: ${Ze.blue(r.s3WebsiteUrl)}`,r.cloudFrontId&&(c+=`
|
|
5
|
+
|
|
6
|
+
CloudFront ID: ${Ze.cyan(r.cloudFrontId)}`,c+=`
|
|
7
|
+
CloudFront URL: ${Ze.blue(r.cloudFrontUrl)}`),Bn(c,"Setup Complete!"),Gn("You are all set!")}catch(o){i.stop("Setup failed"),Xe(`Error: ${o.response?.data?.message||o.message}`)}}catch(e){Xe(`An unexpected error occurred: ${e.message}`)}}import{readdir as jn,writeFile as Kn,access as zn,mkdir as Vn}from"fs/promises";import{join as fi}from"path";import{spinner as Wn,text as mi,isCancel as gi,cancel as Bt,note as Yn,outro as Jn}from"@clack/prompts";import qn from"chalk";async function Xn(){let e=["./app","./src/app"];for(let n of e)try{return await zn(n),n}catch{}return null}async function hi(e){try{let t=await Xn()||"./app",i=await mi({message:"Enter path to your app directory:",placeholder:t,initialValue:t,validate(l){if(l.length===0)return"Path is required"}});gi(i)&&(Bt("Operation cancelled."),process.exit(0));let o=await mi({message:"Enter your website base URL:",placeholder:"https://example.com",validate(l){if(l.length===0)return"Base URL is required";if(!l.startsWith("http"))return"URL must start with http:// or https://"}});gi(o)&&(Bt("Operation cancelled."),process.exit(0));let r=Wn();r.start("Scanning app directory for routes...");let c=await yi(i);r.stop(`Found ${c.length} routes`);let a=Zn(c,o),s=e.output||"./public/sitemap.xml";r.start(`Writing sitemap to ${s}...`);let d=s.substring(0,s.lastIndexOf("/"));if(d)try{await Vn(d,{recursive:!0})}catch{}await Kn(s,a,"utf-8"),r.stop("Sitemap generated successfully!"),Yn(`Routes included:
|
|
8
|
+
${c.map(l=>` \u2022 ${l.path}`).join(`
|
|
9
|
+
`)}`,"Sitemap Summary"),Jn(`Sitemap saved to ${qn.cyan(s)}`)}catch(n){Bt(`An error occurred: ${n.message}`)}}async function yi(e,n=""){let t=[];try{let i=await jn(e,{withFileTypes:!0});for(let o of i){let r=fi(e,o.name);if(!(o.name.startsWith("_")||o.name.startsWith("."))){if(o.isDirectory()){let c=await yi(r,fi(n,o.name));t.push(...c)}else if(o.isFile()){if(o.name==="index.tsx"||o.name==="index.ts"||o.name==="index.jsx"||o.name==="index.js"){let c=n===""?"/":`/${n}`;t.push({path:c,file:r})}else if(o.name.match(/\.(tsx|ts|jsx|js)$/)&&!o.name.includes("_layout")&&!o.name.includes("+")){let c=o.name.replace(/\.(tsx|ts|jsx|js)$/,""),a=`/${n}/${c}`.replace(/\/+/g,"/");t.push({path:a,file:r})}}}}}catch(i){throw new Error(`Failed to scan directory ${e}: ${i.message}`)}return t}function Zn(e,n){let t=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(o=>{let r=o.path;return r=r.replace(/\/\([^)]+\)/g,""),r=r.replace(/\/\[.*?\]/g,"/:id"),r=r.replace(/\/+/g,"/"),r===""&&(r="/"),` <url>
|
|
12
12
|
<loc>${n}${r}</loc>
|
|
@@ -15,13 +15,15 @@ ${e.map(o=>{let r=o.path;return r=r.replace(/\/\([^)]+\)/g,""),r=r.replace(/\/\[
|
|
|
15
15
|
<priority>0.8</priority>
|
|
16
16
|
</url>`}).join(`
|
|
17
17
|
`)}
|
|
18
|
-
</urlset>`}import{randomUUID as
|
|
18
|
+
</urlset>`}import{randomUUID as Ao}from"crypto";import he from"path";import tt from"axios";import Io from"os";import{spinner as Kt,confirm as vi,isCancel as Oi,log as w}from"@clack/prompts";import v from"chalk";import oe from"fs";import{execSync as Ci}from"child_process";import Ni from"adm-zip";import{spinner as Qn,log as yt}from"@clack/prompts";import Ei from"chalk";import Ai from"fs";import Ii from"path";var Si=`#!/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}}"
|
|
22
22
|
|
|
23
23
|
# --- System Setup ---
|
|
24
|
-
exec > >(tee /var/log/user-data.log) 2>&1
|
|
24
|
+
exec > >(tee /var/log/user-data.log | cat) 2>&1
|
|
25
|
+
export PYTHONUNBUFFERED=1
|
|
26
|
+
export GRADLE_OPTS="-Dorg.gradle.console=plain"
|
|
25
27
|
echo "Starting build setup..."
|
|
26
28
|
|
|
27
29
|
# Forward environment variables (includes PRESIGNED_* URLs + project secrets)
|
|
@@ -37,13 +39,14 @@ if [ -f "/opt/mach-prewarmed" ]; then
|
|
|
37
39
|
echo "Pre-warmed AMI detected. Skipping tool installation."
|
|
38
40
|
else
|
|
39
41
|
echo "Fresh AMI detected. Installing tools..."
|
|
40
|
-
apt-get update
|
|
41
|
-
apt-get install -y unzip zip openjdk-17-jdk curl build-essential git-lfs libstdc++6 zlib1g
|
|
42
|
+
apt-get update -qq
|
|
43
|
+
apt-get install -y --no-install-recommends unzip zip openjdk-17-jdk curl build-essential git-lfs libstdc++6 zlib1g pigz
|
|
42
44
|
|
|
43
|
-
# Install Node.js (LTS v20
|
|
45
|
+
# Install Node.js (LTS v20 as base \u2014 overridden below if nodeVersion is set)
|
|
44
46
|
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
|
|
45
47
|
apt-get install -y nodejs
|
|
46
48
|
npm install -g yarn
|
|
49
|
+
echo "[NODE] Base install: $(node -v)"
|
|
47
50
|
|
|
48
51
|
# Install Android SDK
|
|
49
52
|
mkdir -p /opt/android-sdk/cmdline-tools
|
|
@@ -64,32 +67,41 @@ fi
|
|
|
64
67
|
export ANDROID_HOME=/opt/android-sdk
|
|
65
68
|
export PATH=$PATH:$ANDROID_HOME/cmdline-tools/latest/bin:$ANDROID_HOME/platform-tools:$ANDROID_HOME/build-tools/34.0.0
|
|
66
69
|
|
|
67
|
-
#
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
tar -xzf /tmp/gradle-cache.tar.gz -C /root/.gradle
|
|
72
|
-
echo "Gradle cache restored."
|
|
73
|
-
fi
|
|
74
|
-
fi
|
|
75
|
-
|
|
76
|
-
if [ ! -z "$PRESIGNED_CACHE_NPM_DOWNLOAD" ]; then
|
|
77
|
-
if curl -sf -o /tmp/npm-cache.tar.gz "$PRESIGNED_CACHE_NPM_DOWNLOAD"; then
|
|
78
|
-
mkdir -p /root/.npm
|
|
79
|
-
tar -xzf /tmp/npm-cache.tar.gz -C /root
|
|
80
|
-
echo "npm cache restored."
|
|
81
|
-
fi
|
|
82
|
-
fi
|
|
70
|
+
# Install pigz if missing (parallel gzip \u2014 makes tar 3-4x faster)
|
|
71
|
+
command -v pigz >/dev/null 2>&1 || apt-get install -y pigz -qq 2>/dev/null || true
|
|
72
|
+
TAR_COMPRESS="-I pigz"
|
|
73
|
+
command -v pigz >/dev/null 2>&1 || TAR_COMPRESS="-z"
|
|
83
74
|
|
|
84
75
|
# --- Project Setup ---
|
|
85
76
|
export HOME=/root
|
|
86
77
|
|
|
78
|
+
function step_marker() {
|
|
79
|
+
local MARKER="[STEP_START:$1] $(date +%s)"
|
|
80
|
+
echo ""
|
|
81
|
+
echo "$MARKER"
|
|
82
|
+
echo "$MARKER" >> /var/log/user-data.log
|
|
83
|
+
sync
|
|
84
|
+
}
|
|
85
|
+
|
|
87
86
|
function upload_logs() {
|
|
88
87
|
if [ ! -z "$PRESIGNED_LOG_UPLOAD" ]; then
|
|
89
88
|
curl -X PUT -T /var/log/user-data.log "$PRESIGNED_LOG_UPLOAD" --silent || true
|
|
90
89
|
fi
|
|
91
90
|
}
|
|
92
91
|
|
|
92
|
+
function report_status() {
|
|
93
|
+
local STATUS=$1
|
|
94
|
+
local ERROR_MSG=$2
|
|
95
|
+
if [ ! -z "$MACH_API_URL" ] && [ ! -z "$MACH_PROJECT_ID" ] && [ ! -z "$MACH_BUILD_ID" ]; then
|
|
96
|
+
PAYLOAD="{"status":"$STATUS""
|
|
97
|
+
if [ ! -z "$ERROR_MSG" ]; then
|
|
98
|
+
PAYLOAD="$PAYLOAD,"error":"$ERROR_MSG""
|
|
99
|
+
fi
|
|
100
|
+
PAYLOAD="$PAYLOAD}"
|
|
101
|
+
curl -s -X POST "$MACH_API_URL/builds/$MACH_PROJECT_ID/$MACH_BUILD_ID/worker-status" -H "Content-Type: application/json" -d "$PAYLOAD" || true
|
|
102
|
+
fi
|
|
103
|
+
}
|
|
104
|
+
|
|
93
105
|
# Start log uploader (every 5 seconds)
|
|
94
106
|
(
|
|
95
107
|
while true; do
|
|
@@ -99,14 +111,92 @@ function upload_logs() {
|
|
|
99
111
|
) &
|
|
100
112
|
UPLOADER_PID=$!
|
|
101
113
|
|
|
102
|
-
|
|
114
|
+
# Spot interruption watcher \u2014 AWS gives a 2-minute warning via instance metadata.
|
|
115
|
+
# On detection: flush logs, notify API with 'interrupted' status, then let AWS terminate.
|
|
116
|
+
(
|
|
117
|
+
while true; do
|
|
118
|
+
sleep 5
|
|
119
|
+
NOTICE=$(curl -s -o /dev/null -w "%{http_code}" --max-time 2 "http://169.254.169.254/latest/meta-data/spot/termination-time" 2>/dev/null)
|
|
120
|
+
if [ "$NOTICE" = "200" ]; then
|
|
121
|
+
echo "[SPOT] Interruption notice received \u2014 flushing logs and notifying API..."
|
|
122
|
+
upload_logs
|
|
123
|
+
report_status "interrupted" "Spot instance interrupted by AWS \u2014 build will be retried automatically"
|
|
124
|
+
exit 0
|
|
125
|
+
fi
|
|
126
|
+
done
|
|
127
|
+
) &
|
|
128
|
+
SPOT_WATCHER_PID=$!
|
|
129
|
+
|
|
130
|
+
step_marker init
|
|
131
|
+
report_status "building"
|
|
132
|
+
|
|
133
|
+
# Add swap to prevent OOM kills during Metro bundling + Gradle running concurrently
|
|
134
|
+
if [ ! -f /swapfile ]; then
|
|
135
|
+
echo "Setting up 8GB swap..."
|
|
136
|
+
fallocate -l 8G /swapfile
|
|
137
|
+
chmod 600 /swapfile
|
|
138
|
+
mkswap /swapfile
|
|
139
|
+
swapon /swapfile
|
|
140
|
+
echo "Swap enabled: $(free -h | grep Swap)"
|
|
141
|
+
fi
|
|
142
|
+
|
|
143
|
+
mkdir -p /home/ubuntu/build /root/.gradle /root/.npm
|
|
144
|
+
|
|
145
|
+
# --- Kick off ALL downloads in parallel immediately ---
|
|
146
|
+
# Source zip + gradle/npm caches download concurrently.
|
|
147
|
+
# android/ + node_modules caches are applied AFTER source extraction (so source doesn't overwrite them).
|
|
148
|
+
cache_dl_pids=()
|
|
149
|
+
|
|
150
|
+
curl -sf -o /tmp/source.zip "$PRESIGNED_SOURCE_DOWNLOAD" &
|
|
151
|
+
SOURCE_DL_PID=$!
|
|
103
152
|
|
|
104
|
-
|
|
153
|
+
if [ ! -z "$PRESIGNED_CACHE_GRADLE_DOWNLOAD" ]; then
|
|
154
|
+
(curl -sf -o /tmp/gradle-cache.tar.gz "$PRESIGNED_CACHE_GRADLE_DOWNLOAD" && tar $TAR_COMPRESS -xf /tmp/gradle-cache.tar.gz -C /root/.gradle && rm -f /tmp/gradle-cache.tar.gz && echo "Gradle cache restored.") &
|
|
155
|
+
cache_dl_pids+=($!)
|
|
156
|
+
fi
|
|
157
|
+
|
|
158
|
+
if [ ! -z "$PRESIGNED_CACHE_NPM_DOWNLOAD" ]; then
|
|
159
|
+
(curl -sf -o /tmp/npm-cache.tar.gz "$PRESIGNED_CACHE_NPM_DOWNLOAD" && tar $TAR_COMPRESS -xf /tmp/npm-cache.tar.gz -C /root && rm -f /tmp/npm-cache.tar.gz && echo "npm cache restored.") &
|
|
160
|
+
cache_dl_pids+=($!)
|
|
161
|
+
fi
|
|
162
|
+
|
|
163
|
+
# Download node_modules and android caches to /tmp now \u2014 extract after source unzip
|
|
164
|
+
if [ ! -z "$PRESIGNED_CACHE_NODE_MODULES_DOWNLOAD" ]; then
|
|
165
|
+
(curl -sf -o /tmp/node-modules-cache.tar.gz "$PRESIGNED_CACHE_NODE_MODULES_DOWNLOAD" && echo "node_modules archive ready.") &
|
|
166
|
+
cache_dl_pids+=($!)
|
|
167
|
+
fi
|
|
168
|
+
|
|
169
|
+
if [ ! -z "$PRESIGNED_CACHE_ANDROID_DOWNLOAD" ]; then
|
|
170
|
+
(curl -sf -o /tmp/android-cache.tar.gz "$PRESIGNED_CACHE_ANDROID_DOWNLOAD" && echo "android/ archive ready.") &
|
|
171
|
+
cache_dl_pids+=($!)
|
|
172
|
+
fi
|
|
173
|
+
|
|
174
|
+
# Wait for gradle/npm caches (they go to /root, no conflict with source)
|
|
175
|
+
for pid in "\${cache_dl_pids[@]}"; do wait "$pid" || true; done
|
|
176
|
+
|
|
177
|
+
step_marker clone
|
|
178
|
+
|
|
179
|
+
# Wait for source zip, extract first
|
|
180
|
+
wait "$SOURCE_DL_PID"
|
|
181
|
+
if [ $? -ne 0 ]; then
|
|
182
|
+
echo "[ERROR] Failed to download source zip"
|
|
183
|
+
report_status "failed" "Failed to download source zip"
|
|
184
|
+
exit 1
|
|
185
|
+
fi
|
|
105
186
|
cd /home/ubuntu/build
|
|
106
|
-
|
|
107
|
-
|
|
187
|
+
unzip -q -o /tmp/source.zip
|
|
188
|
+
rm -f /tmp/source.zip
|
|
108
189
|
|
|
109
|
-
|
|
190
|
+
# Now overlay node_modules and android/ caches on top of extracted source
|
|
191
|
+
if [ -f /tmp/node-modules-cache.tar.gz ]; then
|
|
192
|
+
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."
|
|
193
|
+
fi
|
|
194
|
+
|
|
195
|
+
if [ -f /tmp/android-cache.tar.gz ]; then
|
|
196
|
+
tar $TAR_COMPRESS -xf /tmp/android-cache.tar.gz -C /home/ubuntu/build && rm -f /tmp/android-cache.tar.gz && echo "android/ cache restored."
|
|
197
|
+
fi
|
|
198
|
+
|
|
199
|
+
echo "Cache restore complete."
|
|
110
200
|
|
|
111
201
|
# CodeArtifact Logic \u2014 use env var if already set (pass as project secret)
|
|
112
202
|
if [ -z "$CODEARTIFACT_AUTH_TOKEN" ] && [ -f ".npmrc" ]; then
|
|
@@ -120,25 +210,72 @@ fi
|
|
|
120
210
|
# --- Node Version Switch ---
|
|
121
211
|
{{NODE_VERSION_SETUP}}
|
|
122
212
|
|
|
213
|
+
# Pre-Install Hook (runs before npm install \u2014 e.g. git credential setup for private packages)
|
|
214
|
+
if [ ! -z "$PRESIGNED_PREBUILD_SCRIPT" ]; then
|
|
215
|
+
step_marker prebuild_hook
|
|
216
|
+
curl -sf -o /tmp/prebuild-hook.sh "$PRESIGNED_PREBUILD_SCRIPT"
|
|
217
|
+
chmod +x /tmp/prebuild-hook.sh
|
|
218
|
+
(bash /tmp/prebuild-hook.sh)
|
|
219
|
+
HOOK_EXIT=$?
|
|
220
|
+
rm -f /tmp/prebuild-hook.sh
|
|
221
|
+
if [ $HOOK_EXIT -ne 0 ]; then
|
|
222
|
+
echo "[ERROR] preBuild hook failed with exit code $HOOK_EXIT"
|
|
223
|
+
upload_logs
|
|
224
|
+
report_status "failed" "preBuild hook failed with exit code $HOOK_EXIT"
|
|
225
|
+
touch done
|
|
226
|
+
[ ! -z "$PRESIGNED_DONE_MARKER" ] && curl -X PUT -T done "$PRESIGNED_DONE_MARKER" --silent
|
|
227
|
+
sleep 5
|
|
228
|
+
sudo shutdown -h now
|
|
229
|
+
exit $HOOK_EXIT
|
|
230
|
+
fi
|
|
231
|
+
fi
|
|
232
|
+
|
|
123
233
|
# Install Deps
|
|
124
|
-
|
|
234
|
+
step_marker deps
|
|
125
235
|
if [ -f "yarn.lock" ]; then
|
|
126
|
-
yarn install --frozen-lockfile
|
|
236
|
+
yarn install --frozen-lockfile --prefer-offline
|
|
127
237
|
else
|
|
128
|
-
npm install --no-audit --no-fund
|
|
238
|
+
npm install --no-audit --no-fund --prefer-offline
|
|
129
239
|
fi
|
|
130
240
|
|
|
131
|
-
#
|
|
132
|
-
|
|
241
|
+
# --- Injected Version Code (Auto-versioning) ---
|
|
242
|
+
# Apply before Expo prebuild so generated Gradle files receive the new versionCode.
|
|
243
|
+
if [ ! -z "$ANDROID_VERSION_CODE" ]; then
|
|
244
|
+
echo "[VERSIONING] Applying injected versionCode: $ANDROID_VERSION_CODE"
|
|
245
|
+
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');}"
|
|
246
|
+
fi
|
|
247
|
+
|
|
248
|
+
# --- Prebuild (expo only) ---
|
|
249
|
+
# Compute a hash of native-affecting files to decide if android/ cache is still valid.
|
|
250
|
+
# Hash covers: app.json/app.config.*, package.json, and any native plugin files.
|
|
251
|
+
if grep -q '"expo"' package.json 2>/dev/null; then
|
|
133
252
|
if [ -f "app.json" ] || [ -f "app.config.ts" ] || [ -f "app.config.js" ]; then
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
253
|
+
PREBUILD_HASH_FILE="/home/ubuntu/build/.mach-prebuild-hash"
|
|
254
|
+
PREBUILD_CURRENT_HASH=$(cat app.json app.config.ts app.config.js 2>/dev/null | cat - <(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) | md5sum | cut -d' ' -f1)
|
|
255
|
+
|
|
256
|
+
ANDROID_CACHE_VALID=false
|
|
257
|
+
if [ -f "$PREBUILD_HASH_FILE" ] && [ -d "android" ] && [ -f "android/gradlew" ]; then
|
|
258
|
+
STORED_HASH=$(cat "$PREBUILD_HASH_FILE" 2>/dev/null)
|
|
259
|
+
if [ "$PREBUILD_CURRENT_HASH" = "$STORED_HASH" ]; then
|
|
260
|
+
ANDROID_CACHE_VALID=true
|
|
261
|
+
echo "[PREBUILD] android/ cache is valid (hash match) \u2014 skipping expo prebuild."
|
|
262
|
+
fi
|
|
263
|
+
fi
|
|
264
|
+
|
|
265
|
+
if [ "$ANDROID_CACHE_VALID" = "false" ]; then
|
|
266
|
+
echo "[PREBUILD] Running expo prebuild..."
|
|
267
|
+
if [ -f "node_modules/.bin/expo" ]; then
|
|
268
|
+
node_modules/.bin/expo prebuild --platform android --no-install
|
|
269
|
+
else
|
|
270
|
+
npx expo prebuild --platform android --no-install
|
|
271
|
+
fi
|
|
272
|
+
echo "$PREBUILD_CURRENT_HASH" > "$PREBUILD_HASH_FILE"
|
|
273
|
+
fi
|
|
137
274
|
fi
|
|
138
275
|
fi
|
|
139
276
|
|
|
140
277
|
# Build
|
|
141
|
-
|
|
278
|
+
step_marker build
|
|
142
279
|
if [ -f "android/gradlew" ]; then
|
|
143
280
|
cd android
|
|
144
281
|
GRADLEW="./gradlew"
|
|
@@ -150,15 +287,37 @@ fi
|
|
|
150
287
|
|
|
151
288
|
chmod +x $GRADLEW
|
|
152
289
|
|
|
290
|
+
if [ ! -z "$ANDROID_VERSION_CODE" ]; then
|
|
291
|
+
if [ -f "app/build.gradle" ]; then
|
|
292
|
+
node -e "const fs=require('fs');const p='app/build.gradle';let s=fs.readFileSync(p,'utf8');s=s.replace(/versionCode\\s+\\d+/,'versionCode '+process.env.ANDROID_VERSION_CODE);fs.writeFileSync(p,s);console.log('[VERSIONING] app/build.gradle versionCode updated');"
|
|
293
|
+
elif [ -f "android/app/build.gradle" ]; then
|
|
294
|
+
node -e "const fs=require('fs');const p='android/app/build.gradle';let s=fs.readFileSync(p,'utf8');s=s.replace(/versionCode\\s+\\d+/,'versionCode '+process.env.ANDROID_VERSION_CODE);fs.writeFileSync(p,s);console.log('[VERSIONING] android/app/build.gradle versionCode updated');"
|
|
295
|
+
fi
|
|
296
|
+
fi
|
|
297
|
+
|
|
153
298
|
# Optimization
|
|
154
299
|
if [ -f "gradle.properties" ]; then
|
|
155
300
|
sed -i '/^org.gradle.jvmargs/d' gradle.properties
|
|
301
|
+
sed -i '/^org.gradle.workers/d' gradle.properties
|
|
302
|
+
sed -i '/^org.gradle.configureondemand/d' gradle.properties
|
|
303
|
+
sed -i '/^org.gradle.caching/d' gradle.properties
|
|
156
304
|
fi
|
|
157
305
|
# Protect against missing trailing newlines
|
|
158
306
|
echo "" >> gradle.properties
|
|
159
|
-
|
|
307
|
+
# 4GB heap, 1GB metaspace \u2014 leaves ~8GB for Metro bundler on c5.2xlarge (16GB RAM + 8GB swap)
|
|
308
|
+
echo "org.gradle.jvmargs=-Xmx4g -XX:MaxMetaspaceSize=1g -XX:+UseG1GC -XX:+HeapDumpOnOutOfMemoryError" >> gradle.properties
|
|
160
309
|
echo "org.gradle.parallel=true" >> gradle.properties
|
|
310
|
+
# Use all 8 vCPUs on c5.2xlarge
|
|
311
|
+
echo "org.gradle.workers.max=8" >> gradle.properties
|
|
312
|
+
# Only configure projects that are needed for the requested tasks
|
|
313
|
+
echo "org.gradle.configureondemand=true" >> gradle.properties
|
|
314
|
+
# Use Gradle build cache (works with the restored ~/.gradle cache)
|
|
315
|
+
echo "org.gradle.caching=true" >> gradle.properties
|
|
161
316
|
echo "expo.enableHermes=true" >> gradle.properties
|
|
317
|
+
# Disable Sentry Gradle plugin upload \u2014 runs after Gradle via sentry-cli instead (avoids hangs).
|
|
318
|
+
# These env vars are read directly by @sentry/react-native's sentry.gradle.
|
|
319
|
+
export SENTRY_DISABLE_AUTO_UPLOAD=true
|
|
320
|
+
export SENTRY_DISABLE_NATIVE_DEBUG_UPLOAD=true
|
|
162
321
|
|
|
163
322
|
if printf "%s" "{{BUILD_COMMAND}}" | grep -iq "release"; then
|
|
164
323
|
echo "[OPTIMIZATION] Enforcing production AAB miniaturization (R8/Proguard & ARM-only ABIs)..."
|
|
@@ -183,17 +342,15 @@ else
|
|
|
183
342
|
echo "[SIGNING] To enable: set ANDROID_KEYSTORE_BASE64, ANDROID_KEY_ALIAS, ANDROID_KEY_PASSWORD as project secrets."
|
|
184
343
|
fi
|
|
185
344
|
|
|
186
|
-
# --- Injected Version Code (Auto-versioning) ---
|
|
187
345
|
if [ ! -z "$ANDROID_VERSION_CODE" ]; then
|
|
188
|
-
echo "[VERSIONING] Applying injected versionCode: $ANDROID_VERSION_CODE"
|
|
189
346
|
SIGNING_FLAGS+=( "-Pandroid.injected.version.code=$ANDROID_VERSION_CODE" )
|
|
190
347
|
fi
|
|
191
348
|
|
|
192
|
-
$GRADLEW {{BUILD_COMMAND}} "\${SIGNING_FLAGS[@]}"
|
|
349
|
+
$GRADLEW {{BUILD_COMMAND}} "\${SIGNING_FLAGS[@]}" --console=plain --no-daemon 2>&1
|
|
193
350
|
BUILD_EXIT_CODE=$?
|
|
194
351
|
|
|
195
352
|
if [ $BUILD_EXIT_CODE -eq 0 ]; then
|
|
196
|
-
|
|
353
|
+
step_marker upload
|
|
197
354
|
|
|
198
355
|
# Upload Artifacts via presigned URLs
|
|
199
356
|
cd /home/ubuntu/build
|
|
@@ -233,48 +390,105 @@ if [ $BUILD_EXIT_CODE -eq 0 ]; then
|
|
|
233
390
|
mv "$AAB_FILE" "\${FINAL_BASE_NAME}.aab"
|
|
234
391
|
curl -X PUT -T "\${FINAL_BASE_NAME}.aab" "$PRESIGNED_ARTIFACT_AAB_UPLOAD" --silent
|
|
235
392
|
fi
|
|
393
|
+
|
|
394
|
+
# --- Sentry Source Map Upload (runs after Gradle, not via Gradle plugin to avoid hangs) ---
|
|
395
|
+
if [ ! -z "$SENTRY_AUTH_TOKEN" ] && [ ! -z "$SENTRY_ORG" ] && [ ! -z "$SENTRY_PROJECT" ]; then
|
|
396
|
+
step_marker sentry
|
|
397
|
+
BUNDLE_FILE="$(find /home/ubuntu/build/android/app/build/generated/assets -name 'index.android.bundle' 2>/dev/null | head -n 1)"
|
|
398
|
+
SOURCEMAP_FILE="$(find /home/ubuntu/build/android/app/build/generated/sourcemaps -name 'index.android.bundle.map' 2>/dev/null | head -n 1)"
|
|
399
|
+
|
|
400
|
+
if [ ! -z "$BUNDLE_FILE" ] && [ ! -z "$SOURCEMAP_FILE" ]; then
|
|
401
|
+
# Derive release name from app.json / package.json
|
|
402
|
+
APP_VERSION=$(node -p "try{const a=require('/home/ubuntu/build/app.json');a.expo?.version||a.version||'1.0.0'}catch(e){require('/home/ubuntu/build/package.json').version||'1.0.0'}" 2>/dev/null || echo "1.0.0")
|
|
403
|
+
APP_PACKAGE=$(node -p "try{const a=require('/home/ubuntu/build/app.json');a.expo?.android?.package||a.expo?.bundleIdentifier||''}catch(e){''}" 2>/dev/null || echo "")
|
|
404
|
+
BUILD_NUMBER=$(node -p "try{const a=require('/home/ubuntu/build/app.json');a.expo?.android?.versionCode||1}catch(e){1}" 2>/dev/null || echo "1")
|
|
405
|
+
|
|
406
|
+
if [ ! -z "$APP_PACKAGE" ]; then
|
|
407
|
+
SENTRY_RELEASE="\${APP_PACKAGE}@\${APP_VERSION}+\${BUILD_NUMBER}"
|
|
408
|
+
else
|
|
409
|
+
SENTRY_RELEASE="\${APP_VERSION}+\${BUILD_NUMBER}"
|
|
410
|
+
fi
|
|
411
|
+
SENTRY_DIST="\${BUILD_NUMBER}"
|
|
412
|
+
|
|
413
|
+
echo "[SENTRY] Uploading source maps for release: $SENTRY_RELEASE dist: $SENTRY_DIST"
|
|
414
|
+
SENTRY_CLI="/home/ubuntu/build/node_modules/@sentry/cli/bin/sentry-cli"
|
|
415
|
+
if [ ! -f "$SENTRY_CLI" ]; then
|
|
416
|
+
SENTRY_CLI="$(which sentry-cli 2>/dev/null || echo '')"
|
|
417
|
+
fi
|
|
418
|
+
|
|
419
|
+
if [ ! -z "$SENTRY_CLI" ]; then
|
|
420
|
+
"$SENTRY_CLI" releases --org "$SENTRY_ORG" --project "$SENTRY_PROJECT" files "$SENTRY_RELEASE" upload-sourcemaps --dist "$SENTRY_DIST" --rewrite "$BUNDLE_FILE" "$SOURCEMAP_FILE" || echo "[SENTRY] Upload failed \u2014 continuing build."
|
|
421
|
+
echo "[SENTRY] Source map upload complete."
|
|
422
|
+
else
|
|
423
|
+
echo "[SENTRY] sentry-cli not found \u2014 skipping source map upload."
|
|
424
|
+
fi
|
|
425
|
+
else
|
|
426
|
+
echo "[SENTRY] Bundle/sourcemap not found \u2014 skipping upload."
|
|
427
|
+
fi
|
|
428
|
+
else
|
|
429
|
+
echo "[SENTRY] SENTRY_AUTH_TOKEN / SENTRY_ORG / SENTRY_PROJECT not set \u2014 skipping upload."
|
|
430
|
+
fi
|
|
236
431
|
else
|
|
237
432
|
echo "\\n[SYSTEM] Gradle build failed with exit code $BUILD_EXIT_CODE. Skipping artifact upload."
|
|
433
|
+
upload_logs
|
|
434
|
+
report_status "failed" "Gradle build failed with exit code $BUILD_EXIT_CODE"
|
|
435
|
+
# Done marker
|
|
436
|
+
touch done
|
|
437
|
+
if [ ! -z "$PRESIGNED_DONE_MARKER" ]; then
|
|
438
|
+
curl -X PUT -T done "$PRESIGNED_DONE_MARKER" --silent
|
|
439
|
+
fi
|
|
440
|
+
sleep 5
|
|
441
|
+
sudo shutdown -h now
|
|
442
|
+
exit $BUILD_EXIT_CODE
|
|
238
443
|
fi
|
|
239
444
|
|
|
240
445
|
# Cleanup keystore from disk
|
|
241
446
|
rm -f /tmp/mach-release.keystore
|
|
242
447
|
|
|
243
|
-
# Save
|
|
244
|
-
|
|
245
|
-
find . -name "package.json" -o -name "package-lock.json" -o -name "build.gradle" -o -name "yarn.lock" | xargs cat | md5sum > "$SIGNATURE_FILE"
|
|
448
|
+
# Save all caches in parallel \u2014 don't block each other or the success report
|
|
449
|
+
cache_pids=()
|
|
246
450
|
|
|
247
|
-
if [
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
tar -czf /tmp/gradle-cache.tar.gz -C /root/.gradle caches wrapper last_signature
|
|
251
|
-
curl -X PUT -T /tmp/gradle-cache.tar.gz "$PRESIGNED_CACHE_GRADLE_UPLOAD" --silent
|
|
252
|
-
fi
|
|
253
|
-
if [ -d "/root/.npm" ] && [ ! -z "$PRESIGNED_CACHE_NPM_UPLOAD" ]; then
|
|
254
|
-
tar -czf /tmp/npm-cache.tar.gz -C /root .npm
|
|
255
|
-
curl -X PUT -T /tmp/npm-cache.tar.gz "$PRESIGNED_CACHE_NPM_UPLOAD" --silent
|
|
256
|
-
fi
|
|
451
|
+
if [ -d "/root/.gradle" ] && [ ! -z "$PRESIGNED_CACHE_GRADLE_UPLOAD" ]; then
|
|
452
|
+
(tar $TAR_COMPRESS -cf /tmp/gradle-cache.tar.gz -C /root/.gradle caches wrapper && curl -X PUT -T /tmp/gradle-cache.tar.gz "$PRESIGNED_CACHE_GRADLE_UPLOAD" --silent && rm -f /tmp/gradle-cache.tar.gz && echo "Gradle cache saved.") &
|
|
453
|
+
cache_pids+=($!)
|
|
257
454
|
fi
|
|
258
455
|
|
|
259
|
-
|
|
260
|
-
|
|
456
|
+
if [ -d "/root/.npm" ] && [ ! -z "$PRESIGNED_CACHE_NPM_UPLOAD" ]; then
|
|
457
|
+
(tar $TAR_COMPRESS -cf /tmp/npm-cache.tar.gz -C /root .npm && curl -X PUT -T /tmp/npm-cache.tar.gz "$PRESIGNED_CACHE_NPM_UPLOAD" --silent && rm -f /tmp/npm-cache.tar.gz && echo "npm cache saved.") &
|
|
458
|
+
cache_pids+=($!)
|
|
459
|
+
fi
|
|
261
460
|
|
|
262
|
-
|
|
461
|
+
if [ -d "/home/ubuntu/build/node_modules" ] && [ ! -z "$PRESIGNED_CACHE_NODE_MODULES_UPLOAD" ]; then
|
|
462
|
+
(tar $TAR_COMPRESS -cf /tmp/node-modules-cache.tar.gz -C /home/ubuntu/build node_modules && curl -X PUT -T /tmp/node-modules-cache.tar.gz "$PRESIGNED_CACHE_NODE_MODULES_UPLOAD" --silent && rm -f /tmp/node-modules-cache.tar.gz && echo "node_modules cache saved.") &
|
|
463
|
+
cache_pids+=($!)
|
|
464
|
+
fi
|
|
465
|
+
|
|
466
|
+
if [ -d "/home/ubuntu/build/android" ] && [ ! -z "$PRESIGNED_CACHE_ANDROID_UPLOAD" ]; then
|
|
467
|
+
(tar $TAR_COMPRESS -cf /tmp/android-cache.tar.gz -C /home/ubuntu/build 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.") &
|
|
468
|
+
cache_pids+=($!)
|
|
469
|
+
fi
|
|
470
|
+
|
|
471
|
+
# Report success immediately \u2014 don't make the user wait for cache uploads
|
|
472
|
+
upload_logs
|
|
473
|
+
report_status "success"
|
|
263
474
|
touch done
|
|
264
475
|
if [ ! -z "$PRESIGNED_DONE_MARKER" ]; then
|
|
265
476
|
curl -X PUT -T done "$PRESIGNED_DONE_MARKER" --silent
|
|
266
477
|
fi
|
|
267
478
|
touch /opt/mach-prewarmed
|
|
268
479
|
|
|
480
|
+
# Wait for background cache saves to finish before shutdown
|
|
481
|
+
for pid in "\${cache_pids[@]}"; do wait "$pid" || true; done
|
|
482
|
+
|
|
269
483
|
echo "Build orchestrator finished. Auto-terminating instance in 5 seconds..."
|
|
270
484
|
sleep 5
|
|
271
485
|
sudo shutdown -h now
|
|
272
|
-
`;var
|
|
273
|
-
`):"",
|
|
486
|
+
`;var bi=async(e,n,t={},i,o)=>{let r=Qn(),c=e.buildProfile||"production",a=c==="production",s=e.apk===!0,d=a?"bundleRelease":"assembleRelease",l=e.buildCommand||(s?"assembleRelease":d),u=e.nodeVersion?[`echo "[NODE] Switching to Node ${e.nodeVersion}..."`,`CURRENT_MAJOR=$(node -e "process.stdout.write(process.version.split('.')[0].replace('v',''))" 2>/dev/null || echo "0")`,`if [ "$CURRENT_MAJOR" != "${e.nodeVersion}" ]; then`,` curl -fsSL https://deb.nodesource.com/setup_${e.nodeVersion}.x | bash - 2>&1`," apt-get install -y nodejs 2>&1",' echo "[NODE] Installed Node $(node -v)"',"else",' echo "[NODE] Already on Node $(node -v) \u2014 no switch needed"',"fi"].join(`
|
|
487
|
+
`):"",p;if(o){let m=Ii.isAbsolute(o)?o:Ii.resolve(process.cwd(),o);Ai.existsSync(m)?(p=Ai.readFileSync(m,"utf-8"),yt.info(Ei.magenta(`\u2713 Loaded preBuild hook: ${o}`))):yt.warn(`preBuild script not found at ${m} \u2014 skipping`)}let g=Si.replace(/\{\{BUILD_ID\}\}/g,n).replace(/\{\{BUILD_COMMAND\}\}/g,l).replace("{{NODE_VERSION_SETUP}}",u).replace("{{ENV_VARS}}",`
|
|
274
488
|
export MACH_APP_NAME="${e.appName||"App"}"
|
|
275
|
-
export MACH_BUILD_PROFILE="${
|
|
489
|
+
export MACH_BUILD_PROFILE="${c}"
|
|
276
490
|
{{ENV_VARS}}
|
|
277
|
-
`);if(e.dryRun){
|
|
491
|
+
`);if(e.dryRun){yt.info("User Data Script (dry run):"),console.log(g);return}r.start("Requesting cloud build instance...");try{let m=await D.post("/builds/launch-android",{projectId:i,buildId:n,platform:e.platform,buildProfile:e.buildProfile,buildCommand:l,instanceType:e.instanceType,ami:e.ami,keepInstance:e.keepInstance,region:e.region,subnet:e.subnet,securityGroup:e.securityGroup,projectSecrets:t,dryRun:e.dryRun,userDataScript:g,preBuildScriptContent:p});if(m.data.status!=="success")throw new Error(m.data.message||"Failed to launch build instance");let E=m.data.instanceId;return r.stop("Build Started"),yt.success(Ei.green(`Build initiated on cloud instance (${E}).`)),{instanceId:E}}catch(m){r.stop("Android Build Failed");let E=m.response?.data?.message||m.message;throw new Error(`Failed to launch Android build: ${E}`)}};import{spinner as eo,log as Be}from"@clack/prompts";import Ne from"chalk";import to from"fs";import{execSync as Qe}from"child_process";var _i=`#!/bin/bash
|
|
278
492
|
# --- Mach Cloud Build Script (iOS) ---
|
|
279
493
|
# All S3 operations use presigned URLs via curl \u2014 zero AWS credentials on Mac.
|
|
280
494
|
|
|
@@ -712,111 +926,112 @@ touch done
|
|
|
712
926
|
if [ ! -z "$PRESIGNED_DONE_MARKER" ]; then
|
|
713
927
|
curl -X PUT -T done "$PRESIGNED_DONE_MARKER" --silent
|
|
714
928
|
fi
|
|
715
|
-
`;var
|
|
716
|
-
`:I.type==="mobileprovision"&&(
|
|
717
|
-
`);o.message("Generating macOS build script...");let
|
|
718
|
-
`:"";if(t)for(let[I,
|
|
719
|
-
`}let x=[
|
|
720
|
-
`),
|
|
721
|
-
`):"",
|
|
722
|
-
${
|
|
723
|
-
${
|
|
724
|
-
${
|
|
725
|
-
`)),o(
|
|
726
|
-
`)),o(
|
|
727
|
-
`)));let p=e;if(["node","npm","npx","pod"].includes(e)){let m
|
|
728
|
-
`)))}let
|
|
729
|
-
\u{1F6D1} Build cancelled from dashboard. Terminating...`)),
|
|
730
|
-
`)},
|
|
731
|
-
`))}catch(
|
|
732
|
-
`)}if(await
|
|
733
|
-
`),
|
|
734
|
-
`),
|
|
735
|
-
`),
|
|
929
|
+
`;var $i=async(e,n,t={},i)=>{let o=eo();e.sshHost||(e.sshHost="localhost",Be.message(Ne.yellow("No SSH host provided, defaulting to localhost."))),o.start(`Connecting to remote Mac at ${Ne.cyan(e.sshHost)}...`);let r=e.sshUser||process.env.USER||"ubuntu",c=e.sshKey,a=`${r}@${e.sshHost}`,s=`ssh ${c?`-i ${c}`:""} -o StrictHostKeyChecking=no ${a}`,d=`scp ${c?`-i ${c}`:""} -o StrictHostKeyChecking=no`;try{let l=r==="ubuntu"?"/home/ubuntu":`/Users/${r}`,u=(t.PROJECT_ID||"default_project").replace(/[^a-zA-Z0-9-_]/g,"_"),p=`${l}/${f.remoteWorkspacesDir}/${u}`;o.message(`Preparing stable workspace: ${p}...`),Qe(`${s} "mkdir -p ${p}"`,{stdio:"inherit"}),o.message("Transferring source code...");let g=`/tmp/${f.nameLower}-source-${n}.zip`;Qe(`${d} ${g} ${a}:${p}/source.zip`,{stdio:"inherit"});let m=e.iosApiKeyPath?`${p}/api_key.p8`:"",E="";e.iosApiKeyPath&&(o.message("Uploading App Store Connect API key..."),Qe(`${d} ${e.iosApiKeyPath} ${a}:${m}`),e.iosApiKeyId&&e.iosApiKeyIssuer&&(E=`-authenticationKeyID ${e.iosApiKeyId} -authenticationKeyIssuerID ${e.iosApiKeyIssuer} -authenticationKeyPath ${m}`));let R={};if(i)try{let I=await D.post(`/builds/${i}/${n}/build-urls`,{platform:"ios"});I.data.status==="success"&&(R=I.data.urls)}catch(I){Be.warn(Ne.yellow(`Could not fetch build URLs: ${I.message}`))}let O="";if(R.credentials&&R.credentials.length>0)for(let I of R.credentials)I.type==="p12"?O+=`curl -sf -o "$CERT_DIR/${I.name}" "${I.downloadUrl}" || true
|
|
930
|
+
`:I.type==="mobileprovision"&&(O+=`curl -sf -o "$PROV_TEMP/${I.name}" "${I.downloadUrl}" || true
|
|
931
|
+
`);o.message("Generating macOS build script...");let k=process.env.CODEARTIFACT_AUTH_TOKEN?`export CODEARTIFACT_AUTH_TOKEN="${process.env.CODEARTIFACT_AUTH_TOKEN}"
|
|
932
|
+
`:"";if(t)for(let[I,_]of Object.entries(t)){let C=_.replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");k+=`export ${I}="${C}"
|
|
933
|
+
`}let x=[k,R.logUpload?`export PRESIGNED_LOG_UPLOAD="${R.logUpload}"`:"",R.doneMarker?`export PRESIGNED_DONE_MARKER="${R.doneMarker}"`:"",R.cacheDerivedDataDownload?`export PRESIGNED_CACHE_DD_DOWNLOAD="${R.cacheDerivedDataDownload}"`:"",R.cacheDerivedDataUpload?`export PRESIGNED_CACHE_DD_UPLOAD="${R.cacheDerivedDataUpload}"`:"",R.cacheNodeModulesDownload?`export PRESIGNED_CACHE_NODE_DOWNLOAD="${R.cacheNodeModulesDownload}"`:"",R.cacheNodeModulesUpload?`export PRESIGNED_CACHE_NODE_UPLOAD="${R.cacheNodeModulesUpload}"`:"",R.cachePodsDownload?`export PRESIGNED_CACHE_PODS_DOWNLOAD="${R.cachePodsDownload}"`:"",R.cachePodsUpload?`export PRESIGNED_CACHE_PODS_UPLOAD="${R.cachePodsUpload}"`:"",R.artifactIpaUpload?`export PRESIGNED_ARTIFACT_IPA_UPLOAD="${R.artifactIpaUpload}"`:"",R.artifactAppZipUpload?`export PRESIGNED_ARTIFACT_APP_ZIP_UPLOAD="${R.artifactAppZipUpload}"`:"",`export BUILD_ID="${n}"`,`export ${f.envPrefix}PROJECT_ID="${u}"`,t.MATCH_ENCRYPTION_PASSPHRASE?`export MATCH_PASSWORD="${t.MATCH_ENCRYPTION_PASSPHRASE}"`:"",t.APPLE_TEAM_ID?`export FASTLANE_TEAM_ID="${t.APPLE_TEAM_ID}"`:"",`export MATCH_KEYCHAIN_NAME="${f.credentialsKeychain}"`,`export MATCH_KEYCHAIN_PASSWORD="${f.keychainPassword}"`].filter(Boolean).join(`
|
|
934
|
+
`),b=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(`
|
|
935
|
+
`):"",M=_i,h={"{{REMOTE_DIR}}":p,"{{ENV_VARS}}":x,"{{CREDENTIAL_DOWNLOADS}}":O,"{{IOS_SCHEME}}":e.iosScheme||"","{{IOS_CONFIG}}":e.iosConfiguration||"Release","{{TEAM_ID}}":e.iosTeamId||"","{{AUTH_PARAMS}}":E,"{{IS_SIMULATOR}}":e.simulator?"true":"false","{{BUILD_ID}}":n,"{{EXPORT_METHOD}}":e.iosExportMethod||"ad-hoc","{{NODE_VERSION_SETUP}}":b};Object.entries(h).forEach(([I,_])=>{M=M.split(I).join(_)});let P=`/tmp/${f.nameLower}-mac-build-${n}.sh`;if(to.writeFileSync(P,M),Qe(`${d} ${P} ${a}:${p}/build.sh`),o.stop("Remote script uploaded."),Be.info(Ne.cyan("Executing remote build. This might take a while...")),Qe(`${s} "bash ${p}/build.sh"`,{stdio:"inherit"}),o.stop("Remote build finished!"),i){o.start("Fetching artifact links...");try{let _=(await D.get(`/builds/${i}/${n}/artifacts`)).data.artifacts||[],C=e.simulator===!0;if(_.length===0&&!C)throw o.stop("Build Failed!"),new Error("Build completed but no artifacts were generated. Check build logs for errors.");if(o.stop("Build Successful!"),_.length>0){Be.success("Build Artifacts Ready:");for(let H of _)console.log(`
|
|
936
|
+
${Ne.yellow(H.name)}:
|
|
937
|
+
${Ne.cyan(H.downloadUrl)}`);console.log(`
|
|
938
|
+
${Ne.dim("Note: Links are valid for 7 days.")}`)}else C&&Be.warn("Simulator build completed. No artifacts uploaded.")}catch(I){o.stop("Could not fetch artifacts"),Be.warn(Ne.yellow(`Artifact listing failed: ${I.message}`))}}}catch(l){throw o.stop("iOS Build Failed"),l}};import io from"crypto";import et from"axios";async function Pi(e,n){try{let t=await no(n),o=(await et.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${e}/edits`,{},{headers:{Authorization:`Bearer ${t}`,Connection:"close"}})).data.id,r=0,a=(await et.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${e}/edits/${o}/tracks`,{headers:{Authorization:`Bearer ${t}`,Connection:"close"}})).data.tracks||[];for(let s of a)if(s.releases){for(let d of s.releases)if(d.versionCodes)for(let l of d.versionCodes){let u=parseInt(l,10);u>r&&(r=u)}}try{let d=(await et.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${e}/edits/${o}/bundles`,{headers:{Authorization:`Bearer ${t}`,Connection:"close"}})).data.bundles||[];for(let l of d)l.versionCode&&l.versionCode>r&&(r=l.versionCode)}catch{}try{let d=(await et.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${e}/edits/${o}/apks`,{headers:{Authorization:`Bearer ${t}`,Connection:"close"}})).data.apks||[];for(let l of d)l.versionCode&&l.versionCode>r&&(r=l.versionCode)}catch{}return r}catch(t){let i=t.response?.data?.error?.message||t.message;throw new Error(`Google Play API Error: ${i}`)}}async function no(e){let n=Math.floor(Date.now()/1e3),t=n+3600,i={alg:"RS256",typ:"JWT"},o={iss:e.client_email,sub:e.client_email,aud:"https://oauth2.googleapis.com/token",iat:n,exp:t,scope:"https://www.googleapis.com/auth/androidpublisher"},r=Buffer.from(JSON.stringify(i)).toString("base64url"),c=Buffer.from(JSON.stringify(o)).toString("base64url"),a=`${r}.${c}`,s=io.createSign("RSA-SHA256");s.update(a);let d=s.sign(e.private_key,"base64url"),l=`${a}.${d}`;return(await et.post("https://oauth2.googleapis.com/token",{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:l},{headers:{Connection:"close"}})).data.access_token}import{spinner as St,log as A,isCancel as Et,confirm as oo,select as Gt}from"@clack/prompts";import y from"chalk";import S from"fs";import $ from"path";import{execSync as G,spawn as Ri}from"child_process";import Ie from"os";import ro from"crypto";var wi=(e,n)=>n.filter(t=>S.existsSync($.join(e,t))).reduce((t,i)=>t.update(S.readFileSync($.join(e,i))),ro.createHash("sha256")).digest("hex").slice(0,16),so=e=>wi(e,["package.json","yarn.lock","package-lock.json","bun.lockb"]),ao=e=>wi(e,["Podfile","Podfile.lock"]),co=e=>{let n=$.join(e,"fingerprint.json");try{return JSON.parse(S.readFileSync(n,"utf-8"))}catch{return{}}},Di=(e,n)=>{S.mkdirSync(e,{recursive:!0}),S.writeFileSync($.join(e,"fingerprint.json"),JSON.stringify(n,null,2))},lo=7200*1e3,uo=(e,n)=>{S.mkdirSync(e,{recursive:!0});let t=$.join(e,"build.lock");if(S.existsSync(t))try{let i=JSON.parse(S.readFileSync(t,"utf-8")),o=Date.now()-(i.timestamp||0);if(o<lo)throw new Error(`Another build is already running for this project (build ${i.buildId}, started ${Math.round(o/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(t,JSON.stringify({buildId:n,pid:process.pid,timestamp:Date.now()}))},po=(e,n)=>{let t=$.join(e,"build.lock");try{S.existsSync(t)&&JSON.parse(S.readFileSync(t,"utf-8")).buildId===n&&S.unlinkSync(t)}catch{}},De=(e,n,t=process.cwd(),i={},o,r)=>new Promise((c,a)=>{let s=["/opt/homebrew/bin","/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin",$.join(Ie.homedir(),".npm-global/bin")],l=[...(process.env.PATH||"").split(":"),...s].filter((m,E,R)=>m&&R.indexOf(m)===E).join(":");process.env[`${f.envPrefix}DEBUG`]&&console.log(y.magenta(`[${f.nameUpper}_DEBUG] Execution PATH: ${l}`));let u={...process.env,...i,PATH:l,LANG:"en_US.UTF-8",LC_ALL:"en_US.UTF-8"};o&&process.env[`${f.envPrefix}DEBUG`]&&(o(y.magenta(`[ENVIRONMENT] node: ${process.execPath}
|
|
939
|
+
`)),o(y.magenta(`[ENVIRONMENT] PATH: ${l}
|
|
940
|
+
`)),o(y.magenta(`[ENVIRONMENT] command: ${e} ${n.join(" ")}
|
|
941
|
+
`)));let p=e;if(["node","npm","npx","pod"].includes(e)){let m=$.dirname(process.execPath),E=$.join(m,e);S.existsSync(E)&&(p=E,o&&o(y.dim(`[EXEC] Using absolute path: ${p}
|
|
942
|
+
`)))}let g=Ri(p,n,{stdio:"pipe",cwd:t,shell:!0,env:u,detached:process.platform!=="win32"});if(r){if(r.aborted){if(g.pid)try{process.kill(-g.pid,"SIGTERM")}catch{g.kill()}return a(new Error("Command aborted"))}r.addEventListener("abort",()=>{if(g.pid)try{process.kill(-g.pid,"SIGTERM")}catch{g.kill()}a(new Error("Command aborted"))})}g.stdout.on("data",m=>{let E=m.toString();process.stdout.write(E),o&&o(E)}),g.stderr.on("data",m=>{let E=m.toString();process.stderr.write(E),o&&o(E)}),g.on("close",m=>{m===0?c(m):a(new Error(`Command failed with code ${m}: ${e} ${n.join(" ")}`))}),g.on("error",m=>a(m))}),fo=e=>{let n=Math.floor(e/1e3%60),t=Math.floor(e/(1e3*60)%60),i=Math.floor(e/(1e3*60*60)%24),o=[];return i>0&&o.push(`${i}h`),t>0&&o.push(`${t}m`),(n>0||o.length===0)&&o.push(`${n}s`),o.join(" ")},Ge=(e,n)=>{let t=[];try{if(!S.existsSync(e))return t;let i=S.readdirSync(e);for(let o of i){let r=$.join(e,o);try{let c=S.statSync(r);if(n.some(s=>o.endsWith(s))){t.push($.resolve(r));continue}c.isDirectory()&&(t=t.concat(Ge(r,n)))}catch{}}}catch{}return t},jt=async(e,n,t={},i,o={})=>{let r=St(),c=Date.now(),a=e.platform,s=e.buildProfile||"production",d=async(h,P={})=>{if(i)for(let I=1;I<=3;I++)try{await D.patch(`/builds/${i}/${n}`,{status:h,...P});return}catch(_){let C=_?.response?.data?.message||_?.message||String(_);console.error(`[reportStatus] attempt ${I}/3 failed (status=${h}): ${C}`),I<3&&await new Promise(H=>setTimeout(H,2e3))}},l=new AbortController,{signal:u}=l,p=null;i&&(p=setInterval(async()=>{try{(await D.get(`/builds/${i}/${n}`)).data.status==="cancelled"&&(A.warn(y.yellow(`
|
|
943
|
+
\u{1F6D1} Build cancelled from dashboard. Terminating...`)),l.abort(),p&&clearInterval(p))}catch{}},5e3));let g=$.join(process.cwd(),".mach-cache"),m="setup",E="",R=null,O=async()=>{if(!E||!i)return;let h=E;E="";try{let P=h;Object.values(t).forEach(I=>{if(I&&I.length>5){let _=I.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");P=P.replace(new RegExp(_,"g"),"[SECRET]")}}),await D.post(`/builds/${i}/${n}/logs`,{log:P,step:m})}catch{}},k=async()=>{R&&(clearTimeout(R),R=null),await O(),po(g,n),p&&(clearInterval(p),p=null);try{let h=$.join(Ie.tmpdir(),`${f.buildPrefix}-${n}.keychain-db`);S.existsSync(h)&&(G(`security delete-keychain "${h}"`,{stdio:"ignore"}),A.info(y.dim("\u{1F511} Build keychain deleted.")))}catch{}try{let h=$.join(Ie.homedir(),"Library/MobileDevice/Provisioning Profiles");if(S.existsSync(h)){let P=S.readdirSync(h).filter(I=>I.includes(n)||I.startsWith(`${f.nameLower}-temp-${n}`));for(let I of P)S.unlinkSync($.join(h,I))}}catch{}},x=async h=>{i&&(E+=h,E.length>=8192?(R&&(clearTimeout(R),R=null),await O()):R||(R=setTimeout(()=>{R=null,O()},2e3)))},b=async h=>{m=h,await x(`[STEP_START:${h}] ${Math.floor(Date.now()/1e3)}
|
|
944
|
+
`)},M=async(h,P,I,_)=>await De(h,P,I,_,C=>{x(C)},u);A.info(y.blue(`\u{1F680} Starting local build for ${a} (${s})...`));try{uo(g,n)}catch(h){throw await d("failed",{error:h.message}),h}if(await d("building"),await b("setup"),i&&a==="ios"&&!e.simulator)try{let h=parseInt(t.BUILD_NUMBER||"0",10),P=await D.post(`/projects/${i}/next-build-number`,{platform:"ios",startFrom:h});P.data.status==="success"&&(t.BUILD_NUMBER=String(P.data.buildNumber),A.info(y.dim(`Auto build number: ${t.BUILD_NUMBER}`)),await x(`[BUILD_NUMBER] ${t.BUILD_NUMBER}
|
|
945
|
+
`))}catch(h){A.warn(y.yellow(`Could not fetch auto build number: ${h.message}`))}await b("lock"),e.developmentClient?(A.info(y.blue("\u2139\uFE0F Configuring build to INCLUDE expo-dev-client (Development Client mode)...")),delete process.env.EXPO_NO_DEV_CLIENT,delete process.env.EXPO_AUTOLINKING_EXCLUDE):(A.info(y.blue("\u2139\uFE0F Configuring build to EXCLUDE expo-dev-client (Production/Staging mode)...")),process.env.EXPO_NO_DEV_CLIENT="1",process.env.EXPO_AUTOLINKING_EXCLUDE="expo-dev-client");try{await b("clone"),A.info(y.dim("Preparing source...")),await b("read_config");let h=$.join(process.cwd(),f.configFileName);if(S.existsSync(h)){let U=JSON.parse(S.readFileSync(h,"utf-8"))?.build?.[s]||{};await x(`[CONFIG] Profile: ${s}, distribution: ${U.distribution||"not set"}, simulator: ${U.simulator||!1}
|
|
946
|
+
`)}if(await b("read_package"),e.nodeVersion){let L=process.env.NVM_DIR||$.join(Ie.homedir(),".nvm"),U=$.join(L,"versions","node"),q;if(S.existsSync(U)){let T=S.readdirSync(U).sort().reverse(),ne=e.nodeVersion.startsWith("v")?e.nodeVersion:`v${e.nodeVersion}`,V=T.find(J=>J===ne||J.startsWith(ne+".")||J.startsWith(`v${e.nodeVersion}.`));V&&(q=$.join(U,V,"bin"))}if(q&&S.existsSync(q)){let T=process.env.PATH||"";process.env.PATH=`${q}:${T}`,await x(`[NODE] Switched to Node ${e.nodeVersion} \u2014 using ${q}
|
|
947
|
+
`),A.info(y.green(`\u2713 Node switched to ${e.nodeVersion} (${q})`))}else await x(`[NODE] Warning: Node ${e.nodeVersion} not found in nvm. Run: nvm install ${e.nodeVersion} on the build machine.
|
|
948
|
+
`),A.warn(y.yellow(`Node ${e.nodeVersion} not found in nvm \u2014 using system default`))}await b("deps"),r.start("Checking dependencies...");let P=co(g),I=so(process.cwd()),_=S.existsSync("node_modules"),C=S.existsSync("yarn.lock"),H=S.existsSync("bun.lockb");_&&P.node&&P.node!==I&&(r.stop("Dependency fingerprint changed \u2014 clearing node_modules for clean install..."),await x(`[CACHE] package.json/lockfile changed \u2014 wiping node_modules
|
|
949
|
+
`),S.rmSync($.join(process.cwd(),"node_modules"),{recursive:!0,force:!0}),_=!1);let B="npm",N=["install","--prefer-offline"];C?(B="yarn",N=["install","--prefer-offline"]):H&&(B="bun",N=["install"]),_?r.stop("Cached node_modules found. Syncing dependencies..."):r.stop("No cached dependencies. Running fresh install..."),e.preBuild&&(A.info(y.blue("Running pre-install hook...")),A.info(y.dim(`> ${e.preBuild}`)),await b("prebuild"),await M("bash",[e.preBuild],process.cwd(),t)),A.info(y.dim(`Running ${B} ${N.join(" ")}...`)),await M(B,N,process.cwd(),t),P.node=I,Di(g,P);let F=JSON.parse(S.readFileSync("package.json","utf-8")),Z=F.dependencies?.expo||F.devDependencies?.expo,K=e.iosBundleIdentifier||"",j=e.name||"";if(Z){r.start(`Enforcing ${f.name} configuration...`);let L=$.join(process.cwd(),"app.json"),U=null;if(S.existsSync(L)){U=S.readFileSync(L,"utf-8");let T=JSON.parse(U);T.expo=T.expo||{},j||(j=T.expo.name||""),a==="ios"&&!K&&(K=T.expo?.ios?.bundleIdentifier||""),e.name&&(T.expo.name=e.name),e.scheme&&(T.expo.scheme=e.scheme),a==="ios"&&e.iosBundleIdentifier?(T.expo.ios=T.expo.ios||{},T.expo.ios.bundleIdentifier=e.iosBundleIdentifier):a==="android"&&e.androidPackage&&(T.expo.android=T.expo.android||{},T.expo.android.package=e.androidPackage),S.writeFileSync(L,JSON.stringify(T,null,2))}let q=["exec","--","expo","prebuild","--platform",a,"--no-install"];try{if(await b("prebuild"),await M("npm",q,process.cwd(),t),a==="ios"&&S.existsSync("ios")){await b("pods"),A.info(y.blue("Running pod install..."));try{let T=$.resolve("ios"),ne=$.join(T,"Podfile");if(!S.existsSync(ne))throw new Error("ios/Podfile not found. Skipping pod install.");let V=S.readFileSync(ne,"utf-8"),J=e.iosDeploymentTarget||"13.4";if(!e.developmentClient&&(A.info(y.blue("\u2139\uFE0F Patching Podfile to EXCLUDE expo-dev-client...")),V.includes("use_expo_modules!")&&!V.includes("exclude:"))){let le=/use_expo_modules!(\s*)$/m;le.test(V)?V=V.replace(le,'use_expo_modules!(exclude: ["expo-dev-client"])$1'):V=V.replace("use_expo_modules!",'use_expo_modules!(exclude: ["expo-dev-client"])')}let se=`
|
|
736
950
|
installer.generated_projects.each do |project|
|
|
737
951
|
project.targets.each do |target|
|
|
738
952
|
target.build_configurations.each do |config|
|
|
739
|
-
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '${
|
|
953
|
+
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '${J}'
|
|
740
954
|
end
|
|
741
955
|
end
|
|
742
956
|
end
|
|
743
957
|
installer.pods_project.targets.each do |target|
|
|
744
958
|
target.build_configurations.each do |config|
|
|
745
|
-
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '${
|
|
959
|
+
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '${J}'
|
|
746
960
|
end
|
|
747
961
|
end
|
|
748
|
-
`,
|
|
749
|
-
${
|
|
962
|
+
`,Ae=/post_install\s+do\s+\|installer\|/;if(Ae.test(V))A.info(y.dim(`Injecting deployment target (${J}) into existing post_install hook...`)),V=V.replace(Ae,`post_install do |installer|
|
|
963
|
+
${se}`),S.writeFileSync(ne,V);else{A.info(y.dim(`Appending new post_install hook for deployment target (${J})...`));let le=`
|
|
750
964
|
post_install do |installer|
|
|
751
|
-
${
|
|
965
|
+
${se}
|
|
752
966
|
end
|
|
753
|
-
`;
|
|
754
|
-
`),
|
|
755
|
-
\u2713 Local build completed successfully in ${
|
|
756
|
-
\u{1F4E6} Generated Artifacts:`)),
|
|
757
|
-
\u274C Build aborted.`)),await
|
|
758
|
-
\u2717 Local build failed: ${
|
|
759
|
-
`)[0]||"unknown"}`))}if(!q)throw new Error("Failed to import P12.");
|
|
760
|
-
`).map(
|
|
967
|
+
`;S.appendFileSync(ne,le)}let Je="/opt/homebrew/bin/pod",Mt=S.existsSync(Je)?Je:"pod",He=ao(T);S.existsSync($.join(T,"Pods"))&&P.pods&&P.pods!==He&&(await x(`[CACHE] Podfile/Podfile.lock changed \u2014 wiping ios/Pods
|
|
968
|
+
`),A.info(y.dim("Podfile fingerprint changed \u2014 clearing Pods for clean install...")),S.rmSync($.join(T,"Pods"),{recursive:!0,force:!0})),A.info(y.dim(`Using pod command: ${Mt} in ${T}`)),await M(Mt,["install"],T,t),P.pods=He,Di(g,P)}catch(T){let ne=T.message||"Unknown error";A.warn(y.yellow(`Native "pod" command failed: ${ne}`)),A.info(y.dim("Falling back to npm exec pod-install...")),A.info(y.magenta(`${f.nameUpper}_DEBUG: Executing pod-install override via npx --yes pod-install@latest`)),await M("npx",["--yes","pod-install@latest","ios"],process.cwd(),t)}if(S.existsSync("ios/Pods")){A.info(y.dim("Disabling signing for Pod targets to prevent conflicts..."));try{G(`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{U&&S.writeFileSync(L,U)}r.stop(`Expo prebuild complete (${f.name} config enforced).`)}let z=[];if(a==="android")await b("build"),z=await mo(e,s,t,L=>x(L),u);else if(a==="ios"){await b("signing"),A.info(y.dim("Preparing credentials..."));let L=o?.distributionType;z=await go(e,n,s,t,i,U=>x(U),u,L,U=>b(U))}e.postBuild&&(A.info(y.blue("Running post-build hook...")),A.info(y.dim(`> ${e.postBuild}`)),await M(e.postBuild,[],process.cwd(),t));let ge=fo(Date.now()-c);if(A.success(y.green(`
|
|
969
|
+
\u2713 Local build completed successfully in ${ge}`)),await d("building",{...K&&{bundleId:K},...j&&{appName:j}}),z.length>0&&(A.info(y.cyan(`
|
|
970
|
+
\u{1F4E6} Generated Artifacts:`)),z.forEach(L=>{let U=$.resolve(L);A.info(y.dim(` - ${L}`)),A.info(y.gray(` Path: ${U}`))}),e.interactive)){let L=await oo({message:"Install on connected device?"});if(!Et(L)&&L){if(a==="android"){let U=z.find(q=>q.endsWith(".apk"))||z[0];await yo(U,q=>x(q))}else if(a==="ios"){let U=z.find(T=>T.endsWith(".ipa"))||z.find(T=>T.endsWith(".app"))||z[0],q=Oe("ios");e.simulator?await So(U,q||"",T=>x(T)):await Eo(U,q||"",T=>x(T))}}}await b("upload");let ve=[];for(let L of z)try{let U=$.join(Ie.tmpdir(),`${n}-${$.basename(L)}`);S.copyFileSync(L,U),ve.push(U),A.info(y.dim(` \u{1F4CB} Preserved artifact: ${$.basename(L)}`))}catch{A.warn(y.yellow(` Failed to preserve artifact: ${$.basename(L)}`))}z=ve,A.info(y.dim("\u{1F9F9} Cleaning workspace (preserving dependency cache)..."));try{let L=process.cwd(),U=new Set(["node_modules"]),q=S.readdirSync(L),T=0;for(let ne of q)if(!U.has(ne)){if(ne==="ios"){let V=$.join(L,"ios"),J=S.readdirSync(V);for(let se of J)if(se!=="Pods")try{S.rmSync($.join(V,se),{recursive:!0,force:!0}),T++}catch{}continue}try{S.rmSync($.join(L,ne),{recursive:!0,force:!0}),T++}catch{}}A.info(y.dim(` Cleaned ${T} items. Cached: node_modules${S.existsSync($.join(L,"ios","Pods"))?", ios/Pods":""}`)),A.info(y.green("\u{1F512} Security: No source code retained on build server. Only public dependencies cached."))}catch{A.warn(y.yellow("Post-build cleanup encountered errors (non-fatal)."))}try{let U=$.join(Ie.homedir(),f.workspacesDir),q=G(`df -k "${U}" | tail -1 | awk '{print $4}'`,{encoding:"utf8"}).trim(),T=parseInt(q,10)*1024;if(T<53687091200&&S.existsSync(U)){A.info(y.dim(` \u26A0\uFE0F Low disk space (${(T/1024/1024/1024).toFixed(0)} GB free). Running cache eviction...`));let ne=$.basename(process.cwd()),V=S.readdirSync(U).filter(J=>J!==ne).map(J=>{let se=$.join(U,J);try{let Ae=S.statSync(se);return Ae.isDirectory()?{name:J,dir:se,mtime:Ae.mtimeMs}:null}catch{return null}}).filter(Boolean);V.sort((J,se)=>J.mtime-se.mtime);for(let J of V){if(T>=53687091200)break;try{S.rmSync(J.dir,{recursive:!0,force:!0}),A.info(y.dim(` \u{1F5D1}\uFE0F Evicted stale workspace: ${J.name}`));let se=G(`df -k "${U}" | tail -1 | awk '{print $4}'`,{encoding:"utf8"}).trim();if(parseInt(se,10)*1024>=53687091200)break}catch{}}}}catch{}return await k(),z}catch(h){throw await k(),h.message==="Command aborted"?(A.warn(y.yellow(`
|
|
971
|
+
\u274C Build aborted.`)),await d("failed",{error:"Aborted by user"}),h):(A.error(y.red(`
|
|
972
|
+
\u2717 Local build failed: ${h.message}`)),await d("failed",{error:h.message}),h)}},mo=async(e,n,t={},i,o)=>{let r=S.existsSync("android/gradlew")?"android/gradlew":S.existsSync("gradlew")?"./gradlew":null;if(!r)throw new Error("Could not find gradlew. Is this an Android project?");let c="assembleRelease";e.distribution==="store"?c="bundleRelease":e.distribution==="internal"&&(c="assembleRelease");let a=e.buildCommand||c;A.info(y.blue(`Running Android build: ${a}...`));let s=r.includes("android/")?"android":".",d=(r.includes("android/"),"./gradlew"),l=[a];if(t.ANDROID_VERSION_CODE){let p=$.join(s,"app/build.gradle");if(S.existsSync(p)){let g=t.ANDROID_VERSION_CODE,m=S.readFileSync(p,"utf-8");m=m.replace(/versionCode\s+\d+/,`versionCode ${g}`),S.writeFileSync(p,m),A.info(y.green(`\u2713 Applied Android versionCode ${g}`))}l.push(`-Pandroid.injected.version.code=${t.ANDROID_VERSION_CODE}`)}await De(d,l,s,t,i,o);let u=$.join(s,"app/build/outputs");return Ge(u,[".apk",".aab"])},go=async(e,n,t,i={},o,r,c,a,s)=>{if(process.platform!=="darwin")throw new Error("iOS builds can only be run on macOS.");let d=$.resolve(process.cwd(),S.existsSync("ios")?"ios":"."),l=S.readdirSync(d),u=l.find(k=>k.endsWith(".xcworkspace")),p=l.find(k=>k.endsWith(".xcodeproj"));if(!u&&!p)throw new Error("Could not find Xcode workspace or project in ios/ directory.");try{let k=G("xcode-select -p").toString().trim();A.info(y.dim(`Using Xcode at: ${k}`))}catch{A.warn(y.dim("Could not detect Xcode path."))}A.info(y.blue("Running iOS build via xcodebuild..."));let g=u?u.replace(".xcworkspace",""):p?.replace(".xcodeproj",""),m=e.iosScheme||g||e.scheme,E=e.developmentClient?"Debug":e.iosConfiguration||"Release",R=(o||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),O=$.join(Ie.homedir(),`Library/Developer/Xcode/DerivedData/${f.nameLower}`,R);if(S.mkdirSync(O,{recursive:!0}),e.simulator){A.info(y.dim(`Building for simulator (Scheme: ${m}, Config: ${E})...`)),await De("xcodebuild",[u?"-workspace":"-project",u||p,"-scheme",m,"-configuration",E,"-sdk","iphonesimulator","-derivedDataPath",O,"CODE_SIGNING_ALLOWED=NO","CODE_SIGNING_REQUIRED=NO"],d,i,r,c);let k=$.join(O,"Build/Products",`${E}-iphonesimulator`),x=Ge(k,[".app"]);if(x.length>0){let b=x[0],M=$.basename(b,".app"),h=$.join(k,`${M}_simulator.zip`);return A.info(y.dim(`Creating simulator artifact: ${h}...`)),G(`cd "${k}" && zip -r "${h}" "${$.basename(b)}"`),[h]}return[]}else{A.info(y.dim(`Archiving (Scheme: ${m}, Config: ${E})...`));let k=$.join(d,"build.xcarchive"),x=$.join(d,"export"),b=i.IOS_DIST_P12,M=i.IOS_PROVISIONING_PROFILE,h=i.IOS_P12_PASSWORD||"",P=[],I,_,C={isAppStore:!1,isDevelopment:!1};if(b&&M){A.info(y.blue("\u{1F510} CI/CD Signing: Importing certificates..."));try{let j=`${f.buildPrefix}-${n}.keychain-db`,z=$.join(Ie.tmpdir(),j),ge=f.keychainPassword;G(`security create-keychain -p "${ge}" "${z}" 2>/dev/null || true`),G(`security set-keychain-settings -t 3600 -l "${z}"`),G(`security unlock-keychain -p "${ge}" "${z}"`);let ve=$.join(Ie.tmpdir(),`cert-${n}.p12`),L=Buffer.from(b,"base64");S.writeFileSync(ve,L),A.info(y.dim(`P12 data size: ${L.length} bytes, first bytes: ${L.slice(0,4).toString("hex")}`)),(L.length<100||L[0]!==48)&&(A.warn(y.yellow("\u26A0\uFE0F P12 data looks corrupted or was not decrypted correctly.")),A.warn(y.yellow(" This usually means MACH_ENCRYPTION_KEY on the Remote API differs from when credentials were uploaded.")));let U=[h,"",f.keychainPassword],q=!1;for(let ce of U)try{G(`security import "${ve}" -k "${z}" -P "${ce}" -A -T /usr/bin/codesign -T /usr/bin/security`,{stdio:"pipe"}),q=!0,A.info(y.dim(`\u2713 P12 imported successfully with password: ${ce?"[set]":"[empty]"}`));break}catch(le){A.info(y.dim(` P12 import attempt with password ${ce?`"${ce.substring(0,3)}..."`:"[empty]"} failed: ${le.message?.split(`
|
|
973
|
+
`)[0]||"unknown"}`))}if(!q)throw new Error("Failed to import P12.");S.unlinkSync(ve),G(`security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "${ge}" "${z}"`);let T=G("security list-keychains -d user",{encoding:"utf-8"}).split(`
|
|
974
|
+
`).map(ce=>ce.trim().replace(/^"|"$/g,"")).filter(ce=>ce.length>0),ne=[z,...T].map(ce=>`"${ce}"`).join(" ");G(`security list-keychains -d user -s ${ne}`),G(`security default-keychain -s "${z}"`);let V=$.join(Ie.homedir(),"Library/MobileDevice/Provisioning Profiles");S.mkdirSync(V,{recursive:!0});let J=Buffer.from(M,"base64"),se=$.join(V,`${f.nameLower}-temp-${n}.mobileprovision`);S.writeFileSync(se,J);let Ae=J.toString("utf-8"),Je=/<key>get-task-allow<\/key>\s*<true\/>/.test(Ae);C={isAppStore:!Ae.includes("<key>ProvisionedDevices</key>")&&!Je,isDevelopment:Je};try{let le=G(`security cms -D -i "${se}"`,{encoding:"utf-8"}).match(/<key>UUID<\/key>\s*<string>([^<]+)<\/string>/);_=le?le[1]:void 0}catch{let le=Ae.match(/<key>UUID<\/key>\s*<string>([^<]+)<\/string>/);_=le?le[1]:void 0}_||(A.warn("Could not extract UUID from provisioning profile. Using fallback."),_=`${f.nameLower}-${n}`);let He=$.join(V,`${_}.mobileprovision`);S.existsSync(He)&&S.unlinkSync(He),S.renameSync(se,He);try{let le=G(`security find-identity -v -p codesigning "${z}"`,{encoding:"utf-8"}).match(/"((?:Apple|iPhone) (?:Distribution|Developer|Development)[^"]*)"/);le&&(I=le[1],A.info(y.blue(`Identity auto-detected from keychain: "${I}"`)))}catch{}I||(I=C.isDevelopment?"Apple Development":"Apple Distribution",A.info(y.blue(`Identity fallback (profile heuristic): "${I}"`))),A.info(y.dim(`Profile type: ${C.isDevelopment?"Development":C.isAppStore?"App Store":"Ad-Hoc"}`)),A.info(y.dim(`Identity Detection: get-task-allow=${C.isDevelopment}, Selected Identity="${I}"`)),P.push("CODE_SIGN_STYLE=Manual"),P.push(`CODE_SIGN_IDENTITY="${I}"`),P.push(`PROVISIONING_PROFILE_SPECIFIER=${_}`),e.iosTeamId&&P.push(`DEVELOPMENT_TEAM=${e.iosTeamId}`)}catch(j){throw A.error(`Signing setup failed: ${j.message}`),j}}else P.push("-allowProvisioningUpdates"),e.iosTeamId&&P.push(`DEVELOPMENT_TEAM=${e.iosTeamId}`);s&&await s("archive"),A.info(y.blue(`Archive detected Identity: "${I}"`)),A.info(y.blue(`Archive detected UUID: "${_}"`)),await De("xcodebuild",["archive",u?"-workspace":"-project",u||p,"-scheme",m,"-configuration",E,"-archivePath",k,"-derivedDataPath",O,...P],d,i,r,c);let H;_?(C.isAppStore?H="app-store":C.isDevelopment?H="development":H="ad-hoc",A.info(y.blue(`Export method from profile: "${H}"`))):(H=e.distribution==="store"?"app-store":e.distribution==="internal"?"ad-hoc":"development",A.warn(y.yellow(`No profile UUID detected. Export method from distribution flag: "${H}"`)));let B=e.iosExportMethod||H,N=Oe("ios"),F=$.join(d,"ExportOptions.plist"),Z=`<?xml version="1.0" encoding="UTF-8"?>
|
|
761
975
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
762
976
|
<plist version="1.0">
|
|
763
977
|
<dict>
|
|
764
978
|
<key>method</key>
|
|
765
|
-
<string>${
|
|
979
|
+
<string>${B}</string>
|
|
766
980
|
<key>destination</key>
|
|
767
981
|
<string>export</string>
|
|
768
982
|
<key>signingStyle</key>
|
|
769
|
-
<string>${
|
|
983
|
+
<string>${_?"manual":"automatic"}</string>
|
|
770
984
|
<key>thinning</key>
|
|
771
985
|
<string><none></string>
|
|
772
986
|
${e.iosTeamId?`<key>teamID</key><string>${e.iosTeamId}</string>`:""}
|
|
773
|
-
${
|
|
987
|
+
${N&&_?`
|
|
774
988
|
<key>provisioningProfiles</key>
|
|
775
989
|
<dict>
|
|
776
|
-
<key>${
|
|
777
|
-
<string>${
|
|
990
|
+
<key>${N}</key>
|
|
991
|
+
<string>${_}</string>
|
|
778
992
|
</dict>`:""}
|
|
779
993
|
</dict>
|
|
780
|
-
</plist>`;if(
|
|
781
|
-
${Z}`)),s&&await s("export"),
|
|
994
|
+
</plist>`;if(S.writeFileSync(F,Z),process.env[`${f.envPrefix}DEBUG`]&&A.info(y.magenta(`[${f.nameUpper}_DEBUG] ExportOptions.plist:
|
|
995
|
+
${Z}`)),s&&await s("export"),A.info(y.blue(`Exporting with Bundle ID: "${N}"`)),A.info(y.blue(`Exporting with Method: "${B}"`)),r){r(y.magenta(`
|
|
782
996
|
[DIAGNOSTIC] Checking available signing identities...
|
|
783
|
-
`));try{let j=
|
|
784
|
-
`))}catch(j){r(
|
|
785
|
-
`))}}await De("xcodebuild",["-exportArchive","-archivePath",
|
|
786
|
-
`)}catch{let
|
|
787
|
-
`),new Error(
|
|
788
|
-
`).slice(1).map(
|
|
789
|
-
`).filter(s=>s.trim().length>0)}catch{}if(
|
|
790
|
-
`).find(s=>s.includes("android.intent.action.MAIN")&&s.includes("android.intent.category.LAUNCHER"))?F(`adb shell monkey -p ${r} -c android.intent.category.LAUNCHER 1`,{stdio:"ignore"}):F(`adb shell monkey -p ${r} -c android.intent.category.LAUNCHER 1`,{stdio:"ignore"})}catch{E.warn("Could not auto-launch app. You may need to open it manually.")}}}catch(i){t.stop("Installation failed."),E.error(S.red(`Failed to install APK: ${i.message}`))}},fo=async(e,n,t)=>{let i=ht();try{if(!F("xcrun simctl list devices booted").toString().includes("(Booted)")){E.warn(S.yellow("No iOS Simulator is currently booted."));let r=F("xcrun simctl list devices --json").toString(),a=JSON.parse(r).devices,c=[];Object.keys(a).forEach(u=>{a[u].forEach(p=>{p.isAvailable&&c.push({...p,runtime:u})})});let s=await Ft({message:"Select a simulator to launch:",options:c.map(u=>({value:u.udid,label:`${u.name} (${u.runtime.split(".").pop()})`}))});if(yt(s))return;i.start(`Booting ${s}...`),F(`xcrun simctl boot ${s}`),F(`open -a Simulator --args -CurrentDeviceUDID ${s}`);let l=0,d=!1;for(;l<30;){try{if(F("xcrun simctl list devices booted").toString().includes(s)){d=!0;break}}catch{}await new Promise(u=>setTimeout(u,2e3)),l++}if(!d)throw i.stop("Simulator boot timed out."),new Error("Simulator boot timed out.");i.stop("Simulator booted.")}i.start("Installing on iOS Simulator..."),await De("xcrun",["simctl","install","booted",e],process.cwd(),{},t),i.stop("Installation complete."),E.info(S.blue(`\u{1F680} Launching ${n}...`)),await De("xcrun",["simctl","launch","booted",n],process.cwd(),{},t)}catch(o){i.stop("Installation failed."),E.error(S.red(`Failed to install on Simulator: ${o.message}`))}},mo=async(e,n,t)=>{let i=ht();i.start("Scanning for connected iOS devices...");try{let o=F("xcrun devicectl list devices --json-output -").toString(),a=(JSON.parse(o).result?.devices||[]).filter(s=>s.connectionProperties?.transportType==="wired"||s.connectionProperties?.transportType==="localNetwork");if(a.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 c=a[0].identifier;if(a.length>1){i.stop();let s=await Ft({message:"Select a device to install on:",options:a.map(l=>({value:l.identifier,label:`${l.deviceProperties?.name||l.name||l.model?.name} (${l.model?.name||"iPhone"}) - ${l.identifier}`}))});if(yt(s))return;c=s,i.start(`Installing on ${c}...`)}else i.message(`Installing on ${a[0].model.name}...`);await De("xcrun",["devicectl","device","install","app","--device",c,e],process.cwd(),{},t),i.stop("Installation complete."),E.info(S.blue(`\u{1F680} Launching ${n}...`)),await De("xcrun",["devicectl","device","launch","app","--device",c,n],process.cwd(),{},t)}catch(o){i.stop("Installation failed."),E.error(S.red(`Failed to install on device: ${o.message}`)),E.info(S.dim('Make sure your device is unlocked and "Developer Mode" is enabled in Settings -> Privacy & Security.'))}};import St from"fs";function Ne(e){if(e){if(!St.existsSync(e))return null;try{return JSON.parse(St.readFileSync(e,"utf-8"))}catch{return null}}if(!St.existsSync(`./${f.configFileName}`))return null;try{return JSON.parse(St.readFileSync(`./${f.configFileName}`,"utf-8"))}catch{return null}}function Ue(e,n,t=new Set){if(t.has(n))throw new Error(`Circular inheritance detected in profile: ${n}`);t.add(n);let i=e.build?.[n];if(!i)return null;let o={...i};if(i.extends){let r=Ue(e,i.extends,t);r&&(o={...r,...i,env:{...r.env,...i.env},ios:{...r.ios,...i.ios},android:{...r.android,...i.android}})}if(o.envGroups&&Array.isArray(o.envGroups)){let r={};for(let a of o.envGroups){let c=e.envGroups?.[a];c?Object.assign(r,c):log.warn(`Environment group not found: ${a}`)}o.env={...r,...o.env}}return o}var je=(e,n=`${f.envPrefix}`)=>{let t={},i=(o,r)=>{if(o)for(let a in o){let c=o[a],s=`${r}${a.toUpperCase().replace(/[^A-Z0-9]/g,"_")}`;c!==null&&typeof c=="object"&&!Array.isArray(c)?i(c,`${s}_`):t[s]=String(c)}};return i(e,n),t};var At=async e=>{e.platform!=="android"&&e.platform!=="ios"&&(w.error(`Platform ${e.platform} is not supported. Use 'android' or 'ios'.`),process.exit(1));let n=Gt(),t=e.buildId||go(),i=e.projectId,o=Date.now(),r=!!i,a=async c=>{if(i)try{await _.patch(`/builds/${i}/${t}`,{status:"failed",error:c})}catch{}};if(e.local&&e.buildId){e.quiet||n.start(`Preparing isolated workspace for build: ${e.buildId}`);try{let c=await _.get(`/builds/${i}/${e.buildId}/source-url`);if(c.data.status!=="success")throw new Error("Failed to get source download URL from API");let s=await tt.get(c.data.downloadUrl,{responseType:"stream"}),l=(i||e.projectId||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),d=we.join(ho.homedir(),f.workspacesDir,l);ce.mkdirSync(d,{recursive:!0});let u=new Set(["node_modules",`.${f.nameLower}-cache-meta`]),p=new Set(["Pods"]);if(ce.existsSync(d)){let N=ce.readdirSync(d);for(let C of N){if(u.has(C))continue;if(C==="ios"){let H=we.join(d,"ios");try{let X=ce.readdirSync(H);for(let g of X)if(!p.has(g))try{ce.rmSync(we.join(H,g),{recursive:!0,force:!0})}catch{}}catch{}continue}let x=we.join(d,C);try{ce.rmSync(x,{recursive:!0,force:!0})}catch{}}}let h=we.join(d,"source.zip"),m=s.data,y=ce.createWriteStream(h);await new Promise((N,C)=>{m.pipe(y),m.on("error",x=>C(x)),y.on("finish",()=>N())}),new vi(h).extractAllTo(d,!0);try{ce.unlinkSync(h)}catch{}process.chdir(d),w.info(v.green(`\u2713 Persistent workspace ready: ${d}`)),w.info(v.dim(` \u{1F4E6} Cached dirs preserved: node_modules=${ce.existsSync(we.join(d,"node_modules"))?"\u2705":"\u274C"}, Pods=${ce.existsSync(we.join(d,"ios","Pods"))?"\u2705":"\u274C"}`)),n.stop()}catch(c){n.stop(`Failed to prepare isolated workspace: ${c.message}`),i&&await a(`Setup Error: ${c.message}`),process.exit(1)}}try{let c=e.repo;if(!c)try{c=wi("git config --get remote.origin.url").toString().trim()}catch{w.warn("Could not detect git repository URL.")}!c&&e.dryRun,c||(c="https://github.com/placeholder/repo.git"),w.info(`Build ID: ${v.cyan(t)}`);let s={},l={},d=Ne(`./${f.configFileName}`);if(d){i=d.projectId;let g=e.buildProfile||"production",D=Ue(d,g);!D&&e.buildProfile&&(w.error(`Build profile '${g}' not found in ${f.configFileName}`),process.exit(1));let I=D||{};process.env.MACH_DEBUG&&w.info(v.dim(`Build profile: ${g} | Platform: ${e.platform} | Distribution: ${I.distribution||"store"} | Environment: ${I.environment||g}`)),I.env&&(l=I.env,w.info(v.blue(`Use Build Profile: ${g}`)));let b=e.platform,O=I[b]||{},G=["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);for(let L of G){let Z=O[L]!==void 0?O[L]:I[L];Z!==void 0&&e[L]===void 0&&(e[L]=Z)}e.branch=e.branch||"main",e.iosConfiguration=e.iosConfiguration||(e.developmentClient||e.simulator?"Debug":"Release"),e.sshUser=e.sshUser||process.env.USER||"ubuntu",e.simulator===void 0&&(e.simulator=!1),e.local===void 0&&(e.local=!1),e.verbose===void 0&&(e.verbose=!1);let M=L=>{if(!L)return L;if(L.startsWith("scripts.")){let Z=L.split(".")[1],K=d.scripts?.[Z];if(K)return K;w.warn(`Script reference not found: ${L}`)}return L};e.buildCommand=M(e.buildCommand),e.preBuild=M(e.preBuild),e.postBuild=M(e.postBuild),!e.scheme&&d.scheme&&(e.scheme=d.scheme);let T={...je(d,f.envPrefix),...je(I,`${f.envPrefix}PROFILE_`)};s={...s,...l,...T},process.env.IOS_P12_PASSWORD&&!s.IOS_P12_PASSWORD&&(s.IOS_P12_PASSWORD=process.env.IOS_P12_PASSWORD),process.env.MATCH_PASSWORD&&!s.MATCH_PASSWORD&&(s.MATCH_PASSWORD=process.env.MATCH_PASSWORD),e.platform==="ios"&&(!e.iosTeamId&&I.ios?.appleTeamId&&(e.iosTeamId=I.ios.appleTeamId),!e.iosTeamId&&d.submit?.[g]?.ios?.appleTeamId&&(e.iosTeamId=d.submit[g].ios.appleTeamId),!e.iosTeamId&&d.submit?.production?.ios?.appleTeamId&&(w.warn(v.yellow(`Check: Using 'production' Team ID for '${g}' build.`)),e.iosTeamId=d.submit.production.ios.appleTeamId),e.iosTeamId?w.info(v.magenta(`\u2713 Injected iOS Team ID from config: ${e.iosTeamId}`)):w.warn(v.yellow("\u26A0\uFE0F No iOS Team ID found. Signing might fail if not managed automatically via Expo.")))}let u="unknown";try{u=wi("git rev-parse --abbrev-ref HEAD").toString().trim()}catch{w.warn("Failed to detect git branch.")}let p="1.0.0";try{ce.existsSync("./package.json")&&(p=JSON.parse(ce.readFileSync("./package.json","utf-8")).version||"1.0.0")}catch{}let h=e.buildProfile||"production",m="Internal";e.developmentClient?m="DevelopmentClient":h.toLowerCase().includes("store")||h.toLowerCase()==="production"?m="Store":h.toLowerCase().includes("preview")||h.toLowerCase().includes("staging")?m="Staging":(h.toLowerCase().includes("development")||h.toLowerCase().includes("dev"))&&(m="Development");let y=e.platform==="ios"?"iOS":"Android",$=e.platform==="ios"&&e.simulator?" (Simulator)":"",N=`${y}${$} v${p} (${m})`;if(i){try{let g=e.buildProfile||"production";w.info(v.blue(`Fetching managed secrets for profile: ${g}...`));let D=e.environment||g,b=(await _.get(`/projects/${i}/secrets/export?env=${D}`)).data;b.status==="success"&&b.secrets&&(s={...s,...b.secrets},Object.keys(b.secrets).length>0&&w.info(v.magenta(`\u2713 Injected ${Object.keys(b.secrets).length} secrets from Dashboard.`)))}catch(g){w.warn(`Failed to load managed secrets from Dashboard: ${g.message}`)}try{w.info(v.blue("Fetching managed credentials..."));let g="development";e.distribution==="store"?g="store":e.distribution==="internal"&&(g=e.platform==="ios"?"adhoc":"internal"),m==="Staging"&&e.developmentClient&&(g="development");let D=await _.get("/credentials/resolve",{params:{projectId:i,platform:e.platform,bundleId:e.iosBundleIdentifier||e.androidPackage,distributionType:g}});if(D.data.status==="success"&&D.data.credentials){let I=D.data.credentials;w.info(v.magenta(`\u2713 Found ${I.length} relevant credentials.`));let b=I.filter(T=>{if(T.distributionType){let L=g==="internal"?"adhoc":g;return T.distributionType===L||T.distributionType===g}return!0});w.info(v.dim(` Filtered to ${b.length} credentials for distributionType: ${g}`));let O=!1,G=!1,M=!1;for(let T of b)if(T.downloadUrl)try{let L="",Z=5;for(;Z>0;)try{let K=await tt.get(T.downloadUrl,{responseType:"arraybuffer",timeout:3e4,headers:{Connection:"close"}});L=Buffer.from(K.data).toString("base64");break}catch(K){if(Z--,Z===0)throw K;w.warn(v.dim(` - Temporary network error downloading ${T.name}. Retrying... (${5-Z}/5)`)),await new Promise(j=>setTimeout(j,2e3))}if(T.type==="ios_cert"&&!O)s.IOS_DIST_P12=L,T.password?(s.IOS_P12_PASSWORD=T.password,w.info(v.dim(` - Injected ${T.name} as IOS_DIST_P12 with password from credential record`))):w.info(v.dim(` - Injected ${T.name} as IOS_DIST_P12`)),O=!0;else if(T.type==="ios_profile"&&!G)s.IOS_PROVISIONING_PROFILE=L,w.info(v.dim(` - Injected ${T.name} as IOS_PROVISIONING_PROFILE`)),G=!0;else if(T.type==="android_keystore"&&!M){s.ANDROID_KEYSTORE_BASE64=L;let K=T.password,j=T.alias||T.meta?.alias;if(K)s.ANDROID_KEY_PASSWORD=K,s.ANDROID_STORE_PASSWORD=K,w.info(v.dim(" - Injected keystore password from credential record"));else{let Ae=["ANDROID_KEY_PASSWORD",...[g==="store"?"PRODUCTION":g==="internal"?"STAGING":"DEVELOPMENT",g.toUpperCase(),"PRODUCTION","STORE","INTERNAL","STAGING","RELEASE","DEBUG"].map(k=>`KEYSTORE_PASSWORD_${k}`),"KEYSTORE_PASSWORD"].find(k=>!!s[k]);Ae&&s[Ae]&&(s.ANDROID_KEY_PASSWORD=s[Ae],s.ANDROID_STORE_PASSWORD=s[Ae])}if(j)s.ANDROID_KEY_ALIAS=j;else{let B=["ANDROID_KEY_ALIAS","KEYSTORE_ALIAS"].find(Se=>!!s[Se]);B&&(s.ANDROID_KEY_ALIAS=s[B])}w.info(v.dim(` - Injected ${T.name} as ANDROID_KEYSTORE_BASE64`)),M=!0}}catch(L){w.warn(`Failed to download credential ${T.name}: ${L.message}`)}}if(e.platform==="android"){let I=d.android?.versionCode==="auto"||d.expo?.android?.versionCode==="auto";if(e.autoVersion||I){n.start("Resolving latest versionCode from Google Play...");try{let b=(D.data.credentials||[]).find(K=>K.type==="google_service_account");if(b||(b=((await _.get(`/credentials/${i}`)).data.credentials||[]).find(j=>j.type==="google_service_account")),!b)throw new Error("Google Service Account not found. Upload it via Dashboard to use auto-versioning.");let O=await _.get(`/credentials/${b.credentialId}/download`,{params:{projectId:i}});if(O.data.status!=="success"||!O.data.downloadUrl)throw new Error("Failed to get secure download URL for service account");let M=(await tt.get(O.data.downloadUrl,{headers:{Connection:"close"}})).data,T=e.androidPackage||d.android?.package||d.expo?.android?.package||d.name,L=await Ii(T,M);if(L==null)throw new Error("Could not retrieve any version information from Google Play.");let Z=L+1;s.ANDROID_VERSION_CODE=Z.toString(),n.stop(`\u2713 Resolved versionCode: ${v.green(Z)} (Latest on Play Store: ${L})`)}catch(b){n.stop("Version resolution failed");let O=b.response?.data?.error?.message||b.message;w.warn(v.yellow(` \u26A0\uFE0F Auto-versioning failed: ${O}`)),w.warn(v.dim(' Falling back to version code from config. To fix: ensure Service Account has "View App Metadata" and "View App Information" permissions in Google Play Console.'))}}}if(e.platform==="ios"&&!e.simulator){let I=!!s.IOS_DIST_P12,b=!!s.IOS_PROVISIONING_PROFILE;if(!I||!b){let O=[...I?[]:["Distribution Certificate"],...b?[]:["Provisioning Profile"]].join(" and ");w.error(v.red(`Missing iOS credentials: ${O}`)),e.quiet&&process.exit(1);let G=e.yes||await _i({message:"Would you like to generate these credentials now?",initialValue:!0});if(G&&!Di(G))return await Je({platform:"ios",profile:h}),e.quiet||w.info(v.green("\u2713 Credentials setup complete! Restarting build phase...")),At(e);e.quiet||w.info(v.yellow(`Run \`${f.nameLower} credentials\` to set up signing credentials manually.`)),process.exit(1)}}if(e.platform==="android"&&(e.distribution==="internal"||e.distribution==="store")&&!(!!s.ANDROID_KEYSTORE_BASE64||!!s.ANDROID_KEYSTORE)){w.error(v.red("Missing Android credentials: Signing Keystore")),e.quiet&&process.exit(1);let b=e.yes||await _i({message:"Would you like to automatically create and upload an Android Keystore for this profile now?",initialValue:!0});if(b&&!Di(b))return await Je({platform:"android",profile:h}),e.quiet||w.info(v.green("\u2713 Android Keystore setup complete! Restarting build phase...")),At(e);e.quiet||w.info(v.yellow(`Run \`${f.nameLower} credentials --platform android\` to set up a signing keystore manually.`)),process.exit(1)}}catch(g){w.warn(`Failed to resolve credentials: ${g.message}`)}}let C=!!(e.local&&e.buildId),x=!!(e.local||e.sshHost),H=!x&&!C;if(C){w.info(v.magenta("\u{1F3D7}\uFE0F Runner Mode: Executing isolated build task..."));let g=await Ht({...e,interactive:!1},t,s,i,{branch:u,version:p,summary:N,buildType:m});await X(g),process.exit(0)}async function X(g){if(i&&g.length>0){let D=Gt(),I=[];e.quiet||D.start("Uploading artifacts to Dashboard...");try{for(let b of g){let O=we.basename(b),G=ce.readFileSync(b),M=we.extname(O).toLowerCase(),T="application/octet-stream",L=await _.post(`/builds/${i}/${t}/artifact-upload-url`,{fileName:O,fileType:T});if(L.data.status!=="success")throw new Error(`Failed to get upload URL for ${O}`);let Z=!1;for(let K=1;K<=3;K++)try{await tt.put(L.data.uploadUrl,G,{headers:{"Content-Type":T},maxBodyLength:1/0,maxContentLength:1/0,timeout:12e4}),Z=!0;break}catch(j){if(w.warn(v.yellow(`Artifact upload attempt ${K}/3 failed (${j.code||j.message})`)),K<3)await new Promise(B=>setTimeout(B,3e3*K));else throw j}Z&&I.push({name:O,url:L.data.downloadUrl,size:G.length,type:M.substring(1)})}e.quiet||D.stop("Artifacts uploaded.")}catch(b){e.quiet||D.stop("Failed to upload artifacts."),w.error(v.red(`Upload error: ${b.message}`));try{await _.patch(`/builds/${i}/${t}`,{status:"completed",artifacts:g.map(O=>we.basename(O)),endTime:Date.now()})}catch(O){w.warn(v.yellow(`Could not set fallback build status: ${O.message}`))}return}if(i&&I.length>0)try{w.info(v.cyan(`
|
|
791
|
-
\u{1F517} Download Links:`));for(let
|
|
792
|
-
\u2713 Build completed and reported to dashboard.`))}catch(
|
|
793
|
-
\u26A0\uFE0F Could not report to dashboard: ${
|
|
794
|
-
\u2717 Build failed: ${s.error||"Unknown error"}`)),process.exit(1);else if(o==="completed"||o==="success"){t.quiet||i.stop("Build successful!"),w.success(v.green(`
|
|
997
|
+
`));try{let j=G("security find-identity -v -p codesigning",{encoding:"utf-8"});r(y.magenta(`${j}
|
|
998
|
+
`))}catch(j){r(y.red(`[DIAGNOSTIC] Failed to list identities: ${j.message}
|
|
999
|
+
`))}}await De("xcodebuild",["-exportArchive","-archivePath",k,"-exportPath",x,"-exportOptionsPlist",F],d,i,r,c),s&&await s("validate");let K=Ge(x,[".ipa"]);for(let j of K)try{G(`unzip -t "${j}"`,{stdio:"pipe"}),r&&r(`[IPA VALID] ${$.basename(j)} \u2014 archive integrity OK
|
|
1000
|
+
`)}catch{let ge=`IPA validation failed for ${$.basename(j)}: archive may be corrupt`;throw r&&r(`[IPA CORRUPT] ${ge}
|
|
1001
|
+
`),new Error(ge)}return K}},Oe=e=>{try{let n=$.join(process.cwd(),f.configFileName);if(S.existsSync(n)){let t=JSON.parse(S.readFileSync(n,"utf-8"));if(e==="android"&&t.android?.package)return t.android.package;if(e==="ios"&&t.ios?.bundleIdentifier)return t.ios.bundleIdentifier}if(e==="android"){let t=["android/app/build.gradle","app/build.gradle","build.gradle"];for(let i of t)if(S.existsSync(i)){let r=S.readFileSync(i,"utf-8").match(/applicationId\s+['"]([^'"]+)['"]/);if(r)return r[1]}}else{let t=$.resolve(process.cwd(),S.existsSync("ios")?"ios":"."),i=Ge(t,["Info.plist"]).filter(c=>!c.includes("/Pods/")&&!c.includes("/build/")&&!c.includes("/DerivedData/"));i.sort((c,a)=>a.split("/").length-c.split("/").length);for(let c of i){let s=S.readFileSync(c,"utf-8").match(/<key>CFBundleIdentifier<\/key>\s*<string>([^<]+)<\/string>/);if(s&&!s[1].includes("$"))return s[1]}let o=Ge(t,[".xcodeproj"]);if(o.length>0){let c=$.join(o[0],"project.pbxproj");if(S.existsSync(c)){let s=S.readFileSync(c,"utf-8").match(/PRODUCT_BUNDLE_IDENTIFIER\s*=\s*"?([^";\s]+)"?;/);if(s)return s[1]}}let r=["app.json","app.config.json","app.config.js","app.config.ts"];for(let c of r)if(S.existsSync(c)){let s=S.readFileSync(c,"utf-8").match(/"bundleIdentifier":\s*"([^"]+)"/);if(s)return s[1]}}}catch{return null}return null},ho=()=>{try{return G("emulator -version",{stdio:"ignore"}),"emulator"}catch{let n=Ie.homedir(),t=[$.join(n,"Library/Android/sdk/emulator/emulator"),$.join(n,"Android/Sdk/emulator/emulator"),"/usr/local/lib/android/sdk/emulator/emulator"];for(let i of t)if(S.existsSync(i))return i}return"emulator"},yo=async(e,n)=>{let t=St();try{if(G("adb devices").toString().split(`
|
|
1002
|
+
`).slice(1).map(c=>c.trim()).filter(c=>c.length>0&&!c.startsWith("*")).map(c=>c.split(" ")[0]).length===0){A.warn(y.yellow("No Android devices or emulators found."));let c=ho(),a=[];try{a=G(`${c} -list-avds`).toString().split(`
|
|
1003
|
+
`).filter(s=>s.trim().length>0)}catch{}if(a.length>0){let s=await Gt({message:"Select an emulator to launch:",options:a.map(u=>({value:u,label:u}))});if(Et(s))return;t.start(`Launching emulator ${s}...`),Ri(c,["-avd",s],{detached:!0,stdio:"ignore"}).unref();let d=0,l=!1;for(;d<60;){try{if(G("adb shell getprop sys.boot_completed",{stdio:"pipe"}).toString().trim()==="1"){l=!0;break}}catch{}await new Promise(u=>setTimeout(u,2e3)),d++}if(!l)throw t.stop("Emulator launch timed out."),new Error("Emulator launch timed out. Please try launching it manually.");t.stop("Emulator launched.")}else throw new Error("No devices found and no emulators available to launch. (Make sure Android SDK is installed)")}t.start("Installing APK on device..."),await De("adb",["install","-r",e],process.cwd(),{},n),t.stop("Installation complete.");let r=Oe("android");if(r){A.info(y.blue(`\u{1F680} Launching ${r}...`));try{G(`adb shell dumpsys package ${r}`).toString().split(`
|
|
1004
|
+
`).find(s=>s.includes("android.intent.action.MAIN")&&s.includes("android.intent.category.LAUNCHER"))?G(`adb shell monkey -p ${r} -c android.intent.category.LAUNCHER 1`,{stdio:"ignore"}):G(`adb shell monkey -p ${r} -c android.intent.category.LAUNCHER 1`,{stdio:"ignore"})}catch{A.warn("Could not auto-launch app. You may need to open it manually.")}}}catch(i){t.stop("Installation failed."),A.error(y.red(`Failed to install APK: ${i.message}`))}},So=async(e,n,t)=>{let i=St();try{if(!G("xcrun simctl list devices booted").toString().includes("(Booted)")){A.warn(y.yellow("No iOS Simulator is currently booted."));let r=G("xcrun simctl list devices --json").toString(),c=JSON.parse(r).devices,a=[];Object.keys(c).forEach(u=>{c[u].forEach(p=>{p.isAvailable&&a.push({...p,runtime:u})})});let s=await Gt({message:"Select a simulator to launch:",options:a.map(u=>({value:u.udid,label:`${u.name} (${u.runtime.split(".").pop()})`}))});if(Et(s))return;i.start(`Booting ${s}...`),G(`xcrun simctl boot ${s}`),G(`open -a Simulator --args -CurrentDeviceUDID ${s}`);let d=0,l=!1;for(;d<30;){try{if(G("xcrun simctl list devices booted").toString().includes(s)){l=!0;break}}catch{}await new Promise(u=>setTimeout(u,2e3)),d++}if(!l)throw i.stop("Simulator boot timed out."),new Error("Simulator boot timed out.");i.stop("Simulator booted.")}i.start("Installing on iOS Simulator..."),await De("xcrun",["simctl","install","booted",e],process.cwd(),{},t),i.stop("Installation complete."),A.info(y.blue(`\u{1F680} Launching ${n}...`)),await De("xcrun",["simctl","launch","booted",n],process.cwd(),{},t)}catch(o){i.stop("Installation failed."),A.error(y.red(`Failed to install on Simulator: ${o.message}`))}},Eo=async(e,n,t)=>{let i=St();i.start("Scanning for connected iOS devices...");try{let o=G("xcrun devicectl list devices --json-output -").toString(),c=(JSON.parse(o).result?.devices||[]).filter(s=>s.connectionProperties?.transportType==="wired"||s.connectionProperties?.transportType==="localNetwork");if(c.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 a=c[0].identifier;if(c.length>1){i.stop();let s=await Gt({message:"Select a device to install on:",options:c.map(d=>({value:d.identifier,label:`${d.deviceProperties?.name||d.name||d.model?.name} (${d.model?.name||"iPhone"}) - ${d.identifier}`}))});if(Et(s))return;a=s,i.start(`Installing on ${a}...`)}else i.message(`Installing on ${c[0].model.name}...`);await De("xcrun",["devicectl","device","install","app","--device",a,e],process.cwd(),{},t),i.stop("Installation complete."),A.info(y.blue(`\u{1F680} Launching ${n}...`)),await De("xcrun",["devicectl","device","launch","app","--device",a,n],process.cwd(),{},t)}catch(o){i.stop("Installation failed."),A.error(y.red(`Failed to install on device: ${o.message}`)),A.info(y.dim('Make sure your device is unlocked and "Developer Mode" is enabled in Settings -> Privacy & Security.'))}};import At from"fs";function Te(e){if(e){if(!At.existsSync(e))return null;try{return JSON.parse(At.readFileSync(e,"utf-8"))}catch{return null}}if(!At.existsSync(`./${f.configFileName}`))return null;try{return JSON.parse(At.readFileSync(`./${f.configFileName}`,"utf-8"))}catch{return null}}function Me(e,n,t=new Set){if(t.has(n))throw new Error(`Circular inheritance detected in profile: ${n}`);t.add(n);let i=e.build?.[n];if(!i)return null;let o={...i};if(i.extends){let r=Me(e,i.extends,t);r&&(o={...r,...i,env:{...r.env,...i.env},ios:{...r.ios,...i.ios},android:{...r.android,...i.android}})}if(o.envGroups&&Array.isArray(o.envGroups)){let r={};for(let c of o.envGroups){let a=e.envGroups?.[c];a?Object.assign(r,a):log.warn(`Environment group not found: ${c}`)}o.env={...r,...o.env}}return o}var je=(e,n=`${f.envPrefix}`)=>{let t={},i=(o,r)=>{if(o)for(let c in o){let a=o[c],s=`${r}${c.toUpperCase().replace(/[^A-Z0-9]/g,"_")}`;a!==null&&typeof a=="object"&&!Array.isArray(a)?i(a,`${s}_`):t[s]=String(a)}};return i(e,n),t};var It=async e=>{e.platform!=="android"&&e.platform!=="ios"&&(w.error(`Platform ${e.platform} is not supported. Use 'android' or 'ios'.`),process.exit(1));let n=Kt(),t=e.buildId||Ao(),i=e.projectId,o=Date.now(),r=!!i,c=async a=>{if(i)try{await D.patch(`/builds/${i}/${t}`,{status:"failed",error:a})}catch{}};if(e.local&&e.buildId){e.quiet||n.start(`Preparing isolated workspace for build: ${e.buildId}`);try{let a=await D.get(`/builds/${i}/${e.buildId}/source-url`);if(a.data.status!=="success")throw new Error("Failed to get source download URL from API");let s=await tt.get(a.data.downloadUrl,{responseType:"stream"}),d=(i||e.projectId||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),l=he.join(Io.homedir(),f.workspacesDir,d);oe.mkdirSync(l,{recursive:!0});let u=new Set(["node_modules",`.${f.nameLower}-cache-meta`]),p=new Set(["Pods"]);if(oe.existsSync(l)){let O=oe.readdirSync(l);for(let k of O){if(u.has(k))continue;if(k==="ios"){let b=he.join(l,"ios");try{let M=oe.readdirSync(b);for(let h of M)if(!p.has(h))try{oe.rmSync(he.join(b,h),{recursive:!0,force:!0})}catch{}}catch{}continue}let x=he.join(l,k);try{oe.rmSync(x,{recursive:!0,force:!0})}catch{}}}let g=he.join(l,"source.zip"),m=s.data,E=oe.createWriteStream(g);await new Promise((O,k)=>{m.pipe(E),m.on("error",x=>k(x)),E.on("finish",()=>O())}),new Ni(g).extractAllTo(l,!0);try{oe.unlinkSync(g)}catch{}process.chdir(l),w.info(v.green(`\u2713 Persistent workspace ready: ${l}`)),w.info(v.dim(` \u{1F4E6} Cached dirs preserved: node_modules=${oe.existsSync(he.join(l,"node_modules"))?"\u2705":"\u274C"}, Pods=${oe.existsSync(he.join(l,"ios","Pods"))?"\u2705":"\u274C"}`)),n.stop()}catch(a){n.stop(`Failed to prepare isolated workspace: ${a.message}`),i&&await c(`Setup Error: ${a.message}`),process.exit(1)}}try{let a=e.repo;if(!a)try{a=Ci("git config --get remote.origin.url").toString().trim()}catch{w.warn("Could not detect git repository URL.")}!a&&e.dryRun,a||(a="https://github.com/placeholder/repo.git"),w.info(`Build ID: ${v.cyan(t)}`);let s={},d={},l=Te(`./${f.configFileName}`);if(l){i=l.projectId;let h=e.buildProfile||"production",P=Me(l,h);!P&&e.buildProfile&&(w.error(`Build profile '${h}' not found in ${f.configFileName}`),process.exit(1));let I=P||{};process.env.MACH_DEBUG&&w.info(v.dim(`Build profile: ${h} | Platform: ${e.platform} | Distribution: ${I.distribution||"store"} | Environment: ${I.environment||h}`)),I.env&&(d=I.env,w.info(v.blue(`Use Build Profile: ${h}`)));let _=e.platform,C=I[_]||{},H=["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=l.name,e.appName=l.name,e.androidPackage=l.android?.package,e.iosBundleIdentifier=l.ios?.bundleIdentifier,e.iosScheme=l.ios?.iosScheme,!e.nodeVersion&&l.nodeVersion&&(e.nodeVersion=l.nodeVersion);for(let F of H){let Z=C[F]!==void 0?C[F]:I[F];Z!==void 0&&e[F]===void 0&&(e[F]=Z)}e.branch=e.branch||"main",e.iosConfiguration=e.iosConfiguration||(e.developmentClient||e.simulator?"Debug":"Release"),e.sshUser=e.sshUser||process.env.USER||"ubuntu",e.simulator===void 0&&(e.simulator=!1),e.local===void 0&&(e.local=!1),e.verbose===void 0&&(e.verbose=!1);let B=F=>{if(!F)return F;if(F.startsWith("scripts.")){let Z=F.split(".")[1],K=l.scripts?.[Z];if(K)return K;w.warn(`Script reference not found: ${F}`)}return F};e.buildCommand=B(e.buildCommand),e.preBuild=B(e.preBuild),e.postBuild=B(e.postBuild),!e.scheme&&l.scheme&&(e.scheme=l.scheme);let N={...je(l,f.envPrefix),...je(I,`${f.envPrefix}PROFILE_`)};s={...s,...d,...N},process.env.IOS_P12_PASSWORD&&!s.IOS_P12_PASSWORD&&(s.IOS_P12_PASSWORD=process.env.IOS_P12_PASSWORD),process.env.MATCH_PASSWORD&&!s.MATCH_PASSWORD&&(s.MATCH_PASSWORD=process.env.MATCH_PASSWORD),e.platform==="ios"&&(!e.iosTeamId&&I.ios?.appleTeamId&&(e.iosTeamId=I.ios.appleTeamId),!e.iosTeamId&&l.submit?.[h]?.ios?.appleTeamId&&(e.iosTeamId=l.submit[h].ios.appleTeamId),!e.iosTeamId&&l.submit?.production?.ios?.appleTeamId&&(w.warn(v.yellow(`Check: Using 'production' Team ID for '${h}' build.`)),e.iosTeamId=l.submit.production.ios.appleTeamId),e.iosTeamId?w.info(v.magenta(`\u2713 Injected iOS Team ID from config: ${e.iosTeamId}`)):w.warn(v.yellow("\u26A0\uFE0F No iOS Team ID found. Signing might fail if not managed automatically via Expo.")))}let u="unknown";try{u=Ci("git rev-parse --abbrev-ref HEAD").toString().trim()}catch{w.warn("Failed to detect git branch.")}let p="1.0.0";try{oe.existsSync("./package.json")&&(p=JSON.parse(oe.readFileSync("./package.json","utf-8")).version||"1.0.0")}catch{}let g=e.buildProfile||"production",m="Internal";e.developmentClient?m="DevelopmentClient":g.toLowerCase().includes("store")||g.toLowerCase()==="production"?m="Store":g.toLowerCase().includes("preview")||g.toLowerCase().includes("staging")?m="Staging":(g.toLowerCase().includes("development")||g.toLowerCase().includes("dev"))&&(m="Development");let E=e.platform==="ios"?"iOS":"Android",R=e.platform==="ios"&&e.simulator?" (Simulator)":"",O=`${E}${R} v${p} (${m})`;if(it(e,{status:"created",projectId:i,buildId:t,platform:e.platform,profile:g,branch:u,version:p,buildType:m,summary:O}),i){try{let h=e.buildProfile||"production";w.info(v.blue(`Fetching managed secrets for profile: ${h}...`));let P=e.environment||h,_=(await D.get(`/projects/${i}/secrets/export?env=${P}`)).data;_.status==="success"&&_.secrets&&(s={...s,..._.secrets},Object.keys(_.secrets).length>0&&w.info(v.magenta(`\u2713 Injected ${Object.keys(_.secrets).length} secrets from Dashboard.`)))}catch(h){w.warn(`Failed to load managed secrets from Dashboard: ${h.message}`)}try{w.info(v.blue("Fetching managed credentials..."));let h="development";e.distribution==="store"?h="store":e.distribution==="internal"&&(h=e.platform==="ios"?"adhoc":"internal"),m==="Staging"&&e.developmentClient&&(h="development");let P=await D.get("/credentials/resolve",{params:{projectId:i,platform:e.platform,bundleId:e.iosBundleIdentifier||e.androidPackage,distributionType:h}});if(P.data.status==="success"&&P.data.credentials){let I=P.data.credentials;w.info(v.magenta(`\u2713 Found ${I.length} relevant credentials.`));let _=I.filter(N=>{if(N.distributionType){let F=h==="internal"?"adhoc":h;return N.distributionType===F||N.distributionType===h}return!0});w.info(v.dim(` Filtered to ${_.length} credentials for distributionType: ${h}`));let C=!1,H=!1,B=!1;for(let N of _)if(N.downloadUrl)try{let F="",Z=5;for(;Z>0;)try{let K=await tt.get(N.downloadUrl,{responseType:"arraybuffer",timeout:3e4,headers:{Connection:"close"}});F=Buffer.from(K.data).toString("base64");break}catch(K){if(Z--,Z===0)throw K;w.warn(v.dim(` - Temporary network error downloading ${N.name}. Retrying... (${5-Z}/5)`)),await new Promise(j=>setTimeout(j,2e3))}if(N.type==="ios_cert"&&!C)s.IOS_DIST_P12=F,N.password?(s.IOS_P12_PASSWORD=N.password,w.info(v.dim(` - Injected ${N.name} as IOS_DIST_P12 with password from credential record`))):w.info(v.dim(` - Injected ${N.name} as IOS_DIST_P12`)),C=!0;else if(N.type==="ios_profile"&&!H)s.IOS_PROVISIONING_PROFILE=F,w.info(v.dim(` - Injected ${N.name} as IOS_PROVISIONING_PROFILE`)),H=!0;else if(N.type==="android_keystore"&&!B){s.ANDROID_KEYSTORE_BASE64=F;let K=N.keystorePassword||N.password,j=N.keyPassword||N.keystorePassword||N.password,z=N.alias||N.meta?.alias;if(K)s.ANDROID_STORE_PASSWORD=K,w.info(v.dim(" - Injected keystore password from credential record"));else{let L=["ANDROID_STORE_PASSWORD",...[h==="store"?"PRODUCTION":h==="internal"?"STAGING":"DEVELOPMENT",h.toUpperCase(),"PRODUCTION","STORE","INTERNAL","STAGING","RELEASE","DEBUG"].map(U=>`KEYSTORE_PASSWORD_${U}`),"KEYSTORE_PASSWORD"].find(U=>!!s[U]);L&&s[L]&&(s.ANDROID_STORE_PASSWORD=s[L])}if(j?(s.ANDROID_KEY_PASSWORD=j,w.info(v.dim(" - Injected key password from credential record"))):s.ANDROID_KEY_PASSWORD=s.ANDROID_STORE_PASSWORD||"",z)s.ANDROID_KEY_ALIAS=z;else{let ge=["ANDROID_KEY_ALIAS","KEYSTORE_ALIAS"].find(ve=>!!s[ve]);ge&&(s.ANDROID_KEY_ALIAS=s[ge])}w.info(v.dim(` - Injected ${N.name} as ANDROID_KEYSTORE_BASE64`)),B=!0}}catch(F){w.warn(`Failed to download credential ${N.name}: ${F.message}`)}}if(e.platform==="android"){let I=l.android?.versionCode==="auto"||l.expo?.android?.versionCode==="auto";if(e.autoVersion||I){n.start("Resolving latest versionCode from Google Play...");try{let _=e.androidPackage||l.android?.package||l.expo?.android?.package||l.name,C=(P.data.credentials||[]).find(K=>K.type==="google_service_account"&&(!K.bundleId||K.bundleId===_));if(C||(C=((await D.get(`/credentials/${i}`)).data.credentials||[]).find(j=>j.type==="google_service_account"&&j.bundleId===_)),!C)throw new Error(`Google Service Account not found for package ${_}. Upload it under this package in Dashboard or run '${f.nameLower} credentials:service --platform android --package-name ${_}'.`);let H=await D.get(`/credentials/${C.credentialId}/download`,{params:{projectId:i}});if(H.data.status!=="success"||!H.data.downloadUrl)throw new Error("Failed to get secure download URL for service account");let N=(await tt.get(H.data.downloadUrl,{headers:{Connection:"close"}})).data,F=await Pi(_,N);if(F==null)throw new Error("Could not retrieve any version information from Google Play.");let Z=F+1;s.ANDROID_VERSION_CODE=Z.toString(),n.stop(`\u2713 Resolved versionCode: ${v.green(Z)} (Latest on Play Store: ${F})`)}catch(_){n.stop("Version resolution failed");let C=_.response?.data?.error?.message||_.message;throw new Error(`Auto-versioning failed: ${C}. Fix Google Play service account permissions or remove android.versionCode="auto".`)}}}if(e.platform==="ios"&&!e.simulator){let I=!!s.IOS_DIST_P12,_=!!s.IOS_PROVISIONING_PROFILE;if(!I||!_){let C=[...I?[]:["Distribution Certificate"],..._?[]:["Provisioning Profile"]].join(" and ");w.error(v.red(`Missing iOS credentials: ${C}`)),e.quiet&&process.exit(1);let H=e.yes||await vi({message:"Would you like to generate these credentials now?",initialValue:!0});if(H&&!Oi(H))return await qe({platform:"ios",profile:g}),e.quiet||w.info(v.green("\u2713 Credentials setup complete! Restarting build phase...")),It(e);e.quiet||w.info(v.yellow(`Run \`${f.nameLower} credentials\` to set up signing credentials manually.`)),process.exit(1)}}if(e.platform==="android"&&(e.distribution==="internal"||e.distribution==="store")&&!(!!s.ANDROID_KEYSTORE_BASE64||!!s.ANDROID_KEYSTORE)){w.error(v.red("Missing Android credentials: Signing Keystore")),e.quiet&&process.exit(1);let _=e.yes||await vi({message:"Would you like to automatically create and upload an Android Keystore for this profile now?",initialValue:!0});if(_&&!Oi(_))return await qe({platform:"android",profile:g}),e.quiet||w.info(v.green("\u2713 Android Keystore setup complete! Restarting build phase...")),It(e);e.quiet||w.info(v.yellow(`Run \`${f.nameLower} credentials --platform android\` to set up a signing keystore manually.`)),process.exit(1)}}catch(h){w.warn(`Failed to resolve credentials: ${h.message}`)}}let k=!!(e.local&&e.buildId),x=!!(e.local||e.sshHost),b=!x&&!k;if(k){w.info(v.magenta("\u{1F3D7}\uFE0F Runner Mode: Executing isolated build task..."));let h=await jt({...e,interactive:!1},t,s,i,{branch:u,version:p,summary:O,buildType:m});await M(h),process.exit(0)}async function M(h){if(i&&h.length>0){let P=Kt(),I=[];e.quiet||P.start("Uploading artifacts to Dashboard...");try{for(let _ of h){let C=he.basename(_),H=oe.readFileSync(_),B=he.extname(C).toLowerCase(),N="application/octet-stream",F=await D.post(`/builds/${i}/${t}/artifact-upload-url`,{fileName:C,fileType:N});if(F.data.status!=="success")throw new Error(`Failed to get upload URL for ${C}`);let Z=!1;for(let K=1;K<=3;K++)try{await tt.put(F.data.uploadUrl,H,{headers:{"Content-Type":N},maxBodyLength:1/0,maxContentLength:1/0,timeout:12e4}),Z=!0;break}catch(j){if(w.warn(v.yellow(`Artifact upload attempt ${K}/3 failed (${j.code||j.message})`)),K<3)await new Promise(z=>setTimeout(z,3e3*K));else throw j}Z&&I.push({name:C,url:F.data.downloadUrl,size:H.length,type:B.substring(1)})}e.quiet||P.stop("Artifacts uploaded.")}catch(_){e.quiet||P.stop("Failed to upload artifacts."),w.error(v.red(`Upload error: ${_.message}`));try{await D.patch(`/builds/${i}/${t}`,{status:"completed",artifacts:h.map(C=>he.basename(C)),endTime:Date.now()})}catch(C){w.warn(v.yellow(`Could not set fallback build status: ${C.message}`))}return}if(i&&I.length>0)try{w.info(v.cyan(`
|
|
1005
|
+
\u{1F517} Download Links:`));for(let _ of I)w.info(v.dim(` - ${_.name}: `)+v.blue.underline(_.url));await D.patch(`/builds/${i}/${t}`,{status:"success",artifacts:I,endTime:Date.now()}),it(e,{status:"success",projectId:i,buildId:t,platform:e.platform,profile:g,branch:u,version:p,buildType:m,summary:O,artifacts:I}),w.success(v.green(`
|
|
1006
|
+
\u2713 Build completed and reported to dashboard.`))}catch(_){w.warn(v.yellow(`
|
|
1007
|
+
\u26A0\uFE0F Could not report to dashboard: ${_.message}`))}}else if(i)try{await D.patch(`/builds/${i}/${t}`,{status:"completed",endTime:Date.now()}),it(e,{status:"completed",projectId:i,buildId:t,platform:e.platform,profile:g,branch:u,version:p,buildType:m,summary:O})}catch{}}if(x){if(w.info(v.cyan(`\u{1F680} Direct Build Mode: Executing on ${e.sshHost||"local"}...`)),i&&!r){let h=process.argv.slice(3).join(" ");await D.post("/builds",{projectId:i,buildId:t,platform:e.platform,status:"building",branch:u,version:p,summary:O,startTime:o,buildType:m,buildProfile:g,buildArgs:h,simulator:!!e.simulator})}if(e.sshHost&&e.platform==="ios"){let h=await $i(e,t,s,i)}else{let h=await jt({...e,interactive:!!e.local},t,s,i,{branch:u,version:p,summary:O,buildType:m});await M(h)}return}if(b&&(w.info(v.blue("\u{1F6F0}\uFE0F Cloud Initiator Mode: Preparing orchestration...")),!e.dryRun)){e.quiet||n.start("Zipping and uploading local source...");let h=await D.post("/builds/source-upload-url",{projectId:i,buildId:t});if(h.data.status!=="success")throw n.stop("Failed to get upload URL."),new Error("Failed to get source upload URL from API");let P=new Ni,I=oe.readdirSync("."),_=["node_modules",".git","dist","build","builds",".gradle",".idea","android/build","ios/build","ios/Pods",`.${f.nameLower}_cli`];for(let B of I){if(_.includes(B))continue;oe.statSync(B).isDirectory()?P.addLocalFolder(B,B):P.addLocalFile(B)}let C=P.toBuffer();e.quiet||n.message(`Uploading source (${(C.length/1024/1024).toFixed(1)} MB)...`);let H=!1;for(let B=1;B<=3;B++)try{await tt.put(h.data.uploadUrl,C,{headers:{"Content-Type":"application/zip"},maxBodyLength:1/0,maxContentLength:1/0,timeout:12e4}),H=!0;break}catch(N){if(B<3)n.message(`Upload attempt ${B} failed (${N.code||N.message}), retrying...`),await new Promise(F=>setTimeout(F,2e3*B));else throw N}if(e.quiet||n.stop("Source uploaded"),i){let B=process.argv.slice(3).join(" ");await D.post("/builds",{projectId:i,buildId:t,platform:e.platform,status:"pending",branch:u,version:p,summary:O,startTime:o,buildType:m,buildProfile:g,buildArgs:B,simulator:!!e.simulator}),w.info(v.green("\u2713 Cloud build registered."))}e.platform==="android"&&await bi(e,t,s,i,e.preBuild),e.quiet||w.info(v.cyan("\u{1F4E1} Connecting to build stream...")),await bo(i,t,e);return}}catch(a){let s=a.message||"Build failed";a.response?.data?.message?s=a.response.data.message:a.message.includes("status code 402")?s="Insufficient wallet balance. Please add credits in the Dashboard.":a.message.includes("status code 403")&&(s="Monthly build quota exceeded. Upgrade your plan in the Dashboard."),i&&!e.local&&await c(s),w.error(v.red(`\u2717 Build failed: ${s}`)),process.exit(1)}};function Ti(e){return`${Ft}/build/${e}`}function it(e,n){if(!e.jsonOutput)return;let t=he.resolve(e.jsonOutput),i={...n,url:n.url||Ti(n.buildId),dashboardUrl:n.dashboardUrl||Ti(n.buildId),updatedAt:new Date().toISOString()};try{let o=he.dirname(t);o&&o!=="."&&oe.mkdirSync(o,{recursive:!0}),oe.writeFileSync(t,JSON.stringify(i,null,2))}catch(o){w.warn(v.yellow(`Could not write build metadata JSON: ${o.message}`))}}async function bo(e,n,t){let i=Kt(),o="pending",r=0,c=0;for(t.quiet||i.start("Connecting to build stream...");;){try{let s=(await D.get(`/builds/${e}/${n}`)).data.build;if(s){if(o=s.status,o==="building")t.quiet||i.message("Build in progress...");else if(o==="failed")t.quiet||i.stop("Build failed."),it(t,{status:"failed",projectId:e,buildId:n,platform:t.platform,error:s.error||"Unknown error",artifacts:s.artifacts||[]}),w.error(v.red(`
|
|
1008
|
+
\u2717 Build failed: ${s.error||"Unknown error"}`)),process.exit(1);else if(o==="completed"||o==="success"){t.quiet||i.stop("Build successful!"),it(t,{status:o,projectId:e,buildId:n,platform:t.platform,artifacts:s.artifacts||[]}),w.success(v.green(`
|
|
795
1009
|
\u2713 Build completed successfully!`));try{t.quiet||(w.info(v.magenta(`
|
|
796
|
-
\u{1F4F1} Installation Hub:`)),w.info(v.dim(" - View & Install Build: ")+v.white.underline(`${
|
|
797
|
-
`);if(u.length>r){for(let p=r;p<u.length;p++)u[p].trim()&&console.log(v.dim(` ${u[p]}`));r=u.length}}}catch{}
|
|
798
|
-
\u2717 Lost connection to Dashboard API.`)),process.exit(1))}await new Promise(
|
|
799
|
-
`).forEach(i=>{if(i.includes("List of devices")||!i.trim())return;let o=i.split(/\s+/);if(o.length<2||o[1]!=="device")return;let r=o[0];t.add(r);let
|
|
800
|
-
`).filter(r=>!!r.trim()),o=e.some(r=>r.platform==="android"&&r.id.startsWith("emulator-"));i.forEach(r=>{o||e.push({id:r,platform:"android",type:"emulator",name:r.replace(/_/g," "),status:"offline",details:`Android Virtual Device: ${r}`})})}catch{}if(process.platform!=="darwin")return e;try{let n=Et("/usr/bin/xcrun simctl list devices --json",{stdio:"pipe"}).toString(),t=JSON.parse(n);Object.entries(t.devices).forEach(([i,o])=>{o.forEach(r=>{r.isAvailable&&e.push({id:r.udid,platform:"ios",type:"simulator",name:r.name,status:r.state?.toLowerCase()==="booted"?"online":"offline",runtime:i,details:`${r.name} (${i})`})})})}catch{}try{let n=Et("/usr/bin/xcrun devicectl list devices --json-output -",{stdio:"pipe"}).toString();(JSON.parse(n).result?.devices||[]).forEach(i=>{let o=i.connectionProperties?.transportType;(o==="wired"||o==="localNetwork")&&e.push({id:i.identifier,platform:"ios",type:"physical",name:i.deviceProperties?.name||"iPhone",status:"online",details:`${i.deviceProperties?.name||"iPhone"} (${i.model?.name||i.hardwareModel||""}) - ${o}`})})}catch{}return e}async function Ri(){process.platform!=="darwin"&&Be.warn("Running on non-macOS \u2014 iOS discovery unavailable, Android only.");let e=So.createServer((n,t)=>{if(t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Access-Control-Allow-Methods","GET, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),n.method==="OPTIONS"){t.writeHead(204),t.end();return}let i=new URL(n.url||"/",`http://localhost:${It}`);if(n.method==="GET"&&i.pathname==="/local/devices"){try{let o=Ao();t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({status:"success",targets:o}))}catch(o){t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({status:"error",message:o.message}))}return}t.writeHead(404),t.end()});e.listen(It,"127.0.0.1",()=>{Be.success(jt.green(`Local device agent running on http://localhost:${It}`)),Be.info(jt.dim("Keep this running while using the Install Hub on the dashboard.")),Be.info(jt.dim("Press Ctrl+C to stop."))}),e.on("error",n=>{n.code==="EADDRINUSE"?Be.error(`Port ${It} is already in use \u2014 agent may already be running.`):Be.error(`Agent error: ${n.message}`),process.exit(1)}),await new Promise(()=>{})}import{createRequire as Zr}from"module";import{text as Io,password as bo,spinner as $o,isCancel as Ti}from"@clack/prompts";import zt from"chalk";import it from"fs";import Oi from"path";import Eo from"os";var Bt=Oi.join(Eo.homedir(),f.configDir),Kt=Oi.join(Bt,"config.json");function Vt(){if(!it.existsSync(Kt))return{};try{return JSON.parse(it.readFileSync(Kt,"utf-8"))}catch{return{}}}function Ci(e){it.existsSync(Bt)||it.mkdirSync(Bt,{recursive:!0});let t={...Vt(),...e};it.writeFileSync(Kt,JSON.stringify(t,null,2))}async function Ni(){let e=Vt(),n=await Io({message:"Enter your email:",placeholder:"user@example.com",initialValue:e.lastLoginEmail,validate(o){if(o.length===0)return"Email is required!"}});if(Ti(n))return;let t=await bo({message:"Enter your password:",validate(o){if(o.length===0)return"Password is required!"}});if(Ti(t))return;let i=$o();i.start("Authenticating...");try{let r=await(await fetch(`${gt}/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:n,password:t})})).json();r.status==="success"&&r.user.token?(ri({id:r.user.id,email:n,token:r.user.token,refreshToken:r.user.refreshToken}),Ci({lastLoginEmail:n}),i.stop(zt.green("Login successful!"))):i.stop(zt.red("Login failed: "+(r.message||"Unknown error")))}catch(o){i.stop(zt.red("Network error: "+o.message))}}import{outro as Po,select as _o,spinner as Do,isCancel as wo}from"@clack/prompts";import bt from"chalk";import Wt from"fs";import vo from"path";async function ki(){if(!ue()){console.log(bt.red(`You are not logged in. Run \`${f.nameLower} login\` first.`));return}let n=Do();n.start("Fetching projects...");try{let{data:t}=await _.get("/projects");if(n.stop("Projects loaded."),t.status!=="success"||!t.projects||t.projects.length===0){console.log(bt.yellow(`No projects found. Run \`${f.nameLower} init\` to create one.`));return}let i=t.projects.map(u=>({value:u.projectId,label:`${u.name} (${u.slug})`})),o=await _o({message:"Select a project to link:",options:i});if(wo(o))return;let r=vo.join(process.cwd(),f.configFileName),a={};if(Wt.existsSync(r))try{a=JSON.parse(Wt.readFileSync(r,"utf-8"))}catch{}let c=t.projects.find(u=>u.projectId===o),s=a.android?.package||Oe("android"),l=a.ios?.bundleIdentifier||Oe("ios"),d={projectId:o,name:c?.name,slug:c?.slug,scheme:c?.slug?.toLowerCase()||"app",android:{package:s||""},ios:{bundleIdentifier:l||""},build:{development:{environment:"development",distribution:"internal"},staging:{environment:"staging",distribution:"internal"},production:{environment:"production",distribution:"store"}},submit:{production:{android:a.submit?.production?.android||{track:"internal"},ios:{ascAppId:a.submit?.production?.ios?.ascAppId||"1234567890",appleTeamId:a.submit?.production?.ios?.appleTeamId||"ABC123DEFG"}}}};Wt.writeFileSync(r,JSON.stringify(d,null,2)),Po(bt.green(`Linked to project ${d.name} (${d.slug})`))}catch(t){n.stop(bt.red("Error fetching projects: "+t.message))}}import{outro as Ro,text as $t,select as Oo,spinner as Co,isCancel as nt}from"@clack/prompts";import ot from"chalk";import To from"fs";import No from"path";import{randomUUID as ko}from"crypto";async function xi(){if(!ue()){console.log(ot.red(`You are not logged in. Run \`${f.nameLower} login\` first.`));return}let n=await $t({message:"Project Name:",placeholder:"My Awesome App",validate(c){if(c.length===0)return"Name is required!"}});if(nt(n))return;let t=await $t({message:"Project Slug (URL friendly):",placeholder:"my-awesome-app",validate(c){if(c.length===0)return"Slug is required!";if(!/^[a-z0-9-]+$/.test(c))return"Slug must be lowercase alphanumeric with dashes."}});if(nt(t))return;let i=await Oo({message:"Platform:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"},{value:"web",label:"Web"},{value:"all",label:"All Platforms"}]});if(nt(i))return;let o="";if(i==="android"||i==="all"){let c=Oe("android");if(o=await $t({message:"Android Package Name:",initialValue:c||"",placeholder:"com.example.app",validate(s){if(s.length===0)return"Package name is required for Android!"}}),nt(o))return}let r="";if(i==="ios"||i==="all"){let c=Oe("ios");if(r=await $t({message:"iOS Bundle Identifier:",initialValue:c||"",placeholder:"com.example.app",validate(s){if(s.length===0)return"Bundle ID is required for iOS!"}}),nt(r))return}let a=Co();a.start("Creating project...");try{let c=ko(),l={projectId:c,name:n,slug:t,storageType:"managed",platforms:i==="all"?["android","ios","web"]:[i]},{data:d}=await _.post("/projects",l);if(d.status==="success"){a.stop(ot.green("Project created successfully!"));let u=No.join(process.cwd(),f.configFileName);To.writeFileSync(u,JSON.stringify({projectId:c,name:n,slug:t,...o?{android:{package:o}}:{},...r?{ios:{bundleIdentifier:r}}:{},build:{development:{environment:"development",distribution:"internal"},staging:{environment:"staging",distribution:"internal"},production:{environment:"production",distribution:"store"}},submit:{production:{android:{track:"internal"},ios:{ascAppId:"1234567890",appleTeamId:"ABC123DEFG",...r?{bundleId:r}:{}}}}},null,2)),Ro(ot.green(`Initialized project ${n} and linked locally!`))}else a.stop(ot.red("creation failed: "+d.message))}catch(c){a.stop(ot.red("Network error: "+c.message))}}import{spinner as Ui,log as me}from"@clack/prompts";import Pt from"chalk";import Li from"fs";import xo from"path";async function Mi(e,n){let t=ue();if(!t){me.error(`You are not logged in. Run \`${f.nameLower} login\` first.`);return}let i=xo.join(process.cwd(),f.configFileName);if(!Li.existsSync(i)){me.error(`No ${f.configFileName} found. Run \`${f.nameLower} init\` or \`${f.nameLower} link\` first.`);return}let o;try{o=JSON.parse(Li.readFileSync(i,"utf-8"))}catch{me.error(`Failed to parse ${f.configFileName}`);return}let{projectId:r}=o;if(!r){me.error(`${f.configFileName} is missing projectId.`);return}e==="set"?await Lo(r,n,t):e==="list"?await Uo(r,t):me.error(`Unknown env action: ${e}. Use 'set' or 'list'.`)}async function Lo(e,n,t){if(n.length===0){me.error(`Usage: ${f.nameLower} env set KEY=VALUE [KEY2=VALUE2 ...]`);return}let i=Ui();i.start("Setting environment variables...");let o=0,r=0;for(let a of n){let[c,...s]=a.split("="),l=s.join("=");if(!c||l===void 0){me.warn(`Invalid format for argument: ${a}. Expected KEY=VALUE.`),r++;continue}try{let d={key:c.trim(),value:l,type:"env",environment:"global",visibility:"secret"},{data:u}=await _.post(`/projects/${e}/secrets`,d);u.status==="success"?o++:(me.error(`Failed to set ${c}: ${u.message}`),r++)}catch(d){me.error(`Network error setting ${c}: ${d.message}`),r++}}i.stop(`Set ${o} variable(s). ${r>0?`${r} failed.`:""}`)}async function Uo(e,n){let t=Ui();t.start("Fetching environment variables...");try{let{data:i}=await _.get(`/projects/${e}/secrets`);if(i.status==="success"){t.stop("Fetched variables.");let o=i.secrets||[];o.length===0?me.info("No environment variables found for this project."):(me.info(Pt.bold("Environment Variables (Global & Scoped):")),o.forEach(r=>{let a=r.visibility==="plain"?r.value:"********";console.log(` ${Pt.cyan(r.key)} = ${a} ${Pt.gray(`[${r.environment}]`)}`)}))}else t.stop(Pt.red(`Failed to fetch variables: ${i.message}`))}catch(i){t.stop("Failed to fetch variables."),me.error(`Network error: ${i.message}`)}}import{spinner as st,text as rt,select as qt,isCancel as ke,cancel as Jt}from"@clack/prompts";import ne from"chalk";import le from"fs";import Ke from"path";import{spawn as Mo,spawnSync as Fo}from"child_process";import Hi from"axios";import Xt from"os";import Ho from"crypto";async function Gi(e){let n=st(),t=ue(),i=`./${f.configFileName}`;if(!le.existsSync(i)){ge(`No ${f.configFileName} found. Run \`${f.nameLower} init\` or \`${f.nameLower} link\` first.`);return}let o=JSON.parse(le.readFileSync(i,"utf-8")),{projectId:r}=o;if(!r){ge(`${f.configFileName} is missing projectId.`);return}ve(ne.dim(`Submit for project: ${o.name||r} `));let a=e.platform;if(!a){let y=await qt({message:"Select platform to submit:",options:[{value:"ios",label:"iOS (App Store Connect / TestFlight)"},{value:"android",label:"Android (Google Play Console)"}]});if(ke(y)){Jt("Operation cancelled");return}a=y}let c=await Go(r,a,e,t?.token);if(!c)return;ve(`Using artifact: ${ne.green(Ke.basename(c))} `),n.start("Fetching submission credentials from Dashboard...");let s;try{let N=((await _.get(`/credentials/${r}`)).data.credentials||[]).filter(C=>a==="ios"?C.type==="asc_api_key":C.type==="google_service_account");if(N.length===0){n.stop("Credentials missing"),ge(`No Service Credentials found for ${a}.`),ve(`Use '${f.nameLower} credentials:service --platform ${a}' or use the Dashboard to upload them.`);return}if(N.length===1)s=N[0],n.stop(`Using: ${s.name}`);else{n.stop("Multiple credentials found");let C=await qt({message:`Choose a ${a==="ios"?"App Store Connect":"Google Play"} credential:`,options:N.map(x=>({value:x.credentialId,label:x.name,hint:`${x.keyId?`ID: ${x.keyId}`:""} ${x.issuerId?`(Issuer: ${x.issuerId.substring(0,8)}...)`:""}`}))});if(ke(C)){Jt("Submission cancelled");return}s=N.find(x=>x.credentialId===C),ve(`Using selected: ${ne.green(s.name)}`)}}catch(y){n.stop("Failed to fetch credentials"),ge(`API Error: ${y.message} `);return}let l=le.mkdtempSync(Ke.join(Xt.tmpdir(),`${f.nameLower}-submit-`)),d=s.keyId||s.meta?.keyId,u=s.issuerId||s.meta?.issuerId,p=s.type==="asc_api_key"?`AuthKey_${d}.p8`:"service-account.json",h=Ke.join(l,p);n.start("Downloading secure key...");try{let y=await _.get(`/credentials/${s.credentialId}/download`,{params:{projectId:r}});if(y.data.status!=="success"||!y.data.downloadUrl)throw new Error("Failed to get secure download URL");let $=await Hi.get(y.data.downloadUrl,{responseType:"arraybuffer"});le.writeFileSync(h,Buffer.from($.data)),n.stop("Key downloaded to secure temp storage")}catch(y){n.stop("Download failed"),ge(`Failed to download key: ${y.message}`);try{le.rmSync(l,{recursive:!0,force:!0})}catch{}return}ve(ne.blue(`Initiating ${a==="ios"?"TestFlight":"Google Play"} submission...`));let m=a==="android"?e.track||o.submit?.production?.android?.track||"internal":void 0;try{if(a==="ios"){if(!d){let N=await rt({message:"Enter App Store Connect Key ID (e.g. 2X948D...):",validate:C=>C.length>0?void 0:"Key ID is required"});if(ke(N))return;d=N}if(!u||u==="undefined"){let N=await rt({message:"Enter App Store Connect Issuer ID (Found on ASC Keys page):",validate:C=>C.length>0?void 0:"Issuer ID is required"});if(ke(N))return;u=N}ve(`Using ASC Key ID: ${d}`),ve(`Using ASC Issuer ID: ${u}`);let y=o.ios?.bundleIdentifier,$=await jo(c,h,u,d,y);if($&&$.apiKeyJsonPath)throw ve(ne.cyan(`
|
|
801
|
-
[DIAGNOSTIC] API key written to: ${
|
|
802
|
-
`)),new Error("fastlane pilot execution failed");
|
|
803
|
-
${(
|
|
1010
|
+
\u{1F4F1} Installation Hub:`)),w.info(v.dim(" - View & Install Build: ")+v.white.underline(`${Ft}/build/${n}`)))}catch{}return}else if(o!=="pending"){t.quiet||i.stop(`Build status: ${o}`);return}}try{let l=(await D.get(`/builds/${e}/${n}/logs`)).data;if(l&&typeof l=="string"&&!t.quiet){let u=l.split(`
|
|
1011
|
+
`);if(u.length>r){for(let p=r;p<u.length;p++)u[p].trim()&&console.log(v.dim(` ${u[p]}`));r=u.length}}}catch{}c=0}catch{c++,c>10&&(i.stop("Connection lost."),w.error(v.red(`
|
|
1012
|
+
\u2717 Lost connection to Dashboard API.`)),process.exit(1))}await new Promise(a=>setTimeout(a,3e3))}}import _o from"http";import{execSync as bt}from"child_process";import zt from"chalk";import{log as Ke}from"@clack/prompts";var _t=7070;function $o(){let e=[];try{let n=bt("adb devices -l",{stdio:"pipe"}).toString(),t=new Set;n.split(`
|
|
1013
|
+
`).forEach(i=>{if(i.includes("List of devices")||!i.trim())return;let o=i.split(/\s+/);if(o.length<2||o[1]!=="device")return;let r=o[0];t.add(r);let c=i.match(/model:([^\s]+)/);e.push({id:r,platform:"android",type:r.startsWith("emulator-")?"emulator":"physical",name:c?c[1].replace(/_/g," "):r,status:"online",details:i.trim()})})}catch{}try{let n=`${process.env.ANDROID_HOME||`${process.env.HOME}/Library/Android/sdk`}/emulator/emulator`,i=bt(`${n} -list-avds`,{stdio:"pipe"}).toString().split(`
|
|
1014
|
+
`).filter(r=>!!r.trim()),o=e.some(r=>r.platform==="android"&&r.id.startsWith("emulator-"));i.forEach(r=>{o||e.push({id:r,platform:"android",type:"emulator",name:r.replace(/_/g," "),status:"offline",details:`Android Virtual Device: ${r}`})})}catch{}if(process.platform!=="darwin")return e;try{let n=bt("/usr/bin/xcrun simctl list devices --json",{stdio:"pipe"}).toString(),t=JSON.parse(n);Object.entries(t.devices).forEach(([i,o])=>{o.forEach(r=>{r.isAvailable&&e.push({id:r.udid,platform:"ios",type:"simulator",name:r.name,status:r.state?.toLowerCase()==="booted"?"online":"offline",runtime:i,details:`${r.name} (${i})`})})})}catch{}try{let n=bt("/usr/bin/xcrun devicectl list devices --json-output -",{stdio:"pipe"}).toString();(JSON.parse(n).result?.devices||[]).forEach(i=>{let o=i.connectionProperties?.transportType;(o==="wired"||o==="localNetwork")&&e.push({id:i.identifier,platform:"ios",type:"physical",name:i.deviceProperties?.name||"iPhone",status:"online",details:`${i.deviceProperties?.name||"iPhone"} (${i.model?.name||i.hardwareModel||""}) - ${o}`})})}catch{}return e}async function ki(){process.platform!=="darwin"&&Ke.warn("Running on non-macOS \u2014 iOS discovery unavailable, Android only.");let e=_o.createServer((n,t)=>{if(t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Access-Control-Allow-Methods","GET, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),n.method==="OPTIONS"){t.writeHead(204),t.end();return}let i=new URL(n.url||"/",`http://localhost:${_t}`);if(n.method==="GET"&&i.pathname==="/local/devices"){try{let o=$o();t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({status:"success",targets:o}))}catch(o){t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({status:"error",message:o.message}))}return}t.writeHead(404),t.end()});e.listen(_t,"127.0.0.1",()=>{Ke.success(zt.green(`Local device agent running on http://localhost:${_t}`)),Ke.info(zt.dim("Keep this running while using the Install Hub on the dashboard.")),Ke.info(zt.dim("Press Ctrl+C to stop."))}),e.on("error",n=>{n.code==="EADDRINUSE"?Ke.error(`Port ${_t} is already in use \u2014 agent may already be running.`):Ke.error(`Agent error: ${n.message}`),process.exit(1)}),await new Promise(()=>{})}import{createRequire as ns}from"module";import{text as Do,password as Ro,spinner as wo,isCancel as Ui}from"@clack/prompts";import Jt from"chalk";import nt from"fs";import xi from"path";import Po from"os";var Vt=xi.join(Po.homedir(),f.configDir),Wt=xi.join(Vt,"config.json");function Yt(){if(!nt.existsSync(Wt))return{};try{return JSON.parse(nt.readFileSync(Wt,"utf-8"))}catch{return{}}}function Li(e){nt.existsSync(Vt)||nt.mkdirSync(Vt,{recursive:!0});let t={...Yt(),...e};nt.writeFileSync(Wt,JSON.stringify(t,null,2))}async function Mi(){let e=Yt(),n=await Do({message:"Enter your email:",placeholder:"user@example.com",initialValue:e.lastLoginEmail,validate(o){if(o.length===0)return"Email is required!"}});if(Ui(n))return;let t=await Ro({message:"Enter your password:",validate(o){if(o.length===0)return"Password is required!"}});if(Ui(t))return;let i=wo();i.start("Authenticating...");try{let r=await(await fetch(`${ht}/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:n,password:t})})).json();r.status==="success"&&r.user.token?(ci({id:r.user.id,email:n,token:r.user.token,refreshToken:r.user.refreshToken}),Li({lastLoginEmail:n}),i.stop(Jt.green("Login successful!"))):i.stop(Jt.red("Login failed: "+(r.message||"Unknown error")))}catch(o){i.stop(Jt.red("Network error: "+o.message))}}import{outro as vo,select as Oo,spinner as Co,isCancel as No}from"@clack/prompts";import $t from"chalk";import qt from"fs";import To from"path";async function Fi(){if(!pe()){console.log($t.red(`You are not logged in. Run \`${f.nameLower} login\` first.`));return}let n=Co();n.start("Fetching projects...");try{let{data:t}=await D.get("/projects");if(n.stop("Projects loaded."),t.status!=="success"||!t.projects||t.projects.length===0){console.log($t.yellow(`No projects found. Run \`${f.nameLower} init\` to create one.`));return}let i=t.projects.map(u=>({value:u.projectId,label:`${u.name} (${u.slug})`})),o=await Oo({message:"Select a project to link:",options:i});if(No(o))return;let r=To.join(process.cwd(),f.configFileName),c={};if(qt.existsSync(r))try{c=JSON.parse(qt.readFileSync(r,"utf-8"))}catch{}let a=t.projects.find(u=>u.projectId===o),s=c.android?.package||Oe("android"),d=c.ios?.bundleIdentifier||Oe("ios"),l={projectId:o,name:a?.name,slug:a?.slug,scheme:a?.slug?.toLowerCase()||"app",android:{package:s||""},ios:{bundleIdentifier:d||""},build:{development:{environment:"development",distribution:"internal"},staging:{environment:"staging",distribution:"internal"},production:{environment:"production",distribution:"store"}},submit:{production:{android:c.submit?.production?.android||{track:"internal"},ios:{ascAppId:c.submit?.production?.ios?.ascAppId||"1234567890",appleTeamId:c.submit?.production?.ios?.appleTeamId||"ABC123DEFG"}}}};qt.writeFileSync(r,JSON.stringify(l,null,2)),vo($t.green(`Linked to project ${l.name} (${l.slug})`))}catch(t){n.stop($t.red("Error fetching projects: "+t.message))}}import{outro as ko,text as Pt,select as xo,spinner as Lo,isCancel as ot}from"@clack/prompts";import rt from"chalk";import Uo from"fs";import Mo from"path";import{randomUUID as Fo}from"crypto";async function Hi(){if(!pe()){console.log(rt.red(`You are not logged in. Run \`${f.nameLower} login\` first.`));return}let n=await Pt({message:"Project Name:",placeholder:"My Awesome App",validate(a){if(a.length===0)return"Name is required!"}});if(ot(n))return;let t=await Pt({message:"Project Slug (URL friendly):",placeholder:"my-awesome-app",validate(a){if(a.length===0)return"Slug is required!";if(!/^[a-z0-9-]+$/.test(a))return"Slug must be lowercase alphanumeric with dashes."}});if(ot(t))return;let i=await xo({message:"Platform:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"},{value:"web",label:"Web"},{value:"all",label:"All Platforms"}]});if(ot(i))return;let o="";if(i==="android"||i==="all"){let a=Oe("android");if(o=await Pt({message:"Android Package Name:",initialValue:a||"",placeholder:"com.example.app",validate(s){if(s.length===0)return"Package name is required for Android!"}}),ot(o))return}let r="";if(i==="ios"||i==="all"){let a=Oe("ios");if(r=await Pt({message:"iOS Bundle Identifier:",initialValue:a||"",placeholder:"com.example.app",validate(s){if(s.length===0)return"Bundle ID is required for iOS!"}}),ot(r))return}let c=Lo();c.start("Creating project...");try{let a=Fo(),d={projectId:a,name:n,slug:t,storageType:"managed",platforms:i==="all"?["android","ios","web"]:[i]},{data:l}=await D.post("/projects",d);if(l.status==="success"){c.stop(rt.green("Project created successfully!"));let u=Mo.join(process.cwd(),f.configFileName);Uo.writeFileSync(u,JSON.stringify({projectId:a,name:n,slug:t,...o?{android:{package:o}}:{},...r?{ios:{bundleIdentifier:r}}:{},build:{development:{environment:"development",distribution:"internal"},staging:{environment:"staging",distribution:"internal"},production:{environment:"production",distribution:"store"}},submit:{production:{android:{track:"internal"},ios:{ascAppId:"1234567890",appleTeamId:"ABC123DEFG",...r?{bundleId:r}:{}}}}},null,2)),ko(rt.green(`Initialized project ${n} and linked locally!`))}else c.stop(rt.red("creation failed: "+l.message))}catch(a){c.stop(rt.red("Network error: "+a.message))}}import{spinner as Gi,log as ye}from"@clack/prompts";import Dt from"chalk";import Bi from"fs";import Ho from"path";async function ji(e,n){let t=pe();if(!t){ye.error(`You are not logged in. Run \`${f.nameLower} login\` first.`);return}let i=Ho.join(process.cwd(),f.configFileName);if(!Bi.existsSync(i)){ye.error(`No ${f.configFileName} found. Run \`${f.nameLower} init\` or \`${f.nameLower} link\` first.`);return}let o;try{o=JSON.parse(Bi.readFileSync(i,"utf-8"))}catch{ye.error(`Failed to parse ${f.configFileName}`);return}let{projectId:r}=o;if(!r){ye.error(`${f.configFileName} is missing projectId.`);return}e==="set"?await Bo(r,n,t):e==="list"?await Go(r,t):ye.error(`Unknown env action: ${e}. Use 'set' or 'list'.`)}async function Bo(e,n,t){if(n.length===0){ye.error(`Usage: ${f.nameLower} env set KEY=VALUE [KEY2=VALUE2 ...]`);return}let i=Gi();i.start("Setting environment variables...");let o=0,r=0;for(let c of n){let[a,...s]=c.split("="),d=s.join("=");if(!a||d===void 0){ye.warn(`Invalid format for argument: ${c}. Expected KEY=VALUE.`),r++;continue}try{let l={key:a.trim(),value:d,type:"env",environment:"global",visibility:"secret"},{data:u}=await D.post(`/projects/${e}/secrets`,l);u.status==="success"?o++:(ye.error(`Failed to set ${a}: ${u.message}`),r++)}catch(l){ye.error(`Network error setting ${a}: ${l.message}`),r++}}i.stop(`Set ${o} variable(s). ${r>0?`${r} failed.`:""}`)}async function Go(e,n){let t=Gi();t.start("Fetching environment variables...");try{let{data:i}=await D.get(`/projects/${e}/secrets`);if(i.status==="success"){t.stop("Fetched variables.");let o=i.secrets||[];o.length===0?ye.info("No environment variables found for this project."):(ye.info(Dt.bold("Environment Variables (Global & Scoped):")),o.forEach(r=>{let c=r.visibility==="plain"?r.value:"********";console.log(` ${Dt.cyan(r.key)} = ${c} ${Dt.gray(`[${r.environment}]`)}`)}))}else t.stop(Dt.red(`Failed to fetch variables: ${i.message}`))}catch(i){t.stop("Failed to fetch variables."),ye.error(`Network error: ${i.message}`)}}import{spinner as at,text as st,select as Zt,isCancel as ke,cancel as Qt}from"@clack/prompts";import re from"chalk";import ie from"fs";import xe from"path";import{spawn as zi}from"child_process";import Vi from"axios";import ei from"os";import jo from"crypto";async function Wi(e){let n=at(),t=pe(),i=`./${f.configFileName}`;if(!ie.existsSync(i)){de(`No ${f.configFileName} found. Run \`${f.nameLower} init\` or \`${f.nameLower} link\` first.`);return}let o=JSON.parse(ie.readFileSync(i,"utf-8")),{projectId:r}=o,c=e.profile||e.buildProfile||"production";if(!r){de(`${f.configFileName} is missing projectId.`);return}Re(re.dim(`Submit for project: ${o.name||r} | Profile: ${c}`));let a=e.platform;if(!a){let O=await Zt({message:"Select platform to submit:",options:[{value:"ios",label:"iOS (App Store Connect / TestFlight)"},{value:"android",label:"Android (Google Play Console)"}]});if(ke(O)){Qt("Operation cancelled");return}a=O}let s=await zo(r,a,e,t?.token);if(!s)return;Re(`Using artifact: ${re.green(xe.basename(s))} `);let d=a==="android"?Ko(o,c):void 0;n.start("Fetching submission credentials from Dashboard...");let l;try{let k=(await D.get(`/credentials/${r}`)).data.credentials||[];if(a==="android"&&!d){n.stop("Package name missing"),de("Could not resolve Android package name. Set android.package in mach.config.json/app.json.");return}let x=k.filter(b=>a==="ios"?b.type==="asc_api_key":b.type==="google_service_account"&&b.bundleId===d);if(x.length===0){n.stop("Credentials missing"),de(a==="android"?`No Google Play service credential found for package ${d}.`:`No Service Credentials found for ${a}.`),Re(a==="android"?`Use '${f.nameLower} credentials:service --platform android --package-name ${d}' or upload it under that package in the Dashboard.`:`Use '${f.nameLower} credentials:service --platform ${a}' or use the Dashboard to upload them.`);return}if(x.length===1)l=x[0],n.stop(`Using: ${l.name}`);else{n.stop("Multiple credentials found");let b=await Zt({message:`Choose a ${a==="ios"?"App Store Connect":"Google Play"} credential:`,options:x.map(M=>({value:M.credentialId,label:M.name,hint:`${M.keyId?`ID: ${M.keyId}`:""} ${M.issuerId?`(Issuer: ${M.issuerId.substring(0,8)}...)`:""}`}))});if(ke(b)){Qt("Submission cancelled");return}l=x.find(M=>M.credentialId===b),Re(`Using selected: ${re.green(l.name)}`)}}catch(O){n.stop("Failed to fetch credentials"),de(`API Error: ${O.message} `);return}let u=ie.mkdtempSync(xe.join(ei.tmpdir(),`${f.nameLower}-submit-`)),p=l.keyId||l.meta?.keyId,g=l.issuerId||l.meta?.issuerId,m=l.type==="asc_api_key"?`AuthKey_${p}.p8`:"service-account.json",E=xe.join(u,m);n.start("Downloading secure key...");try{let O=await D.get(`/credentials/${l.credentialId}/download`,{params:{projectId:r}});if(O.data.status!=="success"||!O.data.downloadUrl)throw new Error("Failed to get secure download URL");let k=await Vi.get(O.data.downloadUrl,{responseType:"arraybuffer"});ie.writeFileSync(E,Buffer.from(k.data)),n.stop("Key downloaded to secure temp storage")}catch(O){n.stop("Download failed"),de(`Failed to download key: ${O.message}`);try{ie.rmSync(u,{recursive:!0,force:!0})}catch{}return}Re(re.blue(`Initiating ${a==="ios"?"TestFlight":"Google Play"} submission...`));let R=a==="android"?e.track||o.submit?.[c]?.android?.track||o.submit?.production?.android?.track||"internal":void 0;try{if(a==="ios"){if(!p){let x=await st({message:"Enter App Store Connect Key ID (e.g. 2X948D...):",validate:b=>b.length>0?void 0:"Key ID is required"});if(ke(x))return;p=x}if(!g||g==="undefined"){let x=await st({message:"Enter App Store Connect Issuer ID (Found on ASC Keys page):",validate:b=>b.length>0?void 0:"Issuer ID is required"});if(ke(x))return;g=x}Re(`Using ASC Key ID: ${p}`),Re(`Using ASC Issuer ID: ${g}`);let O=o.submit?.[c]?.ios?.bundleId||o.ios?.bundleIdentifier,k=await Vo(s,E,g,p,O);if(k&&k.apiKeyJsonPath)throw Re(re.cyan(`
|
|
1015
|
+
[DIAGNOSTIC] API key written to: ${k.apiKeyJsonPath}
|
|
1016
|
+
`)),new Error("fastlane pilot execution failed");Ki(`${a==="ios"?"App Store":"Google Play"} submission successful!`)}else await Wo(s,E,R,d),Ki("Google Play submission successful!")}catch(O){de(`Submission failed: ${O.message}`)}finally{Jo(u),s.includes(`${f.nameLower}-artifact-`)}}function Ko(e,n){if(e.submit?.[n]?.android?.package)return e.submit[n].android.package;if(e.android?.package)return e.android.package;if(e.expo?.android?.package)return e.expo.android.package;let t=xe.join(process.cwd(),"app.json");if(ie.existsSync(t))try{return JSON.parse(ie.readFileSync(t,"utf-8")).expo?.android?.package}catch{}let i=xe.join(process.cwd(),"app.config.json");if(ie.existsSync(i))try{let o=JSON.parse(ie.readFileSync(i,"utf-8"));return o.expo?.android?.package||o.android?.package}catch{}}async function zo(e,n,t,i){let o=t.buildId?"id":t.latest?"latest":null;if(!o){let c=await Zt({message:"Select artifact source:",options:[{value:"latest",label:`Latest Production Build (${f.name})`},{value:"id",label:`Input Build ID (${f.name})`},{value:"url",label:"Remote URL"},{value:"local",label:"Local File Path"}]});if(ke(c))return Qt("Operation cancelled"),null;o=c}if(o==="local"){let c=await st({message:"Enter path to artifact (.ipa/.aab):",validate:a=>{if(!ie.existsSync(a))return"File not found";if(n==="ios"&&!a.endsWith(".ipa"))return"Must be an .ipa file";if(n==="android"&&!a.endsWith(".aab"))return"Must be an .aab file"}});return ke(c)?null:c}let r=at();if(o==="latest"){let c=t.profile||t.buildProfile;r.start(`Fetching latest${c?` ${c}`:""} build...`);try{let a=await D.get(`/builds/${e}`,{params:{limit:50}});if(a.data.status!=="success")throw new Error(a.data.message);let s=a.data.builds||[],d=c?.toLowerCase(),l=b=>b.platform?.toLowerCase()===n.toLowerCase()&&b.status?.toLowerCase()==="success",u=b=>d?[b.buildProfile,b.profile,b.profileName,b.buildType].filter(Boolean).some(M=>String(M).toLowerCase()===d):!0,p=s.filter(b=>l(b)&&u(b)),g=p.find(b=>b.buildType?.toLowerCase()==="store"||b.distribution?.toLowerCase()==="store")||p[0],m=s.some(b=>b.platform?.toLowerCase()===n.toLowerCase()&&b.status?.toLowerCase()==="success");if(!g)return r.stop("No suitable build found"),de(c&&m?`No successful ${n} builds found for profile "${c}".`:"No successful builds found for this platform."),null;r.stop(`Found build: ${g.buildId}`);let E=g.artifacts||[];if(E.length===0||E.every(b=>!(b.url||b.downloadUrl)))try{let b=await D.get(`/builds/${e}/${g.buildId}/artifacts`);b.data.status==="success"&&b.data.artifacts?.length>0?(E=b.data.artifacts.map(M=>({...M,url:M.url||M.downloadUrl})),console.log(re.cyan(` [RECOVERY] Fetched ${E.length} artifact(s) with download URLs.`))):console.log(re.yellow(" [RECOVERY] /artifacts endpoint returned 0 artifacts."))}catch(b){console.log(re.red(` [RECOVERY] /artifacts fetch failed: ${b.message}`))}let O=n==="ios",k=E.find(b=>{let M=(b.type||"").toLowerCase(),h=(b.name||"").toLowerCase();if(console.log(re.dim(` - Checking: ${b.name} (Type: ${b.type}, HasLink: ${!!(b.url||b.downloadUrl)})`)),M)return M===(O?"ipa":"aab");let P=O?".ipa":".aab",I=(b.url||b.downloadUrl||"").toLowerCase();return h.endsWith(P)||I.includes(P)});if(!k||!(k.url||k.downloadUrl))return de("Build found but artifact URL is missing."),null;let x=k.url||k.downloadUrl;return await Xt(x,O?"ios":"android")}catch(a){return r.stop("Fetch failed"),de(`API Error: ${a.message}`),null}}if(o==="id"){let c=t.buildId||await st({message:"Enter Build ID:",validate:a=>a.length<5?"Invalid ID":void 0});if(ke(c))return null;r.start("Fetching build...");try{let a=await D.get(`/build/${c}`);if(a.data.status!=="success")throw new Error(a.data.message);let s=a.data.build;if(!s)throw new Error("Build not found");let d=n==="ios",l=s.artifacts?.find(u=>{if(u.type)return u.type===(d?"ipa":"aab");let p=d?".ipa":".aab";return u.name&&u.name.endsWith(p)||u.url&&u.url.includes(p)});return!l||!l.url?(r.stop("Missing artifact"),de("Artifact URL not found on build record."),null):(r.stop(`Found build: ${s.buildId}`),await Xt(l.url,d?"ios":"android"))}catch(a){return r.stop("Fetch failed"),de(a.message),null}}if(o==="url"){let c=await st({message:"Enter Artifact URL:",validate:a=>a.startsWith("http")?void 0:"Must be a valid URL"});return ke(c)?null:await Xt(c,n)}return null}async function Xt(e,n,t=3){let i=at();i.start("Downloading artifact...");let o=ie.mkdtempSync(xe.join(ei.tmpdir(),`${f.nameLower}-artifact-`)),r=`app.${n==="ios"?"ipa":"aab"}`,c=xe.join(o,r);for(let a=1;a<=t;a++)try{a>1&&(i.message(`Downloading artifact (Retry ${a}/${t})...`),await new Promise(l=>setTimeout(l,2e3*a)));let s=ie.createWriteStream(c),d=await Vi({url:e,method:"GET",responseType:"stream",timeout:6e4});return await new Promise((l,u)=>{d.data.pipe(s);let p=!1;d.data.on("error",g=>{p||(p=!0,s.close(),u(g))}),s.on("finish",()=>{p||l()}),s.on("error",g=>{p||(p=!0,u(g))})}),i.stop("Download complete"),c}catch(s){if(a===t)throw i.stop("Download failed"),s}throw new Error("Download failed after retries")}async function Vo(e,n,t,i,o){let r=at();if(o&&Re(`Bundled ID: ${re.green(o)}`),!t||!i)throw de(`Missing credentials: issuerId=${t}, keyId=${i}. Check your Dashboard.`),new Error("Missing ASC API Key Metadata (IssuerID or KeyID)");let c=ie.readFileSync(n,"utf8"),a;try{a=jo.createPrivateKey(c).export({type:"pkcs8",format:"pem"})}catch{Re("Key normalization failed, falling back to manual re-wrapping..."),a=`-----BEGIN PRIVATE KEY-----
|
|
1017
|
+
${(c.replace(/-----BEGIN[^-]*-----/g,"").replace(/-----END[^-]*-----/g,"").replace(/\s+/g,"").match(/.{1,64}/g)||[]).join(`
|
|
804
1018
|
`)}
|
|
805
|
-
-----END PRIVATE KEY-----`}console.log(
|
|
806
|
-
[DIAGNOSTIC] Key ID: ${i}`)),console.log(
|
|
807
|
-
`)),r.start("Uploading to TestFlight (pilot)...");let s=
|
|
808
|
-
`).
|
|
809
|
-
|
|
810
|
-
|
|
1019
|
+
-----END PRIVATE KEY-----`}console.log(re.yellow(`
|
|
1020
|
+
[DIAGNOSTIC] Key ID: ${i}`)),console.log(re.yellow(`[DIAGNOSTIC] Issuer ID: ${t}`)),console.log(re.yellow(`[DIAGNOSTIC] Key Checksum (Start): ${a.substring(0,45).replace(/\n/g,"\\n")}`)),console.log(re.yellow(`[DIAGNOSTIC] Key Checksum (End): ${a.substring(a.length-28).replace(/\n/g,"\\n")}
|
|
1021
|
+
`)),r.start("Uploading to TestFlight (pilot)...");let s=xe.join(ei.tmpdir(),`api_key_${i}.json`),d={key_id:i,issuer_id:t,key:a,in_house:!1};ie.writeFileSync(s,JSON.stringify(d,null,2));let l={...process.env};return new Promise((u,p)=>{let g=zi("fastlane",["pilot","upload","--ipa",e,"--api_key_path",s,"--skip_submission","true","--skip_waiting_for_build_processing","true"],{stdio:"inherit",env:l});g.on("close",m=>{if(m!==0)r.stop("Pilot failed"),u({apiKeyJsonPath:s});else{r.stop("IPA uploaded to TestFlight");try{ie.unlinkSync(s)}catch{}u({apiKeyJsonPath:null})}}),g.on("error",m=>{try{ie.unlinkSync(s)}catch{}r.stop("Pilot execution error"),p(m)})})}async function Wo(e,n,t="internal",i){let o=at();o.start(`Uploading to Google Play ${t} track (supply)...`);let r=["supply","--aab",e,"--json_key",n,"--track",t];i&&i!=="*"&&r.push("--package_name",i),await new Promise((c,a)=>{let s=zi("fastlane",r,{stdio:["inherit","pipe","pipe"],env:process.env}),d="";s.stdout.on("data",l=>{let u=l.toString();d+=u,process.stdout.write(u)}),s.stderr.on("data",l=>{let u=l.toString();d+=u,process.stderr.write(u)}),s.on("error",l=>{o.stop("Supply execution error"),a(l)}),s.on("close",l=>{if(l===0){o.stop(`AAB uploaded to ${t} track`),c();return}o.stop("Supply failed"),a(new Error(Yo(d,t,i)))})})}function Yo(e,n,t){if(e.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: ${t||"unknown"} | Track: ${n}`,"Build a new Android artifact with a higher versionCode, then submit that build.",`Recommended: ${f.nameLower} build --platform android --profile production --auto-version`,`Then: ${f.nameLower} submit --latest --platform android --profile production --track ${n}`].join(`
|
|
1022
|
+
`);let i=e.match(/Google Api Error:[^\n]+/);return i?i[0]:"fastlane supply execution failed"}function Jo(e){try{ie.existsSync(e)&&ie.rmSync(e,{recursive:!0,force:!0})}catch{}}function de(e){console.log(re.red(`\u274C ${e}`))}function Re(e){console.log(re.gray(`\u2022 ${e}`))}function Ki(e){console.log(re.green(`\u2713 ${e}`))}import{spinner as qo,log as Fe,outro as Xo}from"@clack/prompts";import ti from"chalk";import Yi from"fs";import Zo from"path";import{execSync as Qo}from"child_process";import er from"adm-zip";import tr from"axios";import{randomUUID as ir}from"crypto";async function Ji(e){Fe.info(ti.magenta("\u{1F680} Starting Over-The-Air (OTA) Update via Mach..."));let n=Te();(!n||!n.projectId)&&(Fe.error(`No ${f.configFileName} found or missing projectId. Run \`mach link\` first.`),process.exit(1));let t=n.projectId,i=e.branch||"production",o="1.0.0";try{o=JSON.parse(Yi.readFileSync("./package.json","utf-8")).version||"1.0.0"}catch{Fe.warn("Could not read package.json version. Defaulting to 1.0.0")}let r=qo();r.start(`Compiling JavaScript bundles for OTA (Channel: ${i}, Runtime: ${o})...`);try{Qo("npx expo export --platform all",{stdio:"ignore"})}catch(d){r.stop("Compilation failed."),Fe.error(`Failed to export JS bundles using Expo: ${d.message}`),process.exit(1)}r.message("Zipping artifact payload...");let c=Zo.join(process.cwd(),"dist");Yi.existsSync(c)||(r.stop("Missing dist folder."),Fe.error("The `dist` directory was not created. Export failed."),process.exit(1));let a=new er;a.addLocalFolder(c,"dist");let s=a.toBuffer();r.message("Uploading payload to Mach Cloud...");try{let d=ir(),l=await D.post("/builds/source-upload-url",{projectId:t,buildId:d});if(l.data.status!=="success")throw new Error("Could not secure upload bucket URL");let{uploadUrl:u,key:p}=l.data;await tr.put(u,s,{headers:{"Content-Type":"application/zip"},maxBodyLength:1/0,maxContentLength:1/0}),r.message(`Promoting Update to ${i}...`),await D.post("/updates/publish",{projectId:t,channelName:i,runtimeVersion:o,platform:"android",updateId:`${d}-android`,manifestKey:p}),await D.post("/updates/publish",{projectId:t,channelName:i,runtimeVersion:o,platform:"ios",updateId:`${d}-ios`,manifestKey:p}),r.stop("Update Live!"),Xo(ti.green(`\u2713 OTA Update natively shipped to the '${i}' channel.`)),Fe.info(ti.dim(`Any app running runtime '${o}' will download this bundle smoothly.`))}catch(d){r.stop("Update failed during Cloud Sync."),Fe.error(`Upload error: ${d.message}`),process.exit(1)}}import{intro as nr,outro as qi,log as ze}from"@clack/prompts";import we from"chalk";async function Xi(){nr(we.blue(`${f.name} CLI - User Profile`));let e=pe();if(!e){ze.warn(we.yellow("You are not logged in.")),ze.info(`Run \`${f.nameLower} login\` to authenticate.`),qi();return}ze.info(`${we.bold("Logged in as:")} ${we.green(e.email)}`);try{await D.get("/projects");let t=pe().token.split(".");if(t.length===3){let i=JSON.parse(Buffer.from(t[1],"base64").toString());if(i.exp){let o=new Date(i.exp*1e3),r=new Date,c=o.getTime()-r.getTime();if(c>0){let a=Math.round(c/6e4),s=(a/60).toFixed(1);ze.info(`${we.bold("Token status:")} Valid (Expires in ~${s}h / ${a}m)`)}else ze.warn(`${we.bold("Token status:")} ${we.red("Expired")} (Auto-refresh failed)`)}}}catch{ze.warn(`${we.bold("Token status:")} ${we.red("Unreachable")} (Session might be truly expired)${ht}`)}qi(we.blue("---"))}import{spawn as ar}from"child_process";import{log as Le}from"@clack/prompts";import Ve from"chalk";import cr from"fs";import or from"net";async function rr(e){return new Promise(n=>{let t=or.createServer();t.once("error",i=>{i.code==="EADDRINUSE"?n(!0):n(!1)}),t.once("listening",()=>{t.close(),n(!1)}),t.listen(e,"0.0.0.0")})}async function Zi(e,n=20){let t=e;for(;t<e+n;){if(!await rr(t))return t;t++}throw new Error(`Could not find an available port after ${n} attempts starting from ${e}.`)}import{execSync as ct}from"child_process";import{log as ii}from"@clack/prompts";import ni from"chalk";async function Qi(e){return e.platform==="ios"?en(e.url):sr(e.url)}async function en(e){try{let n=ct("xcrun simctl list devices booted --json").toString(),t=JSON.parse(n),i=null;for(let o in t.devices){let r=t.devices[o].find(c=>c.state==="Booted");if(r){i=r.udid;break}}if(!i)return ii.info(ni.dim("No booted simulator found. Launching default simulator...")),ct("open -a Simulator"),await new Promise(o=>setTimeout(o,3e3)),en(e);ii.info(ni.dim(`Opening deep link on iOS Simulator (${i})...`)),ct(`xcrun simctl openurl ${i} "${e}"`)}catch(n){throw new Error(`Failed to launch iOS Simulator: ${n.message}`)}}async function sr(e){try{let n=ct("adb devices").toString().split(`
|
|
1023
|
+
`).filter(o=>o.includes(" device")).map(o=>o.split(" ")[0]);if(n.length===0)throw new Error("No Android devices or emulators found.");let t=n[0];ii.info(ni.dim(`Opening deep link on Android Device (${t})...`));let i=`adb -s ${t} shell am start -a android.intent.action.VIEW -d "${e}"`;ct(i)}catch(n){throw new Error(`Failed to launch Android: ${n.message}`)}}var tn=async e=>{Le.info(Ve.blue(`Starting ${f.name} Dev Orchestrator...`));let n=Te(),t=e.buildProfile||"development",i=n?Me(n,t):null,o={...process.env};if(n?.projectId)try{Le.info(Ve.dim(`Fetching managed secrets for profile: ${t}...`));let m=await D.get(`/projects/${n.projectId}/secrets/export?env=${t}`);m.data?.status==="success"&&m.data.secrets&&(Object.assign(o,m.data.secrets),Le.info(Ve.magenta(`\u2713 Injected secrets from ${f.name} Dashboard.`)))}catch{Le.warn("Could not fetch managed secrets. Running with local env only.")}n&&Object.assign(o,je(n,f.envPrefix)),i&&(Object.assign(o,je(i,`${f.envPrefix}PROFILE_`)),i.env&&Object.assign(o,i.env));let r=!1;try{let m=JSON.parse(cr.readFileSync("package.json","utf-8"));r=!!(m.dependencies?.expo||m.devDependencies?.expo)}catch{Le.warn("Could not parse package.json. Defaulting to Bare React Native mode.")}let c=Number(e.port||i?.port||8081),a=await Zi(c);a!==c&&Le.info(Ve.yellow(`Port ${c} is busy. ${f.name} is using ${a} instead.`));let s="npx",d=[];r?(d=["expo","start","--port",String(a)],e.clear&&d.push("--clear"),e.tunnel&&d.push("--tunnel"),e.lan&&d.push("--lan"),e.localhost&&d.push("--localhost")):(d=["react-native","start","--port",String(a)],e.clear&&d.push("--clear"));let l=ar(s,d,{stdio:["inherit","pipe","pipe"],shell:!0,env:o}),u=!1,p="127.0.0.1",g=m=>{let E=m.toString(),R=E.match(/http:\/\/(.+):(\d+)/);if(R&&!u&&(p=R[1],u=!0,e.ios||e.android)){let O=e.ios?"ios":"android",x=`exp+${n?.scheme||f.nameLower}://expo-development-client/?url=http%3A%2F%2F${p}%3A${a}`;Le.info(Ve.magenta(`\u{1F680} ${f.name} is launching ${n?.name||"app"} on ${O==="ios"?"iOS":"Android"}...`)),Qi({platform:O,url:x}).catch(b=>Le.error(Ve.red(`Launch failed: ${b.message}`)))}return E.includes("Starting project")||E.includes("Using src/app")||E.includes("Starting Metro Bundler")||E.includes("Opening exp+")||E.includes("Input is required")?null:E};return l.stdout?.on("data",m=>{let E=g(m);E&&process.stdout.write(E)}),l.stderr?.on("data",m=>{let E=g(m);E&&process.stderr.write(E)}),new Promise((m,E)=>{l.on("exit",R=>{R===0?m():E(new Error(`Dev server exited with code ${R}`))}),l.on("error",R=>{E(R)})})};import{log as fe}from"@clack/prompts";import be from"chalk";var nn=async e=>{let n=Te();n||(fe.error(be.red(`No ${f.configFileName} found in the current directory.`)),process.exit(1));let t=e.profile||"development",i=Me(n,t);if(e.json){console.log(JSON.stringify({project:n,resolved:i},null,2));return}fe.info(be.bgBlue.white(` Resolved ${f.name} Config [${t}] `)),fe.info(be.dim("----------------------------------------")),fe.info(`${be.blue("Project ID:")} ${n.projectId}`),fe.info(`${be.blue("Name:")} ${n.name}`),fe.info(`${be.blue("Scheme:")} ${n.scheme}`),i?(fe.info(be.dim(`
|
|
1024
|
+
Profile Settings:`)),fe.info(`${be.cyan("Distribution:")} ${i.distribution||"none"}`),fe.info(`${be.cyan("Development Client:")} ${i.developmentClient||"false"}`),i.env&&Object.keys(i.env).length>0&&(fe.info(be.dim(`
|
|
1025
|
+
Environment Variables:`)),Object.entries(i.env).forEach(([o,r])=>{fe.info(` ${o}=${r}`)}))):fe.warn(`Profile '${t}' not found.`),fe.info(be.dim("----------------------------------------"))};import{log as _e,spinner as ut,text as on,select as rn,confirm as lr,isCancel as lt,cancel as dt,outro as pt,note as dr}from"@clack/prompts";import W from"chalk";import{execSync as ur}from"child_process";async function pr(){try{let e=ur("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[]}}async function fr(e){let n=e.udid,t=e.name,i="";if(!n){let r=ut();r.start("Scanning for connected iOS devices...");let c=await pr();if(r.stop(c.length>0?`Found ${c.length} device(s)`:"No devices detected"),c.length===1)n=c[0].udid,t=t||c[0].name,i=c[0].model,_e.info(`Detected: ${W.bold(t)} (${W.dim(n.substring(0,12)+"...")})`);else if(c.length>1){let a=await rn({message:"Select a device to register:",options:c.map(d=>({value:d.udid,label:`${d.name} (${d.model})`,hint:d.udid.substring(0,12)+"..."}))});if(lt(a)){dt("Cancelled");return}n=a;let s=c.find(d=>d.udid===n);t=t||s.name,i=s.model}else{_e.info(W.dim("No connected devices found. Enter UDID manually."));let a=await on({message:"Device UDID:",placeholder:"00008101-XXXXXXXXXXXX",validate(s){if(s.length<10)return"UDID seems too short"}});if(lt(a)){dt("Cancelled");return}n=a}}if(!t){let r=await on({message:"Device name:",placeholder:"Nitesh's iPhone",validate(c){if(c.length===0)return"Name is required"}});if(lt(r)){dt("Cancelled");return}t=r}let o=ut();o.start("Registering device...");try{await D.post("/devices",{udid:n,name:t,platform:"ios",model:i||void 0,addedVia:"cli"}),o.stop(W.green("Device registered!")),_e.info(` ${W.bold("Name:")} ${t}`),_e.info(` ${W.bold("UDID:")} ${W.dim(n)}`)}catch(r){o.stop(W.red("Failed to register device")),_e.error(r.response?.data?.message||r.message)}pt(W.blue("---"))}async function mr(){let e=ut();e.start("Fetching registered devices...");try{let t=(await D.get("/devices")).data.devices||[];if(e.stop(`${t.length} device(s) registered`),t.length===0){_e.info(W.dim(`No devices registered yet. Run \`${f.nameLower} device register\` to add one.`)),pt(W.blue("---"));return}let i=t.map(o=>{let r=new Date(o.createdAt).toLocaleDateString();return` ${W.bold(o.name.padEnd(24))} ${W.dim(o.udid.padEnd(28))} ${W.cyan(o.addedVia.padEnd(10))} ${W.dim(r)}`});dr(` ${W.bold("Name".padEnd(24))} ${"UDID".padEnd(28)} ${"Via".padEnd(10)} Date
|
|
811
1026
|
`+i.join(`
|
|
812
|
-
`),"Registered Devices")}catch(n){e.stop(
|
|
813
|
-
`),
|
|
814
|
-
`),
|
|
815
|
-
`),
|
|
816
|
-
`),
|
|
817
|
-
`);/__DEV__/.test(m)||t.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:
|
|
818
|
-
Running expo prebuild for deeper analysis...`));try{
|
|
819
|
-
Skipping manifest/plist checks \u2014 no android/ios dirs. Use --prebuild to generate them.`)),r;for(let
|
|
820
|
-
`)),
|
|
821
|
-
`));for(let s of a)ee.error(J.red(`${J.bold(s.name)} ${J.dim(`(${s.arch})`)}`)),ee.info(J.dim(` PT_LOAD alignment: 2**${Math.log2(s.align)} (${s.align} bytes, needs 2**14 = ${Pn})`))}return c.length>0&&(console.log(""),ee.success(J.green(`${c.length} librar${c.length===1?"y":"ies"} correctly aligned (2**14 or higher).`))),console.log(""),a.length===0?(ee.success(J.green.bold("ELF Verification Successful. APK is 16KB compatible.")),!0):(ee.error(J.red.bold(`Found ${a.length} unaligned lib${a.length===1?"":"s"} (arm64-v8a/x86_64 libs need to be aligned).`)),console.log(""),ee.info(J.yellow("To fix this:")),ee.info(J.dim(" 1. Rebuild with NDK r28+ which defaults to 16KB page alignment")),ee.info(J.dim(" 2. Or set -DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON in CMake")),ee.info(J.dim(" 3. Update third-party libraries that ship prebuilt .so files")),ee.info(J.dim(" 4. After rebuilding: zipalign -p -f -v 16 input.apk output.apk")),console.log(""),ee.info(J.dim("Reference: https://developer.android.com/guide/practices/page-sizes")),!1)}catch(o){return t.stop("Analysis failed."),ee.error(J.red(`Failed to analyze APK: ${o.message}`)),!1}finally{try{Ce.rmSync(i,{recursive:!0,force:!0})}catch{}}}function jr(e){let n=Ce.openSync(e,"r");try{let t=Buffer.alloc(64);if(Ce.readSync(n,t,0,64,0),!t.subarray(0,4).equals(Gr))return null;let i=t[4]===2,o=t[5]===1,r=(p,h)=>o?p.readUInt16LE(h):p.readUInt16BE(h),a=(p,h)=>o?p.readUInt32LE(h):p.readUInt32BE(h),c=(p,h)=>Number(o?p.readBigUInt64LE(h):p.readBigUInt64BE(h)),s,l,d;i?(s=c(t,32),l=r(t,54),d=r(t,56)):(s=a(t,28),l=r(t,42),d=r(t,44));let u=null;for(let p=0;p<d;p++){let h=Buffer.alloc(l);if(Ce.readSync(n,h,0,l,s+p*l),a(h,0)!==Hr)continue;let y;i?y=c(h,48):y=a(h,28),y>0&&(u===null||y<u)&&(u=y)}return u??0}catch{return null}finally{Ce.closeSync(n)}}function Dn(e){let n=[];if(!Ce.existsSync(e))return n;let t=Ce.readdirSync(e,{withFileTypes:!0});for(let i of t){let o=Ye.join(e,i.name);i.isDirectory()?n.push(...Dn(o)):i.name.endsWith(".so")&&n.push(o)}return n}function Br(e){return e.includes("arm64-v8a")?"arm64-v8a":e.includes("x86_64")?"x86_64":"unknown"}var Rn=async e=>{if(ue()||(ye.error(_e.red(`You are not logged in. Run \`${f.nameLower} login\` first.`)),process.exit(1)),e.apk){await zr(e);return}let t=process.cwd(),i=xt.join(t,"package.json");mt.existsSync(i)||(ye.error(_e.red("No package.json found. Run this command from a project root.")),process.exit(1));let o=JSON.parse(mt.readFileSync(i,"utf-8")),r=!!(o.dependencies?.expo||o.devDependencies?.expo);e.json||(ye.info(_e.dim(`Project: ${o.name||"unknown"} v${o.version||"0.0.0"}`)),ye.info(_e.dim(`Type: ${r?"Expo":"Bare React Native"}`)),ye.info(""));let a={json:e.json,fix:e.fix,category:e.category,severity:e.severity,prebuild:e.prebuild},c=await In(t,a);e.json?console.log(JSON.stringify($n(c,o),null,2)):bn(c,e.severity);let s=c.some(d=>d.findings.some(u=>u.severity==="critical")),l=c.some(d=>d.findings.some(u=>u.severity==="high"));(s||l)&&process.exit(1)},wn=["16kb"];async function zr(e){let n=e.category?.toLowerCase();n&&!wn.includes(n)&&(ye.error(_e.red(`Unknown APK check category: "${n}"`)),ye.info(_e.dim(`Available APK checks: ${wn.join(", ")}`)),process.exit(1));let t=await Wr(e.apk);t||process.exit(1);let i=!n,o=!1;(i||n==="16kb")&&(await _n(t)||(o=!0)),o&&process.exit(1)}async function Wr(e){if(e.startsWith("build:")){let t=e.slice(6);return await Yr(t)}if(e.startsWith("http://")||e.startsWith("https://"))return await On(e);let n=xt.resolve(e);return mt.existsSync(n)?n:(ye.error(_e.red(`APK file not found: ${n}`)),null)}async function Yr(e){let n=vn();n.start(`Fetching APK from build ${e}...`);try{let t=await _.get(`/build/${e}`);if(t.data.status!=="success")throw new Error(t.data.message);let i=t.data.build;if(!i)throw new Error("Build not found");let o=i.artifacts?.find(r=>r.type?r.type==="apk":r.name?.endsWith(".apk")||r.url?.includes(".apk"));return!o||!o.url?(n.stop("No APK artifact found"),ye.error(_e.red("This build does not have an APK artifact.")),ye.info(_e.dim("Make sure the build produced an APK (not just an AAB).")),null):(n.stop(`Found build: ${i.buildId||e}`),await On(o.url))}catch(t){return n.stop("Failed to fetch build"),ye.error(_e.red(t.message)),null}}async function On(e){let n=vn();n.start("Downloading APK...");try{let t=mt.mkdtempSync(xt.join(Kr.tmpdir(),`${f.nameLower}-audit-`)),i=xt.join(t,"app.apk"),o=await Vr.get(e,{responseType:"arraybuffer"});mt.writeFileSync(i,o.data);let r=(o.data.length/(1024*1024)).toFixed(1);return n.stop(`Downloaded APK (${r} MB)`),i}catch(t){return n.stop("Download failed"),ye.error(_e.red(`Failed to download APK: ${t.message}`)),null}}var Xr=console.log;console.log=()=>{};Jr();console.log=Xr;de(re.bgCyan.black(f.cliTag("Production Build Orchestrator")));var Qr=Zr(import.meta.url),es=Qr("../package.json"),W=new qr;W.name(f.nameLower).description(`${f.name} CLI: Powerful Cloud Infrastructure Tools`).version(es.version).option("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1);W.command("agent").description("Start local device discovery agent for the Install Hub (port 7070)").action(async()=>{await Ri()});W.command("host").description("Setup AWS S3 static hosting and CloudFront").action(async()=>{de(re.bgCyan.black(f.cliTag("Hosting"))),await di()});W.command("sitemap").description("Generate sitemap.xml from Expo Router app structure").option("-o, --output <path>","Output path for sitemap.xml","./public/sitemap.xml").action(async e=>{de(re.bgCyan.black(f.cliTag("Sitemap Generator"))),await mi(e)});W.command("build").description("Run a build on a cloud provider (AWS Spot Instances)").argument("[platform]","Target platform (android, ios)").option("--platform <os>","Target platform alias (android, ios) [Optional]").option("--repo <url>","Git Repository URL").option("--branch <name>","Git Branch").option("--ami <id>","AMI ID").option("--bucket <name>","S3 Bucket for artifacts").option("--region <region>","AWS Region").option("--aws-profile <name>","AWS Credentials Profile").option("-p, --build-profile <name>","Build Profile (e.g. production, staging)","production").option("--profile <name>","Build Profile (alias for --build-profile)").option("--dry-run","Generate User Data script without launching").option("--keep-instance","Do not terminate the instance after build").option("--subnet <id>","VPC Subnet ID to launch the instance in").option("--security-group <id>","VPC Security Group ID to use").option("--ssh-host <host>","Remote host for iOS build (SSH)").option("--ssh-user <user>","SSH username for remote host").option("--ssh-key <path>","Path to private SSH key for remote host").option("--ios-scheme <scheme>","iOS Scheme to build").option("--ios-team-id <id>","Apple Development Team ID").option("--ios-configuration <config>","Xcode configuration (Release/Debug)").option("--ios-export-method <method>","Export method (ad-hoc, app-store, development, enterprise)").option("--ios-api-key-id <id>","App Store Connect API Key ID").option("--ios-api-key-issuer <id>","App Store Connect API Key Issuer ID").option("--ios-api-key-path <path>","Path to App Store Connect API Key (.p8) file").option("--simulator","Build for iOS Simulator (no signing required)").addOption(new Cn("--build-id <id>","Internal build ID").hideHelp()).addOption(new Cn("--project-id <id>","Internal project ID").hideHelp()).option("--local","Run build on local machine").option("--auto-version","Automatically fetch and increment versionCode from Google Play").option("--verbose","Enable verbose logging").option("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1).action(async(e,n)=>{let t=W.opts();n.yes=n.yes||t.yes,n.quiet=n.quiet||t.quiet,n.platform=e||n.platform,n.buildProfile=n.profile||n.buildProfile,n.quiet||de(re.bgCyan.black(f.cliTag("Cloud Build"))),await At(n)});W.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=>{de(re.bgCyan.black(f.cliTag("OTA Update"))),await Bi(e)});W.command("submit").description("Automated Store Submission (App Store / Google Play)").option("--platform <os>","Target platform (ios/android)").option("--track <track>","Google Play Track (internal, alpha, beta, production)","internal").option("--latest","Use the latest successful build for submission").option("--build-id <id>","Use a specific build ID for submission").action(async e=>{de(re.bgCyan.black(f.cliTag("Store Submission"))),await Gi(e)});W.command("login").description(`Login to ${f.name} Dashboard`).action(async()=>{de(re.bgCyan.black(f.cliTag("Login"))),await Ni()});W.command("link").description(`Link local directory to a ${f.name} Project`).action(async()=>{de(re.bgCyan.black(f.cliTag("Link Project"))),await ki()});W.command("me").description("Display currently logged in user details").action(async()=>{await Vi()});W.command("init").description(`Create a new ${f.name} Project`).action(async()=>{de(re.bgCyan.black(f.cliTag("Init Project"))),await xi()});W.command("env").description("Manage Environment Variables").argument("<action>","Action to perform: set or list").argument("[args...]","Key=Value pairs for set action").action(async(e,n)=>{de(re.bgCyan.black(f.cliTag("Env Manager"))),await Mi(e,n)});W.command("start").description("Start the development server (Metro)").option("-p, --build-profile <name>","Build profile (e.g. development, staging)","development").option("--tunnel","Use ngrok tunnel").option("--lan","Use LAN IP").option("--localhost","Use localhost").option("-c, --clear","Clear Metro cache").option("--port <number>","Port to listen on").option("--ios","Start on iOS").option("--android","Start on Android").option("--web","Start on Web").action(async e=>{de(re.bgCyan.black(f.cliTag("Dev Server"))),await qi(e)});W.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 Ji(e)});W.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:n}=await import("./credentials-RNU5D7E7.js");await n(e)});W.command("credentials:setup").description("Automated credential provisioning (iOS/Android) [Legacy]").requiredOption("--platform <os>","Platform: ios or android").option("--profile <name>","Build profile (production, staging, development)").option("--bundle-id <id>","Bundle ID / Package Name (optional, auto-detected)").option("--team-id <id>","Apple Team ID (iOS only)").option("--key-alias <alias>","Android keystore alias (optional, auto-generated)").option("--aws-profile <name>","AWS Credentials Profile (for S3 storage)").option("--force","Force recreate certificates (nuke existing on Apple Portal)",!1).action(async e=>{de(re.bgCyan.black(f.cliTag("Credentials Setup"))),await Je(e),Tn(re.green("Done!"))});W.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)").action(async e=>{de(re.bgCyan.black(f.cliTag("Service Credentials"))),await ci(e),Tn(re.green("Done!"))});var oi=W.command("device").description("Manage registered iOS test devices");oi.command("register").description("Register a connected iOS device or enter UDID manually").option("--udid <udid>","Device UDID (skip auto-detection)").option("--name <name>","Device name").action(async e=>{await _t("register",e)});oi.command("list").description("List all registered devices").action(async()=>{await _t("list",{})});oi.command("remove").description("Remove a registered device").option("--udid <udid>","Device UDID to remove").action(async e=>{await _t("remove",e)});W.command("audit").description("Run automated security audit on the project or APK").option("--apk <path>","Path to APK file (runs APK diagnostics like 16KB alignment)").option("--json","Output results as JSON (for CI/CD)").option("--fix","Auto-apply fixes where possible").option("--category <name>","Run only a specific check category (e.g. 16kb, permissions, secrets)").option("--severity <level>","Minimum severity to display (critical, high, medium, low, info)").option("--prebuild","Run expo prebuild for deeper manifest/plist analysis").action(async e=>{de(re.bgCyan.black(f.cliTag(e.apk?"APK Audit":"Security Audit"))),await Rn(e)});var ts=new Set(["login"]);W.hook("preAction",(e,n)=>{let t=n.name();ts.has(t)||si()});W.on("command:*",()=>{console.error(`Invalid command: %s
|
|
822
|
-
See --help for a list of available commands.`,
|
|
1027
|
+
`),"Registered Devices")}catch(n){e.stop(W.red("Failed to fetch devices")),_e.error(n.response?.data?.message||n.message)}pt(W.blue("---"))}async function gr(e){let n=e.udid;if(!n){let o=ut();o.start("Fetching registered devices...");try{let c=(await D.get("/devices")).data.devices||[];if(o.stop(`${c.length} device(s) found`),c.length===0){_e.info(W.dim("No devices to remove.")),pt(W.blue("---"));return}let a=await rn({message:"Select device to remove:",options:c.map(s=>({value:s.udid,label:s.name,hint:s.udid.substring(0,12)+"..."}))});if(lt(a)){dt("Cancelled");return}n=a}catch(r){o.stop(W.red("Failed to fetch devices")),_e.error(r.response?.data?.message||r.message);return}}let t=await lr({message:`Remove device ${W.dim(n.substring(0,12)+"...")}?`});if(lt(t)||!t){dt("Cancelled");return}let i=ut();i.start("Removing device...");try{await D.delete(`/devices/${encodeURIComponent(n)}`),i.stop(W.green("Device removed"))}catch(o){i.stop(W.red("Failed to remove device")),_e.error(o.response?.data?.message||o.message)}pt(W.blue("---"))}async function Rt(e,n){switch(e){case"register":await fr(n);break;case"list":await mr();break;case"remove":await gr(n);break;default:_e.error(`Unknown action: ${e}`)}}import{log as Ee,spinner as kn}from"@clack/prompts";import Pe from"chalk";import Ut from"path";import gt from"fs";import Jr from"os";import qr from"axios";var Se=(r=>(r.CRITICAL="critical",r.HIGH="high",r.MEDIUM="medium",r.LOW="low",r.INFO="info",r))(Se||{}),$e=(s=>(s.PERMISSIONS="permissions",s.SECRETS="secrets",s.DEPENDENCIES="dependencies",s.STORAGE="storage",s.NETWORK="network",s.DEBUG="debug",s.MANIFEST="manifest",s.ATS="ats",s))($e||{});import{spinner as $n,log as mt}from"@clack/prompts";import me from"chalk";import{execSync as Fr}from"child_process";import Pn from"fs";import Dn from"path";import Ue from"fs";import ft from"path";import{execSync as hr}from"child_process";var sn={"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"}},yr={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 Sr(e){try{let t=hr("npx expo config --type introspect --json 2>/dev/null",{cwd:e,encoding:"utf-8",timeout:3e4});return JSON.parse(t)}catch{}let n=ft.join(e,"app.json");if(Ue.existsSync(n))try{let t=JSON.parse(Ue.readFileSync(n,"utf-8"));return t.expo||t}catch{}return null}function Er(e){let n=[],t=ft.join(e,"node_modules");if(!Ue.existsSync(t))return n;let i=/<uses-permission\s+android:name="([^"]+)"/g;function o(r,c){let a=ft.join(r,"android","src","main","AndroidManifest.xml");if(!Ue.existsSync(a))return;let s=Ue.readFileSync(a,"utf-8"),d;for(;(d=i.exec(s))!==null;)n.push({pkg:c,permission:d[1]});i.lastIndex=0}for(let r of Ue.readdirSync(t)){if(r.startsWith("."))continue;let c=ft.join(t,r);if(r.startsWith("@")){if(!Ue.statSync(c).isDirectory())continue;for(let a of Ue.readdirSync(c))o(ft.join(c,a),`${r}/${a}`)}else o(c,r)}return n}async function an(e,n){let t=[],i=1,o=Sr(e),r=o?.android?.permissions||[],c=o?.android?.blockedPermissions||[];for(let d of r){let l=sn[d];l&&t.push({id:`PERM-${String(i++).padStart(3,"0")}`,title:`${d.split(".").pop()} declared`,description:l.description,severity:l.severity,category:"permissions",file:"app.config.ts",recommendation:"Remove from permissions if not needed, or add justification."})}let a=Er(e);for(let{pkg:d,permission:l}of a){let u=sn[l];u&&(c.includes(l)||r.includes(l)||t.push({id:`PERM-${String(i++).padStart(3,"0")}`,title:`${l.split(".").pop()} injected by ${d}`,description:`${u.description}. Auto-injected via ${d} AndroidManifest.xml`,severity:u.severity,category:"permissions",file:`node_modules/${d}/android/src/main/AndroidManifest.xml`,recommendation:`Add "${l}" to blockedPermissions if not needed.`,autoFixable:!0}))}let s=o?.ios?.infoPlist||{};for(let[d,l]of Object.entries(yr))d in s&&t.push({id:`PERM-${String(i++).padStart(3,"0")}`,title:`iOS: ${d} declared`,description:l.description,severity:l.severity,category:"permissions",file:"app.config.ts",recommendation:`Remove ${d} from infoPlist if the app does not use this capability.`});return{category:"permissions",label:"Permission Audit",findings:t,durationMs:0}}import oi from"fs";import wt from"path";var Ar=[{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"}],Ir=new Set([".ts",".tsx",".js",".jsx"]),br=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function cn(e){let n=[],t=oi.readdirSync(e,{withFileTypes:!0});for(let i of t){if(br.has(i.name))continue;let o=wt.join(e,i.name);i.isDirectory()?n.push(...cn(o)):Ir.has(wt.extname(i.name))&&n.push(o)}return n}function _r(e){let n=e.trim();return n.startsWith("//")||n.startsWith("*")||n.startsWith("/*")}function $r(e){return/process\.env\./i.test(e)||/import\.meta\.env/i.test(e)}async function ln(e,n){let t=[],i=wt.join(e,"src"),o=oi.existsSync(i)?i:e,r=cn(o);for(let c of r){let s=oi.readFileSync(c,"utf-8").split(`
|
|
1028
|
+
`),d=wt.relative(e,c);for(let l=0;l<s.length;l++){let u=s[l];if(!_r(u)&&!$r(u))for(let{id:p,pattern:g,severity:m,label:E}of Ar)g.lastIndex=0,g.test(u)&&t.push({id:p,title:E,description:`Potential ${E.toLowerCase()} found in source code`,severity:m,category:"secrets",file:d,line:l+1,recommendation:`Move to environment variables or a secrets manager. Use \`${f.nameLower} env set\` for managed secrets.`})}}return{category:"secrets",label:"Secrets Detection",findings:t,durationMs:0}}import{execSync as Pr}from"child_process";var Dr={critical:"critical",high:"high",moderate:"medium",low:"low",info:"info"};async function dn(e,n){let t=[],i=1,o;try{o=Pr("npm audit --json 2>/dev/null",{cwd:e,encoding:"utf-8",timeout:6e4})}catch(a){if(o=a.stdout||"",!o)return{category:"dependencies",label:"Dependency CVEs",findings:[],durationMs:0,error:"Failed to run npm audit. Ensure npm is available and dependencies are installed."}}let r;try{r=JSON.parse(o)}catch{return{category:"dependencies",label:"Dependency CVEs",findings:[],durationMs:0,error:"Failed to parse npm audit output."}}let c=r.vulnerabilities||{};for(let[a,s]of Object.entries(c)){let d=Dr[s.severity]||"info",l=Array.isArray(s.via)?s.via.map(u=>typeof u=="string"?u:u.title||u.name).join(", "):String(s.via);t.push({id:`DEP-${String(i++).padStart(3,"0")}`,title:`${a} \u2014 ${s.severity}`,description:`Via: ${l}. Range: ${s.range||"unknown"}`,severity:d,category:"dependencies",recommendation:s.fixAvailable?`Run \`npm audit fix\` or update ${a} to a patched version.`:"No fix available yet. Monitor for updates or evaluate alternatives.",autoFixable:!!s.fixAvailable})}return{category:"dependencies",label:"Dependency CVEs",findings:t,durationMs:0}}import vt from"fs";import Ot from"path";var Rr=/(?:token|password|credential|secret|apiKey|api_key|session|auth|jwt|refresh_token|access_token|private_key|pin|otp)/i,un=/AsyncStorage\s*\.\s*(?:setItem|mergeItem)\s*\(\s*['"`]([^'"`]+)['"`]/g,wr=/from\s+['"]@react-native-async-storage\/async-storage['"]|from\s+['"]react-native['"].*AsyncStorage/,vr=new Set([".ts",".tsx",".js",".jsx"]),Or=new Set(["node_modules",".expo",".git","android","ios","dist","build"]);function pn(e){let n=[];if(!vt.existsSync(e))return n;let t=vt.readdirSync(e,{withFileTypes:!0});for(let i of t){if(Or.has(i.name))continue;let o=Ot.join(e,i.name);i.isDirectory()?n.push(...pn(o)):vr.has(Ot.extname(i.name))&&n.push(o)}return n}async function fn(e,n){let t=[],i=1,o=Ot.join(e,"src"),r=vt.existsSync(o)?o:e,c=pn(r);for(let a of c){let s=vt.readFileSync(a,"utf-8");if(!wr.test(s))continue;let d=s.split(`
|
|
1029
|
+
`),l=Ot.relative(e,a);for(let u=0;u<d.length;u++){let p=d[u];un.lastIndex=0;let g;for(;(g=un.exec(p))!==null;){let m=g[1];Rr.test(m)&&t.push({id:`STOR-${String(i++).padStart(3,"0")}`,title:`AsyncStorage used for "${m}"`,description:`Sensitive data key "${m}" stored in AsyncStorage (unencrypted).`,severity:"high",category:"storage",file:l,line:u+1,recommendation:"Use expo-secure-store (SecureStore) for sensitive data instead of AsyncStorage."})}}}return{category:"storage",label:"Insecure Storage",findings:t,durationMs:0}}import Ct from"fs";import Nt from"path";var mn=/['"`](http:\/\/(?!localhost|127\.0\.0\.1|10\.|192\.168\.|0\.0\.0\.0|172\.(?:1[6-9]|2\d|3[01])\.)[^'"`\s]+)['"`]/g,Cr=/\/api\/|\/v[0-9]+\/|\/graphql|\/rest\//i,Nr=new Set([".ts",".tsx",".js",".jsx"]),Tr=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function gn(e){let n=[];if(!Ct.existsSync(e))return n;let t=Ct.readdirSync(e,{withFileTypes:!0});for(let i of t){if(Tr.has(i.name))continue;let o=Nt.join(e,i.name);i.isDirectory()?n.push(...gn(o)):Nr.has(Nt.extname(i.name))&&n.push(o)}return n}async function hn(e,n){let t=[],i=1,o=Nt.join(e,"src"),r=Ct.existsSync(o)?o:e,c=gn(r);for(let a of c){let d=Ct.readFileSync(a,"utf-8").split(`
|
|
1030
|
+
`),l=Nt.relative(e,a);for(let u=0;u<d.length;u++){let p=d[u],g=p.trim();if(g.startsWith("//")||g.startsWith("*"))continue;mn.lastIndex=0;let m;for(;(m=mn.exec(p))!==null;){let E=m[1],R=Cr.test(E);t.push({id:`NET-${String(i++).padStart(3,"0")}`,title:`Insecure HTTP URL${R?" (API endpoint)":""}`,description:`Plain HTTP URL found: ${E}`,severity:R?"high":"medium",category:"network",file:l,line:u+1,recommendation:"Use HTTPS instead of HTTP for all network requests."})}}}return{category:"network",label:"HTTP URLs",findings:t,durationMs:0}}import Tt from"fs";import kt from"path";var yn=/(?:debug|debugMode|devMode|enableDebug)\s*[:=]\s*true/gi,Sn=/console\.(?:log|warn|info|debug)\s*\([^)]*(?:token|password|secret|credential|key|auth)/gi,kr=new Set([".ts",".tsx",".js",".jsx"]),xr=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function En(e){let n=[];if(!Tt.existsSync(e))return n;let t=Tt.readdirSync(e,{withFileTypes:!0});for(let i of t){if(xr.has(i.name))continue;let o=kt.join(e,i.name);i.isDirectory()?n.push(...En(o)):kr.has(kt.extname(i.name))&&n.push(o)}return n}async function An(e,n){let t=[],i=1,o=kt.join(e,"src"),r=Tt.existsSync(o)?o:e,c=En(r);for(let a of c){let d=Tt.readFileSync(a,"utf-8").split(`
|
|
1031
|
+
`),l=kt.relative(e,a);for(let u=0;u<d.length;u++){let p=d[u],g=p.trim();if(!(g.startsWith("//")||g.startsWith("*"))&&(yn.lastIndex=0,yn.test(p)&&t.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:l,line:u+1,recommendation:"Use __DEV__ or environment variables instead of hardcoded debug flags."}),Sn.lastIndex=0,Sn.test(p))){let m=d.slice(Math.max(0,u-3),u).join(`
|
|
1032
|
+
`);/__DEV__/.test(m)||t.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:l,line:u+1,recommendation:"Wrap in __DEV__ check or remove sensitive data from console output."})}}}return{category:"debug",label:"Debug/Dev Flags",findings:t,durationMs:0}}import In from"fs";import ri from"path";var Lr=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 Ur(e){let n=[ri.join(e,"android","app","src","main","AndroidManifest.xml"),ri.join(e,"android","AndroidManifest.xml")];for(let t of n)if(In.existsSync(t))return t;return null}async function bn(e,n){let t=[],i=1,o=Ur(e);if(!o)return{category:"manifest",label:"Android Manifest",findings:[],durationMs:0,error:"No AndroidManifest.xml found. Run with --prebuild or run `expo prebuild` first."};let r=In.readFileSync(o,"utf-8"),c=ri.relative(e,o),a=/<(activity|service|receiver|provider)\s+([^>]*?)(?:\/>|>)/gs,s;for(;(s=a.exec(r))!==null;){let d=s[1],l=s[2],p=l.match(/android:name="([^"]+)"/)?.[1]||"unknown";if(Lr.has(p))continue;let g=/android:exported="true"/.test(l),m=/android:permission="/.test(l);g&&!m&&t.push({id:`MAN-${String(i++).padStart(3,"0")}`,title:`Exported ${d}: ${p.split(".").pop()}`,description:`${p} is exported=true without android:permission protection`,severity:"medium",category:"manifest",file:c,recommendation:'Set android:exported="false" or add an android:permission attribute.'})}return/android:allowBackup="true"/.test(r)&&t.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:c,recommendation:'Set android:allowBackup="false" via expo-build-properties plugin.',autoFixable:!0}),/android:debuggable="true"/.test(r)&&t.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:c,recommendation:"Ensure debuggable is false for production builds. This is usually set automatically for release builds."}),{category:"manifest",label:"Android Manifest",findings:t,durationMs:0}}import xt from"fs";import si from"path";function Mr(e){let n=si.join(e,"ios");if(!xt.existsSync(n))return null;let t=xt.readdirSync(n,{withFileTypes:!0});for(let i of t){if(!i.isDirectory()||i.name==="Pods"||i.name.startsWith("."))continue;let o=si.join(n,i.name,"Info.plist");if(xt.existsSync(o))return o}return null}async function _n(e,n){let t=[],i=1,o=Mr(e);if(!o)return{category:"ats",label:"iOS ATS Config",findings:[],durationMs:0,error:"No Info.plist found. Run with --prebuild or run `expo prebuild` first."};let r=xt.readFileSync(o,"utf-8"),c=si.relative(e,o),a=r.match(/<key>NSAppTransportSecurity<\/key>\s*<dict>([\s\S]*?)<\/dict>/);if(a){let s=a[1];/<key>NSAllowsArbitraryLoads<\/key>\s*<true\s*\/>/.test(s)&&t.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:c,recommendation:"Remove NSAllowsArbitraryLoads or set to false. Use domain-specific exceptions only if absolutely necessary."});let d=s.match(/<key>NSExceptionDomains<\/key>\s*<dict>([\s\S]*?)<\/dict>/);if(d){let l=d[1].match(/<key>([^<]+)<\/key>/g);if(l)for(let u of l){let p=u.replace(/<\/?key>/g,"");p!=="NSExceptionDomains"&&t.push({id:`ATS-${String(i++).padStart(3,"0")}`,title:`ATS exception: ${p}`,description:`ATS exception configured for ${p}`,severity:"low",category:"ats",file:c,recommendation:`Verify that the ATS exception for ${p} is necessary. Use HTTPS where possible.`})}}}return{category:"ats",label:"iOS ATS Config",findings:t,durationMs:0}}var Hr=[{category:"permissions",label:"Permission Audit",fn:an,requiresPrebuild:!1},{category:"secrets",label:"Secrets Detection",fn:ln,requiresPrebuild:!1},{category:"dependencies",label:"Dependency CVEs",fn:dn,requiresPrebuild:!1},{category:"storage",label:"Insecure Storage",fn,requiresPrebuild:!1},{category:"network",label:"HTTP URLs",fn:hn,requiresPrebuild:!1},{category:"debug",label:"Debug/Dev Flags",fn:An,requiresPrebuild:!1},{category:"manifest",label:"Android Manifest",fn:bn,requiresPrebuild:!0},{category:"ats",label:"iOS ATS Config",fn:_n,requiresPrebuild:!0}];async function Rn(e,n){let t=Hr;n.category&&(t=t.filter(c=>c.category===n.category),t.length===0&&(mt.error(me.red(`Unknown category: ${n.category}`)),mt.info(me.dim(`Available: ${Object.values($e).join(", ")}`)),process.exit(1)));let i=t.filter(c=>!c.requiresPrebuild),o=t.filter(c=>c.requiresPrebuild),r=[];for(let c of i){let a=$n();a.start(me.dim(`Running ${c.label}...`));try{let s=Date.now(),d=await c.fn(e,n);d.durationMs=Date.now()-s,r.push(d);let l=d.findings.length;a.stop(l>0?me.yellow(`${c.label} \u2014 ${l} finding(s)`):me.green(`${c.label} \u2014 clean`))}catch(s){a.stop(me.red(`${c.label} \u2014 error`)),r.push({category:c.category,label:c.label,findings:[],durationMs:0,error:s.message})}}if(o.length>0){let c=Dn.join(e,"android"),a=Dn.join(e,"ios"),s=Pn.existsSync(c)||Pn.existsSync(a);if(!s&&n.prebuild){n.json||mt.info(me.dim(`
|
|
1033
|
+
Running expo prebuild for deeper analysis...`));try{Fr("npx expo prebuild --no-install",{cwd:e,stdio:"pipe"})}catch{return mt.warn(me.yellow("Prebuild failed \u2014 skipping manifest/plist checks.")),r}}else if(!s)return n.json||mt.info(me.dim(`
|
|
1034
|
+
Skipping manifest/plist checks \u2014 no android/ios dirs. Use --prebuild to generate them.`)),r;for(let d of o){let l=$n();l.start(me.dim(`Running ${d.label}...`));try{let u=Date.now(),p=await d.fn(e,n);p.durationMs=Date.now()-u,r.push(p);let g=p.findings.length;l.stop(g>0?me.yellow(`${d.label} \u2014 ${g} finding(s)`):me.green(`${d.label} \u2014 clean`))}catch(u){l.stop(me.red(`${d.label} \u2014 error`)),r.push({category:d.category,label:d.label,findings:[],durationMs:0,error:u.message})}}}return r}import te from"chalk";import{log as Q}from"@clack/prompts";var We={critical:te.bgRed.white.bold,high:te.red.bold,medium:te.yellow.bold,low:te.blue,info:te.dim},Lt={critical:0,high:1,medium:2,low:3,info:4};function Br(e,n){if(!n)return!0;let t=Lt[n];return t===void 0?!0:Lt[e]<=t}function wn(e,n){let t=0,i={critical:0,high:0,medium:0,low:0,info:0};for(let c of e){let a=c.findings.filter(d=>Br(d.severity,n));if(a.length===0&&!c.error)continue;if(Q.info(""),Q.info(te.bold(` ${c.label}`)+te.dim(` ${a.length} finding(s)`)),Q.info(te.dim(" "+"\u2500".repeat(60))),c.error){Q.error(te.red(` Error: ${c.error}`));continue}let s=[...a].sort((d,l)=>Lt[d.severity]-Lt[l.severity]);for(let d of s){let l=We[d.severity](` ${d.severity.toUpperCase()} `);Q.info(` ${l} ${te.bold(d.id)} ${d.title}`),Q.info(te.dim(` ${d.description}`)),d.file&&Q.info(te.dim(` File: ${d.file}${d.line?`:${d.line}`:""}`)),Q.info(te.cyan(` Fix: ${d.recommendation}`)),Q.info(""),i[d.severity]++,t++}}Q.info(""),Q.info(te.bold(" Summary")),Q.info(te.dim(" "+"\u2500".repeat(60))),Q.info(` Total: ${te.bold(String(t))} finding(s)`),Q.info(` ${We.critical(` ${i.critical} Critical `)} ${We.high(` ${i.high} High `)} ${We.medium(` ${i.medium} Medium `)} ${We.low(` ${i.low} Low `)} ${We.info(` ${i.info} Info `)}`);let o=i.critical>0,r=i.high>0;o||r?(Q.info(""),Q.error(te.red.bold(` FAIL \u2014 ${i.critical} critical, ${i.high} high issue(s) found`))):t>0?(Q.info(""),Q.warn(te.yellow(" PASS (with warnings) \u2014 no critical or high issues"))):(Q.info(""),Q.success(te.green.bold(" PASS \u2014 no issues found")))}function vn(e,n){let t=e.flatMap(o=>o.findings),i={};for(let o of Object.values(Se))i[o]=t.filter(r=>r.severity===o).length;return{version:"1.0.0",timestamp:new Date().toISOString(),project:n.name||"unknown",projectVersion:n.version||"0.0.0",summary:{total:t.length,...i},passed:i.critical===0&&i.high===0,checks:e.map(o=>({category:o.category,label:o.label,findingCount:o.findings.length,durationMs:o.durationMs,error:o.error||null})),findings:t}}import{log as ee,spinner as Gr}from"@clack/prompts";import X from"chalk";import Ce from"fs";import jr from"os";import Ye from"path";import{execSync as Kr}from"child_process";var On=16384,zr=1,Vr=Buffer.from([127,69,76,70]);async function Cn(e){ee.info(X.bold.underline("16KB Page Alignment Check")),console.log("");let n=Ye.resolve(e);if(!Ce.existsSync(n))return ee.error(X.red(`APK file not found: ${n}`)),!1;if(!n.endsWith(".apk"))return ee.error(X.red("The provided file is not an APK file.")),!1;let t=Gr();t.start("Extracting and analyzing native libraries...");let i=Ce.mkdtempSync(Ye.join(jr.tmpdir(),"mach-16kb-"));try{try{Kr(`unzip -o -q "${n}" "lib/arm64-v8a/*.so" "lib/x86_64/*.so" -d "${i}" 2>/dev/null`,{encoding:"utf-8",maxBuffer:50*1024*1024})}catch{}let o=Nn(Ye.join(i,"lib"));if(o.length===0)return t.stop("Analysis complete."),ee.info(X.yellow("No arm64-v8a or x86_64 native libraries found in the APK.")),ee.info(X.dim("16KB alignment check only applies to arm64-v8a and x86_64 architectures.")),!0;let r=[];for(let s of o){let d=Ye.relative(i,s),l=Yr(d),u=Ye.basename(s),p=Wr(s);p!==null&&r.push({name:u,filePath:d,arch:l,align:p,compatible:p>=On})}if(t.stop("Analysis complete."),r.length===0)return ee.info(X.yellow("No valid ELF shared libraries found.")),!0;let c=r.filter(s=>!s.compatible),a=r.filter(s=>s.compatible);if(ee.info(X.dim(`Checked ${r.length} native librar${r.length===1?"y":"ies"}
|
|
1035
|
+
`)),c.length>0){ee.info(X.red.bold(`Incompatible libraries:
|
|
1036
|
+
`));for(let s of c)ee.error(X.red(`${X.bold(s.name)} ${X.dim(`(${s.arch})`)}`)),ee.info(X.dim(` PT_LOAD alignment: 2**${Math.log2(s.align)} (${s.align} bytes, needs 2**14 = ${On})`))}return a.length>0&&(console.log(""),ee.success(X.green(`${a.length} librar${a.length===1?"y":"ies"} correctly aligned (2**14 or higher).`))),console.log(""),c.length===0?(ee.success(X.green.bold("ELF Verification Successful. APK is 16KB compatible.")),!0):(ee.error(X.red.bold(`Found ${c.length} unaligned lib${c.length===1?"":"s"} (arm64-v8a/x86_64 libs need to be aligned).`)),console.log(""),ee.info(X.yellow("To fix this:")),ee.info(X.dim(" 1. Rebuild with NDK r28+ which defaults to 16KB page alignment")),ee.info(X.dim(" 2. Or set -DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON in CMake")),ee.info(X.dim(" 3. Update third-party libraries that ship prebuilt .so files")),ee.info(X.dim(" 4. After rebuilding: zipalign -p -f -v 16 input.apk output.apk")),console.log(""),ee.info(X.dim("Reference: https://developer.android.com/guide/practices/page-sizes")),!1)}catch(o){return t.stop("Analysis failed."),ee.error(X.red(`Failed to analyze APK: ${o.message}`)),!1}finally{try{Ce.rmSync(i,{recursive:!0,force:!0})}catch{}}}function Wr(e){let n=Ce.openSync(e,"r");try{let t=Buffer.alloc(64);if(Ce.readSync(n,t,0,64,0),!t.subarray(0,4).equals(Vr))return null;let i=t[4]===2,o=t[5]===1,r=(p,g)=>o?p.readUInt16LE(g):p.readUInt16BE(g),c=(p,g)=>o?p.readUInt32LE(g):p.readUInt32BE(g),a=(p,g)=>Number(o?p.readBigUInt64LE(g):p.readBigUInt64BE(g)),s,d,l;i?(s=a(t,32),d=r(t,54),l=r(t,56)):(s=c(t,28),d=r(t,42),l=r(t,44));let u=null;for(let p=0;p<l;p++){let g=Buffer.alloc(d);if(Ce.readSync(n,g,0,d,s+p*d),c(g,0)!==zr)continue;let E;i?E=a(g,48):E=c(g,28),E>0&&(u===null||E<u)&&(u=E)}return u??0}catch{return null}finally{Ce.closeSync(n)}}function Nn(e){let n=[];if(!Ce.existsSync(e))return n;let t=Ce.readdirSync(e,{withFileTypes:!0});for(let i of t){let o=Ye.join(e,i.name);i.isDirectory()?n.push(...Nn(o)):i.name.endsWith(".so")&&n.push(o)}return n}function Yr(e){return e.includes("arm64-v8a")?"arm64-v8a":e.includes("x86_64")?"x86_64":"unknown"}var xn=async e=>{if(pe()||(Ee.error(Pe.red(`You are not logged in. Run \`${f.nameLower} login\` first.`)),process.exit(1)),e.apk){await Xr(e);return}let t=process.cwd(),i=Ut.join(t,"package.json");gt.existsSync(i)||(Ee.error(Pe.red("No package.json found. Run this command from a project root.")),process.exit(1));let o=JSON.parse(gt.readFileSync(i,"utf-8")),r=!!(o.dependencies?.expo||o.devDependencies?.expo);e.json||(Ee.info(Pe.dim(`Project: ${o.name||"unknown"} v${o.version||"0.0.0"}`)),Ee.info(Pe.dim(`Type: ${r?"Expo":"Bare React Native"}`)),Ee.info(""));let c={json:e.json,fix:e.fix,category:e.category,severity:e.severity,prebuild:e.prebuild},a=await Rn(t,c);e.json?console.log(JSON.stringify(vn(a,o),null,2)):wn(a,e.severity);let s=a.some(l=>l.findings.some(u=>u.severity==="critical")),d=a.some(l=>l.findings.some(u=>u.severity==="high"));(s||d)&&process.exit(1)},Tn=["16kb"];async function Xr(e){let n=e.category?.toLowerCase();n&&!Tn.includes(n)&&(Ee.error(Pe.red(`Unknown APK check category: "${n}"`)),Ee.info(Pe.dim(`Available APK checks: ${Tn.join(", ")}`)),process.exit(1));let t=await Zr(e.apk);t||process.exit(1);let i=!n,o=!1;(i||n==="16kb")&&(await Cn(t)||(o=!0)),o&&process.exit(1)}async function Zr(e){if(e.startsWith("build:")){let t=e.slice(6);return await Qr(t)}if(e.startsWith("http://")||e.startsWith("https://"))return await Ln(e);let n=Ut.resolve(e);return gt.existsSync(n)?n:(Ee.error(Pe.red(`APK file not found: ${n}`)),null)}async function Qr(e){let n=kn();n.start(`Fetching APK from build ${e}...`);try{let t=await D.get(`/build/${e}`);if(t.data.status!=="success")throw new Error(t.data.message);let i=t.data.build;if(!i)throw new Error("Build not found");let o=i.artifacts?.find(r=>r.type?r.type==="apk":r.name?.endsWith(".apk")||r.url?.includes(".apk"));return!o||!o.url?(n.stop("No APK artifact found"),Ee.error(Pe.red("This build does not have an APK artifact.")),Ee.info(Pe.dim("Make sure the build produced an APK (not just an AAB).")),null):(n.stop(`Found build: ${i.buildId||e}`),await Ln(o.url))}catch(t){return n.stop("Failed to fetch build"),Ee.error(Pe.red(t.message)),null}}async function Ln(e){let n=kn();n.start("Downloading APK...");try{let t=gt.mkdtempSync(Ut.join(Jr.tmpdir(),`${f.nameLower}-audit-`)),i=Ut.join(t,"app.apk"),o=await qr.get(e,{responseType:"arraybuffer"});gt.writeFileSync(i,o.data);let r=(o.data.length/(1024*1024)).toFixed(1);return n.stop(`Downloaded APK (${r} MB)`),i}catch(t){return n.stop("Download failed"),Ee.error(Pe.red(`Failed to download APK: ${t.message}`)),null}}var is=console.log;console.log=()=>{};ts();console.log=is;ue(ae.bgCyan.black(f.cliTag("Production Build Orchestrator")));var os=ns(import.meta.url),rs=os("../package.json"),Y=new es;Y.name(f.nameLower).description(`${f.name} CLI: Powerful Cloud Infrastructure Tools`).version(rs.version).option("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1);Y.command("agent").description("Start local device discovery agent for the Install Hub (port 7070)").action(async()=>{await ki()});Y.command("host").description("Setup AWS S3 static hosting and CloudFront").action(async()=>{ue(ae.bgCyan.black(f.cliTag("Hosting"))),await pi()});Y.command("sitemap").description("Generate sitemap.xml from Expo Router app structure").option("-o, --output <path>","Output path for sitemap.xml","./public/sitemap.xml").action(async e=>{ue(ae.bgCyan.black(f.cliTag("Sitemap Generator"))),await hi(e)});Y.command("build").description("Run a build on a cloud provider (AWS Spot Instances)").argument("[platform]","Target platform (android, ios)").option("--platform <os>","Target platform alias (android, ios) [Optional]").option("--repo <url>","Git Repository URL").option("--branch <name>","Git Branch").option("--ami <id>","AMI ID").option("--bucket <name>","S3 Bucket for artifacts").option("--region <region>","AWS Region").option("--aws-profile <name>","AWS Credentials Profile").option("-p, --build-profile <name>","Build Profile (e.g. production, staging)","production").option("--profile <name>","Build Profile (alias for --build-profile)").option("--dry-run","Generate User Data script without launching").option("--keep-instance","Do not terminate the instance after build").option("--subnet <id>","VPC Subnet ID to launch the instance in").option("--security-group <id>","VPC Security Group ID to use").option("--ssh-host <host>","Remote host for iOS build (SSH)").option("--ssh-user <user>","SSH username for remote host").option("--ssh-key <path>","Path to private SSH key for remote host").option("--ios-scheme <scheme>","iOS Scheme to build").option("--ios-team-id <id>","Apple Development Team ID").option("--ios-configuration <config>","Xcode configuration (Release/Debug)").option("--ios-export-method <method>","Export method (ad-hoc, app-store, development, enterprise)").option("--ios-api-key-id <id>","App Store Connect API Key ID").option("--ios-api-key-issuer <id>","App Store Connect API Key Issuer ID").option("--ios-api-key-path <path>","Path to App Store Connect API Key (.p8) file").option("--simulator","Build for iOS Simulator (no signing required)").addOption(new Un("--build-id <id>","Internal build ID").hideHelp()).addOption(new Un("--project-id <id>","Internal project ID").hideHelp()).option("--local","Run build on local machine").option("--auto-version","Automatically fetch and increment versionCode from Google Play").option("--verbose","Enable verbose logging").option("--json-output <path>","Write build metadata JSON to a file for CI/CD").option("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1).action(async(e,n)=>{let t=Y.opts();n.yes=n.yes||t.yes,n.quiet=n.quiet||t.quiet,n.platform=e||n.platform,n.buildProfile=n.profile||n.buildProfile,n.quiet||ue(ae.bgCyan.black(f.cliTag("Cloud Build"))),await It(n)});Y.command("update").description("Deploy an Over-The-Air (OTA) update to your live channel").option("--branch <name>","Channel or Branch to deploy to (e.g., production)","production").action(async e=>{ue(ae.bgCyan.black(f.cliTag("OTA Update"))),await Ji(e)});Y.command("submit").description("Automated Store Submission (App Store / Google Play)").option("--platform <os>","Target platform (ios/android)").option("-p, --profile <name>","Build/submission profile to submit from (e.g. production, preprod)").option("--track <track>","Google Play Track (internal, alpha, beta, production)").option("--latest","Use the latest successful build for submission").option("--build-id <id>","Use a specific build ID for submission").action(async e=>{ue(ae.bgCyan.black(f.cliTag("Store Submission"))),await Wi(e)});Y.command("login").description(`Login to ${f.name} Dashboard`).action(async()=>{ue(ae.bgCyan.black(f.cliTag("Login"))),await Mi()});Y.command("link").description(`Link local directory to a ${f.name} Project`).action(async()=>{ue(ae.bgCyan.black(f.cliTag("Link Project"))),await Fi()});Y.command("me").description("Display currently logged in user details").action(async()=>{await Xi()});Y.command("init").description(`Create a new ${f.name} Project`).action(async()=>{ue(ae.bgCyan.black(f.cliTag("Init Project"))),await Hi()});Y.command("env").description("Manage Environment Variables").argument("<action>","Action to perform: set or list").argument("[args...]","Key=Value pairs for set action").action(async(e,n)=>{ue(ae.bgCyan.black(f.cliTag("Env Manager"))),await ji(e,n)});Y.command("start").description("Start the development server (Metro)").option("-p, --build-profile <name>","Build profile (e.g. development, staging)","development").option("--tunnel","Use ngrok tunnel").option("--lan","Use LAN IP").option("--localhost","Use localhost").option("-c, --clear","Clear Metro cache").option("--port <number>","Port to listen on").option("--ios","Start on iOS").option("--android","Start on Android").option("--web","Start on Web").action(async e=>{ue(ae.bgCyan.black(f.cliTag("Dev Server"))),await tn(e)});Y.command("config").description("Show resolved configuration for a profile").option("-p, --profile <name>","Build profile to resolve","development").option("--json","Output as JSON").action(async e=>{await nn(e)});Y.command("credentials").description("Unified, interactive credential management (iOS/Android)").option("-p, --profile <name>","Build profile (production, staging, development)").option("--force","Force recreate certificates (nuke existing on Apple Portal)",!1).action(async e=>{let{credentialsMainCommand:n}=await import("./credentials-XU7FSPK4.js");await n(e)});Y.command("credentials:setup").description("Automated credential provisioning (iOS/Android) [Legacy]").requiredOption("--platform <os>","Platform: ios or android").option("--profile <name>","Build profile (production, staging, development)").option("--bundle-id <id>","Bundle ID / Package Name (optional, auto-detected)").option("--team-id <id>","Apple Team ID (iOS only)").option("--key-alias <alias>","Android keystore alias (optional, auto-generated)").option("--aws-profile <name>","AWS Credentials Profile (for S3 storage)").option("--force","Force recreate certificates (nuke existing on Apple Portal)",!1).action(async e=>{ue(ae.bgCyan.black(f.cliTag("Credentials Setup"))),await qe(e),Mn(ae.green("Done!"))});Y.command("credentials:service").description("Upload Service Credentials (ASC API Key / Google Service JSON) [Legacy]").requiredOption("--platform <os>","Platform: ios or android").option("--file <path>","Path to credential file (.p8 or .json)").option("--issuer-id <id>","ASC API Key Issuer ID (iOS only)").option("--key-id <id>","ASC API Key ID (iOS only)").option("--bundle-id <id>","Bundle identifier / Android package name to attach this service credential to").option("--package-name <name>","Android package name to attach this service credential to").action(async e=>{ue(ae.bgCyan.black(f.cliTag("Service Credentials"))),await di(e),Mn(ae.green("Done!"))});var ai=Y.command("device").description("Manage registered iOS test devices");ai.command("register").description("Register a connected iOS device or enter UDID manually").option("--udid <udid>","Device UDID (skip auto-detection)").option("--name <name>","Device name").action(async e=>{await Rt("register",e)});ai.command("list").description("List all registered devices").action(async()=>{await Rt("list",{})});ai.command("remove").description("Remove a registered device").option("--udid <udid>","Device UDID to remove").action(async e=>{await Rt("remove",e)});Y.command("audit").description("Run automated security audit on the project or APK").option("--apk <path>","Path to APK file (runs APK diagnostics like 16KB alignment)").option("--json","Output results as JSON (for CI/CD)").option("--fix","Auto-apply fixes where possible").option("--category <name>","Run only a specific check category (e.g. 16kb, permissions, secrets)").option("--severity <level>","Minimum severity to display (critical, high, medium, low, info)").option("--prebuild","Run expo prebuild for deeper manifest/plist analysis").action(async e=>{ue(ae.bgCyan.black(f.cliTag(e.apk?"APK Audit":"Security Audit"))),await xn(e)});var ss=new Set(["login"]);Y.hook("preAction",(e,n)=>{let t=n.name();ss.has(t)||li()});Y.on("command:*",()=>{console.error(`Invalid command: %s
|
|
1037
|
+
See --help for a list of available commands.`,Y.args.join(" ")),process.exit(1)});process.argv.slice(2).length||Y.help();Y.parse(process.argv);
|