@stacksjs/buddy 0.75.468 → 0.75.473

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.
@@ -30,6 +30,11 @@ export declare interface TestFlightBuild {
30
30
  processingState: string
31
31
  expired: boolean
32
32
  }
33
+ export declare interface TestFlightGroup {
34
+ id: string
35
+ name: string
36
+ isInternalGroup: boolean
37
+ }
33
38
  export declare interface WaitForBuildOptions {
34
39
  timeoutMs: number
35
40
  intervalMs?: number
@@ -37,10 +42,19 @@ export declare interface WaitForBuildOptions {
37
42
  now?: () => number
38
43
  onWait?: (elapsedMs: number) => void
39
44
  }
45
+ export declare interface TestFlightDeliveryOptions extends WaitForBuildOptions {
46
+ groups?: readonly string[]
47
+ notes?: Record<string, string>
48
+ keepBuilds?: number
49
+ }
40
50
  declare type Fetch = (input: string, init?: RequestInit) => Promise<Response>;
41
51
  export declare class AppStoreConnect {
42
52
  constructor(token: string, fetchImpl?: Fetch);
43
53
  static connect(credentials: AppStoreConnectCredentials, fetchImpl?: Fetch): Promise<AppStoreConnect>;
54
+ internalTestFlightGroups(appId: string, names: readonly string[]): Promise<TestFlightGroup[]>;
55
+ assignBuildToInternalGroups(appId: string, build: TestFlightBuild, names: readonly string[]): Promise<TestFlightGroup[]>;
56
+ testFlightStatus(buildId: string): Promise<{ internalBuildState: string, groupIds: string[] }>;
57
+ deliverBuild(appId: string, version: string, number: number, options: TestFlightDeliveryOptions): Promise<TestFlightBuild | null>;
44
58
  appId(bundleId: string): Promise<string>;
45
59
  latestXcodeCloudRun(appId: string): Promise<number | null>;
46
60
  builds(appId: string): Promise<TestFlightBuild[]>;
@@ -1,2 +1,2 @@
1
1
  import{existsSync,readFileSync}from"node:fs";import{nextBuildNumber}from"@stacksjs/bumpx";const API="https://api.appstoreconnect.apple.com";export function appStoreConnectCredentials(env=process.env){const keyId=env.APP_STORE_CONNECT_KEY_ID?.trim(),issuerId=env.APP_STORE_CONNECT_ISSUER_ID?.trim();let privateKey=env.APP_STORE_CONNECT_PRIVATE_KEY?.trim();const keyPath=env.APP_STORE_CONNECT_PRIVATE_KEY_PATH?.trim();if(!privateKey&&keyPath&&existsSync(keyPath))privateKey=readFileSync(keyPath,"utf8").trim();if(!keyId||!issuerId||!privateKey)return null;return{keyId,issuerId,privateKey:privateKey.replace(/\\n/g,`
2
- `)}}function base64url(bytes){return(typeof bytes==="string"?Buffer.from(bytes):Buffer.from(bytes)).toString("base64").replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_")}export async function appStoreConnectToken(credentials,now=Date.now()){const pem=credentials.privateKey.replace(/-----(BEGIN|END) PRIVATE KEY-----/g,"").replace(/\s+/g,""),key=await crypto.subtle.importKey("pkcs8",Buffer.from(pem,"base64"),{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),iat=Math.floor(now/1000),header=base64url(JSON.stringify({alg:"ES256",kid:credentials.keyId,typ:"JWT"})),payload=base64url(JSON.stringify({iss:credentials.issuerId,iat,exp:iat+1200,aud:"appstoreconnect-v1"})),signature=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},key,Buffer.from(`${header}.${payload}`));return`${header}.${payload}.${base64url(new Uint8Array(signature))}`}export class AppStoreConnect{token;fetchImpl;tokenProvider;renewAt=Number.POSITIVE_INFINITY;renewing;constructor(token,fetchImpl=fetch){this.token=token;this.fetchImpl=fetchImpl}static async connect(credentials,fetchImpl){const{keyId,issuerId,privateKey}=credentials,issue=async()=>{const now=Date.now();return{token:await appStoreConnectToken({keyId,issuerId,privateKey},now),renewAt:now+900000}},issued=await issue(),api=new AppStoreConnect(issued.token,fetchImpl);api.tokenProvider=issue;api.renewAt=issued.renewAt;return api}async authorization(){if(this.tokenProvider&&Date.now()>=this.renewAt){if(!this.renewing)this.renewing=this.tokenProvider().then((issued)=>{this.token=issued.token;this.renewAt=issued.renewAt}).finally(()=>{this.renewing=void 0});await this.renewing}return`Bearer ${this.token}`}async request(path,init={}){const response=await this.fetchImpl(`${API}${path}`,{...init,headers:{Authorization:await this.authorization(),"Content-Type":"application/json",...init.headers}});if(!response.ok){const body=await response.text().catch(()=>"");throw Error(`App Store Connect ${init.method??"GET"} ${path} answered ${response.status}${body?`: ${body.slice(0,300)}`:""}`)}return response.status===204?null:await response.json()}async appId(bundleId){const id=(await this.request(`/v1/apps?filter[bundleId]=${encodeURIComponent(bundleId)}&limit=1`))?.data?.[0]?.id;if(!id)throw Error(`App Store Connect has no app with the bundle id ${bundleId}`);return id}async latestXcodeCloudRun(appId){const productId=(await this.request(`/v1/ciProducts?filter[app]=${appId}&limit=1`))?.data?.[0]?.id;if(!productId)return null;const runs=await this.request(`/v1/ciProducts/${productId}/buildRuns?sort=-number&limit=1&fields[ciBuildRuns]=number`),number=Number(runs?.data?.[0]?.attributes?.number);return Number.isSafeInteger(number)&&number>=0?number:null}async builds(appId){return((await this.request(`/v1/builds?filter[app]=${appId}&sort=-uploadedDate&limit=50&fields[builds]=version,uploadedDate,processingState,expired`))?.data??[]).map((build)=>({id:build.id,number:Number(build.attributes?.version),uploadedDate:String(build.attributes?.uploadedDate??""),processingState:String(build.attributes?.processingState??""),expired:Boolean(build.attributes?.expired)}))}async build(appId,version,number){const query=`filter[app]=${appId}&filter[version]=${encodeURIComponent(String(number))}&filter[preReleaseVersion.version]=${encodeURIComponent(version)}&limit=1&fields[builds]=version,uploadedDate,processingState,expired`,build=(await this.request(`/v1/builds?${query}`))?.data?.[0];return build?{id:build.id,number:Number(build.attributes?.version),uploadedDate:String(build.attributes?.uploadedDate??""),processingState:String(build.attributes?.processingState??""),expired:Boolean(build.attributes?.expired)}:null}async setWhatToTest(buildId,notes){const existing=await this.request(`/v1/builds/${buildId}/betaBuildLocalizations?limit=50&fields[betaBuildLocalizations]=locale,whatsNew`),byLocale=new Map((existing?.data??[]).map((row)=>[String(row.attributes?.locale),String(row.id)]));for(const[locale,whatsNew]of Object.entries(notes)){const id=byLocale.get(locale);if(id)await this.request(`/v1/betaBuildLocalizations/${id}`,{method:"PATCH",body:JSON.stringify({data:{type:"betaBuildLocalizations",id,attributes:{whatsNew}}})});else await this.request("/v1/betaBuildLocalizations",{method:"POST",body:JSON.stringify({data:{type:"betaBuildLocalizations",attributes:{locale,whatsNew},relationships:{build:{data:{type:"builds",id:buildId}}}}})})}}async expire(buildId){await this.request(`/v1/builds/${buildId}`,{method:"PATCH",body:JSON.stringify({data:{type:"builds",id:buildId,attributes:{expired:!0}}})})}}export function buildsToExpire(builds,keep=1){return builds.filter((build)=>!build.expired&&build.processingState==="VALID").sort((a,b)=>b.number-a.number).slice(Math.max(0,keep))}export function tagForXcodeCloudRun(version,latestRun){return`v${version}-build.${nextBuildNumber(latestRun)}`}export async function waitForBuild(api,appId,version,number,options){const sleep=options.sleep??((ms)=>new Promise((resolve)=>setTimeout(resolve,ms))),now=options.now??Date.now,interval=options.intervalMs??30000,start=now();for(;;){const build=await api.build(appId,version,number);if(build)return build;const elapsed=now()-start;if(elapsed+interval>options.timeoutMs)return null;options.onWait?.(elapsed);await sleep(interval)}}
2
+ `)}}function base64url(bytes){return(typeof bytes==="string"?Buffer.from(bytes):Buffer.from(bytes)).toString("base64").replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_")}export async function appStoreConnectToken(credentials,now=Date.now()){const pem=credentials.privateKey.replace(/-----(BEGIN|END) PRIVATE KEY-----/g,"").replace(/\s+/g,""),key=await crypto.subtle.importKey("pkcs8",Buffer.from(pem,"base64"),{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),iat=Math.floor(now/1000),header=base64url(JSON.stringify({alg:"ES256",kid:credentials.keyId,typ:"JWT"})),payload=base64url(JSON.stringify({iss:credentials.issuerId,iat,exp:iat+1200,aud:"appstoreconnect-v1"})),signature=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},key,Buffer.from(`${header}.${payload}`));return`${header}.${payload}.${base64url(new Uint8Array(signature))}`}export class AppStoreConnect{token;fetchImpl;tokenProvider;renewAt=Number.POSITIVE_INFINITY;renewing;constructor(token,fetchImpl=fetch){this.token=token;this.fetchImpl=fetchImpl}static async connect(credentials,fetchImpl){const{keyId,issuerId,privateKey}=credentials,issue=async()=>{const now=Date.now();return{token:await appStoreConnectToken({keyId,issuerId,privateKey},now),renewAt:now+900000}},issued=await issue(),api=new AppStoreConnect(issued.token,fetchImpl);api.tokenProvider=issue;api.renewAt=issued.renewAt;return api}async authorization(){if(this.tokenProvider&&Date.now()>=this.renewAt){if(!this.renewing)this.renewing=this.tokenProvider().then((issued)=>{this.token=issued.token;this.renewAt=issued.renewAt}).finally(()=>{this.renewing=void 0});await this.renewing}return`Bearer ${this.token}`}async request(path,init={}){const response=await this.fetchImpl(`${API}${path}`,{...init,signal:init.signal??AbortSignal.timeout(30000),headers:{Authorization:await this.authorization(),"Content-Type":"application/json",...init.headers}});if(!response.ok){const body=await response.text().catch(()=>"");throw Error(`App Store Connect ${init.method??"GET"} ${path} answered ${response.status}${body?`: ${body.slice(0,300)}`:""}`)}return response.status===204?null:await response.json()}async pages(path){const rows=[],visited=new Set;while(path){if(visited.has(path))throw Error("App Store Connect repeated a pagination link");visited.add(path);const page=await this.request(path);rows.push(...page?.data??[]);if(!page?.links?.next)break;const next=new URL(page.links.next,API);if(next.origin!==API||!next.pathname.startsWith("/v1/")||next.username||next.password)throw Error("App Store Connect returned an unsafe pagination link");path=next.pathname+next.search}return rows}async internalTestFlightGroups(appId,names){if(!Array.isArray(names)||names.some((name)=>typeof name!=="string"||!name.trim()))throw Error("ios.testFlightGroups must contain nonempty internal group names");if(!names.length)return[];const groups=(await this.pages(`/v1/apps/${encodeURIComponent(appId)}/betaGroups?limit=200&fields[betaGroups]=name,isInternalGroup`)).map((row)=>({id:String(row.id),name:String(row.attributes?.name??""),isInternalGroup:row.attributes?.isInternalGroup===!0}));return[...new Set(names.map((name)=>name.trim()))].map((name)=>{const matching=groups.filter((group)=>group.name===name);if(matching.length!==1||!matching[0].isInternalGroup)throw Error(`TestFlight group ${JSON.stringify(name)} must name one existing internal group for this app`);return matching[0]})}async assignBuildToInternalGroups(appId,build,names){if(build.processingState!=="VALID"||build.expired)throw Error("Only a processed, unexpired build can be distributed to TestFlight");const groups=await this.internalTestFlightGroups(appId,names);if(!groups.length)return groups;const assigned=new Set((await this.pages(`/v1/builds/${encodeURIComponent(build.id)}/betaGroups?limit=200&fields[betaGroups]=name,isInternalGroup`)).map((group)=>group.id));for(const group of groups){if(assigned.has(group.id))continue;await this.request(`/v1/betaGroups/${encodeURIComponent(group.id)}/relationships/builds`,{method:"POST",body:JSON.stringify({data:[{type:"builds",id:build.id}]})})}return groups}async testFlightStatus(buildId){const[detail,groups]=await Promise.all([this.request(`/v1/builds/${encodeURIComponent(buildId)}/buildBetaDetail`),this.pages(`/v1/builds/${encodeURIComponent(buildId)}/betaGroups?limit=200&fields[betaGroups]=name,isInternalGroup`)]);return{internalBuildState:String(detail?.data?.attributes?.internalBuildState??""),groupIds:groups.map((group)=>String(group.id))}}async deliverBuild(appId,version,number,options){const interval=options.intervalMs??30000,keep=options.keepBuilds??1;if(!Number.isFinite(options.timeoutMs)||options.timeoutMs<0||!Number.isFinite(interval)||interval<=0||!Number.isSafeInteger(keep)||keep<0)throw Error("TestFlight delivery needs a nonnegative wait/retention count and a positive polling interval");const now=options.now??Date.now,sleep=options.sleep??((ms)=>new Promise((resolve)=>setTimeout(resolve,ms))),start=now(),groups=await this.internalTestFlightGroups(appId,options.groups??[]);let appliedBuild;for(;;){const build=await this.build(appId,version,number);if(build?.expired||build&&["FAILED","INVALID"].includes(build.processingState))throw Error(`TestFlight build ${number} is ${build.expired?"expired":build.processingState}`);if(build?.processingState==="VALID"){if(appliedBuild!==build.id){if(options.notes&&Object.keys(options.notes).length)await this.setWhatToTest(build.id,options.notes);await this.assignBuildToInternalGroups(appId,build,options.groups??[]);appliedBuild=build.id}const status=await this.testFlightStatus(build.id);if(status.internalBuildState==="IN_BETA_TESTING"&&groups.every((group)=>status.groupIds.includes(group.id))){if(options.timeoutMs>0&&now()-start>options.timeoutMs)return null;const older=(await this.builds(appId)).filter((candidate)=>candidate.number<number);for(const retiring of buildsToExpire(older,keep))await this.expire(retiring.id);return build}}const elapsed=now()-start;if(elapsed+interval>options.timeoutMs)return null;options.onWait?.(elapsed);await sleep(interval)}}async appId(bundleId){const id=(await this.request(`/v1/apps?filter[bundleId]=${encodeURIComponent(bundleId)}&limit=1`))?.data?.[0]?.id;if(!id)throw Error(`App Store Connect has no app with the bundle id ${bundleId}`);return id}async latestXcodeCloudRun(appId){const productId=(await this.request(`/v1/ciProducts?filter[app]=${appId}&limit=1`))?.data?.[0]?.id;if(!productId)return null;const runs=await this.request(`/v1/ciProducts/${productId}/buildRuns?sort=-number&limit=1&fields[ciBuildRuns]=number`),number=Number(runs?.data?.[0]?.attributes?.number);return Number.isSafeInteger(number)&&number>=0?number:null}async builds(appId){return(await this.pages(`/v1/builds?filter[app]=${encodeURIComponent(appId)}&sort=-uploadedDate&limit=200&fields[builds]=version,uploadedDate,processingState,expired`)).map((build)=>({id:build.id,number:Number(build.attributes?.version),uploadedDate:String(build.attributes?.uploadedDate??""),processingState:String(build.attributes?.processingState??""),expired:Boolean(build.attributes?.expired)}))}async build(appId,version,number){const query=`filter[app]=${appId}&filter[version]=${encodeURIComponent(String(number))}&filter[preReleaseVersion.version]=${encodeURIComponent(version)}&limit=1&fields[builds]=version,uploadedDate,processingState,expired`,build=(await this.request(`/v1/builds?${query}`))?.data?.[0];return build?{id:build.id,number:Number(build.attributes?.version),uploadedDate:String(build.attributes?.uploadedDate??""),processingState:String(build.attributes?.processingState??""),expired:Boolean(build.attributes?.expired)}:null}async setWhatToTest(buildId,notes){const existing=await this.request(`/v1/builds/${buildId}/betaBuildLocalizations?limit=50&fields[betaBuildLocalizations]=locale,whatsNew`),byLocale=new Map((existing?.data??[]).map((row)=>[String(row.attributes?.locale),String(row.id)]));for(const[locale,whatsNew]of Object.entries(notes)){const id=byLocale.get(locale);if(id)await this.request(`/v1/betaBuildLocalizations/${id}`,{method:"PATCH",body:JSON.stringify({data:{type:"betaBuildLocalizations",id,attributes:{whatsNew}}})});else await this.request("/v1/betaBuildLocalizations",{method:"POST",body:JSON.stringify({data:{type:"betaBuildLocalizations",attributes:{locale,whatsNew},relationships:{build:{data:{type:"builds",id:buildId}}}}})})}}async expire(buildId){await this.request(`/v1/builds/${buildId}`,{method:"PATCH",body:JSON.stringify({data:{type:"builds",id:buildId,attributes:{expired:!0}}})})}}export function buildsToExpire(builds,keep=1){return builds.filter((build)=>!build.expired&&build.processingState==="VALID").sort((a,b)=>b.number-a.number).slice(Math.max(0,keep))}export function tagForXcodeCloudRun(version,latestRun){return`v${version}-build.${nextBuildNumber(latestRun)}`}export async function waitForBuild(api,appId,version,number,options){const sleep=options.sleep??((ms)=>new Promise((resolve)=>setTimeout(resolve,ms))),now=options.now??Date.now,interval=options.intervalMs??30000,start=now();for(;;){const build=await api.build(appId,version,number);if(build)return build;const elapsed=now()-start;if(elapsed+interval>options.timeoutMs)return null;options.onWait?.(elapsed);await sleep(interval)}}
@@ -1,6 +1,7 @@
1
1
  import type { CLI } from '@stacksjs/types';
2
2
  /** `--wait` as minutes, or null when the release should not wait. */
3
3
  export declare function waitMinutes(value: IosReleaseOptions['wait']): number | null;
4
+ export declare function retainedBuildCount(value: number | string | undefined): number;
4
5
  export declare function release(buddy: CLI): void;
5
6
  export declare function resolveGitHubActionsUrl(remoteUrl?: string, repository?: unknown, serverUrl?: unknown): string;
6
7
  declare interface IosReleaseOptions {
@@ -1,13 +1,13 @@
1
- import{execFileSync}from"node:child_process";import{existsSync,readFileSync,renameSync,rmSync,writeFileSync}from"node:fs";import{join}from"node:path";import{pathToFileURL}from"node:url";import process from"node:process";import{resolveXcodegen}from"@stacksjs/actions/build/ios-toolchain";import{describeGitHubRelease,publishGitHubRelease,resolveGitHubToken}from"@stacksjs/actions/github-release";import{validateReleaseEvidencePlan,verifyReleaseEvidence}from"@stacksjs/actions/release-evidence";import{assertPublicationAllowed}from"@stacksjs/actions/publication-preflight";import{runAction}from"@stacksjs/actions/run-action";import{intro,italic,log,onUnknownSubcommand,outro}from"@stacksjs/cli";import{printAsync}from"@stacksjs/cli/output";import{Action}from"@stacksjs/enums";import{withholdEnv}from"@stacksjs/env";import{ExitCode}from"@stacksjs/types";import{AppStoreConnect,appStoreConnectCredentials,buildsToExpire,waitForBuild}from"../app-store-connect";import{bumpedVersion,iosReleaseSummary,iosVersionIn,nextBuildTag,pushIosReleaseTag,unreleasableSite,withIosVersion}from"../release-ios";import{appStoreLocales,commitsBetween,committedWhatToTest,fitNotes,NO_VISIBLE_CHANGES,PLAY_NOTES_LIMIT,previousMobileTag,resolveNotes,TESTFLIGHT_NOTES_LIMIT,testerNotes,writeWhatToTest,XCODE_CLOUD_NOTES_LIMIT}from"@stacksjs/actions/release-notes";import{resultFailed}from"../result";const descriptions={release:"Release a new version of your libraries/packages",project:"Target a specific project",dryRun:"Run the release without actually releasing",bump:"Non-interactive bump: patch | minor | major | prepatch | preminor | premajor | prerelease | pre | release | build | calendar | x.y.z",verbose:"Enable verbose output",skipGithubRelease:"Push the tag without creating its GitHub release"},IOS_PROJECT_DIR="storage/framework/mobile/ios",DEFAULT_WAIT_MINUTES=60;async function loadMobileConfig(configPath){return(await import(pathToFileURL(configPath).href)).default??{}}export function waitMinutes(value){if(value===void 0||value===!1)return null;if(value===!0||value==="")return DEFAULT_WAIT_MINUTES;const minutes=Number(value);if(!Number.isFinite(minutes)||minutes<0)throw Error(`--wait takes minutes, not ${String(value)}`);return minutes}function buildNumberOf(tag){const match=/^v(\d+\.\d+\.\d+)-build\.(\d+)$/.exec(tag);if(!match)throw Error(`${tag} is not an iOS build tag (v<version>-build.<n>)`);return{version:match[1],number:Number(match[2])}}function notesLocales(mobile){return mobile.release?.locales?.length?[...new Set(mobile.release.locales)]:appStoreLocales(mobile.ios?.nativeMessages?.languages)}async function applyWhatToTest(store,tag,notes,locales,minutes){try{const{version,number}=buildNumberOf(tag);if(minutes>0)log.info(`Waiting up to ${minutes} min for TestFlight build ${number} to reach App Store Connect\u2026`);const build=await waitForBuild(store.api,store.appId,version,number,{timeoutMs:minutes*60000,onWait:(elapsed)=>log.debug(`TestFlight build ${number} not there yet (${Math.round(elapsed/1000)}s)`)});if(!build){log.warn(`TestFlight build ${number} is not in App Store Connect yet; once it is, run \`buddy release:notes ${tag} --testflight\`.`);return!1}const text=fitNotes(notes,TESTFLIGHT_NOTES_LIMIT);await store.api.setWhatToTest(build.id,Object.fromEntries(locales.map((locale)=>[locale,text])));log.info(`Set What to Test on TestFlight build ${number} (${locales.join(", ")})`);return!0}catch(error){log.warn(`Could not set What to Test: ${error instanceof Error?error.message:String(error)}. Retry with \`buddy release:notes ${tag} --testflight\`.`);return!1}}function githubSummary(summary,notes){return`${summary.trim()}
1
+ import{execFileSync}from"node:child_process";import{existsSync,readFileSync,renameSync,rmSync,writeFileSync}from"node:fs";import{join}from"node:path";import{pathToFileURL}from"node:url";import process from"node:process";import{resolveXcodegen}from"@stacksjs/actions/build/ios-toolchain";import{describeGitHubRelease,publishGitHubRelease,resolveGitHubToken}from"@stacksjs/actions/github-release";import{validateReleaseEvidencePlan,verifyReleaseEvidence}from"@stacksjs/actions/release-evidence";import{assertPublicationAllowed}from"@stacksjs/actions/publication-preflight";import{runAction}from"@stacksjs/actions/run-action";import{intro,italic,log,onUnknownSubcommand,outro}from"@stacksjs/cli";import{printAsync}from"@stacksjs/cli/output";import{Action}from"@stacksjs/enums";import{withholdEnv}from"@stacksjs/env";import{ExitCode}from"@stacksjs/types";import{AppStoreConnect,appStoreConnectCredentials,buildsToExpire,waitForBuild}from"../app-store-connect";import{bumpedVersion,iosReleaseSummary,iosVersionIn,nextBuildTag,pushIosReleaseTag,unreleasableSite,withIosVersion}from"../release-ios";import{appStoreLocales,commitsBetween,committedWhatToTest,fitNotes,NO_VISIBLE_CHANGES,PLAY_NOTES_LIMIT,previousMobileTag,resolveNotes,TESTFLIGHT_NOTES_LIMIT,testerNotes,writeWhatToTest,XCODE_CLOUD_NOTES_LIMIT}from"@stacksjs/actions/release-notes";import{resultFailed}from"../result";const descriptions={release:"Release a new version of your libraries/packages",project:"Target a specific project",dryRun:"Run the release without actually releasing",bump:"Non-interactive bump: patch | minor | major | prepatch | preminor | premajor | prerelease | pre | release | build | calendar | x.y.z",verbose:"Enable verbose output",skipGithubRelease:"Push the tag without creating its GitHub release"},IOS_PROJECT_DIR="storage/framework/mobile/ios",DEFAULT_WAIT_MINUTES=60;async function loadMobileConfig(configPath){return(await import(pathToFileURL(configPath).href)).default??{}}export function waitMinutes(value){if(value===void 0||value===!1)return null;if(value===!0||value==="")return DEFAULT_WAIT_MINUTES;const minutes=Number(value);if(!Number.isFinite(minutes)||minutes<0)throw Error(`--wait takes minutes, not ${String(value)}`);return minutes}export function retainedBuildCount(value){if(value!==void 0&&typeof value!=="number"&&typeof value!=="string"||typeof value==="string"&&!/^(0|[1-9]\d*)$/.test(value.trim()))throw Error("--keep-builds needs a nonnegative integer");const count=Number(value??1);if(!Number.isSafeInteger(count)||count<0)throw Error("--keep-builds needs a nonnegative integer");return count}function buildNumberOf(tag){const match=/^v(\d+\.\d+\.\d+)-build\.(\d+)$/.exec(tag);if(!match)throw Error(`${tag} is not an iOS build tag (v<version>-build.<n>)`);return{version:match[1],number:Number(match[2])}}function notesLocales(mobile){return mobile.release?.locales?.length?[...new Set(mobile.release.locales)]:appStoreLocales(mobile.ios?.nativeMessages?.languages)}async function applyWhatToTest(store,tag,notes,locales,minutes){try{const{version,number}=buildNumberOf(tag);if(minutes>0)log.info(`Waiting up to ${minutes} min for TestFlight build ${number} to reach App Store Connect\u2026`);const build=await waitForBuild(store.api,store.appId,version,number,{timeoutMs:minutes*60000,onWait:(elapsed)=>log.debug(`TestFlight build ${number} not there yet (${Math.round(elapsed/1000)}s)`)});if(!build){log.warn(`TestFlight build ${number} is not in App Store Connect yet; once it is, run \`buddy release:notes ${tag} --testflight\`.`);return!1}const text=fitNotes(notes,TESTFLIGHT_NOTES_LIMIT);await store.api.setWhatToTest(build.id,Object.fromEntries(locales.map((locale)=>[locale,text])));log.info(`Set What to Test on TestFlight build ${number} (${locales.join(", ")})`);return!0}catch(error){log.warn(`Could not set What to Test: ${error instanceof Error?error.message:String(error)}. Retry with \`buddy release:notes ${tag} --testflight\`.`);return!1}}async function deliverTestFlight(store,tag,notes,locales,minutes,groups,keep){const{version,number}=buildNumberOf(tag);try{if(await store.api.deliverBuild(store.appId,version,number,{timeoutMs:minutes*60000,groups,keepBuilds:keep,notes:notes===void 0?void 0:Object.fromEntries(locales.map((locale)=>[locale,fitNotes(notes,TESTFLIGHT_NOTES_LIMIT)])),onWait:(elapsed)=>log.debug(`TestFlight build ${number} is not ready for its testers (${Math.round(elapsed/1000)}s)`)})){log.info(`TestFlight build ${number} is IN_BETA_TESTING${groups.length?` for ${groups.join(", ")}`:""}; older build retention is complete`);return!0}log.warn(`TestFlight build ${number} is not available to its testers yet. Older builds remain available. Resume with \`buddy release:testflight ${tag} --wait\`.`)}catch(error){log.warn(`TestFlight delivery is incomplete: ${error instanceof Error?error.message:String(error)}. Resume with \`buddy release:testflight ${tag} --wait\`.`)}return!1}function githubSummary(summary,notes){return`${summary.trim()}
2
2
 
3
3
  ## What to Test
4
4
 
5
5
  ${notes.trim()}`}function git(...args){return execFileSync("git",args,{encoding:"utf8",stdio:["ignore","pipe","pipe"]}).trim()}async function releaseIos(options){const root=process.cwd();if(!options.dryRun)await assertPublicationAllowed({cwd:root,channel:"ios"});const configPath=join(root,"config/mobile.ts");if(!existsSync(configPath))throw Error("config/mobile.ts not found: run this in a Stacks app with a mobile config");const xcodegen=await resolveXcodegen(root);log.info(`xcodegen ${xcodegen.version} from Pantry (${xcodegen.path})`);const branch=git("rev-parse","--abbrev-ref","HEAD");if(branch!=="main")throw Error(`releases are cut from main; this is ${branch}`);if(git("status","--porcelain","--untracked-files=no"))throw Error("commit or stash your changes first, so the release is exactly what is on main");if(!options.dryRun){git("pull","--quiet","--rebase","origin","main");git("fetch","--quiet","--tags","origin");await assertPublicationAllowed({cwd:root,channel:"ios"})}const source=readFileSync(configPath,"utf8"),current=iosVersionIn(source);if(!current)throw Error("config/mobile.ts declares no iOS `version`");const version=options.bump?bumpedVersion(current,options.bump):current,existingTags=git("tag","--list",`v${version}-build.*`).split(`
6
- `).filter(Boolean);let tag=nextBuildTag(version,existingTags);const wait=waitMinutes(options.wait),mobile=await loadMobileConfig(configPath),credentials=appStoreConnectCredentials();let store=null,numberedByXcodeCloud=!1;if(credentials){const bundleId=mobile.ios?.bundleId;if(!bundleId)throw Error("config/mobile.ts declares no ios.bundleId");const api=await AppStoreConnect.connect(credentials);store={api,appId:await api.appId(bundleId)};const latestRun=await api.latestXcodeCloudRun(store.appId);if(latestRun!==null){tag=nextBuildTag(version,existingTags,latestRun);numberedByXcodeCloud=!0}}else log.warn("No App Store Connect API key (APP_STORE_CONNECT_KEY_ID, _ISSUER_ID, _PRIVATE_KEY_PATH): the tag counts releases, not the build number TestFlight will show, and older builds stay listed.");log.info(`Releasing ${tag}${version===current?"":` (version ${current} \u2192 ${version})`}`);const keep=Math.max(0,Number(options.keepBuilds??1)||0),summary=iosReleaseSummary(tag,{numberedByXcodeCloud}),releaseConfig=mobile.release??{},previous=previousMobileTag(root,"HEAD"),commits=commitsBetween(root,previous,"HEAD"),generateOptions={types:releaseConfig.noteTypes,excludeScopes:releaseConfig.excludeScopes},notes=resolveNotes({cwd:root,flags:options,config:releaseConfig,generate:()=>testerNotes(commits,generateOptions)}),githubNotes=notes.source==="generated"?testerNotes(commits,{...generateOptions,markdown:!0})||NO_VISIBLE_CHANGES:notes.text,locales=notesLocales(mobile),origin=notes.source==="generated"?`${commits.length} commits since ${previous??"the first commit"}`:{flag:"--notes",env:"RELEASE_NOTES",config:"config/mobile.ts release.notes"}[notes.source];if(wait!==null&&!numberedByXcodeCloud)log.warn("--wait needs an App Store Connect API key and an Xcode Cloud product to know the TestFlight build; Xcode Cloud still reads the What to Test file.");if(options.dryRun){log.info(`What to Test (${origin}; ${locales.map((locale)=>`TestFlight/WhatToTest.${locale}.txt`).join(", ")}):
6
+ `).filter(Boolean);let tag=nextBuildTag(version,existingTags);const wait=waitMinutes(options.wait),mobile=await loadMobileConfig(configPath),credentials=appStoreConnectCredentials();let store=null,numberedByXcodeCloud=!1;if(credentials){const bundleId=mobile.ios?.bundleId;if(!bundleId)throw Error("config/mobile.ts declares no ios.bundleId");const api=await AppStoreConnect.connect(credentials);store={api,appId:await api.appId(bundleId)};const latestRun=await api.latestXcodeCloudRun(store.appId);if(latestRun!==null){tag=nextBuildTag(version,existingTags,latestRun);numberedByXcodeCloud=!0}}else log.warn("No App Store Connect API key (APP_STORE_CONNECT_KEY_ID, _ISSUER_ID, _PRIVATE_KEY_PATH): the tag counts releases, not the build number TestFlight will show, and older builds stay listed.");log.info(`Releasing ${tag}${version===current?"":` (version ${current} \u2192 ${version})`}`);const keep=retainedBuildCount(options.keepBuilds),groups=mobile.ios?.testFlightGroups??[];if(!Array.isArray(groups))throw Error("ios.testFlightGroups must be an array of existing internal group names");if(groups.length&&!store)throw Error("ios.testFlightGroups requires an App Store Connect API key");if(store)await store.api.internalTestFlightGroups(store.appId,groups);const summary=iosReleaseSummary(tag,{numberedByXcodeCloud}),releaseConfig=mobile.release??{},previous=previousMobileTag(root,"HEAD"),commits=commitsBetween(root,previous,"HEAD"),generateOptions={types:releaseConfig.noteTypes,excludeScopes:releaseConfig.excludeScopes},notes=resolveNotes({cwd:root,flags:options,config:releaseConfig,generate:()=>testerNotes(commits,generateOptions)}),githubNotes=notes.source==="generated"?testerNotes(commits,{...generateOptions,markdown:!0})||NO_VISIBLE_CHANGES:notes.text,locales=notesLocales(mobile),origin=notes.source==="generated"?`${commits.length} commits since ${previous??"the first commit"}`:{flag:"--notes",env:"RELEASE_NOTES",config:"config/mobile.ts release.notes"}[notes.source];if(wait!==null&&!numberedByXcodeCloud)log.warn("--wait needs an App Store Connect API key and an Xcode Cloud product to know the TestFlight build; Xcode Cloud still reads the What to Test file.");if(options.dryRun){log.info(`What to Test (${origin}; ${locales.map((locale)=>`TestFlight/WhatToTest.${locale}.txt`).join(", ")}):
7
7
 
8
- ${fitNotes(notes.text,XCODE_CLOUD_NOTES_LIMIT)}`);if(store){const retiring=buildsToExpire(await store.api.builds(store.appId),keep);log.info(retiring.length?`Would expire TestFlight builds ${retiring.map((b)=>b.number).join(", ")}`:"No TestFlight builds to expire")}if(!options.skipGithubRelease){const preview=await publishGitHubRelease({cwd:root,tag,ref:"HEAD",name:summary.name,summary:githubSummary(summary.body,githubNotes),dryRun:!0});log.info(preview.draft?`Would create the GitHub release ${tag} (${preview.draft.name}):
8
+ ${fitNotes(notes.text,XCODE_CLOUD_NOTES_LIMIT)}`);if(store){const retiring=buildsToExpire(await store.api.builds(store.appId),keep);log.info(retiring.length?`After the new build is available to its testers, would expire TestFlight builds ${retiring.map((b)=>b.number).join(", ")}`:"No TestFlight builds to expire")}if(!options.skipGithubRelease){const preview=await publishGitHubRelease({cwd:root,tag,ref:"HEAD",name:summary.name,summary:githubSummary(summary.body,githubNotes),dryRun:!0});log.info(preview.draft?`Would create the GitHub release ${tag} (${preview.draft.name}):
9
9
 
10
- ${preview.draft.body}`:describeGitHubRelease(tag,preview))}return tag}const paths=["config/mobile.ts","storage/framework/mobile/ios"];if(version!==current){writeFileSync(configPath,withIosVersion(source,version));const pkgPath=join(root,"package.json");if(existsSync(pkgPath)){const pkg=readFileSync(pkgPath,"utf8");writeFileSync(pkgPath,pkg.replace(/("version"\s*:\s*)"[^"]*"/,`$1"${version}"`));paths.push("package.json")}}const devOverrides=["MOBILE_URL","IOS_APP_VERSION","IOS_BUILD_NUMBER"];for(const key of devOverrides)delete process.env[key];const result=await runAction(Action.BuildIos,{env:{...withholdEnv(devOverrides),NODE_ENV:"production"}});if(resultFailed(result))throw result.error??Error("the iOS build failed");const craftConfigPath=join(root,IOS_PROJECT_DIR,"craft.config.json");if(existsSync(craftConfigPath)){const problem=unreleasableSite(JSON.parse(readFileSync(craftConfigPath,"utf8")));if(problem)throw Error(`${problem}. Set ios.url in config/mobile.ts to the production site. Nothing was committed, tagged or pushed; restore the build output and any version bump with \`git checkout -- ${paths.join(" ")}\`.`)}const written=writeWhatToTest(root,IOS_PROJECT_DIR,notes.text,locales);log.info(`What to Test from ${origin}: ${written.join(", ")}`);git("add","--",...paths);if(git("diff","--cached","--name-only"))git("commit","--quiet","-m",`chore(release): ${tag}`);pushIosReleaseTag(root,tag);if(!options.skipGithubRelease){const published=await publishGitHubRelease({cwd:root,tag,name:summary.name,summary:githubSummary(summary.body,githubNotes)});if(published.status==="failed")log.warn(describeGitHubRelease(tag,published));else log.info(describeGitHubRelease(tag,published))}if(store){try{const retiring=buildsToExpire(await store.api.builds(store.appId),keep);for(const build of retiring)await store.api.expire(build.id);if(retiring.length)log.info(`Expired TestFlight builds ${retiring.map((b)=>b.number).join(", ")}`)}catch(error){log.warn(`Could not expire older TestFlight builds: ${error instanceof Error?error.message:String(error)}`)}if(wait!==null&&numberedByXcodeCloud)await applyWhatToTest(store,tag,notes.text,locales,wait)}return tag}function notesForTag(root,tag,mobile,options){const releaseConfig=mobile.release??{},generateOptions={types:releaseConfig.noteTypes,excludeScopes:releaseConfig.excludeScopes},from=options.from||previousMobileTag(root,`${tag}^`),commits=commitsBetween(root,from,tag),plainGenerated=testerNotes(commits,generateOptions)||NO_VISIBLE_CHANGES,committed=options.from?null:committedWhatToTest(root,tag,IOS_PROJECT_DIR),handWritten=committed&&committed.trim()!==fitNotes(plainGenerated,XCODE_CLOUD_NOTES_LIMIT)?committed.trim():null,notes=resolveNotes({cwd:root,flags:options,config:releaseConfig,generate:()=>handWritten??plainGenerated});if(notes.source!=="generated"||handWritten)return{text:notes.text,plain:notes.text};return{text:options.markdown?testerNotes(commits,{...generateOptions,markdown:!0})||NO_VISIBLE_CHANGES:plainGenerated,plain:plainGenerated}}async function releaseNotesCommand(tagArgument,options){const root=process.cwd(),configPath=join(root,"config/mobile.ts"),mobile=existsSync(configPath)?await loadMobileConfig(configPath):{},tag=tagArgument||previousMobileTag(root,"HEAD");if(!tag||!git("tag","--list",tag))throw Error(tagArgument?`there is no tag ${tagArgument}`:"there is no mobile release tag (v*-build.*) yet");const notes=notesForTag(root,tag,mobile,options);if(options.testflight){const credentials=appStoreConnectCredentials();if(!credentials)throw Error("--testflight needs an App Store Connect API key (APP_STORE_CONNECT_KEY_ID, _ISSUER_ID, _PRIVATE_KEY_PATH)");const bundleId=mobile.ios?.bundleId;if(!bundleId)throw Error("config/mobile.ts declares no ios.bundleId");const api=await AppStoreConnect.connect(credentials),store={api,appId:await api.appId(bundleId)};if(!await applyWhatToTest(store,tag,notes.plain,notesLocales(mobile),waitMinutes(options.wait)??0))process.exitCode=ExitCode.FatalError;return}const limit=options.play?PLAY_NOTES_LIMIT:options.markdown?Number.POSITIVE_INFINITY:TESTFLIGHT_NOTES_LIMIT;await printAsync(Number.isFinite(limit)?fitNotes(notes.text,limit):notes.text)}export function release(buddy){buddy.command("release",descriptions.release).option("--dry-run",descriptions.dryRun,{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--bump <type>",descriptions.bump).option("--preid <identifier>","Prerelease channel, for example beta or rc").option("--skip-github-release",descriptions.skipGithubRelease,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy release` ...",options);if(options.dryRun)log.warn("Dry run enabled. No changes will be made or committed.");const startTime=await intro("buddy release"),result=await runAction(Action.Release,options);if(resultFailed(result)){await log.error("Failed to release",result.error);process.exit(ExitCode.FatalError)}await outro(options.dryRun?"Dry run complete. Nothing was committed, tagged or pushed.":"Triggered CI/CD Release via GitHub Actions",{startTime,useSeconds:!0});if(!options.dryRun)log.info(`Follow along: ${italic(resolveGitHubActionsUrl(readOriginRemote()))}`)});buddy.command("release:ios","Ship the iOS app: regenerate its project for production, commit, tag and push").option("--bump <type>","build | patch | minor | major | x.y.z (default: a new build of the current marketing version)").option("--keep-builds <n>","TestFlight builds to keep besides the new one; older ones are expired (needs an App Store Connect API key)",{default:1}).option("--skip-github-release",descriptions.skipGithubRelease,{default:!1}).option("--notes <text>","What to Test for this build, instead of the notes generated from the commits since the previous build").option("--notes-file <path>","Read What to Test from a file (also RELEASE_NOTES / RELEASE_NOTES_FILE, or release.notes in config/mobile.ts)").option("--wait [minutes]","Wait for the build to reach App Store Connect, then set its What to Test there too (default 60 minutes; needs an App Store Connect API key)").option("--dry-run",descriptions.dryRun,{default:!1}).action(async(options)=>{const startTime=await intro("buddy release:ios");try{const tag=await releaseIos(options);await outro(options.dryRun?`Dry run complete: would release ${tag}`:`Released ${tag}`,{startTime,useSeconds:!0});if(!options.dryRun)log.info('A CI that builds tags (Xcode Cloud: Tag Changes, prefix "v") turns it into a TestFlight build now.')}catch(error){await log.error("Failed to release the iOS app",error);process.exit(ExitCode.FatalError)}});buddy.command("release:notes [tag]","Print the tester notes of a mobile release tag (default: the newest v*-build.* tag), or set them as its TestFlight What to Test").option("--from <ref>","Generate from the commits since this ref instead of the previous build tag").option("--play","Fit the notes to Google Play's 500-character What's new",{default:!1}).option("--markdown","Markdown, as the GitHub release shows the notes",{default:!1}).option("--testflight","Set the notes as the TestFlight build's What to Test through App Store Connect",{default:!1}).option("--wait [minutes]","With --testflight: wait this long for the build to appear (default 60)").option("--notes <text>","Use this text instead").option("--notes-file <path>","Read the text from a file instead").action(async(tag,options)=>{try{await releaseNotesCommand(tag,options)}catch(error){await log.error("Failed to produce the release notes",error);process.exit(ExitCode.FatalError)}});buddy.command("release:github [tag]","Create the GitHub release for a pushed tag (default: the newest), with the changes since the tag before it").option("--dry-run","Print the release instead of creating it",{default:!1}).action(async(tag,options)=>{const startTime=await intro("buddy release:github");try{if(!options.dryRun)await assertPublicationAllowed({cwd:process.cwd(),channel:"github-release"});const target=tag||git("describe","--tags","--abbrev=0");if(!git("tag","--list",target))throw Error(`there is no tag ${target}`);const ios=/^v\d+\.\d+\.\d+-build\.\d+$/.test(target)?iosReleaseSummary(target,{numberedByXcodeCloud:appStoreConnectCredentials()!==null}):null;let summary=ios?.body;if(ios){const configPath=join(process.cwd(),"config/mobile.ts"),mobile=existsSync(configPath)?await loadMobileConfig(configPath):{};summary=githubSummary(ios.body,notesForTag(process.cwd(),target,mobile,{markdown:!0}).text)}const result=await publishGitHubRelease({cwd:process.cwd(),tag:target,name:ios?.name,summary,dryRun:options.dryRun});if(result.status==="failed")throw Error(describeGitHubRelease(target,result));log.info(options.dryRun&&result.draft?`Would create the GitHub release ${target} (${result.draft.name}):
10
+ ${preview.draft.body}`:describeGitHubRelease(tag,preview))}return tag}const paths=["config/mobile.ts","storage/framework/mobile/ios"];if(version!==current){writeFileSync(configPath,withIosVersion(source,version));const pkgPath=join(root,"package.json");if(existsSync(pkgPath)){const pkg=readFileSync(pkgPath,"utf8");writeFileSync(pkgPath,pkg.replace(/("version"\s*:\s*)"[^"]*"/,`$1"${version}"`));paths.push("package.json")}}const devOverrides=["MOBILE_URL","IOS_APP_VERSION","IOS_BUILD_NUMBER"];for(const key of devOverrides)delete process.env[key];const result=await runAction(Action.BuildIos,{env:{...withholdEnv(devOverrides),NODE_ENV:"production"}});if(resultFailed(result))throw result.error??Error("the iOS build failed");const craftConfigPath=join(root,IOS_PROJECT_DIR,"craft.config.json");if(existsSync(craftConfigPath)){const problem=unreleasableSite(JSON.parse(readFileSync(craftConfigPath,"utf8")));if(problem)throw Error(`${problem}. Set ios.url in config/mobile.ts to the production site. Nothing was committed, tagged or pushed; restore the build output and any version bump with \`git checkout -- ${paths.join(" ")}\`.`)}const written=writeWhatToTest(root,IOS_PROJECT_DIR,notes.text,locales);log.info(`What to Test from ${origin}: ${written.join(", ")}`);git("add","--",...paths);if(git("diff","--cached","--name-only"))git("commit","--quiet","-m",`chore(release): ${tag}`);pushIosReleaseTag(root,tag);if(!options.skipGithubRelease){const published=await publishGitHubRelease({cwd:root,tag,name:summary.name,summary:githubSummary(summary.body,githubNotes)});if(published.status==="failed")log.warn(describeGitHubRelease(tag,published));else log.info(describeGitHubRelease(tag,published))}if(store)if(wait!==null&&numberedByXcodeCloud){if(!await deliverTestFlight(store,tag,notes.text,locales,wait,groups,keep))process.exitCode=ExitCode.FatalError}else log.info(`Older TestFlight builds are retained. Complete tester delivery with \`buddy release:testflight ${tag} --wait\`.`);return tag}function notesForTag(root,tag,mobile,options){const releaseConfig=mobile.release??{},generateOptions={types:releaseConfig.noteTypes,excludeScopes:releaseConfig.excludeScopes},from=options.from||previousMobileTag(root,`${tag}^`),commits=commitsBetween(root,from,tag),plainGenerated=testerNotes(commits,generateOptions)||NO_VISIBLE_CHANGES,committed=options.from?null:committedWhatToTest(root,tag,IOS_PROJECT_DIR),handWritten=committed&&committed.trim()!==fitNotes(plainGenerated,XCODE_CLOUD_NOTES_LIMIT)?committed.trim():null,notes=resolveNotes({cwd:root,flags:options,config:releaseConfig,generate:()=>handWritten??plainGenerated});if(notes.source!=="generated"||handWritten)return{text:notes.text,plain:notes.text};return{text:options.markdown?testerNotes(commits,{...generateOptions,markdown:!0})||NO_VISIBLE_CHANGES:plainGenerated,plain:plainGenerated}}async function releaseNotesCommand(tagArgument,options){const root=process.cwd(),configPath=join(root,"config/mobile.ts"),mobile=existsSync(configPath)?await loadMobileConfig(configPath):{},tag=tagArgument||previousMobileTag(root,"HEAD");if(!tag||!git("tag","--list",tag))throw Error(tagArgument?`there is no tag ${tagArgument}`:"there is no mobile release tag (v*-build.*) yet");const notes=notesForTag(root,tag,mobile,options);if(options.testflight){const credentials=appStoreConnectCredentials();if(!credentials)throw Error("--testflight needs an App Store Connect API key (APP_STORE_CONNECT_KEY_ID, _ISSUER_ID, _PRIVATE_KEY_PATH)");const bundleId=mobile.ios?.bundleId;if(!bundleId)throw Error("config/mobile.ts declares no ios.bundleId");const api=await AppStoreConnect.connect(credentials),store={api,appId:await api.appId(bundleId)};if(!await applyWhatToTest(store,tag,notes.plain,notesLocales(mobile),waitMinutes(options.wait)??0))process.exitCode=ExitCode.FatalError;return}const limit=options.play?PLAY_NOTES_LIMIT:options.markdown?Number.POSITIVE_INFINITY:TESTFLIGHT_NOTES_LIMIT;await printAsync(Number.isFinite(limit)?fitNotes(notes.text,limit):notes.text)}async function releaseTestFlightCommand(tagArgument,options){const root=process.cwd();if(!options.dryRun)await assertPublicationAllowed({cwd:root,channel:"ios"});const mobile=await loadMobileConfig(join(root,"config/mobile.ts")),tag=tagArgument||previousMobileTag(root,"HEAD");if(!tag||!git("tag","--list",tag))throw Error("Select an existing mobile release tag");buildNumberOf(tag);const credentials=appStoreConnectCredentials();if(!credentials||!mobile.ios?.bundleId)throw Error("TestFlight delivery needs an App Store Connect API key and ios.bundleId");const api=await AppStoreConnect.connect(credentials),store={api,appId:await api.appId(mobile.ios.bundleId)},groups=mobile.ios.testFlightGroups??[];await api.internalTestFlightGroups(store.appId,groups);const keep=retainedBuildCount(options.keepBuilds);if(options.dryRun){log.info(`Would deliver ${tag}${groups.length?` to ${groups.join(", ")}`:" using its existing internal tester access"}, confirm IN_BETA_TESTING, then retain ${keep} older builds. Nothing was distributed or expired.`);return}if(!await deliverTestFlight(store,tag,void 0,notesLocales(mobile),waitMinutes(options.wait)??DEFAULT_WAIT_MINUTES,groups,keep))process.exitCode=ExitCode.FatalError}export function release(buddy){buddy.command("release",descriptions.release).option("--dry-run",descriptions.dryRun,{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--bump <type>",descriptions.bump).option("--preid <identifier>","Prerelease channel, for example beta or rc").option("--skip-github-release",descriptions.skipGithubRelease,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy release` ...",options);if(options.dryRun)log.warn("Dry run enabled. No changes will be made or committed.");const startTime=await intro("buddy release"),result=await runAction(Action.Release,options);if(resultFailed(result)){await log.error("Failed to release",result.error);process.exit(ExitCode.FatalError)}await outro(options.dryRun?"Dry run complete. Nothing was committed, tagged or pushed.":"Triggered CI/CD Release via GitHub Actions",{startTime,useSeconds:!0});if(!options.dryRun)log.info(`Follow along: ${italic(resolveGitHubActionsUrl(readOriginRemote()))}`)});buddy.command("release:ios","Ship the iOS app: regenerate its project for production, commit, tag and push").option("--bump <type>","build | patch | minor | major | x.y.z (default: a new build of the current marketing version)").option("--keep-builds <n>","Older TestFlight builds to retain after the replacement is available to testers (needs an App Store Connect API key)",{default:1}).option("--skip-github-release",descriptions.skipGithubRelease,{default:!1}).option("--notes <text>","What to Test for this build, instead of the notes generated from the commits since the previous build").option("--notes-file <path>","Read What to Test from a file (also RELEASE_NOTES / RELEASE_NOTES_FILE, or release.notes in config/mobile.ts)").option("--wait [minutes]","Wait for processing, notes and configured internal TestFlight group delivery (default 60 minutes; needs an App Store Connect API key)").option("--dry-run",descriptions.dryRun,{default:!1}).action(async(options)=>{const startTime=await intro("buddy release:ios");try{const tag=await releaseIos(options);await outro(options.dryRun?`Dry run complete: would release ${tag}`:process.exitCode?`Published ${tag}; TestFlight delivery is incomplete`:`Released ${tag}`,{startTime,useSeconds:!0});if(!options.dryRun)log.info('A CI that builds tags (Xcode Cloud: Tag Changes, prefix "v") turns it into a TestFlight build now.')}catch(error){await log.error("Failed to release the iOS app",error);process.exit(ExitCode.FatalError)}});buddy.command("release:testflight [tag]","Complete internal tester delivery for an existing iOS release tag").option("--wait [minutes]","Wait for processing and tester availability (default 60 minutes)").option("--keep-builds <n>","Older builds to retain after tester delivery succeeds",{default:1}).option("--dry-run",descriptions.dryRun,{default:!1}).action(async(tag,options)=>{try{await releaseTestFlightCommand(tag,options)}catch(error){await log.error("Failed to deliver the TestFlight build",error);process.exit(ExitCode.FatalError)}});buddy.command("release:notes [tag]","Print the tester notes of a mobile release tag (default: the newest v*-build.* tag), or set them as its TestFlight What to Test").option("--from <ref>","Generate from the commits since this ref instead of the previous build tag").option("--play","Fit the notes to Google Play's 500-character What's new",{default:!1}).option("--markdown","Markdown, as the GitHub release shows the notes",{default:!1}).option("--testflight","Set the notes as the TestFlight build's What to Test through App Store Connect",{default:!1}).option("--wait [minutes]","With --testflight: wait this long for the build to appear (default 60)").option("--notes <text>","Use this text instead").option("--notes-file <path>","Read the text from a file instead").action(async(tag,options)=>{try{await releaseNotesCommand(tag,options)}catch(error){await log.error("Failed to produce the release notes",error);process.exit(ExitCode.FatalError)}});buddy.command("release:github [tag]","Create the GitHub release for a pushed tag (default: the newest), with the changes since the tag before it").option("--dry-run","Print the release instead of creating it",{default:!1}).action(async(tag,options)=>{const startTime=await intro("buddy release:github");try{if(!options.dryRun)await assertPublicationAllowed({cwd:process.cwd(),channel:"github-release"});const target=tag||git("describe","--tags","--abbrev=0");if(!git("tag","--list",target))throw Error(`there is no tag ${target}`);const ios=/^v\d+\.\d+\.\d+-build\.\d+$/.test(target)?iosReleaseSummary(target,{numberedByXcodeCloud:appStoreConnectCredentials()!==null}):null;let summary=ios?.body;if(ios){const configPath=join(process.cwd(),"config/mobile.ts"),mobile=existsSync(configPath)?await loadMobileConfig(configPath):{};summary=githubSummary(ios.body,notesForTag(process.cwd(),target,mobile,{markdown:!0}).text)}const result=await publishGitHubRelease({cwd:process.cwd(),tag:target,name:ios?.name,summary,dryRun:options.dryRun});if(result.status==="failed")throw Error(describeGitHubRelease(target,result));log.info(options.dryRun&&result.draft?`Would create the GitHub release ${target} (${result.draft.name}):
11
11
 
12
12
  ${result.draft.body}`:describeGitHubRelease(target,result));await outro(options.dryRun?"Dry run complete. Nothing was created.":`GitHub release for ${target}`,{startTime,useSeconds:!0})}catch(error){await log.error("Failed to create the GitHub release",error);process.exit(ExitCode.FatalError)}});buddy.command("release:verify <plan>","Verify exact source gates, published archives and installed consumer checks").option("--output <path>","Save the successful verification receipt as JSON").action(async(planPath,options)=>{let temporary;try{const plan=JSON.parse(readFileSync(planPath,"utf8"));validateReleaseEvidencePlan(plan);const receipt=await verifyReleaseEvidence(plan,{cwd:process.cwd(),token:resolveGitHubToken()??void 0}),json=`${JSON.stringify(receipt,null,2)}
13
13
  `;if(options.output){temporary=`${options.output}.${crypto.randomUUID()}.tmp`;writeFileSync(temporary,json,{flag:"wx",mode:384});renameSync(temporary,options.output);temporary=void 0;await printAsync(`Verified release evidence saved to ${options.output}`)}else await printAsync(json.trimEnd())}catch(error){if(temporary)rmSync(temporary,{force:!0});await log.error("Release verification failed",error);process.exitCode=ExitCode.FatalError}});onUnknownSubcommand(buddy,"release")}export function resolveGitHubActionsUrl(remoteUrl,repository=process.env.GITHUB_REPOSITORY,serverUrl=process.env.GITHUB_SERVER_URL??"https://github.com"){const repo=repository?.trim()||remoteUrl?.trim().match(/github\.com[/:]([^/\s]+\/[^/\s]+?)(?:\.git)?$/)?.[1];return repo?`${serverUrl.replace(/\/$/,"")}/${repo}/actions`:"https://github.com/stacksjs/stacks/actions"}function readOriginRemote(){try{return execFileSync("git",["config","--get","remote.origin.url"],{encoding:"utf8"}).trim()}catch{return}}
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/buddy",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.468",
5
+ "version": "0.75.473",
6
6
  "description": "Meet Buddy. The Stacks runtime.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -95,72 +95,72 @@
95
95
  "prepublishOnly": "bun run build"
96
96
  },
97
97
  "dependencies": {
98
- "@stacksjs/actions": "0.75.468",
99
- "@stacksjs/ai": "0.75.468",
100
- "@stacksjs/alias": "0.75.468",
101
- "@stacksjs/analytics": "0.75.468",
102
- "@stacksjs/api": "0.75.468",
103
- "@stacksjs/arrays": "0.75.468",
104
- "@stacksjs/auth": "0.75.468",
105
- "@stacksjs/browser-extension": "0.75.468",
106
- "@stacksjs/build": "0.75.468",
98
+ "@stacksjs/actions": "0.75.473",
99
+ "@stacksjs/ai": "0.75.473",
100
+ "@stacksjs/alias": "0.75.473",
101
+ "@stacksjs/analytics": "0.75.473",
102
+ "@stacksjs/api": "0.75.473",
103
+ "@stacksjs/arrays": "0.75.473",
104
+ "@stacksjs/auth": "0.75.473",
105
+ "@stacksjs/browser-extension": "0.75.473",
106
+ "@stacksjs/build": "0.75.473",
107
107
  "@stacksjs/bumpx": "^0.2.26",
108
- "@stacksjs/cache": "0.75.468",
109
- "@stacksjs/chat": "0.75.468",
108
+ "@stacksjs/cache": "0.75.473",
109
+ "@stacksjs/chat": "0.75.473",
110
110
  "@stacksjs/clapp": "^0.2.16",
111
- "@stacksjs/cli": "0.75.468",
112
- "@stacksjs/cloud": "0.75.468",
113
- "@stacksjs/cms": "0.75.468",
114
- "@stacksjs/collections": "0.75.468",
115
- "@stacksjs/commerce": "0.75.468",
116
- "@stacksjs/config": "0.75.468",
117
- "@stacksjs/database": "0.75.468",
118
- "@stacksjs/desktop-build": "0.75.468",
119
- "@stacksjs/dns": "0.75.468",
111
+ "@stacksjs/cli": "0.75.473",
112
+ "@stacksjs/cloud": "0.75.473",
113
+ "@stacksjs/cms": "0.75.473",
114
+ "@stacksjs/collections": "0.75.473",
115
+ "@stacksjs/commerce": "0.75.473",
116
+ "@stacksjs/config": "0.75.473",
117
+ "@stacksjs/database": "0.75.473",
118
+ "@stacksjs/desktop-build": "0.75.473",
119
+ "@stacksjs/dns": "0.75.473",
120
120
  "@stacksjs/dnsx": "^0.2.3",
121
- "@stacksjs/email": "0.75.468",
122
- "@stacksjs/enums": "0.75.468",
123
- "@stacksjs/env": "0.75.468",
124
- "@stacksjs/error-handling": "0.75.468",
125
- "@stacksjs/events": "0.75.468",
126
- "@stacksjs/features": "0.75.468",
127
- "@stacksjs/git": "0.75.468",
121
+ "@stacksjs/email": "0.75.473",
122
+ "@stacksjs/enums": "0.75.473",
123
+ "@stacksjs/env": "0.75.473",
124
+ "@stacksjs/error-handling": "0.75.473",
125
+ "@stacksjs/events": "0.75.473",
126
+ "@stacksjs/features": "0.75.473",
127
+ "@stacksjs/git": "0.75.473",
128
128
  "@stacksjs/gitit": "^0.2.5",
129
- "@stacksjs/health": "0.75.468",
129
+ "@stacksjs/health": "0.75.473",
130
130
  "@stacksjs/httx": "^0.1.10",
131
- "@stacksjs/image": "0.75.468",
132
- "@stacksjs/lint": "0.75.468",
133
- "@stacksjs/logging": "0.75.468",
134
- "@stacksjs/notifications": "0.75.468",
135
- "@stacksjs/objects": "0.75.468",
136
- "@stacksjs/orm": "0.75.468",
137
- "@stacksjs/path": "0.75.468",
138
- "@stacksjs/payments": "0.75.468",
139
- "@stacksjs/realtime": "0.75.468",
140
- "@stacksjs/router": "0.75.468",
131
+ "@stacksjs/image": "0.75.473",
132
+ "@stacksjs/lint": "0.75.473",
133
+ "@stacksjs/logging": "0.75.473",
134
+ "@stacksjs/notifications": "0.75.473",
135
+ "@stacksjs/objects": "0.75.473",
136
+ "@stacksjs/orm": "0.75.473",
137
+ "@stacksjs/path": "0.75.473",
138
+ "@stacksjs/payments": "0.75.473",
139
+ "@stacksjs/realtime": "0.75.473",
140
+ "@stacksjs/router": "0.75.473",
141
141
  "@stacksjs/rpx": "^0.11.54",
142
- "@stacksjs/scheduler": "0.75.468",
143
- "@stacksjs/search-engine": "0.75.468",
144
- "@stacksjs/security": "0.75.468",
145
- "@stacksjs/server": "0.75.468",
146
- "@stacksjs/sites": "0.75.468",
147
- "@stacksjs/skills": "0.75.468",
148
- "@stacksjs/socials": "0.75.468",
149
- "@stacksjs/storage": "0.75.468",
150
- "@stacksjs/strings": "0.75.468",
151
- "@stacksjs/stx": "0.2.798",
152
- "@stacksjs/testing": "0.75.468",
153
- "@stacksjs/tinker": "0.75.468",
142
+ "@stacksjs/scheduler": "0.75.473",
143
+ "@stacksjs/search-engine": "0.75.473",
144
+ "@stacksjs/security": "0.75.473",
145
+ "@stacksjs/server": "0.75.473",
146
+ "@stacksjs/sites": "0.75.473",
147
+ "@stacksjs/skills": "0.75.473",
148
+ "@stacksjs/socials": "0.75.473",
149
+ "@stacksjs/storage": "0.75.473",
150
+ "@stacksjs/strings": "0.75.473",
151
+ "@stacksjs/stx": "0.2.800",
152
+ "@stacksjs/testing": "0.75.473",
153
+ "@stacksjs/tinker": "0.75.473",
154
154
  "@stacksjs/tlsx": "^0.13.19",
155
- "@stacksjs/ts-cloud": "^0.16.91",
156
- "@stacksjs/tunnel": "0.75.468",
157
- "@stacksjs/types": "0.75.468",
158
- "@stacksjs/ui": "0.75.468",
159
- "@stacksjs/utils": "0.75.468",
160
- "@stacksjs/validation": "0.75.468",
155
+ "@stacksjs/ts-cloud": "^0.16.92",
156
+ "@stacksjs/tunnel": "0.75.473",
157
+ "@stacksjs/types": "0.75.473",
158
+ "@stacksjs/ui": "0.75.473",
159
+ "@stacksjs/utils": "0.75.473",
160
+ "@stacksjs/validation": "0.75.473",
161
161
  "ajv": "^8.20.0",
162
162
  "ajv-formats": "^3.0.1",
163
- "bun-plugin-stx": "0.2.798",
163
+ "bun-plugin-stx": "0.2.800",
164
164
  "ts-pantry": "^0.11.164"
165
165
  },
166
166
  "devDependencies": {