@radhya/mach 1.4.14 → 1.4.16
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 +20 -1
- package/dist/index.js +5 -11
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -80,6 +80,16 @@ mach credentials
|
|
|
80
80
|
|
|
81
81
|
Mach walks you through each step: choosing a bundle ID, picking a distribution type (development / ad-hoc / App Store), and syncing certificates. Everything is encrypted at rest and injected at build time.
|
|
82
82
|
|
|
83
|
+
### Multiple Bundle IDs
|
|
84
|
+
|
|
85
|
+
One project can have multiple bundle identifiers (e.g. `com.example.app`, `com.example.app.staging`, `com.example.app.dev`). Each bundle ID has its own independent set of credentials per distribution type. Select or add a bundle ID at the start of `mach credentials` — or skip the prompt with the `--bundle-id` flag for CI:
|
|
86
|
+
|
|
87
|
+
```bash
|
|
88
|
+
mach credentials --bundle-id com.example.app.staging
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
The Dashboard shows each bundle ID as a row. Clicking it reveals its Distribution certificate, Provisioning profile, and Service credentials — matching the same layout as Expo's credentials screen. A **Password stored** badge confirms the P12 export password is saved and will be injected at build time automatically.
|
|
92
|
+
|
|
83
93
|
## Configuration
|
|
84
94
|
|
|
85
95
|
Create a `mach.config.json` in your project root:
|
|
@@ -89,6 +99,7 @@ Create a `mach.config.json` in your project root:
|
|
|
89
99
|
"projectId": "your-project-id",
|
|
90
100
|
"name": "MyApp",
|
|
91
101
|
"slug": "my-app",
|
|
102
|
+
"nodeVersion": "24",
|
|
92
103
|
"ios": {
|
|
93
104
|
"bundleIdentifier": "com.example.myapp"
|
|
94
105
|
},
|
|
@@ -120,6 +131,14 @@ Create a `mach.config.json` in your project root:
|
|
|
120
131
|
}
|
|
121
132
|
```
|
|
122
133
|
|
|
134
|
+
### Root Properties
|
|
135
|
+
|
|
136
|
+
| Property | Description |
|
|
137
|
+
|----------|-------------|
|
|
138
|
+
| `projectId` | Auto-generated UUID linking to your Dashboard project |
|
|
139
|
+
| `name` | App display name |
|
|
140
|
+
| `nodeVersion` | Node.js version to use on the build machine (e.g. `"24"`, `"20.11.0"`). Switches via nvm before installing deps |
|
|
141
|
+
|
|
123
142
|
### Profile Properties
|
|
124
143
|
|
|
125
144
|
| Property | Description |
|
|
@@ -242,7 +261,7 @@ Generate tokens from the Mach Dashboard under **Settings → Access Tokens**.
|
|
|
242
261
|
| Variable | Description |
|
|
243
262
|
|----------|-------------|
|
|
244
263
|
| `MACH_TOKEN` | Personal access token for CI/CD (skips login) |
|
|
245
|
-
| `MACH_DEBUG` |
|
|
264
|
+
| `MACH_DEBUG` | Set to `1` to print resolved build profile and platform details |
|
|
246
265
|
| `MACH_P12_PASSWORD` | iOS certificate password (avoids interactive prompt) |
|
|
247
266
|
|
|
248
267
|
## Requirements
|
package/dist/index.js
CHANGED
|
@@ -269,11 +269,8 @@ touch /opt/mach-prewarmed
|
|
|
269
269
|
echo "Build orchestrator finished. Auto-terminating instance in 5 seconds..."
|
|
270
270
|
sleep 5
|
|
271
271
|
sudo shutdown -h now
|
|
272
|
-
`;var Si=async(e,n,t={},i)=>{let o=Wn(),r=e.buildProfile||"production",a=r==="production",c=e.apk===!0,s=a?"bundleRelease":"assembleRelease",l=e.buildCommand||(c?"assembleRelease":s),d=e.nodeVersion
|
|
273
|
-
|
|
274
|
-
nvm install ${e.nodeVersion} 2>/dev/null || true
|
|
275
|
-
nvm use ${e.nodeVersion}
|
|
276
|
-
echo "Switched to Node $(node -v) via nvm"`:"",u=hi.replace(/\{\{BUILD_ID\}\}/g,n).replace(/\{\{BUILD_COMMAND\}\}/g,l).replace("{{NODE_VERSION_SETUP}}",d).replace("{{ENV_VARS}}",`
|
|
272
|
+
`;var Si=async(e,n,t={},i)=>{let o=Wn(),r=e.buildProfile||"production",a=r==="production",c=e.apk===!0,s=a?"bundleRelease":"assembleRelease",l=e.buildCommand||(c?"assembleRelease":s),d=e.nodeVersion?['export NVM_DIR="$HOME/.nvm"','[ -s "$NVM_DIR/nvm.sh" ] && source "$NVM_DIR/nvm.sh"',`nvm install ${e.nodeVersion} 2>/dev/null || true`,`nvm use ${e.nodeVersion}`,'export PATH="$NVM_BIN:$PATH"','echo "[NODE] Using Node $(node -v) at $(which node)"'].join(`
|
|
273
|
+
`):"",u=hi.replace(/\{\{BUILD_ID\}\}/g,n).replace(/\{\{BUILD_COMMAND\}\}/g,l).replace("{{NODE_VERSION_SETUP}}",d).replace("{{ENV_VARS}}",`
|
|
277
274
|
export MACH_APP_NAME="${e.appName||"App"}"
|
|
278
275
|
export MACH_BUILD_PROFILE="${r}"
|
|
279
276
|
{{ENV_VARS}}
|
|
@@ -717,11 +714,8 @@ fi
|
|
|
717
714
|
`);o.message("Generating macOS build script...");let O=process.env.CODEARTIFACT_AUTH_TOKEN?`export CODEARTIFACT_AUTH_TOKEN="${process.env.CODEARTIFACT_AUTH_TOKEN}"
|
|
718
715
|
`:"";if(t)for(let[I,b]of Object.entries(t)){let R=b.replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");O+=`export ${I}="${R}"
|
|
719
716
|
`}let L=[O,P.logUpload?`export PRESIGNED_LOG_UPLOAD="${P.logUpload}"`:"",P.doneMarker?`export PRESIGNED_DONE_MARKER="${P.doneMarker}"`:"",P.cacheDerivedDataDownload?`export PRESIGNED_CACHE_DD_DOWNLOAD="${P.cacheDerivedDataDownload}"`:"",P.cacheDerivedDataUpload?`export PRESIGNED_CACHE_DD_UPLOAD="${P.cacheDerivedDataUpload}"`:"",P.cacheNodeModulesDownload?`export PRESIGNED_CACHE_NODE_DOWNLOAD="${P.cacheNodeModulesDownload}"`:"",P.cacheNodeModulesUpload?`export PRESIGNED_CACHE_NODE_UPLOAD="${P.cacheNodeModulesUpload}"`:"",P.cachePodsDownload?`export PRESIGNED_CACHE_PODS_DOWNLOAD="${P.cachePodsDownload}"`:"",P.cachePodsUpload?`export PRESIGNED_CACHE_PODS_UPLOAD="${P.cachePodsUpload}"`:"",P.artifactIpaUpload?`export PRESIGNED_ARTIFACT_IPA_UPLOAD="${P.artifactIpaUpload}"`:"",P.artifactAppZipUpload?`export PRESIGNED_ARTIFACT_APP_ZIP_UPLOAD="${P.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(`
|
|
720
|
-
`),H=e.nodeVersion
|
|
721
|
-
[ -
|
|
722
|
-
nvm install ${e.nodeVersion} 2>/dev/null || true
|
|
723
|
-
nvm use ${e.nodeVersion}
|
|
724
|
-
echo "Switched to Node $(node -v) via nvm"`:"",q=Ai,y={"{{REMOTE_DIR}}":p,"{{ENV_VARS}}":L,"{{CREDENTIAL_DOWNLOADS}}":N,"{{IOS_SCHEME}}":e.iosScheme||"","{{IOS_CONFIG}}":e.iosConfiguration||"Release","{{TEAM_ID}}":e.iosTeamId||"","{{AUTH_PARAMS}}":h,"{{IS_SIMULATOR}}":e.simulator?"true":"false","{{BUILD_ID}}":n,"{{EXPORT_METHOD}}":e.iosExportMethod||"ad-hoc","{{NODE_VERSION_SETUP}}":H};Object.entries(y).forEach(([I,b])=>{q=q.split(I).join(b)});let w=`/tmp/${f.nameLower}-mac-build-${n}.sh`;if(Jn.writeFileSync(w,q),Qe(`${l} ${w} ${c}:${p}/build.sh`),o.stop("Remote script uploaded."),He.info(Te.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 b=(await $.get(`/builds/${i}/${n}/artifacts`)).data.artifacts||[],R=e.simulator===!0;if(b.length===0&&!R)throw o.stop("Build Failed!"),new Error("Build completed but no artifacts were generated. Check build logs for errors.");if(o.stop("Build Successful!"),b.length>0){He.success("Build Artifacts Ready:");for(let G of b)console.log(`
|
|
717
|
+
`),H=e.nodeVersion?['export NVM_DIR="$HOME/.nvm"','[ -s "$NVM_DIR/nvm.sh" ] && source "$NVM_DIR/nvm.sh"',`nvm install ${e.nodeVersion} 2>/dev/null || true`,`nvm use ${e.nodeVersion}`,'export PATH="$NVM_BIN:$PATH"','echo "[NODE] Using Node $(node -v) at $(which node)"'].join(`
|
|
718
|
+
`):"",q=Ai,y={"{{REMOTE_DIR}}":p,"{{ENV_VARS}}":L,"{{CREDENTIAL_DOWNLOADS}}":N,"{{IOS_SCHEME}}":e.iosScheme||"","{{IOS_CONFIG}}":e.iosConfiguration||"Release","{{TEAM_ID}}":e.iosTeamId||"","{{AUTH_PARAMS}}":h,"{{IS_SIMULATOR}}":e.simulator?"true":"false","{{BUILD_ID}}":n,"{{EXPORT_METHOD}}":e.iosExportMethod||"ad-hoc","{{NODE_VERSION_SETUP}}":H};Object.entries(y).forEach(([I,b])=>{q=q.split(I).join(b)});let w=`/tmp/${f.nameLower}-mac-build-${n}.sh`;if(Jn.writeFileSync(w,q),Qe(`${l} ${w} ${c}:${p}/build.sh`),o.stop("Remote script uploaded."),He.info(Te.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 b=(await $.get(`/builds/${i}/${n}/artifacts`)).data.artifacts||[],R=e.simulator===!0;if(b.length===0&&!R)throw o.stop("Build Failed!"),new Error("Build completed but no artifacts were generated. Check build logs for errors.");if(o.stop("Build Successful!"),b.length>0){He.success("Build Artifacts Ready:");for(let G of b)console.log(`
|
|
725
719
|
${Te.yellow(G.name)}:
|
|
726
720
|
${Te.cyan(G.downloadUrl)}`);console.log(`
|
|
727
721
|
${Te.dim("Note: Links are valid for 7 days.")}`)}else R&&He.warn("Simulator build completed. No artifacts uploaded.")}catch(I){o.stop("Could not fetch artifacts"),He.warn(Te.yellow(`Artifact listing failed: ${I.message}`))}}}catch(d){throw o.stop("iOS Build Failed"),d}};import Xn from"crypto";import et from"axios";async function Ii(e,n){try{let t=await Zn(n),o=(await et.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${e}/edits`,{},{headers:{Authorization:`Bearer ${t}`,Connection:"close"}})).data.id,r=0,c=(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 c)if(s.releases){for(let l of s.releases)if(l.versionCodes)for(let d of l.versionCodes){let u=parseInt(d,10);u>r&&(r=u)}}try{let l=(await et.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${e}/edits/${o}/bundles`,{headers:{Authorization:`Bearer ${t}`,Connection:"close"}})).data.bundles||[];for(let d of l)d.versionCode&&d.versionCode>r&&(r=d.versionCode)}catch{}try{let l=(await et.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${e}/edits/${o}/apks`,{headers:{Authorization:`Bearer ${t}`,Connection:"close"}})).data.apks||[];for(let d of l)d.versionCode&&d.versionCode>r&&(r=d.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 Zn(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"),a=Buffer.from(JSON.stringify(o)).toString("base64url"),c=`${r}.${a}`,s=Xn.createSign("RSA-SHA256");s.update(c);let l=s.sign(e.private_key,"base64url"),d=`${c}.${l}`;return(await et.post("https://oauth2.googleapis.com/token",{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:d},{headers:{Connection:"close"}})).data.access_token}import{spinner as ht,log as A,isCancel as yt,confirm as Qn,select as Ft}from"@clack/prompts";import S from"chalk";import E from"fs";import _ from"path";import{execSync as F,spawn as Pi}from"child_process";import _e from"os";import eo from"crypto";var $i=(e,n)=>n.filter(t=>E.existsSync(_.join(e,t))).reduce((t,i)=>t.update(E.readFileSync(_.join(e,i))),eo.createHash("sha256")).digest("hex").slice(0,16),to=e=>$i(e,["package.json","yarn.lock","package-lock.json","bun.lockb"]),io=e=>$i(e,["Podfile","Podfile.lock"]),no=e=>{let n=_.join(e,"fingerprint.json");try{return JSON.parse(E.readFileSync(n,"utf-8"))}catch{return{}}},bi=(e,n)=>{E.mkdirSync(e,{recursive:!0}),E.writeFileSync(_.join(e,"fingerprint.json"),JSON.stringify(n,null,2))},oo=7200*1e3,ro=(e,n)=>{E.mkdirSync(e,{recursive:!0});let t=_.join(e,"build.lock");if(E.existsSync(t))try{let i=JSON.parse(E.readFileSync(t,"utf-8")),o=Date.now()-(i.timestamp||0);if(o<oo)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}E.writeFileSync(t,JSON.stringify({buildId:n,pid:process.pid,timestamp:Date.now()}))},so=(e,n)=>{let t=_.join(e,"build.lock");try{E.existsSync(t)&&JSON.parse(E.readFileSync(t,"utf-8")).buildId===n&&E.unlinkSync(t)}catch{}},De=(e,n,t=process.cwd(),i={},o,r)=>new Promise((a,c)=>{let s=[_.dirname(process.execPath),"/opt/homebrew/bin","/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin",_.join(_e.homedir(),".npm-global/bin"),_.join(_e.homedir(),".nvm/current/bin")],l=process.env.PATH||"",d=[...s,...l.split(":")].filter((m,h,P)=>m&&P.indexOf(m)===h).join(":");process.env[`${f.envPrefix}DEBUG`]&&console.log(S.magenta(`[${f.nameUpper}_DEBUG] Execution PATH: ${d}`));let u={...process.env,...i,PATH:d,LANG:"en_US.UTF-8",LC_ALL:"en_US.UTF-8"};o&&process.env[`${f.envPrefix}DEBUG`]&&(o(S.magenta(`[ENVIRONMENT] node: ${process.execPath}
|
|
@@ -798,7 +792,7 @@ ${J}`)),s&&await s("export"),A.info(S.blue(`Exporting with Bundle ID: "${C}"`)),
|
|
|
798
792
|
`);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{}a=0}catch{a++,a>10&&(i.stop("Connection lost."),D.error(v.red(`
|
|
799
793
|
\u2717 Lost connection to Dashboard API.`)),process.exit(1))}await new Promise(c=>setTimeout(c,3e3))}}import So from"http";import{execSync as Et}from"child_process";import Bt from"chalk";import{log as je}from"@clack/prompts";var It=7070;function Ao(){let e=[];try{let n=Et("adb devices -l",{stdio:"pipe"}).toString(),t=new Set;n.split(`
|
|
800
794
|
`).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 a=i.match(/model:([^\s]+)/);e.push({id:r,platform:"android",type:r.startsWith("emulator-")?"emulator":"physical",name:a?a[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=Et(`${n} -list-avds`,{stdio:"pipe"}).toString().split(`
|
|
801
|
-
`).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"&&je.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",()=>{je.success(Bt.green(`Local device agent running on http://localhost:${It}`)),je.info(Bt.dim("Keep this running while using the Install Hub on the dashboard.")),je.info(Bt.dim("Press Ctrl+C to stop."))}),e.on("error",n=>{n.code==="EADDRINUSE"?je.error(`Port ${It} is already in use \u2014 agent may already be running.`):je.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 Po,isCancel as Ti}from"@clack/prompts";import Vt from"chalk";import it from"fs";import Oi from"path";import Eo from"os";var jt=Oi.join(Eo.homedir(),f.configDir),Kt=Oi.join(jt,"config.json");function zt(){if(!it.existsSync(Kt))return{};try{return JSON.parse(it.readFileSync(Kt,"utf-8"))}catch{return{}}}function Ci(e){it.existsSync(jt)||it.mkdirSync(jt,{recursive:!0});let t={...zt(),...e};it.writeFileSync(Kt,JSON.stringify(t,null,2))}async function Ni(){let e=zt(),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=Po();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(Vt.green("Login successful!"))):i.stop(Vt.red("Login failed: "+(r.message||"Unknown error")))}catch(o){i.stop(Vt.red("Network error: "+o.message))}}import{outro as $o,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:{base:{},development:{extends:"base",developmentClient:!0,environment:"development",ios:{simulator:!0}},staging:{extends:"base",environment:"staging",distribution:"internal"},production:{extends:"base",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)),$o(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 Pt,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 Pt({message:"Project Name:",placeholder:"My Awesome App",validate(c){if(c.length===0)return"Name is required!"}});if(nt(n))return;let t=await Pt({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 Pt({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 Pt({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:{},staging:{extends:"development"},production:{extends:"development"}},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 $t 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($t.bold("Environment Variables (Global & Scoped):")),o.forEach(r=>{let a=r.visibility==="plain"?r.value:"********";console.log(` ${$t.cyan(r.key)} = ${a} ${$t.gray(`[${r.environment}]`)}`)}))}else t.stop($t.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 ie 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(ie.dim(`Submit for project: ${o.name||r} `));let a=e.platform;if(!a){let h=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(h)){Jt("Operation cancelled");return}a=h}let c=await Go(r,a,e,t?.token);if(!c)return;ve(`Using artifact: ${ie.green(Ke.basename(c))} `),n.start("Fetching submission credentials from Dashboard...");let s;try{let N=((await $.get(`/credentials/${r}`)).data.credentials||[]).filter(O=>a==="ios"?O.type==="asc_api_key":O.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 O=await qt({message:`Choose a ${a==="ios"?"App Store Connect":"Google Play"} credential:`,options:N.map(L=>({value:L.credentialId,label:L.name,hint:`${L.keyId?`ID: ${L.keyId}`:""} ${L.issuerId?`(Issuer: ${L.issuerId.substring(0,8)}...)`:""}`}))});if(ke(O)){Jt("Submission cancelled");return}s=N.find(L=>L.credentialId===O),ve(`Using selected: ${ie.green(s.name)}`)}}catch(h){n.stop("Failed to fetch credentials"),ge(`API Error: ${h.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",g=Ke.join(l,p);n.start("Downloading secure key...");try{let h=await $.get(`/credentials/${s.credentialId}/download`,{params:{projectId:r}});if(h.data.status!=="success"||!h.data.downloadUrl)throw new Error("Failed to get secure download URL");let P=await Hi.get(h.data.downloadUrl,{responseType:"arraybuffer"});le.writeFileSync(g,Buffer.from(P.data)),n.stop("Key downloaded to secure temp storage")}catch(h){n.stop("Download failed"),ge(`Failed to download key: ${h.message}`);try{le.rmSync(l,{recursive:!0,force:!0})}catch{}return}ve(ie.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:O=>O.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:O=>O.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 h=o.ios?.bundleIdentifier,P=await Bo(c,g,u,d,h);if(P&&P.apiKeyJsonPath)throw ve(ie.cyan(`
|
|
795
|
+
`).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"&&je.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",()=>{je.success(Bt.green(`Local device agent running on http://localhost:${It}`)),je.info(Bt.dim("Keep this running while using the Install Hub on the dashboard.")),je.info(Bt.dim("Press Ctrl+C to stop."))}),e.on("error",n=>{n.code==="EADDRINUSE"?je.error(`Port ${It} is already in use \u2014 agent may already be running.`):je.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 Po,isCancel as Ti}from"@clack/prompts";import Vt from"chalk";import it from"fs";import Oi from"path";import Eo from"os";var jt=Oi.join(Eo.homedir(),f.configDir),Kt=Oi.join(jt,"config.json");function zt(){if(!it.existsSync(Kt))return{};try{return JSON.parse(it.readFileSync(Kt,"utf-8"))}catch{return{}}}function Ci(e){it.existsSync(jt)||it.mkdirSync(jt,{recursive:!0});let t={...zt(),...e};it.writeFileSync(Kt,JSON.stringify(t,null,2))}async function Ni(){let e=zt(),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=Po();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(Vt.green("Login successful!"))):i.stop(Vt.red("Login failed: "+(r.message||"Unknown error")))}catch(o){i.stop(Vt.red("Network error: "+o.message))}}import{outro as $o,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)),$o(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 Pt,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 Pt({message:"Project Name:",placeholder:"My Awesome App",validate(c){if(c.length===0)return"Name is required!"}});if(nt(n))return;let t=await Pt({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 Pt({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 Pt({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 $t 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($t.bold("Environment Variables (Global & Scoped):")),o.forEach(r=>{let a=r.visibility==="plain"?r.value:"********";console.log(` ${$t.cyan(r.key)} = ${a} ${$t.gray(`[${r.environment}]`)}`)}))}else t.stop($t.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 ie 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(ie.dim(`Submit for project: ${o.name||r} `));let a=e.platform;if(!a){let h=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(h)){Jt("Operation cancelled");return}a=h}let c=await Go(r,a,e,t?.token);if(!c)return;ve(`Using artifact: ${ie.green(Ke.basename(c))} `),n.start("Fetching submission credentials from Dashboard...");let s;try{let N=((await $.get(`/credentials/${r}`)).data.credentials||[]).filter(O=>a==="ios"?O.type==="asc_api_key":O.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 O=await qt({message:`Choose a ${a==="ios"?"App Store Connect":"Google Play"} credential:`,options:N.map(L=>({value:L.credentialId,label:L.name,hint:`${L.keyId?`ID: ${L.keyId}`:""} ${L.issuerId?`(Issuer: ${L.issuerId.substring(0,8)}...)`:""}`}))});if(ke(O)){Jt("Submission cancelled");return}s=N.find(L=>L.credentialId===O),ve(`Using selected: ${ie.green(s.name)}`)}}catch(h){n.stop("Failed to fetch credentials"),ge(`API Error: ${h.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",g=Ke.join(l,p);n.start("Downloading secure key...");try{let h=await $.get(`/credentials/${s.credentialId}/download`,{params:{projectId:r}});if(h.data.status!=="success"||!h.data.downloadUrl)throw new Error("Failed to get secure download URL");let P=await Hi.get(h.data.downloadUrl,{responseType:"arraybuffer"});le.writeFileSync(g,Buffer.from(P.data)),n.stop("Key downloaded to secure temp storage")}catch(h){n.stop("Download failed"),ge(`Failed to download key: ${h.message}`);try{le.rmSync(l,{recursive:!0,force:!0})}catch{}return}ve(ie.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:O=>O.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:O=>O.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 h=o.ios?.bundleIdentifier,P=await Bo(c,g,u,d,h);if(P&&P.apiKeyJsonPath)throw ve(ie.cyan(`
|
|
802
796
|
[DIAGNOSTIC] API key written to: ${P.apiKeyJsonPath}
|
|
803
797
|
`)),new Error("fastlane pilot execution failed");Fi(`${a==="ios"?"App Store":"Google Play"} submission successful!`)}else{let h=o.android?.package||s.bundleId;await jo(c,g,m,h),Fi("Google Play submission successful!")}}catch(h){ge(`Submission failed: ${h.message}`)}finally{Ko(l),c.includes(`${f.nameLower}-artifact-`)}}async function Go(e,n,t,i){let o=t.buildId?"id":t.latest?"latest":null;if(!o&&(o=await qt({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"}]}),ke(o)))return Jt("Operation cancelled"),null;if(o==="local"){let a=await rt({message:"Enter path to artifact (.ipa/.aab):",validate:c=>{if(!le.existsSync(c))return"File not found";if(n==="ios"&&!c.endsWith(".ipa"))return"Must be an .ipa file";if(n==="android"&&!c.endsWith(".aab"))return"Must be an .aab file"}});return ke(a)?null:a}let r=st();if(o==="latest"){r.start("Fetching latest build...");try{let a=await $.get(`/builds/${e}`,{params:{limit:50}});if(a.data.status!=="success")throw new Error(a.data.message);let c=a.data.builds||[],s=c.find(m=>m.platform?.toLowerCase()===n.toLowerCase()&&m.status?.toLowerCase()==="success"&&m.buildType?.toLowerCase()==="store")||c.find(m=>m.platform?.toLowerCase()===n.toLowerCase()&&m.status?.toLowerCase()==="success");if(!s)return r.stop("No suitable build found"),ge("No successful builds found for this platform."),null;r.stop(`Found build: ${s.buildId}`);let l=s.artifacts||[];if(l.length===0||l.every(m=>!(m.url||m.downloadUrl)))try{let m=await $.get(`/builds/${e}/${s.buildId}/artifacts`);m.data.status==="success"&&m.data.artifacts?.length>0?(l=m.data.artifacts.map(h=>({...h,url:h.url||h.downloadUrl})),console.log(ie.cyan(` [RECOVERY] Fetched ${l.length} artifact(s) with download URLs.`))):console.log(ie.yellow(" [RECOVERY] /artifacts endpoint returned 0 artifacts."))}catch(m){console.log(ie.red(` [RECOVERY] /artifacts fetch failed: ${m.message}`))}let u=n==="ios",p=l.find(m=>{let h=(m.type||"").toLowerCase(),P=(m.name||"").toLowerCase();if(console.log(ie.dim(` - Checking: ${m.name} (Type: ${m.type}, HasLink: ${!!(m.url||m.downloadUrl)})`)),h)return h===(u?"ipa":"aab");let N=u?".ipa":".aab",O=(m.url||m.downloadUrl||"").toLowerCase();return P.endsWith(N)||O.includes(N)});if(!p||!(p.url||p.downloadUrl))return ge("Build found but artifact URL is missing."),null;let g=p.url||p.downloadUrl;return await Yt(g,u?"ios":"android")}catch(a){return r.stop("Fetch failed"),ge(`API Error: ${a.message}`),null}}if(o==="id"){let a=t.buildId||await rt({message:"Enter Build ID:",validate:c=>c.length<5?"Invalid ID":void 0});if(ke(a))return null;r.start("Fetching build...");try{let c=await $.get(`/build/${a}`);if(c.data.status!=="success")throw new Error(c.data.message);let s=c.data.build;if(!s)throw new Error("Build not found");let l=n==="ios",d=s.artifacts?.find(u=>{if(u.type)return u.type===(l?"ipa":"aab");let p=l?".ipa":".aab";return u.name&&u.name.endsWith(p)||u.url&&u.url.includes(p)});return!d||!d.url?(r.stop("Missing artifact"),ge("Artifact URL not found on build record."),null):(r.stop(`Found build: ${s.buildId}`),await Yt(d.url,l?"ios":"android"))}catch(c){return r.stop("Fetch failed"),ge(c.message),null}}if(o==="url"){let a=await rt({message:"Enter Artifact URL:",validate:c=>c.startsWith("http")?void 0:"Must be a valid URL"});return ke(a)?null:await Yt(a,n)}return null}async function Yt(e,n,t=3){let i=st();i.start("Downloading artifact...");let o=le.mkdtempSync(Ke.join(Xt.tmpdir(),`${f.nameLower}-artifact-`)),r=`app.${n==="ios"?"ipa":"aab"}`,a=Ke.join(o,r);for(let c=1;c<=t;c++)try{c>1&&(i.message(`Downloading artifact (Retry ${c}/${t})...`),await new Promise(d=>setTimeout(d,2e3*c)));let s=le.createWriteStream(a),l=await Hi({url:e,method:"GET",responseType:"stream",timeout:6e4});return await new Promise((d,u)=>{l.data.pipe(s);let p=!1;l.data.on("error",g=>{p||(p=!0,s.close(),u(g))}),s.on("finish",()=>{p||d()}),s.on("error",g=>{p||(p=!0,u(g))})}),i.stop("Download complete"),a}catch(s){if(c===t)throw i.stop("Download failed"),s}throw new Error("Download failed after retries")}async function Bo(e,n,t,i,o){let r=st();if(o&&ve(`Bundled ID: ${ie.green(o)}`),!t||!i)throw ge(`Missing credentials: issuerId=${t}, keyId=${i}. Check your Dashboard.`),new Error("Missing ASC API Key Metadata (IssuerID or KeyID)");let a=le.readFileSync(n,"utf8"),c;try{c=Ho.createPrivateKey(a).export({type:"pkcs8",format:"pem"})}catch{ve("Key normalization failed, falling back to manual re-wrapping..."),c=`-----BEGIN PRIVATE KEY-----
|
|
804
798
|
${(a.replace(/-----BEGIN[^-]*-----/g,"").replace(/-----END[^-]*-----/g,"").replace(/\s+/g,"").match(/.{1,64}/g)||[]).join(`
|