@sprid/release 0.1.1

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.
@@ -0,0 +1,256 @@
1
+ /**
2
+ * Push ASO screenshots to App Store Connect, per listing locale × display type:
3
+ *
4
+ * 1. POST /appScreenshotSets → reservation with uploadOperations
5
+ * 2. PUT bytes to each pre-signed S3 operation URL — using ONLY the
6
+ * `requestHeaders` ASC returns. Do NOT add the Bearer token to the S3
7
+ * PUT (AWS rejects the mixed signature with 400).
8
+ * 3. PATCH /appScreenshots/:id { uploaded: true, sourceFileChecksum: md5 }
9
+ *
10
+ * Idempotent: each set is re-created fresh, so re-runs replace the full
11
+ * slide-deck rather than appending. Also defensively deletes any sets for
12
+ * deprecated display types (e.g. older iPhone/iPad sizes) so prior runs don't
13
+ * leave stale slides.
14
+ *
15
+ * Config-driven via `config.ascScreenshots {dir, glob, displayType, ...}`,
16
+ * resolved with the same `{lang}` glob approach as `play/screenshots.ts`.
17
+ */
18
+
19
+ import { createHash } from 'node:crypto';
20
+ import { readdirSync, readFileSync } from 'node:fs';
21
+ import { basename, dirname, resolve } from 'node:path';
22
+ import { listingLocaleMap, releasePath, type AppReleaseConfig } from '../config.ts';
23
+ import { createAscClient } from './client.ts';
24
+ import { EDITABLE_STATES } from './version.ts';
25
+
26
+ /**
27
+ * ASC screenshot upload source (for the `asc-screenshots` command). Add this as
28
+ * an optional `ascScreenshots?: AscScreenshotsConfig` field on `AppReleaseConfig`
29
+ * in config.ts.
30
+ */
31
+ export interface AscScreenshotsConfig {
32
+ /** Base dir holding per-language screenshot folders, relative to cwd. */
33
+ dir: string;
34
+ /**
35
+ * Glob (under `dir`) for one language's ordered screenshots, with `{lang}`
36
+ * replaced by the copy-locale key (e.g. `{lang}/aso/app_{lang}_iphone-65_*.jpg`).
37
+ */
38
+ glob: string;
39
+ /** ASC display type the set targets (e.g. `APP_IPHONE_65`). */
40
+ displayType: string;
41
+ /**
42
+ * Display types wiped defensively before each run so switching `displayType`
43
+ * doesn't leave stale slide-decks (e.g. older iPhone/iPad sizes).
44
+ */
45
+ deprecatedTypes?: string[];
46
+ }
47
+
48
+ /** Config carrying the (optional) ascScreenshots field — see config.ts. */
49
+ type ConfigWithAscScreenshots = AppReleaseConfig & { ascScreenshots?: AscScreenshotsConfig };
50
+
51
+ export interface PushAscScreenshotsOptions {
52
+ config: AppReleaseConfig;
53
+ /** ASC locale → copy-locale key (defaults to listingLocales.apple / locales.apple). */
54
+ localeMap?: Record<string, string>;
55
+ execute?: boolean;
56
+ }
57
+
58
+ interface UploadOperation {
59
+ method: string;
60
+ url: string;
61
+ length: number;
62
+ offset: number;
63
+ requestHeaders: Array<{ name: string; value: string }>;
64
+ }
65
+
66
+ // Resolve `<dir>/<glob with {lang}>` where the glob's last segment has a single
67
+ // `*` wildcard (e.g. `en/aso/app_en_iphone-65_*.jpg`). Node fs, no bun dep —
68
+ // mirrors `filesFor` in play/screenshots.ts.
69
+ function filesFor(dir: string, glob: string, lang: string): string[] {
70
+ const full = resolve(dir, glob.replaceAll('{lang}', lang));
71
+ const folder = dirname(full);
72
+ const namePattern = basename(full);
73
+ const rx = new RegExp('^' + namePattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*') + '$');
74
+ let names: string[];
75
+ try {
76
+ names = readdirSync(folder);
77
+ } catch {
78
+ return [];
79
+ }
80
+ return names
81
+ .filter((n) => rx.test(n))
82
+ .sort()
83
+ .map((n) => resolve(folder, n));
84
+ }
85
+
86
+ export async function pushAscScreenshots({ config, localeMap, execute = false }: PushAscScreenshotsOptions): Promise<void> {
87
+ const sc = (config as ConfigWithAscScreenshots).ascScreenshots;
88
+ if (!sc) {
89
+ throw new Error(
90
+ 'release.config.ts needs `ascScreenshots {dir, glob, displayType}` for asc-screenshots.',
91
+ );
92
+ }
93
+ console.log(`App Store Connect screenshot push ${execute ? '(EXECUTE)' : '(DRY RUN)'}`);
94
+
95
+ const map = listingLocaleMap(config, 'apple', localeMap);
96
+ const dir = releasePath(config, sc.dir);
97
+ const displayType = sc.displayType;
98
+ const deprecatedTypes = sc.deprecatedTypes ?? [];
99
+ const sources = new Map(Object.entries(map).map(([locale, lang]) => {
100
+ const files = filesFor(dir, sc.glob, lang);
101
+ if (!files.length) throw new Error(`No replacement screenshots for ${locale}: ${sc.glob}`);
102
+ for (const file of files) if (!readFileSync(file).length) throw new Error(`Empty screenshot: ${file}`);
103
+ return [locale, files];
104
+ }));
105
+ console.log(JSON.stringify({ displayType, deprecatedTypes, sources: Object.fromEntries(sources) }, null, 2));
106
+ if (!execute) return;
107
+ const client = createAscClient(config);
108
+
109
+
110
+ // The S3 PUT goes to AWS, not ASC, so it can't use client.api(). Use raw fetch
111
+ // with ONLY the requestHeaders ASC pre-signed (no Bearer token).
112
+ async function putChunk(op: UploadOperation, chunk: Buffer): Promise<void> {
113
+ const headers: Record<string, string> = {};
114
+ for (const h of op.requestHeaders) headers[h.name] = h.value;
115
+ // Node fetch accepts a Buffer body; reuse the requestHeaders ASC pre-signed.
116
+ const res = await fetch(op.url, { method: op.method, headers, body: new Uint8Array(chunk) });
117
+ if (!res.ok) {
118
+ const text = await res.text();
119
+ throw new Error(`chunk upload failed: ${res.status}\n${text}`);
120
+ }
121
+ }
122
+
123
+ async function uploadScreenshot(setId: string, filePath: string): Promise<void> {
124
+ const bytes = readFileSync(filePath);
125
+ const fileName = basename(filePath);
126
+
127
+ // 1. Reserve.
128
+ const reserved = await client.api('/appScreenshots', {
129
+ method: 'POST',
130
+ body: JSON.stringify({
131
+ data: {
132
+ type: 'appScreenshots',
133
+ attributes: { fileSize: bytes.length, fileName },
134
+ relationships: {
135
+ appScreenshotSet: { data: { type: 'appScreenshotSets', id: setId } },
136
+ },
137
+ },
138
+ }),
139
+ });
140
+ const screenshotId: string = reserved.data.id;
141
+ const ops: UploadOperation[] = reserved.data.attributes.uploadOperations ?? [];
142
+
143
+ // 2. PUT bytes to each pre-signed S3 operation.
144
+ for (const op of ops) {
145
+ const chunk = bytes.subarray(op.offset, op.offset + op.length);
146
+ await putChunk(op, chunk);
147
+ }
148
+
149
+ // 3. Commit with checksum so ASC verifies the assembled upload.
150
+ const md5 = createHash('md5').update(bytes).digest('hex');
151
+ await client.api(`/appScreenshots/${screenshotId}`, {
152
+ method: 'PATCH',
153
+ body: JSON.stringify({
154
+ data: {
155
+ type: 'appScreenshots',
156
+ id: screenshotId,
157
+ attributes: { uploaded: true, sourceFileChecksum: md5 },
158
+ },
159
+ }),
160
+ });
161
+ }
162
+
163
+ console.log(`\n→ Finding app with bundleId=${client.bundleId}`);
164
+ const app = await client.findApp();
165
+ console.log(` ✓ App: ${app.name} (id=${app.id})`);
166
+
167
+ // Find the editable app store version + its localizations.
168
+ console.log(`\n→ Fetching editable app store version`);
169
+ const versions = await client.api(`/apps/${app.id}/appStoreVersions?limit=5`);
170
+ const editableVersion = (versions.data ?? []).find((v: any) =>
171
+ EDITABLE_STATES.has(v.attributes.appStoreState ?? v.attributes.appVersionState),
172
+ );
173
+ if (!editableVersion) {
174
+ throw new Error('No editable App Store version. Create a version before uploading screenshots.');
175
+ }
176
+ console.log(` ✓ Editable version: ${editableVersion.attributes.versionString} (id=${editableVersion.id})`);
177
+
178
+ const vLocs = await client.api(
179
+ `/appStoreVersions/${editableVersion.id}/appStoreVersionLocalizations`,
180
+ );
181
+ const localizationByLocale: Record<string, string> = {};
182
+ for (const l of vLocs.data ?? []) localizationByLocale[l.attributes.locale] = l.id;
183
+ console.log(` ✓ Localizations: ${Object.keys(localizationByLocale).join(', ')}`);
184
+
185
+ // Tally first so dry-run shows the full plan.
186
+ for (const [locale, lang] of Object.entries(map)) {
187
+ const localizationId = localizationByLocale[locale];
188
+ if (!localizationId) {
189
+ throw new Error(`No editable localization for ${locale}. Push metadata before screenshots.`);
190
+ }
191
+ const files = sources.get(locale)!;
192
+ console.log(`\n[${locale}] ${displayType.padEnd(24)} ← ${files.length} file(s)`);
193
+ for (const f of files) console.log(` ${basename(f)}`);
194
+ }
195
+
196
+ if (!execute) {
197
+ console.log('\n(dry run — pass execute:true to push)');
198
+ return;
199
+ }
200
+
201
+ const activeTypes = new Set([displayType]);
202
+
203
+ for (const [locale, lang] of Object.entries(map)) {
204
+ const localizationId = localizationByLocale[locale];
205
+ if (!localizationId) continue;
206
+ console.log(`\n[${locale}]`);
207
+
208
+ // List existing sets, then wipe sets for the type we're recreating plus any
209
+ // deprecated types. Upload failures can leave a partially replaced set.
210
+ const setsRes = await client.api(
211
+ `/appStoreVersionLocalizations/${localizationId}/appScreenshotSets`,
212
+ );
213
+ const existing: { id: string; displayType: string }[] = (setsRes.data ?? []).map((s: any) => ({
214
+ id: s.id,
215
+ displayType: s.attributes.screenshotDisplayType,
216
+ }));
217
+ for (const set of existing) {
218
+ const shouldDelete = activeTypes.has(set.displayType) || deprecatedTypes.includes(set.displayType);
219
+ if (shouldDelete) {
220
+ await client.api(`/appScreenshotSets/${set.id}`, { method: 'DELETE' });
221
+ console.log(` deleted existing set ${set.displayType} (${set.id})`);
222
+ }
223
+ }
224
+
225
+ const files = sources.get(locale)!;
226
+ if (files.length === 0) {
227
+ console.log(` ${displayType}: no files, skipping`);
228
+ continue;
229
+ }
230
+
231
+ // Create a fresh set, then upload each slide.
232
+ const createRes = await client.api('/appScreenshotSets', {
233
+ method: 'POST',
234
+ body: JSON.stringify({
235
+ data: {
236
+ type: 'appScreenshotSets',
237
+ attributes: { screenshotDisplayType: displayType },
238
+ relationships: {
239
+ appStoreVersionLocalization: {
240
+ data: { type: 'appStoreVersionLocalizations', id: localizationId },
241
+ },
242
+ },
243
+ },
244
+ }),
245
+ });
246
+ const setId: string = createRes.data.id;
247
+ console.log(` ${displayType}: new set ${setId}`);
248
+
249
+ for (const file of files) {
250
+ await uploadScreenshot(setId, file);
251
+ console.log(` ✓ ${basename(file)}`);
252
+ }
253
+ }
254
+
255
+ console.log('\n✓ Done');
256
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Review submissions — the one open slot Apple gives an app per platform, and
3
+ * the cancelling that frees it.
4
+ *
5
+ * Two different situations end up here, and only one of them is routine:
6
+ *
7
+ * - a submission App Review already REJECTED (`UNRESOLVED_ISSUES`) still holds
8
+ * the slot. It accepts new items and then refuses `submitted: true`, so it
9
+ * has to be retired before a resubmission can be created. Nothing live is
10
+ * withdrawn — that review is over.
11
+ * - a submission still QUEUED (`WAITING_FOR_REVIEW`) locks its version record:
12
+ * the version can't take a new build, and Apple won't let a second version
13
+ * be created alongside it. Cancelling it gives the version back, at the cost
14
+ * of its place in the queue. That is a real cost, so it never happens
15
+ * without `--replace-submission`.
16
+ *
17
+ * An `IN_REVIEW` submission is deliberately not cancellable here. A reviewer is
18
+ * looking at it; throwing that away is a decision for a person, not a flag.
19
+ */
20
+
21
+ import type { AscClient } from './client.ts';
22
+
23
+ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
24
+
25
+ /** Submission states that can take new items AND be submitted. */
26
+ export const OPEN_SUBMISSION_STATES = new Set(['READY_FOR_REVIEW']);
27
+
28
+ /** A rejected submission: closed, but still occupying the one open slot. */
29
+ export const REJECTED_SUBMISSION_STATE = 'UNRESOLVED_ISSUES';
30
+
31
+ /** Queued behind Apple's review queue — cancellable, at the cost of the queue place. */
32
+ export const QUEUED_SUBMISSION_STATE = 'WAITING_FOR_REVIEW';
33
+
34
+ /** A reviewer has it open. Not cancellable by this tool. */
35
+ export const ACTIVE_SUBMISSION_STATE = 'IN_REVIEW';
36
+
37
+ export interface Submission {
38
+ id: string;
39
+ state: string;
40
+ }
41
+
42
+ /** Every submission ASC knows about for this app on iOS, newest first. */
43
+ export async function listSubmissions(client: AscClient, appId: string): Promise<Submission[]> {
44
+ const res = await client.api(
45
+ `/apps/${appId}/reviewSubmissions?filter[platform]=IOS&limit=20&fields[reviewSubmissions]=state`,
46
+ );
47
+ return (res.data ?? []).map((s: any) => ({ id: s.id, state: s.attributes.state as string }));
48
+ }
49
+
50
+ /**
51
+ * Cancel a submission and WAIT for the slot to actually free.
52
+ *
53
+ * Cancelling is asynchronous: the PATCH answers `CANCELING`, and both the slot
54
+ * and the version stay locked until it reaches a settled state. Polling rather
55
+ * than racing is what makes the caller's next create/attach succeed.
56
+ */
57
+ export async function cancelSubmission(
58
+ client: AscClient,
59
+ id: string,
60
+ why: string,
61
+ timeoutMin = 10,
62
+ ): Promise<void> {
63
+ console.log(` … ${why} — cancelling submission ${id}`);
64
+ await client.api(`/reviewSubmissions/${id}`, {
65
+ method: 'PATCH',
66
+ body: JSON.stringify({ data: { type: 'reviewSubmissions', id, attributes: { canceled: true } } }),
67
+ });
68
+
69
+ const deadline = Date.now() + timeoutMin * 60_000;
70
+ for (;;) {
71
+ const res = await client.api(`/reviewSubmissions/${id}?fields[reviewSubmissions]=state`);
72
+ const state = res?.data?.attributes?.state;
73
+ if (state !== 'CANCELING') {
74
+ console.log(` ✓ submission closed (state=${state})`);
75
+ return;
76
+ }
77
+ if (Date.now() > deadline) {
78
+ throw new Error(
79
+ `Timed out after ${timeoutMin} min waiting for submission ${id} to finish cancelling. ` +
80
+ `Cancel it in App Store Connect and re-run with \`asc-submit\`.`,
81
+ );
82
+ }
83
+ await sleep(15_000);
84
+ }
85
+ }
@@ -0,0 +1,227 @@
1
+ /** Local build and store release support. All app settings come from the consuming configuration. */
2
+ import { listingLocaleMap } from '../config.ts';
3
+ import type { AppReleaseConfig } from '../config.ts';
4
+ import { createAscClient, type AscClient } from './client.ts';
5
+ import { pushAscMetadata } from './metadata.ts';
6
+ import { stage } from '../progress.ts';
7
+ import {
8
+ OPEN_SUBMISSION_STATES,
9
+ REJECTED_SUBMISSION_STATE,
10
+ cancelSubmission,
11
+ } from './submissions.ts';
12
+ import {
13
+ attachBuild,
14
+ backfillWhatsNew,
15
+ ensureExportCompliance,
16
+ resolveVersion,
17
+ waitForBuild,
18
+ } from './version.ts';
19
+
20
+
21
+ async function ensureReviewContact(client: AscClient, versionId: string, config: AppReleaseConfig): Promise<void> {
22
+ const contact = config.reviewContact;
23
+ if (!contact) return;
24
+ console.log(`\n→ App Review contact`);
25
+ const existing = await client.api(`/appStoreVersions/${versionId}/appStoreReviewDetail`).catch(() => null);
26
+ const detail = existing?.data;
27
+ const a = detail?.attributes ?? {};
28
+ if (a.contactFirstName && a.contactLastName && a.contactEmail && a.contactPhone) {
29
+ console.log(` ✓ already set (${a.contactFirstName} ${a.contactLastName}, ${a.contactEmail})`);
30
+ return;
31
+ }
32
+ const attributes = {
33
+ contactFirstName: contact.firstName,
34
+ contactLastName: contact.lastName,
35
+ contactEmail: contact.email,
36
+ contactPhone: contact.phone,
37
+ ...(contact.notes ? { notes: contact.notes } : {}),
38
+ };
39
+ if (detail?.id) {
40
+ await client.api(`/appStoreReviewDetails/${detail.id}`, {
41
+ method: 'PATCH',
42
+ body: JSON.stringify({ data: { type: 'appStoreReviewDetails', id: detail.id, attributes } }),
43
+ });
44
+ } else {
45
+ await client.api(`/appStoreReviewDetails`, {
46
+ method: 'POST',
47
+ body: JSON.stringify({
48
+ data: {
49
+ type: 'appStoreReviewDetails',
50
+ attributes,
51
+ relationships: { appStoreVersion: { data: { type: 'appStoreVersions', id: versionId } } },
52
+ },
53
+ }),
54
+ });
55
+ }
56
+ console.log(` ✓ set ${contact.firstName} ${contact.lastName}, ${contact.email}, ${contact.phone}`);
57
+ }
58
+
59
+ export interface SubmitOptions {
60
+
61
+ version: string;
62
+
63
+ build: string;
64
+
65
+ attachOnly?: boolean;
66
+
67
+ pushStoreCopy?: boolean;
68
+
69
+ replaceSubmission?: boolean;
70
+
71
+ timeoutMin?: number;
72
+
73
+ releaseNotes?: Record<string, string>;
74
+ }
75
+
76
+ const DEFAULT_NOTES: Record<string, string> = {
77
+ en: 'Bug fixes and improvements.',
78
+ };
79
+
80
+
81
+ function notesByAscLocale(config: AppReleaseConfig, notes: Record<string, string>): Record<string, string> {
82
+ const out: Record<string, string> = {};
83
+ for (const [ascLocale, copyKey] of Object.entries(config.locales?.apple ?? listingLocaleMap(config, 'apple'))) {
84
+ const text = notes[copyKey] ?? DEFAULT_NOTES[copyKey];
85
+ if (text) out[ascLocale] = text;
86
+ }
87
+ return out;
88
+ }
89
+
90
+ export async function submitForReview(config: AppReleaseConfig, opts: SubmitOptions): Promise<void> {
91
+ const { version, build } = opts;
92
+ const client = createAscClient(config);
93
+ console.log(`App Store review submission — target build ${version} (${build})`);
94
+ if (opts.attachOnly) console.log(' (attach-only: will NOT submit for review)');
95
+
96
+ const app = await client.findApp();
97
+ console.log(`\n→ App: ${app.name} (id=${app.id})`);
98
+
99
+ // 1. Wait for the build to finish processing. Apple's queue, not ours — the
100
+ // ETA here is the least reliable of any stage, so the progress line says
101
+ // elapsed against the last wait rather than pretending to know.
102
+ const buildRec = await stage('asc-processing', `Waiting for build ${version} (${build}) to finish processing on Apple's side`, () =>
103
+ waitForBuild(client, app.id, version, build, opts.timeoutMin ?? 45),
104
+ );
105
+
106
+ // 2. Resolve the version record, named to match the build.
107
+ console.log(`\n→ Resolving App Store version record for ${version}`);
108
+ const versionId = await resolveVersion(client, app.id, version, { replaceSubmission: opts.replaceSubmission });
109
+
110
+ // 3. Attach the build.
111
+ console.log(`\n→ Attaching build ${version} (${build})`);
112
+ await attachBuild(client, versionId, buildRec.id);
113
+ console.log(' ✓ build attached');
114
+
115
+ // 4. Export compliance.
116
+ console.log(`\n→ Export compliance`);
117
+ await ensureExportCompliance(client, buildRec);
118
+
119
+ // 4b. Optionally push the full store copy to the now-editable version, BEFORE
120
+ // submitting. Opt-in (see SubmitOptions.pushStoreCopy): keeps a routine
121
+ // ship from clobbering listing text, but lets a copy-bearing release (or a
122
+ // one-shot `asc-submit --push-store-copy`) get the new description live in
123
+ // the same pass instead of silently shipping the carried-forward text.
124
+ // MUST run before the whatsNew backfill below: pushing copy can CREATE new
125
+ // version localizations (e.g. en-GB from englishUkFallback), and a fresh
126
+ // localization with no whatsNew makes the review submission 409. Backfill
127
+ // after, so those new locales get release notes too.
128
+ if (opts.pushStoreCopy) {
129
+ if (!config.storeCopy) {
130
+ console.log('\n⚠ --push-store-copy set but release.config has no storeCopy — skipping copy push.');
131
+ } else {
132
+ console.log(`\n→ Pushing store copy (description/keywords/name/subtitle)`);
133
+ await pushAscMetadata({
134
+ config,
135
+ copy: config.storeCopy,
136
+ localeMap: config.listingLocales?.apple,
137
+ execute: true,
138
+ });
139
+ }
140
+ }
141
+
142
+ // 4c. Release notes — after any copy push so localizations created by the push
143
+ // (e.g. a freshly-added en-GB) are covered, not just the pre-existing ones.
144
+ console.log(`\n→ Ensuring release notes ("What's New")`);
145
+ await backfillWhatsNew(client, versionId, notesByAscLocale(config, opts.releaseNotes ?? {}));
146
+
147
+ // 4d. App Review contact. Apple requires a human it can ring, and the fields
148
+ // live on the VERSION — so a version this tool created via the API starts
149
+ // with all four null and `POST /reviewSubmissionItems` answers 409, listing
150
+ // them one by one. A version created in the ASC web UI gets them from the
151
+ // submit form instead, which is why this only bites the first time an app
152
+ // submits through the API.
153
+ await ensureReviewContact(client, versionId, config);
154
+
155
+ if (opts.attachOnly) {
156
+ console.log('\n✓ Build attached + notes set. Stopped before submission (attach-only).');
157
+ return;
158
+ }
159
+
160
+ // 5. Create / reuse a reviewSubmission, add the version, submit.
161
+ console.log(`\n→ Preparing review submission`);
162
+ const existing = await client.api(
163
+ `/apps/${app.id}/reviewSubmissions?filter[platform]=IOS&limit=20&fields[reviewSubmissions]=state`,
164
+ );
165
+ let submission = (existing.data ?? []).find((s: any) => OPEN_SUBMISSION_STATES.has(s.attributes.state));
166
+ if (!submission) {
167
+ // A rejection leaves a submission behind that looks open, accepts items and
168
+ // then refuses to submit. Retire it first or the create below 409s too.
169
+ const rejected = (existing.data ?? []).find(
170
+ (s: any) => s.attributes.state === REJECTED_SUBMISSION_STATE,
171
+ );
172
+ if (rejected) {
173
+ await cancelSubmission(
174
+ client,
175
+ rejected.id,
176
+ `submission was rejected (${REJECTED_SUBMISSION_STATE}) and a resubmission needs a fresh one`,
177
+ );
178
+ }
179
+ }
180
+ if (submission) {
181
+ console.log(` ✓ reusing open reviewSubmission id=${submission.id} state=${submission.attributes.state}`);
182
+ } else {
183
+ const created = await client.api(`/reviewSubmissions`, {
184
+ method: 'POST',
185
+ body: JSON.stringify({
186
+ data: {
187
+ type: 'reviewSubmissions',
188
+ attributes: { platform: 'IOS' },
189
+ relationships: { app: { data: { type: 'apps', id: app.id } } },
190
+ },
191
+ }),
192
+ });
193
+ submission = created.data;
194
+ console.log(` ✓ created reviewSubmission id=${submission.id}`);
195
+ }
196
+
197
+ const items = await client.api(`/reviewSubmissions/${submission.id}/items?include=appStoreVersion&limit=50`);
198
+ const alreadyItem = (items.data ?? []).some(
199
+ (it: any) => it.relationships?.appStoreVersion?.data?.id === versionId,
200
+ );
201
+ if (alreadyItem) {
202
+ console.log(' ✓ version already an item on this submission');
203
+ } else {
204
+ await client.api(`/reviewSubmissionItems`, {
205
+ method: 'POST',
206
+ body: JSON.stringify({
207
+ data: {
208
+ type: 'reviewSubmissionItems',
209
+ relationships: {
210
+ reviewSubmission: { data: { type: 'reviewSubmissions', id: submission.id } },
211
+ appStoreVersion: { data: { type: 'appStoreVersions', id: versionId } },
212
+ },
213
+ },
214
+ }),
215
+ });
216
+ console.log(' ✓ added version to submission');
217
+ }
218
+
219
+ console.log(`\n→ Submitting for review`);
220
+ await client.api(`/reviewSubmissions/${submission.id}`, {
221
+ method: 'PATCH',
222
+ body: JSON.stringify({
223
+ data: { type: 'reviewSubmissions', id: submission.id, attributes: { submitted: true } },
224
+ }),
225
+ });
226
+ console.log('\n✓ Submitted for App Store review.');
227
+ }
@@ -0,0 +1,34 @@
1
+ /** Local build and store release support. All app settings come from the consuming configuration. */
2
+ import { releasePath } from '../config.ts';
3
+ import type { AppReleaseConfig } from '../config.ts';
4
+ import { ascIssuer, ascKeyId, resolveAscKeyPath } from '../config.ts';
5
+ import { mkdirSync, copyFileSync, chmodSync, existsSync } from 'node:fs';
6
+ import { homedir } from 'node:os';
7
+ import { resolve } from 'node:path';
8
+ import { run } from '../build/exec.ts';
9
+ import { stage } from '../progress.ts';
10
+
11
+ export async function uploadIpa(config: AppReleaseConfig, ipaPath: string): Promise<void> {
12
+ if (!existsSync(ipaPath)) throw new Error(`IPA not found: ${ipaPath}`);
13
+ if (!ascKeyId(config) || !ascIssuer(config)) throw new Error('ASC key ID and issuer are required.');
14
+ const source = resolveAscKeyPath(config);
15
+ const directory = resolve(homedir(), '.appstoreconnect/private_keys');
16
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
17
+ const installed = resolve(directory, `AuthKey_${ascKeyId(config)}.p8`);
18
+ if (source !== installed) copyFileSync(source, installed);
19
+ chmodSync(installed, 0o600);
20
+ await stage('ios-upload', `Uploading IPA to App Store Connect (${ipaPath})`, () =>
21
+ run('xcrun', [
22
+ 'altool',
23
+ '--upload-app',
24
+ '-f',
25
+ ipaPath,
26
+ '-t',
27
+ 'ios',
28
+ '--apiKey',
29
+ ascKeyId(config),
30
+ '--apiIssuer',
31
+ ascIssuer(config),
32
+ ]),
33
+ );
34
+ }