Merge store-ops: TestFlight wait / expire, IAP review submissions, pulls, offers, CPP, events, reports, triage, ASO rank, ads scan
Conflicts resolved for both sides: - cli/lib/plist.ts, cli/lib/zip.ts: one implementation each. plist reads XML (text or bytes, attributes tolerated) and binary plists; ads scan now reads bytes, so a binary Info.plist works too. zip gains unzip() for the Play report exports on top of zipEntries / zipRead. - apple upload waits with testflight wait's loop (waitForBuild) instead of its own copy; BUILD_DONE removed. - config, credentials (profiles, keystore, ASC_VENDOR_NUMBER, now also a profile key), command table, MCP tools, credentials template, README, CHANGELOG: union. - MCP: --write stays forbidden; the three pull tools are the listed local-file exception (LOCAL_WRITE_TOOLS), so scan --write remains unreachable. - Adapters and API coverage tables regenerated.
This commit is contained in:
commit
b724cd4043
60 changed files with 4500 additions and 183 deletions
|
|
@ -66,6 +66,18 @@ export async function ascClient(root: string, bundleId: string, appIdHint?: stri
|
|||
}
|
||||
}
|
||||
|
||||
/** GET of a binary answer (sales / finance reports: application/a-gzip). null on 404 (Apple answers 404 when there
|
||||
* is no report for that date: no sales, or not published yet). */
|
||||
async function bytes(path: string, accept = 'application/a-gzip'): Promise<Uint8Array | null> {
|
||||
for (let attempt = 1; ; attempt++) {
|
||||
const r = await fetch('https://api.appstoreconnect.apple.com' + path, { headers: { Authorization: 'Bearer ' + jwt(), Accept: accept } });
|
||||
if ((r.status >= 500 || r.status === 429) && attempt < 5) { await r.body?.cancel(); await Bun.sleep(2000 * attempt); continue; }
|
||||
if (r.status === 404) { await r.body?.cancel(); return null; }
|
||||
if (!r.ok) throw new Error(`GET ${path.replace(/\?.*$/, '')} -> ${r.status} ${errorBody(await r.text(), 600)}`);
|
||||
return new Uint8Array(await r.arrayBuffer());
|
||||
}
|
||||
}
|
||||
|
||||
/** Every item of a paged GET. */
|
||||
async function all(path: string): Promise<J[]> {
|
||||
const out: J[] = [];
|
||||
|
|
@ -115,5 +127,5 @@ export async function ascClient(root: string, bundleId: string, appIdHint?: stri
|
|||
return res.id;
|
||||
}
|
||||
|
||||
return { asc, all, maybe, getAs, app, editableVersion, editableAppInfo, uploadAsset, keyId: k.keyId };
|
||||
return { asc, all, maybe, getAs, bytes, app, editableVersion, editableAppInfo, uploadAsset, keyId: k.keyId };
|
||||
}
|
||||
|
|
|
|||
145
cli/apple/cpp.ts
Normal file
145
cli/apple/cpp.ts
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
// App Store custom product pages from apple.customProductPages.
|
||||
// storebound apple cpp list [--json]
|
||||
// storebound apple cpp create [--name "..."] [--dry] [--json] pages missing on App Store Connect + localizations
|
||||
// storebound apple cpp upload --name "..." [--only en-US,tr] [--src store/renders] [--dry] screenshots (the page's variant)
|
||||
// storebound apple cpp submit --name "..." [--dry] [--yes] into a review submission (the owner's step; asks)
|
||||
// storebound apple cpp visible --name "..." [--off] [--dry] [--yes] show / hide an approved page (asks)
|
||||
// create and upload change nothing customers see (MCP tools, dry by default). A page's screenshots come from the
|
||||
// renders of its shots variant (<renders>/<variant>/<lang>/ios69 ...), MD5-idempotent like apple screenshots.
|
||||
// Pure parts and sources: cli/lib/cpp-events.ts.
|
||||
import { existsSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import type { Ctx } from '../lib/ctx';
|
||||
import { byAppleLocale, confirm, need } from '../lib/ctx';
|
||||
import { CPP_EDITABLE, CPP_LIMITS, cppCreateBody, cppLocales, type CustomProductPageDef, planCppLocales, reviewItemReq } from '../lib/cpp-events';
|
||||
import { done, log, printJson, warn } from '../lib/log';
|
||||
import { textTable } from '../lib/table';
|
||||
import { numberedImages } from '../play/images';
|
||||
import { variantRoot } from '../shots/lib';
|
||||
import { type Asc, ascClient, type J } from './asc';
|
||||
import { describeReq, execute, one, type Req } from './jsonapi';
|
||||
import { displaySets, syncScreenshotSet } from './screenshots';
|
||||
|
||||
const TAG = 'cpp';
|
||||
const USAGE = 'usage: storebound apple cpp list | create [--name n] | upload --name n | submit --name n | visible --name n [--off]';
|
||||
|
||||
interface Page { id: string; name: string; url?: string; visible?: boolean; version?: { id: string; state: string; deepLink?: string | null } }
|
||||
|
||||
async function pagesOf(c: Asc, appId: string): Promise<Page[]> {
|
||||
const out: Page[] = [];
|
||||
for (const p of await c.all(`/v1/apps/${appId}/appCustomProductPages?limit=200`)) {
|
||||
const vs = await c.all(`/v1/appCustomProductPages/${p.id}/appCustomProductPageVersions?limit=50`);
|
||||
const v = vs.find((x: J) => CPP_EDITABLE.has(x.attributes.state)) ?? vs.at(-1);
|
||||
out.push({ id: p.id, name: p.attributes.name, url: p.attributes.url, visible: p.attributes.visible, ...(v ? { version: { id: v.id, state: v.attributes.state, deepLink: v.attributes.deepLink } } : {}) });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** A draft review submission of the app (READY_FOR_REVIEW), or the request that creates one. */
|
||||
async function draftSubmission(c: Asc, appId: string): Promise<string | null> {
|
||||
return (await c.all(`/v1/reviewSubmissions?filter[app]=${appId}&filter[platform]=IOS&filter[state]=READY_FOR_REVIEW&limit=10`))[0]?.id ?? null;
|
||||
}
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root, resolve } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
const sub = a._[0];
|
||||
if (!sub) throw new Error(USAGE);
|
||||
const dry = a.has('dry');
|
||||
const defs = config.apple?.customProductPages ?? [];
|
||||
const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId);
|
||||
const appId = await c.app();
|
||||
const pages = await pagesOf(c, appId);
|
||||
const pick = (): { def: CustomProductPageDef; page: Page | undefined } => {
|
||||
const name = need(a.get('name'), '--name "<page name>"');
|
||||
const def = defs.find(d => d.name === name);
|
||||
if (!def) throw new Error(`no custom product page "${name}" in apple.customProductPages`);
|
||||
return { def, page: pages.find(p => p.name === name) };
|
||||
};
|
||||
|
||||
if (sub === 'list') {
|
||||
const rows = [...pages.map(p => [p.name, p.visible ? 'visible' : 'hidden', p.version?.state ?? '', defs.some(d => d.name === p.name) ? 'config' : '', p.url ?? '']),
|
||||
...defs.filter(d => !pages.some(p => p.name === d.name)).map(d => [d.name, '', 'not created', 'config', ''])];
|
||||
if (a.has('json')) { printJson({ pages, missing: defs.filter(d => !pages.some(p => p.name === d.name)).map(d => d.name), limit: CPP_LIMITS.pages }); return; }
|
||||
console.log(rows.length ? textTable(['page', 'visible', 'version', 'source', 'url'], rows) : 'no custom product pages');
|
||||
done(TAG, `${pages.length} of ${CPP_LIMITS.pages} custom product pages used`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (sub === 'create') {
|
||||
const only = a.get('name');
|
||||
const reqs: Req[] = [];
|
||||
for (const d of defs.filter(x => !only || x.name === only)) {
|
||||
const locs = cppLocales(d, config.languages);
|
||||
const page = pages.find(p => p.name === d.name);
|
||||
if (!page) { reqs.push({ method: 'POST', path: '/v1/appCustomProductPages', note: `page "${d.name}" with ${locs.length} locale(s)`, body: cppCreateBody(appId, d, locs) }); continue; }
|
||||
if (!page.version || !CPP_EDITABLE.has(page.version.state)) { log(TAG, `"${d.name}": version ${page.version?.state ?? 'missing'}, not editable (a new version: App Store Connect)`); continue; }
|
||||
const have = (await c.all(`/v1/appCustomProductPageVersions/${page.version.id}/appCustomProductPageLocalizations?limit=200`)).map((l: J) => ({ id: l.id, locale: l.attributes.locale, promotionalText: l.attributes.promotionalText }));
|
||||
reqs.push(...planCppLocales(page.version.id, have, locs));
|
||||
if ((d.deepLink ?? null) !== (page.version.deepLink ?? null) && d.deepLink) reqs.push({ method: 'PATCH', path: `/v1/appCustomProductPageVersions/${page.version.id}`, note: `"${d.name}" deep link`,
|
||||
body: { data: { type: 'appCustomProductPageVersions', id: page.version.id, attributes: { deepLink: d.deepLink } } } });
|
||||
}
|
||||
if (pages.length + reqs.filter(r => r.path === '/v1/appCustomProductPages').length > CPP_LIMITS.pages) throw new Error(`more than ${CPP_LIMITS.pages} custom product pages`);
|
||||
if (a.has('json')) printJson({ dryRun: dry, requests: reqs.map(r => describeReq(r)) });
|
||||
if (!reqs.length) { done(TAG, 'custom product pages up to date'); return; }
|
||||
await execute(c.asc, reqs, { dry, tag: TAG });
|
||||
done(TAG, dry ? `dry run: ${reqs.length} change(s)` : `${reqs.length} change(s); next: storebound apple cpp upload --name "<page>"`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (sub === 'upload') {
|
||||
const { def, page } = pick();
|
||||
if (!page?.version) throw new Error(`"${def.name}" is not on App Store Connect yet (storebound apple cpp create)`);
|
||||
if (!CPP_EDITABLE.has(page.version.state)) throw new Error(`"${def.name}": version ${page.version.state}, screenshots can only change on an editable version`);
|
||||
const src = variantRoot(resolve(a.get('src') ?? config.renders ?? config.shots?.out ?? 'store/renders'), def.variant, config.shots?.variants);
|
||||
const only = a.list('only');
|
||||
const langOf = byAppleLocale(config.languages);
|
||||
let sets = 0;
|
||||
for (const loc of await c.all(`/v1/appCustomProductPageVersions/${page.version.id}/appCustomProductPageLocalizations?limit=200`)) {
|
||||
const locale: string = loc.attributes.locale;
|
||||
if (only.length && !only.includes(locale)) continue;
|
||||
const lang = langOf.get(locale);
|
||||
if (!lang) { warn(TAG, `${locale}: no language with apple: "${locale}", skipped`); continue; }
|
||||
const existing = await c.all(`/v1/appCustomProductPageLocalizations/${loc.id}/appScreenshotSets?limit=50`);
|
||||
for (const [dir, type] of Object.entries(displaySets(config.apple))) {
|
||||
const d = join(src, lang.id, dir);
|
||||
const files = existsSync(d) ? numberedImages(d).filter(f => f.endsWith('.png')).slice(0, 10) : [];
|
||||
if (!files.length) { warn(TAG, `${locale}: nothing in ${d}, skipped`); continue; }
|
||||
await syncScreenshotSet(c, { rel: 'appCustomProductPageLocalization', type: 'appCustomProductPageLocalizations', id: loc.id }, existing, type, files, `"${def.name}" ${locale} ${type}`, dry);
|
||||
sets++;
|
||||
}
|
||||
}
|
||||
done(TAG, `${sets} screenshot set(s) ${dry ? 'checked (dry run)' : 'synced'} for "${def.name}"`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (sub === 'submit') {
|
||||
const { def, page } = pick();
|
||||
if (!page?.version) throw new Error(`"${def.name}" is not on App Store Connect yet (storebound apple cpp create)`);
|
||||
if (!['PREPARE_FOR_SUBMISSION', 'REJECTED'].includes(page.version.state)) { done(TAG, `"${def.name}": version is ${page.version.state}, nothing to submit`); return; }
|
||||
const draft = await draftSubmission(c, appId);
|
||||
const create: Req = { method: 'POST', path: '/v1/reviewSubmissions', note: 'new draft review submission', body: { data: { type: 'reviewSubmissions', attributes: { platform: 'IOS' }, relationships: { app: one('apps', appId) } } } };
|
||||
const item = reviewItemReq(draft ?? '${submission}', 'appCustomProductPageVersion', page.version.id, `custom product page "${def.name}"`);
|
||||
if (dry) { await execute(c.asc, [...(draft ? [] : [create]), item, { method: 'PATCH', path: `/v1/reviewSubmissions/${draft ?? '${submission}'}`, note: 'submit for App Review' }], { dry, tag: TAG }); return; }
|
||||
if (!(await confirm(ctx, `Send custom product page "${def.name}" to App Review now?`))) return;
|
||||
const sid = draft ?? ((await c.asc('POST', create.path, create.body)).data.id as string);
|
||||
await c.asc('POST', item.path, reviewItemReq(sid, 'appCustomProductPageVersion', page.version.id, '').body);
|
||||
await c.asc('PATCH', `/v1/reviewSubmissions/${sid}`, { data: { type: 'reviewSubmissions', id: sid, attributes: { submitted: true } } });
|
||||
done(TAG, `"${def.name}" submitted (review submission ${sid}); after approval: storebound apple cpp visible --name "${def.name}"`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (sub === 'visible') {
|
||||
const { def, page } = pick();
|
||||
if (!page) throw new Error(`"${def.name}" is not on App Store Connect yet`);
|
||||
const visible = !a.has('off');
|
||||
if (page.visible === visible) { done(TAG, `"${def.name}" is already ${visible ? 'visible' : 'hidden'}`); return; }
|
||||
const req: Req = { method: 'PATCH', path: `/v1/appCustomProductPages/${page.id}`, note: `"${def.name}" ${visible ? 'visible' : 'hidden'}`, body: { data: { type: 'appCustomProductPages', id: page.id, attributes: { visible } } } };
|
||||
if (dry) { await execute(c.asc, [req], { dry, tag: TAG }); return; }
|
||||
if (!(await confirm(ctx, `${visible ? 'Show' : 'Hide'} custom product page "${def.name}" on the App Store?`))) return;
|
||||
await execute(c.asc, [req], { dry: false, tag: TAG });
|
||||
done(TAG, `"${def.name}" ${visible ? 'visible' : 'hidden'}${page.url ? ` (${page.url})` : ''}`);
|
||||
return;
|
||||
}
|
||||
throw new Error(`unknown cpp command "${sub}"\n${USAGE}`);
|
||||
}
|
||||
126
cli/apple/events.ts
Normal file
126
cli/apple/events.ts
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
// App Store in-app events from apple.events.
|
||||
// storebound apple events list [--json]
|
||||
// storebound apple events create [--name "<reference name>"] [--dry] [--json] missing events + localizations
|
||||
// storebound apple events upload --name "..." [--dry] event card (16:9) + details page (9:16) images per locale
|
||||
// storebound apple events submit --name "..." [--dry] [--yes] into a review submission (the owner's step; asks)
|
||||
// An approved event is published by its own schedule (publishStart): sending it to review is the moment it is decided,
|
||||
// so `submit` asks first and is not an MCP tool. Up to 10 published and 15 approved events per app.
|
||||
// Pure parts and sources: cli/lib/cpp-events.ts.
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import type { Ctx } from '../lib/ctx';
|
||||
import { confirm, need } from '../lib/ctx';
|
||||
import { type AppEventDef, checkEventMedia, EVENT_EDITABLE, EVENT_LIMITS, eventCreateBody, planEventLocales, reviewItemReq } from '../lib/cpp-events';
|
||||
import { done, log, printJson, warn } from '../lib/log';
|
||||
import { textTable } from '../lib/table';
|
||||
import { imageInfo } from '../shots/spec';
|
||||
import { ascClient, type J } from './asc';
|
||||
import { describeReq, execute, one, type Req } from './jsonapi';
|
||||
|
||||
const TAG = 'events';
|
||||
const USAGE = 'usage: storebound apple events list | create [--name n] | upload --name n | submit --name n';
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root, resolve } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
const sub = a._[0];
|
||||
if (!sub) throw new Error(USAGE);
|
||||
const dry = a.has('dry');
|
||||
const defs = config.apple?.events ?? [];
|
||||
const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId);
|
||||
const appId = await c.app();
|
||||
const events = await c.all(`/v1/apps/${appId}/appEvents?limit=200`);
|
||||
const localeOf = (langId: string): string | undefined => config.languages.find(l => l.id === langId)?.apple;
|
||||
const pick = (): { def: AppEventDef; ev: J | undefined } => {
|
||||
const name = need(a.get('name'), '--name "<reference name>"');
|
||||
const def = defs.find(d => d.referenceName === name);
|
||||
if (!def) throw new Error(`no event "${name}" in apple.events`);
|
||||
return { def, ev: events.find((e: J) => e.attributes.referenceName === name) };
|
||||
};
|
||||
|
||||
if (sub === 'list') {
|
||||
const rows = events.map((e: J) => { const s = e.attributes.territorySchedules?.[0] ?? {}; return [e.attributes.referenceName, e.attributes.badge ?? '', e.attributes.eventState ?? '', (s.eventStart ?? '').slice(0, 16), (s.eventEnd ?? '').slice(0, 16), defs.some(d => d.referenceName === e.attributes.referenceName) ? 'config' : '']; });
|
||||
for (const d of defs.filter(d => !events.some((e: J) => e.attributes.referenceName === d.referenceName))) rows.push([d.referenceName, d.badge, 'not created', d.schedule.eventStart.slice(0, 16), d.schedule.eventEnd.slice(0, 16), 'config']);
|
||||
if (a.has('json')) { printJson({ events: events.map((e: J) => ({ id: e.id, ...e.attributes })), missing: defs.filter(d => !events.some((e: J) => e.attributes.referenceName === d.referenceName)).map(d => d.referenceName) }); return; }
|
||||
console.log(rows.length ? textTable(['event', 'badge', 'state', 'start', 'end', 'source'], rows) : 'no in-app events');
|
||||
const published = events.filter((e: J) => e.attributes.eventState === 'PUBLISHED').length, approved = events.filter((e: J) => ['APPROVED', 'ACCEPTED', 'PUBLISHED'].includes(e.attributes.eventState)).length;
|
||||
done(TAG, `${published} of ${EVENT_LIMITS.published} published, ${approved} of ${EVENT_LIMITS.approved} approved`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (sub === 'create') {
|
||||
const only = a.get('name');
|
||||
const territories = (await c.all('/v1/territories?limit=200')).map((t: J) => t.id as string);
|
||||
const reqs: Req[] = [];
|
||||
const created: { def: AppEventDef; index: number }[] = [];
|
||||
for (const d of defs.filter(x => !only || x.referenceName === only)) {
|
||||
const want = Object.entries(d.listings).flatMap(([lang, x]) => { const locale = localeOf(lang); return locale ? [{ locale, ...x }] : []; });
|
||||
const primary = localeOf(d.primaryLanguage ?? '') ?? want[0]?.locale ?? 'en-US';
|
||||
const ev = events.find((e: J) => e.attributes.referenceName === d.referenceName);
|
||||
if (!ev) { created.push({ def: d, index: reqs.length }); reqs.push({ method: 'POST', path: '/v1/appEvents', note: `event "${d.referenceName}" (${d.badge}, ${d.schedule.eventStart} to ${d.schedule.eventEnd})`, body: eventCreateBody(appId, d, primary, d.schedule.territories ?? territories) }); continue; }
|
||||
if (!EVENT_EDITABLE.has(ev.attributes.eventState)) { log(TAG, `"${d.referenceName}": ${ev.attributes.eventState}, not editable`); continue; }
|
||||
const have = (await c.all(`/v1/appEvents/${ev.id}/localizations?limit=200`)).map((l: J) => ({ id: l.id, ...l.attributes }));
|
||||
reqs.push(...planEventLocales(ev.id, have, want));
|
||||
}
|
||||
if (a.has('json')) printJson({ dryRun: dry, requests: reqs.map(r => describeReq(r)) });
|
||||
if (!reqs.length) { done(TAG, 'in-app events up to date'); return; }
|
||||
if (dry) {
|
||||
await execute(c.asc, reqs, { dry, tag: TAG });
|
||||
for (const x of created) log(TAG, `then: ${Object.keys(x.def.listings).length} localization(s) for "${x.def.referenceName}"`);
|
||||
done(TAG, 'dry run: nothing changed');
|
||||
return;
|
||||
}
|
||||
const out = await execute(c.asc, reqs, { dry: false, tag: TAG }) as J[];
|
||||
for (const x of created) {
|
||||
const id = out[x.index].data.id as string;
|
||||
const want = Object.entries(x.def.listings).flatMap(([lang, t]) => { const locale = localeOf(lang); return locale ? [{ locale, ...t }] : []; });
|
||||
await execute(c.asc, planEventLocales(id, [], want), { dry: false, tag: TAG });
|
||||
}
|
||||
done(TAG, 'in-app events created / updated; next: storebound apple events upload --name "<event>"');
|
||||
return;
|
||||
}
|
||||
|
||||
if (sub === 'upload') {
|
||||
const { def, ev } = pick();
|
||||
if (!ev) throw new Error(`"${def.referenceName}" is not on App Store Connect yet (storebound apple events create)`);
|
||||
if (!EVENT_EDITABLE.has(ev.attributes.eventState)) throw new Error(`"${def.referenceName}": ${ev.attributes.eventState}, media can only change on a draft`);
|
||||
let n = 0;
|
||||
for (const loc of await c.all(`/v1/appEvents/${ev.id}/localizations?limit=200`)) {
|
||||
const lang = config.languages.find(l => l.apple === loc.attributes.locale);
|
||||
if (!lang) continue;
|
||||
const have = await c.all(`/v1/appEventLocalizations/${loc.id}/appEventScreenshots?limit=50`);
|
||||
for (const [key, kind] of [['card', 'EVENT_CARD'], ['details', 'EVENT_DETAILS_PAGE']] as const) {
|
||||
const tpl = def.media?.[key];
|
||||
if (!tpl) continue;
|
||||
const file = resolve(tpl.replaceAll('{lang}', lang.id));
|
||||
if (!existsSync(file)) { warn(TAG, `${loc.attributes.locale} ${kind}: no ${file}`); continue; }
|
||||
const info = imageInfo(readFileSync(file));
|
||||
const problems = checkEventMedia(kind, info.w, info.h, info.format);
|
||||
if (problems.length) throw new Error(`${file}: ${problems.join('; ')}`);
|
||||
if (have.some((s: J) => s.attributes.appEventAssetType === kind && s.attributes.fileSize === info.bytes)) { log(TAG, `${loc.attributes.locale} ${kind}: up to date`); continue; }
|
||||
if (dry) { log(TAG, `${loc.attributes.locale} ${kind}: would upload ${file} (${info.w}x${info.h})`); n++; continue; }
|
||||
for (const s of have.filter((x: J) => x.attributes.appEventAssetType === kind)) await c.asc('DELETE', `/v1/appEventScreenshots/${s.id}`);
|
||||
await c.uploadAsset('appEventScreenshots', { appEventLocalization: { data: { type: 'appEventLocalizations', id: loc.id } } }, file, { appEventAssetType: kind });
|
||||
log(TAG, `${loc.attributes.locale} ${kind}: uploaded`);
|
||||
n++;
|
||||
}
|
||||
}
|
||||
done(TAG, `${n} image(s) ${dry ? 'to upload (dry run)' : 'uploaded'} for "${def.referenceName}"`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (sub === 'submit') {
|
||||
const { def, ev } = pick();
|
||||
if (!ev) throw new Error(`"${def.referenceName}" is not on App Store Connect yet`);
|
||||
if (!EVENT_EDITABLE.has(ev.attributes.eventState) && ev.attributes.eventState !== 'READY_FOR_REVIEW') { done(TAG, `"${def.referenceName}" is ${ev.attributes.eventState}, nothing to submit`); return; }
|
||||
const draft = (await c.all(`/v1/reviewSubmissions?filter[app]=${appId}&filter[platform]=IOS&filter[state]=READY_FOR_REVIEW&limit=10`))[0]?.id as string | undefined;
|
||||
const create: Req = { method: 'POST', path: '/v1/reviewSubmissions', note: 'new draft review submission', body: { data: { type: 'reviewSubmissions', attributes: { platform: 'IOS' }, relationships: { app: one('apps', appId) } } } };
|
||||
if (dry) { await execute(c.asc, [...(draft ? [] : [create]), reviewItemReq(draft ?? '${submission}', 'appEvent', ev.id, `in-app event "${def.referenceName}"`), { method: 'PATCH', path: `/v1/reviewSubmissions/${draft ?? '${submission}'}`, note: 'submit for App Review' }], { dry, tag: TAG }); return; }
|
||||
if (!(await confirm(ctx, `Send in-app event "${def.referenceName}" to App Review? Once approved it is published on ${def.schedule.publishStart} by its schedule.`))) return;
|
||||
const sid = draft ?? ((await c.asc('POST', create.path, create.body)).data.id as string);
|
||||
await c.asc('POST', '/v1/reviewSubmissionItems', reviewItemReq(sid, 'appEvent', ev.id, '').body);
|
||||
await c.asc('PATCH', `/v1/reviewSubmissions/${sid}`, { data: { type: 'reviewSubmissions', id: sid, attributes: { submitted: true } } });
|
||||
done(TAG, `"${def.referenceName}" submitted (review submission ${sid})`);
|
||||
return;
|
||||
}
|
||||
throw new Error(`unknown events command "${sub}"\n${USAGE}`);
|
||||
}
|
||||
105
cli/apple/iap-submit.ts
Normal file
105
cli/apple/iap-submit.ts
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
// Send in-app purchases and subscriptions to App Review through a review submission (the owner's action).
|
||||
// storebound apple iap-submit [--only id1,id2] [--with-version] [--new-version] [--no-submit] [--dry] [--yes] [--json]
|
||||
// Default: every product and subscription of the config sold on the App Store. The plan (cli/lib/review-submit.ts)
|
||||
// says which version of each goes in, which items are first of their type (those need an app version in the same
|
||||
// submission: --with-version adds the editable one, and then submitting submits the app too), and what is left out.
|
||||
// --new-version: approved or rejected products get a new draft version first (POST inAppPurchaseVersions /
|
||||
// subscriptionVersions) so changed metadata can go to review. --no-submit: only fill the draft submission; the owner
|
||||
// presses "Submit for Review" in App Store Connect. Without --no-submit the last step asks first (never under MCP).
|
||||
import { sellsOn } from '../lib/config';
|
||||
import type { Ctx } from '../lib/ctx';
|
||||
import { confirm, need } from '../lib/ctx';
|
||||
import { done, log, printJson, warn } from '../lib/log';
|
||||
import { allSubscriptions } from '../lib/subscriptions';
|
||||
import { bindIds, latestVersion, newVersionReq, type PIap, planIapSubmission, type PSub, type SubmitState, versionsOf } from '../lib/review-submit';
|
||||
import { type Asc, ascClient, type J } from './asc';
|
||||
import { describeReq, execute } from './jsonapi';
|
||||
|
||||
const TAG = 'iap-submit';
|
||||
|
||||
export async function readSubmitState(c: Asc, appId: string, want: string[]): Promise<SubmitState> {
|
||||
const appVersions = (await c.all(`/v1/apps/${appId}/appStoreVersions?filter[platform]=IOS&limit=50`)).map((v: J) => ({ id: v.id, versionString: v.attributes.versionString,
|
||||
state: v.attributes.appVersionState ?? v.attributes.appStoreState }));
|
||||
const iaps: PIap[] = [];
|
||||
for (const p of await c.all(`/v1/apps/${appId}/inAppPurchasesV2?limit=200`)) {
|
||||
// every product counts for "first of its type"; versions are only read for the products we submit
|
||||
const versions = want.includes(p.attributes.productId) ? versionsOf(await c.all(`/v2/inAppPurchases/${p.id}/versions?limit=200`)) : [];
|
||||
iaps.push({ id: p.id, productId: p.attributes.productId, type: p.attributes.inAppPurchaseType, state: p.attributes.state, versions });
|
||||
}
|
||||
const subs: PSub[] = [];
|
||||
const groups: SubmitState['groups'] = [];
|
||||
for (const g of await c.all(`/v1/apps/${appId}/subscriptionGroups?limit=200`)) {
|
||||
const members = await c.all(`/v1/subscriptionGroups/${g.id}/subscriptions?limit=200`);
|
||||
const wanted = members.some((s: J) => want.includes(s.attributes.productId));
|
||||
groups.push({ id: g.id, name: g.attributes.referenceName, versions: wanted ? versionsOf(await c.all(`/v1/subscriptionGroups/${g.id}/versions?limit=200`)) : [] });
|
||||
for (const s of members) subs.push({ id: s.id, productId: s.attributes.productId, groupId: g.id, state: s.attributes.state,
|
||||
versions: want.includes(s.attributes.productId) ? versionsOf(await c.all(`/v1/subscriptions/${s.id}/versions?limit=200`)) : [] });
|
||||
}
|
||||
const drafts = await c.all(`/v1/reviewSubmissions?filter[app]=${appId}&filter[platform]=IOS&filter[state]=READY_FOR_REVIEW&limit=10`);
|
||||
let draft: SubmitState['draft'] = null;
|
||||
if (drafts[0]) {
|
||||
const items = await c.all(`/v1/reviewSubmissions/${drafts[0].id}/items?include=appStoreVersion,inAppPurchaseVersion,subscriptionVersion,subscriptionGroupVersion&limit=200`);
|
||||
const ids = items.flatMap((it: J) => Object.values(it.relationships ?? {}).map((r: J) => r?.data?.id).filter(Boolean)) as string[];
|
||||
draft = { id: drafts[0].id, itemVersionIds: ids };
|
||||
}
|
||||
return { appVersions, iaps, subs, groups, draft };
|
||||
}
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
const dry = a.has('dry');
|
||||
const only = a.list('only');
|
||||
const ids = [...(config.products ?? []).filter(p => sellsOn(config, p, 'apple')).map(p => p.id), ...allSubscriptions(config.subscriptions).filter(x => sellsOn(config, x.sub, 'apple')).map(x => x.sub.id)]
|
||||
.filter(id => !only.length || only.includes(id));
|
||||
for (const id of only) if (!ids.includes(id)) throw new Error(`--only ${id}: not a product or subscription of the config sold on the App Store`);
|
||||
if (!ids.length) throw new Error('no in-app purchases or subscriptions in the config for the App Store');
|
||||
const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId);
|
||||
const appId = await c.app();
|
||||
let state = await readSubmitState(c, appId, ids);
|
||||
|
||||
if (a.has('new-version')) {
|
||||
const reqs = [
|
||||
...state.iaps.filter(p => ids.includes(p.productId) && ['APPROVED', 'REJECTED', 'DEVELOPER_REJECTED'].includes(latestVersion(p.versions)?.state ?? '')).map(p => newVersionReq('iap', p.id, p.productId)),
|
||||
...state.subs.filter(p => ids.includes(p.productId) && ['APPROVED', 'REJECTED', 'DEVELOPER_REJECTED'].includes(latestVersion(p.versions)?.state ?? '')).map(p => newVersionReq('sub', p.id, p.productId)),
|
||||
];
|
||||
if (reqs.length) {
|
||||
await execute(c.asc, reqs, { dry, tag: TAG });
|
||||
if (!dry) state = await readSubmitState(c, appId, ids);
|
||||
}
|
||||
}
|
||||
|
||||
const plan = planIapSubmission(state, ids, { withVersion: a.has('with-version') });
|
||||
const prepare = plan.prepare.map(r => bindIds(r, { app: appId }));
|
||||
if (a.has('json')) {
|
||||
printJson({ dryRun: dry, items: plan.items, skipped: plan.skipped, firstOfType: plan.firstOfType, hasApprovedVersion: plan.hasApprovedVersion,
|
||||
needsAppVersion: plan.needsAppVersion, blockers: plan.blockers, draft: state.draft?.id ?? null, requests: [...prepare, plan.submit].map(r => describeReq(r)) });
|
||||
if (dry || plan.blockers.length) { if (plan.blockers.length) process.exitCode = 1; return; }
|
||||
} else {
|
||||
for (const it of plan.items) log(TAG, `submit: ${it.label}`);
|
||||
for (const s of plan.skipped) log(TAG, `skip ${s.id}: ${s.why}`);
|
||||
if (plan.firstOfType.length) log(TAG, `first ${plan.firstOfType.join(' / ')} of the app: needs an app version in the same submission`);
|
||||
for (const b of plan.blockers) warn(TAG, b);
|
||||
}
|
||||
if (plan.blockers.length) { process.exitCode = 1; done(TAG, 'nothing sent: fix the blockers above'); return; }
|
||||
if (!plan.items.length) { done(TAG, 'nothing to submit'); return; }
|
||||
if (dry) {
|
||||
await execute(c.asc, [...prepare, plan.submit], { dry, tag: TAG });
|
||||
done(TAG, `dry run: ${plan.items.length} item(s) would go into ${state.draft ? `draft ${state.draft.id}` : 'a new draft submission'}`);
|
||||
return;
|
||||
}
|
||||
const what = `${plan.items.length} item(s)${plan.appVersion ? `, including app version ${plan.appVersion.versionString}` : ''}`;
|
||||
if (!(await confirm(ctx, `Add ${what} to ${state.draft ? 'the draft' : 'a new draft'} review submission?`))) return;
|
||||
let sid = state.draft?.id;
|
||||
for (const r of prepare) {
|
||||
const out = await c.asc(r.method, r.path, bindIds(r, { submission: sid }).body);
|
||||
if (r.path === '/v1/reviewSubmissions') sid = out.data.id;
|
||||
log(TAG, `${describeReq(bindIds(r, { submission: sid }))}: done`);
|
||||
}
|
||||
if (a.has('no-submit')) { done(TAG, `draft review submission ${sid} ready: press "Submit for Review" in App Store Connect (Apps > Distribution > App Review)`); return; }
|
||||
if (!(await confirm(ctx, `Submit review submission ${sid} (${what}) to App Review now?${plan.appVersion ? ' This submits the app version too.' : ''}`))) {
|
||||
done(TAG, `draft ${sid} kept; submit it in App Store Connect or re-run`); return;
|
||||
}
|
||||
await c.asc('PATCH', `/v1/reviewSubmissions/${sid}`, bindIds(plan.submit, { submission: sid }).body);
|
||||
done(TAG, `review submission ${sid} submitted (storebound apple status shows its state)`);
|
||||
}
|
||||
|
|
@ -4,11 +4,17 @@
|
|||
// - appInfoLocalizations: name, subtitle, privacy policy URL per locale
|
||||
// - appStoreVersionLocalizations: description, keywords, promotional text, what's new (not on a first version),
|
||||
// support + marketing URL per locale
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { parseAppStoreListing } from '../lib/copy';
|
||||
// And the other way round (read-only on App Store Connect):
|
||||
// storebound apple listing pull [--version x.y.z] [--write] [--json]
|
||||
// the live texts (the editable version if there is one, else the newest; --version picks one) into the App Store
|
||||
// listing file: shows the diff, writes only with --write.
|
||||
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { type AppleCopy, parseAppStoreListing } from '../lib/copy';
|
||||
import { compactDiff } from '../lib/diff';
|
||||
import { mergeAppleListing, overLimits } from '../lib/listing-pull';
|
||||
import type { Ctx } from '../lib/ctx';
|
||||
import { need } from '../lib/ctx';
|
||||
import { done, log } from '../lib/log';
|
||||
import { done, log, printJson, warn } from '../lib/log';
|
||||
import { ascClient, type J } from './asc';
|
||||
|
||||
export function readAppleCopy(ctx: Ctx) {
|
||||
|
|
@ -34,9 +40,51 @@ async function upsertLocs(c: Awaited<ReturnType<typeof ascClient>>, list: string
|
|||
}
|
||||
}
|
||||
|
||||
/** apple listing pull: live texts -> diff -> (with --write) the App Store listing file. */
|
||||
async function pull(ctx: Ctx): Promise<void> {
|
||||
const { config, root, resolve } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId);
|
||||
const appId = await c.app();
|
||||
const versions = await c.all(`/v1/apps/${appId}/appStoreVersions?filter[platform]=IOS&limit=50`);
|
||||
const want = a.get('version');
|
||||
const sorted = [...versions].sort((x: J, y: J) => String(y.attributes.createdDate ?? '').localeCompare(String(x.attributes.createdDate ?? '')));
|
||||
const v = want ? sorted.find((x: J) => x.attributes.versionString === want) : (await c.editableVersion()) ?? sorted[0];
|
||||
if (!v) throw new Error(want ? `no iOS version ${want} on App Store Connect` : 'no iOS version on App Store Connect yet');
|
||||
const infos = await c.all(`/v1/apps/${appId}/appInfos`);
|
||||
const live = v.attributes.appVersionState ?? v.attributes.appStoreState;
|
||||
// the app info that belongs to the version: the editable one while a version is being prepared, else the live one
|
||||
const info = ['READY_FOR_DISTRIBUTION', 'READY_FOR_SALE'].includes(live)
|
||||
? infos.find((i: J) => ['READY_FOR_DISTRIBUTION', 'READY_FOR_SALE'].includes(i.attributes.state ?? i.attributes.appStoreState)) ?? infos[0]
|
||||
: await c.editableAppInfo();
|
||||
const remote: Record<string, AppleCopy> = {};
|
||||
for (const l of await c.all(`/v1/appInfos/${info.id}/appInfoLocalizations?limit=200`)) remote[l.attributes.locale] = { name: l.attributes.name ?? undefined, subtitle: l.attributes.subtitle ?? undefined };
|
||||
for (const l of await c.all(`/v1/appStoreVersions/${v.id}/appStoreVersionLocalizations?limit=200`)) {
|
||||
const at = l.attributes;
|
||||
remote[at.locale] = { ...remote[at.locale], description: at.description ?? undefined, keywords: at.keywords ?? undefined, promotionalText: at.promotionalText ?? undefined, whatsNew: at.whatsNew ?? undefined };
|
||||
}
|
||||
const file = resolve(config.apple?.listing ?? 'store/appstore.md');
|
||||
const before = existsSync(file) ? readFileSync(file, 'utf8') : '# App Store listing copy\n\nPulled from App Store Connect by `storebound apple listing pull`.\n';
|
||||
const r = mergeAppleListing(before, remote);
|
||||
const over = overLimits(r.changes, 'apple');
|
||||
const diff = compactDiff(before, r.md);
|
||||
if (a.has('json')) printJson({ version: v.attributes.versionString, state: live, file, write: a.has('write') && !a.has('dry'), changes: r.changes, added: r.added, overLimits: over, diff });
|
||||
else {
|
||||
log('apple', `pull: version ${v.attributes.versionString} (${live}), ${Object.keys(remote).length} locales`);
|
||||
for (const ch of r.changes) log('apple', `${ch.section} ${ch.field}: ${ch.from === null ? 'new' : 'changed'}`);
|
||||
if (diff.length) console.log(diff.join('\n'));
|
||||
}
|
||||
for (const o of over) warn('apple', `over the limit on the store: ${o}`);
|
||||
if (!r.changes.length) { done('apple', `${file} already matches the store`); return; }
|
||||
if (!a.has('write') || a.has('dry')) { done('apple', `${r.changes.length} change(s); nothing written (add --write to update ${file})`); return; }
|
||||
writeFileSync(file, r.md);
|
||||
done('apple', `${file}: ${r.changes.length} change(s) written${r.added.length ? `, new locales ${r.added.join(', ')}` : ''}`);
|
||||
}
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
if (a._[0] === 'pull') return pull(ctx);
|
||||
const version = a.get('version');
|
||||
if (!version) throw new Error('usage: apple listing --version 1.0.0 [--build N] [--dry]');
|
||||
const listing = readAppleCopy(ctx);
|
||||
|
|
|
|||
92
cli/apple/offer-codes.ts
Normal file
92
cli/apple/offer-codes.ts
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
// Offer codes for one-time purchases (consumable, non-consumable, non-renewing) from products[].offerCodes.
|
||||
// storebound apple offer-codes [--only id1,id2] [--codes] [--dry] [--yes] [--json]
|
||||
// Creates the missing campaigns (by name) with their prices: free, or the USA price point of `usd` and its
|
||||
// equalizations (every territory, or `territories`). A campaign alone lets nobody redeem anything. Codes are made only
|
||||
// with --codes, after a confirmation: custom codes (anyone who has the code) and one-time-use batches; the one-time
|
||||
// codes are saved to .storebound/offer-codes/ (gitignored; treat them like vouchers). Each app may have 10 active
|
||||
// offers and 1 million codes per quarter (App Store Connect Help). Subscription offer codes: apple subscriptions.
|
||||
// Pure parts and sources: cli/lib/offers.ts.
|
||||
import { mkdirSync, writeFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { sellsOn } from '../lib/config';
|
||||
import type { Ctx } from '../lib/ctx';
|
||||
import { confirm, need } from '../lib/ctx';
|
||||
import { done, log, printJson, warn } from '../lib/log';
|
||||
import { iapCustomCodeReq, iapOfferCodeBody, iapOneTimeCodesReq, type TerritoryPoint, validateIapOfferCodes } from '../lib/offers';
|
||||
import { applePoints, pickPoint } from '../lib/subscriptions';
|
||||
import { pages } from '../prices';
|
||||
import { ascClient, type J } from './asc';
|
||||
import { describeReq, execute, type Req } from './jsonapi';
|
||||
|
||||
const TAG = 'offer-codes';
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root, resolve } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
const dry = a.has('dry');
|
||||
const only = a.list('only');
|
||||
const products = (config.products ?? []).filter(p => p.offerCodes?.length && sellsOn(config, p, 'apple') && (!only.length || only.includes(p.id)));
|
||||
if (!products.length) throw new Error('no products with offerCodes for the App Store (products[].offerCodes in storebound.config.ts)');
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
const problems = products.flatMap(p => validateIapOfferCodes(p.id, p.offerCodes, p.type, today));
|
||||
if (problems.length) throw new Error(problems.join('; '));
|
||||
const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId);
|
||||
const appId = await c.app();
|
||||
const report: Record<string, unknown>[] = [];
|
||||
const codeReqs: { req: Req; product: string; campaign: string; oneTime: boolean }[] = [];
|
||||
let active = 0;
|
||||
|
||||
for (const p of products) {
|
||||
const iap = (await c.asc('GET', `/v1/apps/${appId}/inAppPurchasesV2?filter[productId]=${encodeURIComponent(p.id)}`)).data?.[0];
|
||||
if (!iap) { warn(TAG, `${p.id}: not on App Store Connect (storebound apple iap)`); report.push({ product: p.id, missing: true }); continue; }
|
||||
const existing = await c.all(`/v2/inAppPurchases/${iap.id}/offerCodes?include=customCodes,oneTimeUseCodes&limit=200`);
|
||||
active += existing.filter((x: J) => x.attributes.active).length;
|
||||
let usaPoints: ReturnType<typeof applePoints> | null = null;
|
||||
const prices = async (oc: NonNullable<typeof p.offerCodes>[number]): Promise<TerritoryPoint[]> => {
|
||||
if (oc.free) {
|
||||
const all = oc.territories ?? (await c.all('/v1/territories?limit=200')).map((t: J) => t.id as string);
|
||||
return all.map(territory => ({ territory }));
|
||||
}
|
||||
usaPoints ??= applePoints(await pages(c, `/v2/inAppPurchases/${iap.id}/pricePoints?filter[territory]=USA&include=territory&limit=200`));
|
||||
const usa = pickPoint(usaPoints, 'USA', oc.usd!);
|
||||
const eq = applePoints(await pages(c, `/v1/inAppPurchasePricePoints/${usa.id}/equalizations?include=territory&limit=200`));
|
||||
const all = [{ territory: 'USA', pointId: usa.id }, ...eq.filter(x => x.territory !== 'USA').map(x => ({ territory: x.territory, pointId: x.id }))];
|
||||
return oc.territories ? all.filter(x => oc.territories!.includes(x.territory)) : all;
|
||||
};
|
||||
for (const oc of p.offerCodes!) {
|
||||
const cur = existing.find((x: J) => x.attributes.name === oc.name);
|
||||
let id: string | undefined = cur?.id;
|
||||
if (!cur) {
|
||||
const body = iapOfferCodeBody(iap.id, oc, await prices(oc));
|
||||
const req: Req = { method: 'POST', path: '/v1/inAppPurchaseOfferCodes', body, note: `${p.id}: campaign "${oc.name}" (${oc.free ? 'free' : `USD ${oc.usd}`}, ${body.included.length} territories)` };
|
||||
if (dry) log(TAG, `would ${describeReq(req)}`);
|
||||
else { id = ((await execute(c.asc, [req], { dry, tag: TAG }))[0] as J).data.id; active++; }
|
||||
} else log(TAG, `${p.id}: campaign "${oc.name}" exists (${cur.attributes.active ? 'active' : 'inactive'}, ${cur.attributes.productionCodeCount ?? 0} production codes)`);
|
||||
const haveCustom = new Set(cur ? (await c.all(`/v1/inAppPurchaseOfferCodes/${cur.id}/customCodes?limit=200`)).map((x: J) => x.attributes.customCode) : []);
|
||||
for (const cc of oc.customCodes ?? []) if (!haveCustom.has(cc.code)) codeReqs.push({ req: iapCustomCodeReq(id ?? '${new campaign}', cc), product: p.id, campaign: oc.name, oneTime: false });
|
||||
// one-time batches are not matched one by one: a batch is created when the campaign has fewer batches than configured
|
||||
const batches = cur ? (await c.all(`/v1/inAppPurchaseOfferCodes/${cur.id}/oneTimeUseCodes?limit=200`)).length : 0;
|
||||
for (const b of (oc.oneTimeCodes ?? []).slice(batches)) codeReqs.push({ req: iapOneTimeCodesReq(id ?? '${new campaign}', b), product: p.id, campaign: oc.name, oneTime: true });
|
||||
report.push({ product: p.id, campaign: oc.name, exists: !!cur, codesToCreate: codeReqs.filter(x => x.campaign === oc.name && x.product === p.id).map(x => x.req.note) });
|
||||
}
|
||||
}
|
||||
if (active > 10) warn(TAG, `${active} active offer code campaigns: App Store Connect allows 10 active offers per app at a time`);
|
||||
if (a.has('json')) printJson({ dryRun: dry, campaigns: report, codes: codeReqs.map(x => describeReq(x.req)) });
|
||||
if (!codeReqs.length) { done(TAG, dry ? 'offer codes checked (dry run)' : 'offer codes done'); return; }
|
||||
if (!a.has('codes')) { for (const x of codeReqs) log(TAG, `not created without --codes: ${x.req.note}`); done(TAG, `${codeReqs.length} code request(s) left; run with --codes (asks first)`); return; }
|
||||
if (dry) { await execute(c.asc, codeReqs.map(x => x.req), { dry, tag: TAG }); done(TAG, 'dry run: no codes created'); return; }
|
||||
if (!(await confirm(ctx, `Create ${codeReqs.length} code request(s) (${codeReqs.map(x => x.req.note).join('; ')})? Codes count against the 1 million per quarter and can be redeemed by anyone who gets them.`))) return;
|
||||
const dir = resolve('.storebound/offer-codes');
|
||||
for (const x of codeReqs) {
|
||||
const out = (await execute(c.asc, [x.req], { dry: false, tag: TAG }))[0] as J;
|
||||
if (!x.oneTime) continue;
|
||||
// the codes of a one-time-use batch (text/csv); saved locally, never printed
|
||||
const values = await c.bytes(`/v1/inAppPurchaseOfferCodeOneTimeUseCodes/${out.data.id}/values`, 'text/csv');
|
||||
if (!values) { warn(TAG, `${x.product} "${x.campaign}": codes not ready yet; download them in App Store Connect`); continue; }
|
||||
mkdirSync(dir, { recursive: true });
|
||||
const file = join(dir, `${x.product}-${x.campaign.replace(/[^A-Za-z0-9._-]+/g, '_')}-${out.data.id}.csv`);
|
||||
writeFileSync(file, values);
|
||||
log(TAG, `${x.product} "${x.campaign}": one-time codes saved to ${file}`);
|
||||
}
|
||||
done(TAG, `${codeReqs.length} code request(s) done`);
|
||||
}
|
||||
61
cli/apple/preorder.ts
Normal file
61
cli/apple/preorder.ts
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
// App Store pre-orders through the app availability API.
|
||||
// storebound apple preorder status [--json]
|
||||
// storebound apple preorder enable --release-date YYYY-MM-DD [--territories USA,DEU] [--dry] [--yes] [--json]
|
||||
// storebound apple preorder end [--territories USA,DEU] [--dry] [--yes] [--json]
|
||||
// status: per territory available, release date, pre-order on, publish date, content statuses. enable puts the
|
||||
// territories (default: all the app is available in and not yet released) on pre-order with that release date; end
|
||||
// stops the pre-order and releases the app there at once. Both are public, so they show the dry run and ask first;
|
||||
// neither is an MCP tool. Apple requires an approved version first; the release date is 2-180 days ahead for a new
|
||||
// app (up to 365 days for an existing app in a new region). Google Play pre-registration has no API: Play Console >
|
||||
// Grow users > Pre-registration (see the app-store-promotion skill). Pure parts and sources: cli/lib/offers.ts.
|
||||
import type { Ctx } from '../lib/ctx';
|
||||
import { confirm, need } from '../lib/ctx';
|
||||
import { done, printJson, warn } from '../lib/log';
|
||||
import { endPreOrderReq, planPreOrder, territoryRows } from '../lib/offers';
|
||||
import { textTable } from '../lib/table';
|
||||
import { ascClient, type J } from './asc';
|
||||
import { describeReq, execute } from './jsonapi';
|
||||
|
||||
const TAG = 'preorder';
|
||||
const USAGE = 'usage: storebound apple preorder status | enable --release-date YYYY-MM-DD [--territories USA,DEU] | end [--territories USA]';
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
const sub = a._[0];
|
||||
if (!sub || !['status', 'enable', 'end'].includes(sub)) throw new Error(USAGE);
|
||||
const dry = a.has('dry');
|
||||
const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId);
|
||||
const appId = await c.app();
|
||||
const avail = (await c.maybe(`/v1/apps/${appId}/appAvailabilityV2`))?.data;
|
||||
if (!avail) throw new Error('the app has no availability yet: set territories first (storebound apple appinfo, or Pricing and Availability in App Store Connect)');
|
||||
const pagesOut: J[] = [];
|
||||
for (let url: string | null = `/v2/appAvailabilities/${avail.id}/territoryAvailabilities?include=territory&limit=200`; url;) { const p: J = await c.asc('GET', url); pagesOut.push(p); url = p.links?.next ?? null; }
|
||||
const rows = territoryRows(pagesOut);
|
||||
const territories = a.list('territories').length ? a.list('territories') : null;
|
||||
|
||||
if (sub === 'status') {
|
||||
const pre = rows.filter(r => r.preOrderEnabled);
|
||||
if (a.has('json')) { printJson({ availableInNewTerritories: avail.attributes?.availableInNewTerritories ?? null, territories: rows }); return; }
|
||||
console.log(textTable(['territory', 'available', 'release date', 'pre-order', 'pre-order published', 'status'],
|
||||
rows.filter(r => !territories || territories.includes(r.territory)).map(r => [r.territory, r.available ? 'yes' : 'no', r.releaseDate ?? '', r.preOrderEnabled ? 'on' : '', r.preOrderPublishDate ?? '', (r.contentStatuses ?? []).join(' ')])));
|
||||
done(TAG, `${rows.length} territories, ${pre.length} on pre-order`);
|
||||
return;
|
||||
}
|
||||
|
||||
const plan = sub === 'enable'
|
||||
? planPreOrder(rows, need(a.get('release-date'), '--release-date YYYY-MM-DD'), territories)
|
||||
: { reqs: [endPreOrderReq(rows, territories)].filter(r => r !== null), problems: [] as string[], warnings: [] as string[] };
|
||||
for (const w of plan.warnings) warn(TAG, w);
|
||||
if (plan.problems.length) throw new Error(plan.problems.join('; '));
|
||||
if (a.has('json') && dry) { printJson({ dryRun: true, requests: plan.reqs.map(r => describeReq(r)), warnings: plan.warnings }); return; }
|
||||
if (!plan.reqs.length) { done(TAG, sub === 'enable' ? 'pre-order already set up like that' : 'no territory is on pre-order'); return; }
|
||||
if (dry) { await execute(c.asc, plan.reqs, { dry, tag: TAG }); done(TAG, 'dry run: nothing changed'); return; }
|
||||
const q = sub === 'enable'
|
||||
? `Put the app on pre-order in ${plan.reqs.length} territor${plan.reqs.length === 1 ? 'y' : 'ies'} with release date ${a.get('release-date')}? The pre-order page goes public once you release an approved version.`
|
||||
: `End the pre-order and release the app now (${plan.reqs[0]!.note})?`;
|
||||
if (!(await confirm(ctx, q))) return;
|
||||
await execute(c.asc, plan.reqs, { dry: false, tag: TAG });
|
||||
if (a.has('json')) printJson({ dryRun: false, requests: plan.reqs.map(r => describeReq(r)) });
|
||||
done(TAG, sub === 'enable' ? 'pre-order set (storebound apple preorder status)' : 'pre-order ended; the app is released in those territories');
|
||||
}
|
||||
62
cli/apple/promoted.ts
Normal file
62
cli/apple/promoted.ts
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
// Promoted in-app purchases on the App Store product page, from apple.promoted.
|
||||
// storebound apple promoted [--enable] [--dry] [--yes] [--json]
|
||||
// Status (what is promoted, enabled, its review state), then: creates the missing promoted purchases disabled,
|
||||
// updates visibleForAllUsers, sets the display order. --enable also switches them on, which shows them on the
|
||||
// product page once approved: that asks first and is not an MCP tool. Each promoted purchase needs its promotional
|
||||
// image (App Store Connect) and the app must handle purchases started on the App Store (StoreKit PurchaseIntent).
|
||||
// At most 20 at a time. Pure parts and sources: cli/lib/offers.ts.
|
||||
import type { Ctx } from '../lib/ctx';
|
||||
import { confirm, need } from '../lib/ctx';
|
||||
import { done, log, printJson, warn } from '../lib/log';
|
||||
import { planPromoted, type PromotedNow, promotedOrderReq } from '../lib/offers';
|
||||
import { textTable } from '../lib/table';
|
||||
import { ascClient, type J } from './asc';
|
||||
import { describeReq, execute } from './jsonapi';
|
||||
|
||||
const TAG = 'promoted';
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
const dry = a.has('dry');
|
||||
const cfg = config.apple?.promoted;
|
||||
const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId);
|
||||
const appId = await c.app();
|
||||
const products = new Map<string, { apiId: string; kind: 'iap' | 'sub' }>();
|
||||
for (const p of await c.all(`/v1/apps/${appId}/inAppPurchasesV2?limit=200`)) products.set(p.attributes.productId, { apiId: p.id, kind: 'iap' });
|
||||
for (const g of await c.all(`/v1/apps/${appId}/subscriptionGroups?limit=200`))
|
||||
for (const s of await c.all(`/v1/subscriptionGroups/${g.id}/subscriptions?limit=200`)) products.set(s.attributes.productId, { apiId: s.id, kind: 'sub' });
|
||||
const byApiId = new Map([...products.entries()].map(([pid, v]) => [v.apiId, pid] as const));
|
||||
const raw = await c.asc('GET', `/v1/apps/${appId}/promotedPurchases?include=inAppPurchaseV2,subscription&limit=50`);
|
||||
const now: PromotedNow[] = (raw.data ?? []).map((p: J) => ({ id: p.id, enabled: !!p.attributes.enabled, visibleForAllUsers: !!p.attributes.visibleForAllUsers, state: p.attributes.state,
|
||||
productId: byApiId.get(p.relationships?.inAppPurchaseV2?.data?.id ?? p.relationships?.subscription?.data?.id ?? '') ?? '?' }));
|
||||
const status = now.map((p, i) => [i + 1, p.productId, p.enabled ? 'enabled' : 'off', p.visibleForAllUsers ? 'everyone' : 'app decides', p.state ?? '']);
|
||||
if (!cfg) {
|
||||
if (a.has('json')) printJson({ promoted: now });
|
||||
else console.log(now.length ? textTable(['#', 'product', 'enabled', 'visible to', 'state'], status) : 'no promoted in-app purchases');
|
||||
done(TAG, 'apple.promoted is not set: status only');
|
||||
return;
|
||||
}
|
||||
const plan = planPromoted(appId, cfg, now, products, { enable: a.has('enable') });
|
||||
const order = promotedOrderReq(appId, cfg, now);
|
||||
for (const u of plan.unknown) warn(TAG, `${u}: not on App Store Connect (storebound apple iap / apple subscriptions)`);
|
||||
if (plan.extra.length) log(TAG, `promoted on the store but not in apple.promoted (left as they are): ${plan.extra.join(', ')}`);
|
||||
if (now.length + plan.create.length > 20) throw new Error(`${now.length + plan.create.length} promoted purchases: at most 20`);
|
||||
const reqs = [...plan.create, ...plan.update];
|
||||
if (a.has('json')) printJson({ dryRun: dry, promoted: now, requests: [...reqs, ...(order ? [order] : [])].map(r => describeReq(r)), unknown: plan.unknown, extra: plan.extra });
|
||||
else if (now.length) console.log(textTable(['#', 'product', 'enabled', 'visible to', 'state'], status));
|
||||
if (!reqs.length && !order) { done(TAG, 'promoted purchases up to date'); return; }
|
||||
if (dry) { await execute(c.asc, [...reqs, ...(order ? [order] : [])], { dry, tag: TAG }); done(TAG, 'dry run: nothing changed'); return; }
|
||||
const enabling = reqs.some(r => JSON.stringify(r.body).includes('"enabled":true'));
|
||||
if (enabling && !(await confirm(ctx, 'Switch promoted purchases on? Once approved they show on the App Store product page.'))) return;
|
||||
await execute(c.asc, reqs, { dry: false, tag: TAG });
|
||||
// the order covers the purchases that exist now (new ones included)
|
||||
if (plan.create.length || order) {
|
||||
const fresh = await c.asc('GET', `/v1/apps/${appId}/promotedPurchases?include=inAppPurchaseV2,subscription&limit=50`);
|
||||
const after: PromotedNow[] = (fresh.data ?? []).map((p: J) => ({ id: p.id, enabled: !!p.attributes.enabled, visibleForAllUsers: !!p.attributes.visibleForAllUsers,
|
||||
productId: byApiId.get(p.relationships?.inAppPurchaseV2?.data?.id ?? p.relationships?.subscription?.data?.id ?? '') ?? '?' }));
|
||||
const o = promotedOrderReq(appId, cfg, after);
|
||||
if (o) await execute(c.asc, [o], { dry: false, tag: TAG });
|
||||
}
|
||||
done(TAG, `promoted purchases updated${a.has('enable') ? '' : ' (not switched on: --enable when the images are approved)'}`);
|
||||
}
|
||||
|
|
@ -5,6 +5,10 @@
|
|||
// storebound apple testflight what-to-test --build N [--version x.y.z] [--locale en-US,tr] [--text "..."] [--dry]
|
||||
// storebound apple testflight info [--dry] Test Information + Beta App Review contact / notes
|
||||
// storebound apple testflight distribute --build N --group a,b [--version x.y.z] [--internal-only] [--submit-review] [--dry] [--yes]
|
||||
// storebound apple testflight wait --build N [--version x.y.z] [--timeout 60m] [--dry] [--json] until processing ends
|
||||
// exit codes: 0 VALID, 1 FAILED / INVALID, 7 timeout; --dry checks once and does not wait
|
||||
// storebound apple testflight expire (--keep N | --older-than D) [--version x.y.z] [--dry] [--yes] [--json]
|
||||
// expires old builds (permanent; asks first); builds attached to an App Store version and processing builds stay
|
||||
// Testers come from a CSV in .storebound/ (gitignored; never commit tester emails): email, first_name, last_name,
|
||||
// groups (";"-separated). Emails are masked in every log line. Adding testers makes Apple email TestFlight invitations
|
||||
// (once the group has a build), so `testers` asks first; `--remove` takes testers out of the managed groups.
|
||||
|
|
@ -16,6 +20,8 @@ import { confirm, need } from '../lib/ctx';
|
|||
import { reviewContact } from '../lib/credentials';
|
||||
import { done, log, printJson, warn } from '../lib/log';
|
||||
import { textTable } from '../lib/table';
|
||||
import { BUILD_WAIT_EXIT, type BuildSeen, expireCandidates, planExpire, validHint, waitDelay, type WaitOutcome, waitOutcome } from '../lib/build-ops';
|
||||
import { parseDuration } from '../lib/release';
|
||||
import {
|
||||
type ApiBuild, betaDescriptions, betaReadiness, betaReviewReq, buildsWithVersion, type Group, groupFromApi, inviteReq, maskEmail,
|
||||
parseTesters, pickBuild, planBetaInfo, planBetaReviewDetail, planDistribute, planGroups, planTesters, planWhatToTest, whatToTestFromListing,
|
||||
|
|
@ -24,7 +30,56 @@ import { type Asc, ascClient, type J } from './asc';
|
|||
import { execute } from './jsonapi';
|
||||
|
||||
const TAG = 'testflight';
|
||||
const USAGE = 'usage: storebound apple testflight status | groups | testers | what-to-test --build N | info | distribute --build N --group <names>';
|
||||
const USAGE = 'usage: storebound apple testflight status | groups | testers | what-to-test --build N | info | distribute --build N --group <names> | wait --build N | expire --keep N | --older-than D';
|
||||
|
||||
/** The state of build `number` (of `marketing` version) right now; found: false while App Store Connect does not list it. */
|
||||
async function seeBuild(c: Asc, appId: string, number: string, marketing?: string): Promise<BuildSeen & { version?: string }> {
|
||||
const q = new URLSearchParams({ 'filter[app]': appId, 'filter[version]': number, 'filter[preReleaseVersion.platform]': 'IOS', include: 'preReleaseVersion,buildBetaDetail', limit: '50' });
|
||||
if (marketing) q.set('filter[preReleaseVersion.version]', marketing);
|
||||
const resp = await c.asc('GET', `/v1/builds?${q}`);
|
||||
const hits = buildsWithVersion(resp).filter(b => b.attributes.version === number && (!marketing || b.marketing === marketing));
|
||||
if (!hits.length) return { found: false };
|
||||
const b = pickBuild(hits, number, marketing);
|
||||
const d = (resp.included ?? []).find((x: J) => x.type === 'buildBetaDetails' && x.id === (b as J).relationships?.buildBetaDetail?.data?.id)?.attributes;
|
||||
return { found: true, processingState: b.attributes.processingState, internal: d?.internalBuildState ?? null, external: d?.externalBuildState ?? null, version: b.marketing };
|
||||
}
|
||||
|
||||
export interface BuildWait { outcome: WaitOutcome; timedOut: boolean; seen: BuildSeen & { version?: string }; waitedSeconds: number }
|
||||
|
||||
/**
|
||||
* Polls build `number` until processing ends (VALID, or FAILED / INVALID) or `timeoutMs` passes; logs each state change.
|
||||
* `once` reads the state a single time. Shared by `testflight wait` and `apple upload` (which waits after the upload).
|
||||
*/
|
||||
export async function waitForBuild(c: Asc, appId: string, number: string, o: { marketing?: string; timeoutMs: number; once?: boolean; tag?: string }): Promise<BuildWait> {
|
||||
const started = Date.now();
|
||||
let delay: number | null = null, last = '';
|
||||
for (;;) {
|
||||
const seen = await seeBuild(c, appId, number, o.marketing);
|
||||
const outcome = waitOutcome(seen);
|
||||
const line = outcome === 'missing' ? 'not listed yet (App Store Connect lists it once processing starts)' : `${seen.processingState}${seen.internal ? `, internal ${seen.internal}` : ''}`;
|
||||
if (line !== last) { log(o.tag ?? TAG, `build ${number}${seen.version ? ` (${seen.version})` : ''}: ${line} [${Math.round((Date.now() - started) / 60_000)} min]`); last = line; }
|
||||
const result = (timedOut: boolean): BuildWait => ({ outcome, timedOut, seen, waitedSeconds: Math.round((Date.now() - started) / 1000) });
|
||||
if (outcome === 'valid' || outcome === 'failed') return result(false);
|
||||
if (o.once) return result(false);
|
||||
delay = waitDelay(delay);
|
||||
if (Date.now() + delay - started > o.timeoutMs) return result(true);
|
||||
await Bun.sleep(delay);
|
||||
}
|
||||
}
|
||||
|
||||
/** The closing line for a finished wait (VALID with the next step, or FAILED / INVALID with what to do). */
|
||||
export function waitMessage(number: string, r: BuildWait): string {
|
||||
return r.outcome === 'valid'
|
||||
? `build ${number} is VALID; ${validHint(r.seen).replace('N', number)}`
|
||||
: `build ${number} is ${r.seen.processingState}: read the email from App Store Connect (missing icons, wrong SDK, invalid signature), fix and upload a new build number`;
|
||||
}
|
||||
|
||||
/** Every page of a GET, with `included` kept (c.all keeps only data). */
|
||||
async function pagesOf(c: Asc, path: string): Promise<J[]> {
|
||||
const out: J[] = [];
|
||||
for (let url: string | null = path; url;) { const page: J = await c.asc('GET', url); out.push(page); url = page.links?.next ?? null; }
|
||||
return out;
|
||||
}
|
||||
|
||||
async function groups(c: Asc, appId: string): Promise<Group[]> {
|
||||
return (await c.all(`/v1/apps/${appId}/betaGroups?limit=200`)).map(groupFromApi);
|
||||
|
|
@ -187,5 +242,35 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
done(TAG, `build ${number}: ${reqs.length ? `added to ${reqs.length} group(s)` : 'already in every group'}`);
|
||||
return;
|
||||
}
|
||||
if (sub === 'wait') {
|
||||
const number = need(a.get('build'), '--build N (the exact build number you uploaded)');
|
||||
const marketing = a.get('version');
|
||||
const r = await waitForBuild(c, appId, number, { marketing, timeoutMs: parseDuration(a.str('timeout', '60m')), once: dry });
|
||||
const code = r.outcome === 'valid' ? BUILD_WAIT_EXIT.valid : r.outcome === 'failed' ? BUILD_WAIT_EXIT.failed : BUILD_WAIT_EXIT.timeout;
|
||||
if (a.has('json')) printJson({ build: number, version: r.seen.version ?? marketing ?? null, outcome: r.timedOut ? 'timeout' : r.outcome, processingState: r.seen.processingState ?? null,
|
||||
internal: r.seen.internal ?? null, external: r.seen.external ?? null, waitedSeconds: r.waitedSeconds });
|
||||
log(TAG, r.outcome === 'valid' || r.outcome === 'failed' ? waitMessage(number, r) : dry ? 'dry run: checked once, not waiting' : `timeout after ${Math.round(r.waitedSeconds / 60)} min; still ${r.outcome} (re-run to keep waiting)`);
|
||||
process.exit(code);
|
||||
}
|
||||
|
||||
if (sub === 'expire') {
|
||||
const keep = a.get('keep') === undefined ? undefined : a.num('keep', 0);
|
||||
const olderThanDays = a.get('older-than') === undefined ? undefined : a.num('older-than', 0);
|
||||
const q = new URLSearchParams({ 'filter[app]': appId, 'filter[expired]': 'false', 'filter[preReleaseVersion.platform]': 'IOS', sort: '-uploadedDate', include: 'preReleaseVersion,appStoreVersion', limit: '200' });
|
||||
if (a.get('version')) q.set('filter[preReleaseVersion.version]', a.get('version')!);
|
||||
const plan = planExpire(expireCandidates(await pagesOf(c, `/v1/builds?${q}`)), { keep, olderThanDays });
|
||||
const row = (b: { build: string; version?: string; uploaded: string }, what: string) => [b.version ?? '', b.build, b.uploaded.slice(0, 10), what];
|
||||
const summary = { expire: plan.expire.map(b => ({ build: b.build, version: b.version ?? null, uploaded: b.uploaded })), keep: plan.keep.length,
|
||||
protected: plan.protected.map(p => ({ build: p.b.build, version: p.b.version ?? null, why: p.why })) };
|
||||
if (a.has('json') && dry) { printJson({ dryRun: true, ...summary }); return; }
|
||||
if (!a.has('json')) console.log(textTable(['version', 'build', 'uploaded', ''], [...plan.expire.map(b => row(b, 'expire')), ...plan.protected.map(p => row(p.b, `keep: ${p.why}`)), ...plan.keep.map(b => row(b, 'keep'))]));
|
||||
if (!plan.reqs.length) { done(TAG, 'nothing to expire'); if (a.has('json')) printJson({ dryRun: dry, ...summary, expired: [] }); return; }
|
||||
if (dry) { await execute(c.asc, plan.reqs, { dry, tag: TAG }); done(TAG, `dry run: ${plan.reqs.length} build(s) would be expired`); return; }
|
||||
if (!(await confirm(ctx, `Expire ${plan.reqs.length} build(s) (${plan.expire.map(b => b.build).join(', ')})? Testers lose them; an expired build cannot be brought back.`))) return;
|
||||
await execute(c.asc, plan.reqs, { dry: false, tag: TAG });
|
||||
if (a.has('json')) printJson({ dryRun: false, ...summary, expired: plan.expire.map(b => b.build) });
|
||||
done(TAG, `${plan.reqs.length} build(s) expired`);
|
||||
return;
|
||||
}
|
||||
throw new Error(`unknown testflight command "${sub}"\n${USAGE}`);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,7 +8,8 @@
|
|||
// Xcode needed, works on any OS.
|
||||
// --via altool: `xcrun altool --upload-package` with the API key (Xcode's own uploader; macOS).
|
||||
// Both are listed by Apple (App Store Connect Help > Upload builds); neither is deprecated. Then the build is polled
|
||||
// until processingState is VALID (exit 0), INVALID / FAILED (exit 1) or the timeout (exit 7).
|
||||
// with `apple testflight wait` (waitForBuild) until processingState is VALID (exit 0), INVALID / FAILED (exit 1) or the
|
||||
// timeout (exit 7).
|
||||
// An upload is a write: --dry shows the plan; a real run asks first (--yes in scripts).
|
||||
import { closeSync, existsSync, openSync, readdirSync, readSync, statSync } from 'node:fs';
|
||||
import { basename, join, relative } from 'node:path';
|
||||
|
|
@ -17,8 +18,10 @@ import type { Ctx } from '../lib/ctx';
|
|||
import { confirm, need } from '../lib/ctx';
|
||||
import { done, log, printJson, warn } from '../lib/log';
|
||||
import { compareBuild, nextBuildNumber, nextPollDelay, parseDuration, WAIT_EXIT } from '../lib/release';
|
||||
import { altoolArgs, BUILD_DONE, buildUploadReqs, ipaInfo, showCmd, UPLOAD_DONE, uploadProblems } from '../lib/xcode';
|
||||
import { altoolArgs, buildUploadReqs, ipaInfo, showCmd, UPLOAD_DONE, uploadProblems } from '../lib/xcode';
|
||||
import { BUILD_WAIT_EXIT } from '../lib/build-ops';
|
||||
import { type Asc, ascClient, type J } from './asc';
|
||||
import { waitForBuild, waitMessage } from './testflight';
|
||||
import { describeReq } from './jsonapi';
|
||||
|
||||
const TAG = 'upload';
|
||||
|
|
@ -93,20 +96,6 @@ async function altoolUpload(root: string, ipa: string): Promise<void> {
|
|||
} finally { k.cleanup(); }
|
||||
}
|
||||
|
||||
/** Polls the build until processed. */
|
||||
async function waitProcessing(c: Asc, appId: string, info: ReturnType<typeof ipaInfo>, deadline: number): Promise<string> {
|
||||
const q = new URLSearchParams({ 'filter[app]': appId, 'filter[version]': info.build, 'filter[preReleaseVersion.version]': info.version, 'filter[preReleaseVersion.platform]': 'IOS', limit: '5' });
|
||||
for (let delay: number | null = null; ;) {
|
||||
const b = ((await c.asc('GET', `/v1/builds?${q}`)).data as J[])[0];
|
||||
const state = b?.attributes?.processingState ?? 'NOT_YET_VISIBLE';
|
||||
if (BUILD_DONE.has(state)) return state;
|
||||
if (Date.now() > deadline) return 'TIMEOUT';
|
||||
delay = nextPollDelay(delay, { first: 30_000, max: 120_000 });
|
||||
log(TAG, `build ${info.build}: ${state}, next check in ${Math.round(delay / 1000)} s`);
|
||||
await Bun.sleep(delay);
|
||||
}
|
||||
}
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root, resolve } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
|
|
@ -154,10 +143,12 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
try { await apiUpload(c, appId, ipa, info, deadline); } catch (e) { if ((e as { exit?: number }).exit) { warn(TAG, (e as Error).message); process.exit((e as { exit: number }).exit); } throw e; }
|
||||
} else await altoolUpload(root, ipa);
|
||||
if (!wait) { if (json) printJson({ ...summary, uploaded: true }); done(TAG, `build ${info.build} uploaded; storebound apple status shows when it is VALID`); return; }
|
||||
const state = await waitProcessing(c, appId, info, deadline);
|
||||
// the same poll as `storebound apple testflight wait`, within what is left of --timeout
|
||||
const r = await waitForBuild(c, appId, info.build, { marketing: info.version, timeoutMs: Math.max(0, deadline - Date.now()), tag: TAG });
|
||||
const state = r.timedOut || (r.outcome !== 'valid' && r.outcome !== 'failed') ? 'TIMEOUT' : r.seen.processingState ?? 'UNKNOWN';
|
||||
if (json) printJson({ ...summary, uploaded: true, processingState: state });
|
||||
if (state === 'VALID') { done(TAG, `build ${info.build} is VALID. Next: storebound apple encryption --build ${info.build}, apple testflight distribute --build ${info.build} --group <name> --dry`); return; }
|
||||
if (state === 'TIMEOUT') { warn(TAG, `build ${info.build} not processed after ${a.str('timeout', '60m')}; check again with storebound apple status`); process.exit(WAIT_EXIT.timeout); }
|
||||
warn(TAG, `build ${info.build} is ${state}: Apple emails the reason (ITMS-xxxxx) to the team; fix it and upload a new build number`);
|
||||
process.exit(1);
|
||||
if (r.outcome === 'valid') { done(TAG, `${waitMessage(info.build, r)}. Then: apple testflight distribute --build ${info.build} --group <name> --dry`); return; }
|
||||
if (state === 'TIMEOUT') { warn(TAG, `build ${info.build} not processed after ${a.str('timeout', '60m')}; keep waiting with storebound apple testflight wait --build ${info.build} --version ${info.version}`); process.exit(BUILD_WAIT_EXIT.timeout); }
|
||||
warn(TAG, `${waitMessage(info.build, r)} (Apple emails the ITMS-xxxxx reason to the team)`);
|
||||
process.exit(BUILD_WAIT_EXIT.failed);
|
||||
}
|
||||
|
|
|
|||
70
cli/apple/win-back.ts
Normal file
70
cli/apple/win-back.ts
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
// Win-back offers for lapsed subscribers from subscriptions[].subscriptions[].winBack.
|
||||
// storebound apple win-back [--only sub1,sub2] [--dry] [--yes] [--json]
|
||||
// Lists what each subscription has (GET /v1/subscriptions/{id}/winBackOffers) and creates the configured offers that
|
||||
// are missing (by offer id). A win-back offer goes live by itself on its start date (Manage Subscriptions, the
|
||||
// in-app offer sheet, the App Store when promoted), so creating one is the owner's step: dry run first, then a
|
||||
// terminal confirmation; never an MCP tool. The subscription must be approved; reference name, offer id and price
|
||||
// cannot be changed afterwards (App Store Connect Help). Pure parts and sources: cli/lib/offers.ts.
|
||||
import type { Ctx } from '../lib/ctx';
|
||||
import { confirm, need } from '../lib/ctx';
|
||||
import { done, log, printJson, warn } from '../lib/log';
|
||||
import { type TerritoryPoint, validateWinBack, winBackBody } from '../lib/offers';
|
||||
import { allSubscriptions, applePoints, pickPoint } from '../lib/subscriptions';
|
||||
import { textTable } from '../lib/table';
|
||||
import { pages } from '../prices';
|
||||
import { ascClient, type J } from './asc';
|
||||
import { describeReq, execute, type Req } from './jsonapi';
|
||||
|
||||
const TAG = 'win-back';
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
const dry = a.has('dry');
|
||||
const only = a.list('only');
|
||||
const subs = allSubscriptions(config.subscriptions).map(x => x.sub).filter(s => s.winBack?.length && (!only.length || only.includes(s.id)));
|
||||
if (!subs.length) throw new Error('no subscriptions with winBack offers (subscriptions[].subscriptions[].winBack in storebound.config.ts)');
|
||||
const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId);
|
||||
const appId = await c.app();
|
||||
const onStore = new Map<string, J>();
|
||||
for (const g of await c.all(`/v1/apps/${appId}/subscriptionGroups?limit=200`))
|
||||
for (const s of await c.all(`/v1/subscriptionGroups/${g.id}/subscriptions?limit=200`)) onStore.set(s.attributes.productId, s);
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
const reqs: Req[] = [];
|
||||
const rows: (string | number)[][] = [];
|
||||
const skipped: { id: string; why: string }[] = [];
|
||||
|
||||
for (const s of subs) {
|
||||
const remote = onStore.get(s.id);
|
||||
if (!remote) { skipped.push({ id: s.id, why: 'not on App Store Connect (storebound apple subscriptions)' }); continue; }
|
||||
const existing = await c.all(`/v1/subscriptions/${remote.id}/winBackOffers?limit=200`);
|
||||
for (const o of existing) rows.push([s.id, o.attributes.offerId, o.attributes.offerMode, o.attributes.startDate ?? '', o.attributes.endDate ?? '', o.attributes.priority ?? '']);
|
||||
const missing = s.winBack!.filter(o => !existing.some((x: J) => x.attributes.offerId === o.id));
|
||||
if (!missing.length) continue;
|
||||
if (remote.attributes.state !== 'APPROVED') { skipped.push({ id: s.id, why: `subscription is ${remote.attributes.state}: win-back offers need an approved subscription` }); continue; }
|
||||
const problems = validateWinBack(s.id, missing, today);
|
||||
if (problems.length) { skipped.push({ id: s.id, why: problems.join('; ') }); continue; }
|
||||
let usa: ReturnType<typeof applePoints> | null = null;
|
||||
for (const o of missing) {
|
||||
let prices: TerritoryPoint[];
|
||||
if (o.type === 'free') prices = (await c.all(`/v1/subscriptions/${remote.id}/prices?include=territory&limit=200`)).map((x: J) => ({ territory: x.relationships?.territory?.data?.id })).filter((x: TerritoryPoint) => !!x.territory);
|
||||
else {
|
||||
usa ??= applePoints(await pages(c, `/v1/subscriptions/${remote.id}/pricePoints?filter[territory]=USA&include=territory&limit=200`));
|
||||
const point = pickPoint(usa, 'USA', o.usd!);
|
||||
const eq = applePoints(await pages(c, `/v1/subscriptionPricePoints/${point.id}/equalizations?include=territory&limit=200`));
|
||||
prices = [{ territory: 'USA', pointId: point.id }, ...eq.filter(x => x.territory !== 'USA').map(x => ({ territory: x.territory, pointId: x.id }))];
|
||||
}
|
||||
reqs.push({ method: 'POST', path: '/v1/winBackOffers', body: winBackBody(remote.id, s.period, o, prices),
|
||||
note: `${s.id}: win-back "${o.id}" ${o.type}${o.usd ? ` USD ${o.usd}` : ''}, from ${o.start}${o.end ? ` to ${o.end}` : ''}, ${prices.length} territories` });
|
||||
}
|
||||
}
|
||||
if (a.has('json')) printJson({ dryRun: dry, existing: rows.map(r => ({ subscription: r[0], offerId: r[1], mode: r[2], start: r[3], end: r[4], priority: r[5] })), create: reqs.map(r => describeReq(r)), skipped });
|
||||
else if (rows.length) console.log(textTable(['subscription', 'offer', 'mode', 'start', 'end', 'priority'], rows));
|
||||
for (const s of skipped) warn(TAG, `${s.id}: ${s.why}`);
|
||||
if (!reqs.length) { done(TAG, 'no win-back offer to create'); return; }
|
||||
if (dry) { await execute(c.asc, reqs, { dry, tag: TAG }); done(TAG, `dry run: ${reqs.length} win-back offer(s) would be created`); return; }
|
||||
if (!(await confirm(ctx, `Create ${reqs.length} win-back offer(s)? Each goes live by itself on its start date; reference name, offer id and price cannot be changed afterwards.`))) return;
|
||||
await execute(c.asc, reqs, { dry: false, tag: TAG });
|
||||
log(TAG, 'the redemption URL of each offer is in App Store Connect (Subscriptions > the subscription > Win-Back Offers)');
|
||||
done(TAG, `${reqs.length} win-back offer(s) created`);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue