Merge remote-tracking branch 'origin/main' into apple-name

# Conflicts:
#	CHANGELOG.md
This commit is contained in:
CRTkafa 2026-10-11 19:40:51 +00:00
commit 59371304fe
15 changed files with 457 additions and 21 deletions

View file

@ -5,11 +5,16 @@
// Size: an App Store screenshot size (iPhone or iPad, e.g. 1320 x 2868 or 1290 x 2796); Apple processes the upload
// after it is committed and fails other sizes with IMAGE_INCORRECT_DIMENSIONS, so the size is checked before the
// upload and the delivery state is read back after it (an upload is only "done" when Apple says COMPLETE).
// Config products missing from the store's list (it lags a minute after `apple iap` creates them) are named with a
// warning and the exit code is 1, so nothing is skipped silently (docs/pitfalls.md). --dry ends with the plan table.
import { existsSync, readFileSync } from 'node:fs';
import { join, relative } from 'node:path';
import { sellsOn } from '../lib/config';
import type { Ctx } from '../lib/ctx';
import { need } from '../lib/ctx';
import { dryPlan, type PlanRow } from '../lib/dry';
import { done, log, warn } from '../lib/log';
import { reportMissing } from '../lib/store-lag';
import { IMAGE_SPECS, imageInfo } from '../shots/spec';
import { ascClient, md5 } from './asc';
@ -39,28 +44,27 @@ export async function run(ctx: Ctx): Promise<void> {
const defs = new Map((config.products ?? []).map(p => [p.id, p]));
const shotOf = (id: string) => c.maybe(`/v2/inAppPurchases/${id}/appStoreReviewScreenshot`).then(r => r?.data as Shot | undefined);
const iaps = await c.all(`/v1/apps/${appId}/inAppPurchasesV2?limit=200`);
const seen = new Set(iaps.map((p: any) => p.attributes.productId));
const missingInStore = [...defs.keys()].filter(id => !seen.has(id));
if (missingInStore.length)
warn('apple', `not in App Store Connect yet: ${missingInStore.join(', ')} (created moments ago? the store's list can lag a minute; run again)`);
const want = (config.products ?? []).filter(p => sellsOn(config, p, 'apple')).map(p => p.id);
const missing = reportMissing('apple', 'products', want, iaps.map(p => p.attributes.productId as string), { fail: true });
const rows: PlanRow[] = missing.map(id => ({ item: id, action: 'skip', detail: 'not in the store\'s list yet (run apple iap first, or re-run in a minute)' }));
let problems = 0;
for (const p of iaps) {
const sku: string = p.attributes.productId;
const def = defs.get(sku);
const file = def?.reviewScreenshot ? resolve(def.reviewScreenshot)
: ['png', 'jpg', 'jpeg'].map(e => resolve(join(config.apple?.reviewShots ?? 'store/iap-review', `${sku}.${e}`))).find(existsSync);
if (!file || !existsSync(file)) { warn('apple', `${sku}: no review screenshot (set products[].reviewScreenshot)`); problems++; continue; }
if (!file || !existsSync(file)) { warn('apple', `${sku}: no review screenshot (set products[].reviewScreenshot)`); rows.push({ item: sku, action: 'skip', detail: 'no review screenshot' }); problems++; continue; }
const buf = readFileSync(file);
const bad = reviewShotProblem(buf);
const cur = await shotOf(p.id);
const curState = stateOf(cur);
if (bad) {
warn('apple', `${sku}: ${relative(root, file)}: ${bad}${cur ? `; App Store Connect has ${curState}${errorsOf(cur) ? ` (${errorsOf(cur)})` : ''}` : ''}`);
problems++; continue;
rows.push({ item: sku, action: 'skip', detail: bad }); problems++; continue;
}
if (cur && cur.attributes.sourceFileChecksum === md5(buf) && curState !== 'FAILED') { log('apple', `${sku}: screenshot up to date (${curState})`); continue; }
if (cur && cur.attributes.sourceFileChecksum === md5(buf) && curState !== 'FAILED') { log('apple', `${sku}: screenshot up to date (${curState})`); rows.push({ item: sku, action: 'keep' }); continue; }
const why = !cur ? 'none in App Store Connect' : curState === 'FAILED' ? `the one there FAILED${errorsOf(cur) ? ` (${errorsOf(cur)})` : ''}` : 'a different file is there';
if (dry) { log('apple', `${sku}: would upload ${relative(root, file)} (${why})`); continue; }
if (dry) { log('apple', `${sku}: would upload ${relative(root, file)} (${why})`); rows.push({ item: sku, action: cur ? 'replace' : 'upload', detail: `${relative(root, file)} (${why})` }); continue; }
if (cur) await c.asc('DELETE', `/v1/inAppPurchaseAppStoreReviewScreenshots/${cur.id}`);
await c.uploadAsset('inAppPurchaseAppStoreReviewScreenshots', { inAppPurchaseV2: { data: { type: 'inAppPurchases', id: p.id } } }, file);
// Apple processes the asset after the commit: read the state back (COMPLETE, or FAILED with the reason)
@ -90,6 +94,7 @@ export async function run(ctx: Ctx): Promise<void> {
else if (stateOf(shot) !== 'COMPLETE') lack.push(`Apple to finish processing the screenshot (${stateOf(shot)}; check again in a minute)`);
log('apple', `${p.attributes.productId}: MISSING_METADATA${lack.length ? `: needs ${lack.join(', ')}` : ' (all parts present: Apple may still be updating the state)'}`);
}
if (dry) console.log(dryPlan('apple iap-review', rows));
if (problems) process.exitCode = 1;
done('apple', dry ? 'iap-review dry run (nothing uploaded)' : 'iap-review done (READY_TO_SUBMIT = complete; first IAPs go to review with a version, from the IAP page)');
}

View file

@ -4,11 +4,16 @@
// storebound apple iap [--dry] [--only id1,id2]
// Then `apple iap-review` for the review screenshots. First IAPs can only be submitted together with an app version,
// from the IAP page in the web UI (see the store-iap-setup skill).
// --dry reads everything (read-only) and prints one plan row per product. After a real run the store's product list
// is read again: a product created a moment ago can be missing from it for a minute, and `apple iap-review` would
// then skip it, so that gap is named (docs/pitfalls.md).
import { sellsOn } from '../lib/config';
import { APPLE_IAP_LIMITS } from '../lib/copy';
import type { Ctx } from '../lib/ctx';
import { need } from '../lib/ctx';
import { dryPlan, type PlanRow } from '../lib/dry';
import { done, log, step } from '../lib/log';
import { LAG_HINT, reportMissing } from '../lib/store-lag';
import { appleTerritory, nearestPrices, samePrice } from '../lib/money';
import { ascClient, type J } from './asc';
@ -35,17 +40,20 @@ export async function run(ctx: Ctx): Promise<void> {
throw new Error(`${territory} has no ${price} price point (nearest ${nearestPrices(seen, price).join(', ')})`);
}
const rows: PlanRow[] = [];
const created: string[] = [];
for (const [i, p] of products.entries()) {
const tag = step(i + 1, products.length, p.id);
const found = await c.asc('GET', `/v1/apps/${appId}/inAppPurchasesV2?filter[productId]=${encodeURIComponent(p.id)}`);
let id: string = found.data[0]?.id;
if (dry) { log('apple', `${tag}: ${id ? `exists (${found.data[0].attributes.state})` : 'missing'} (dry)`); continue; }
if (dry) { rows.push(await planProduct(p, id, found.data[0]?.attributes?.state)); continue; }
if (!id) {
const first = Object.values(p.listings)[0]!;
id = (await c.asc('POST', '/v2/inAppPurchases', { data: { type: 'inAppPurchases',
attributes: { name: p.referenceName ?? first.title, productId: p.id, inAppPurchaseType: APPLE_IAP_TYPE[p.type],
familySharable: p.familySharable ?? false, ...(p.reviewNote ? { reviewNote: p.reviewNote } : {}) },
relationships: { app: { data: { type: 'apps', id: appId } } } } })).data.id;
created.push(p.id);
log('apple', `${tag}: created`);
} else log('apple', `${tag}: exists`);
@ -82,5 +90,30 @@ export async function run(ctx: Ctx): Promise<void> {
log('apple', ` available in ${territories.length} territories + new ones`);
}
}
done('apple', dry ? 'iap checked (dry run)' : 'iap done (next: apple iap-review for the review screenshots)');
if (dry) {
console.log(dryPlan('apple iap', rows));
const absent = rows.filter(r => r.action === 'create').map(r => r.item);
if (absent.length) log('apple', `not on App Store Connect: ${absent.join(', ')}. If you created them in the last minutes, ${LAG_HINT} before acting on this plan`);
done('apple', 'iap checked (dry run)');
return;
}
if (created.length) {
await Bun.sleep(Number(process.env.STOREBOUND_LIST_SETTLE_MS ?? 3000));
const listed = (await c.all(`/v1/apps/${appId}/inAppPurchasesV2?limit=200`)).map((x: J) => x.attributes.productId as string);
if (reportMissing('apple', 'new products', created, listed, { fail: false }).length) log('apple', 'wait a minute before apple iap-review, or it cannot see them');
}
done('apple', 'iap done (next: apple iap-review for the review screenshots)');
/** What a real run would do to one product, from read-only calls. */
async function planProduct(p: (typeof products)[number], id: string | undefined, state: string | undefined): Promise<PlanRow> {
const locales = Object.keys(p.listings).map(l => langs.get(l)?.apple).filter((l): l is string => !!l);
const prices = [`USA ${p.usd}`, ...(p.overrides ?? []).map(o => `${appleTerritory(o)} ${o.price}`)].join(', ');
if (!id) return { item: p.id, action: 'create', detail: `${APPLE_IAP_TYPE[p.type]}; localizations ${locales.join(', ')}; prices ${prices}; ${territories.length} territories + new ones` };
const have = new Set((await c.all(`/v2/inAppPurchases/${id}/inAppPurchaseLocalizations`)).map((l: J) => l.attributes.locale));
const add = locales.filter(l => !have.has(l));
const sched = await c.maybe(`/v2/inAppPurchases/${id}/iapPriceSchedule?include=manualPrices`);
const avail = await c.maybe(`/v2/inAppPurchases/${id}/inAppPurchaseAvailability`);
const parts = [add.length ? `localizations ${add.join(', ')}` : '', sched?.included?.length ? '' : `prices ${prices}`, avail?.data ? '' : `availability ${territories.length} territories + new ones`].filter(Boolean);
return parts.length ? { item: p.id, action: 'update', detail: `${parts.join('; ')} (state ${state ?? '?'})` } : { item: p.id, action: 'keep' };
}
}

61
cli/lib/dry.ts Normal file
View file

@ -0,0 +1,61 @@
// Dry-run plans every write command shows the same way, so the owner sees WHAT would change, not only how many
// things ("listing: 20 locales" is not a plan). Pure. `tests/dry-plan.test.ts` scans cli/** for --dry branches that
// print nothing but a count (docs/pitfalls.md, "Dry runs that print no plan").
import { textTable } from './table';
export interface PlanRow {
/** What is changed: a product id, a locale, a file, a build. */
item: string;
/** create, update, upload, replace, delete, keep ... */
action: string;
/** The concrete change: fields, values, old -> new. */
detail?: string;
}
/**
* Standard dry-run plan: a title line and one aligned row per change. Rows whose action is "keep" are counted in the
* title but left out of the table, so a long "nothing to do" list does not hide the real changes.
*/
export function dryPlan(title: string, rows: PlanRow[]): string {
const change = rows.filter(r => r.action !== 'keep');
const kept = rows.length - change.length;
const head = `dry run: ${title}: ${change.length ? `${change.length} change(s)` : 'nothing to change'}${kept ? `, ${kept} unchanged` : ''}; nothing written`;
if (!change.length) return head;
return `${head}\n${textTable(['item', 'action', 'detail'], change.map(r => [r.item, r.action, r.detail ?? '']))}`;
}
/** A source line that leaves a --dry branch (`if (dry) return` / `if (a.has('dry')) { ...; return; }`) at the top level of a function. */
const DRY = String.raw`(?:dry|(?:ctx\.)?a(?:rgs)?\.has\('dry'\))`;
const EXIT = new RegExp(String.raw`^ (?:\} )?if \(${DRY}\) (?:\{ )?(?:.*\b)?return\b`);
/** Output that is a plan by itself: the shared table, the request lister, JSON, or printing the content that would be written. */
const RICH = /dryPlan\(|execute\(|printJson\(|describeReq\(|console\.log\((?!['`])|process\.stdout\.write\(/;
const OUT = /\b(?:log|done|say|warn|console\.log)\(\s*(?:[A-Za-z_'".]+,\s*)?(['`])(.*)\1/;
/** Interpolations that only count or name sections: `${x.length}`, `${n}`, `${Object.keys(listing).join(', ')}`, `${dry ? ...}`. */
const countOnly = (e: string): boolean => /(?:\.length|\.size|\bn|count|total)\s*$/.test(e.trim()) || /Object\.keys\(/.test(e) || /\bdry\s*\?|^\s*(?:TAG|tag)\s*$/.test(e);
/** True when the line prints something that names the concrete change (not only a count). */
export function isPlanLine(line: string): boolean {
if (RICH.test(line)) return true;
const m = OUT.exec(line);
if (!m) return false;
const parts = [...m[2]!.matchAll(/\$\{([^{}]*(?:\{[^{}]*\}[^{}]*)*)\}/g)].map(x => x[1]!);
if (parts.some(p => !countOnly(p))) return true;
// a literal that spells out the one request ("would POST /v1/analyticsReportRequests {accessType=ONGOING}")
return !parts.length && /\bwould\b/.test(m[2]!) && !/nothing|\d+ \w+\(s\)/.test(m[2]!);
}
/**
* --dry exits in one source file that print nothing but a count before them (scanning back to the start of the
* enclosing top-level function, at most 40 lines). Returns 1-based line numbers. Pure; heuristic by design.
*/
export function countOnlyDryExits(source: string): number[] {
const lines = source.split('\n');
const out: number[] = [];
lines.forEach((l, i) => {
if (!EXIT.test(l)) return;
let from = i;
while (from > 0 && i - from < 40 && !/^(?:export )?(?:async )?function |^\}/.test(lines[from - 1]!)) from--;
if (!lines.slice(from, i + 1).some(isPlanLine)) out.push(i + 1);
});
return out;
}

25
cli/lib/store-lag.ts Normal file
View file

@ -0,0 +1,25 @@
// Store lists lag right after a create: App Store Connect's /inAppPurchasesV2 (and Play's oneTimeProducts list) can
// leave out a product created a minute ago. A command that walks the store's list then silently skips it. These
// helpers compare the config's product ids with what the store returned, so the gap is said out loud
// (docs/pitfalls.md, "Store lists lag right after create").
import { warn } from './log';
export const LAG_HINT = "the store's list can lag a minute after creating; re-run";
/** Config ids the store's list does not contain, in config order. Pure. */
export function missingFromStore(want: string[], got: Iterable<string>): string[] {
const have = new Set(got);
return [...new Set(want)].filter(id => !have.has(id));
}
/**
* Warns with the missing ids and the lag hint. `fail` sets a non-zero exit code (the command could not do its job for
* them, e.g. a dry-run plan that would skip them). Returns the missing ids.
*/
export function reportMissing(tag: string, what: string, want: string[], got: Iterable<string>, o: { fail: boolean }): string[] {
const missing = missingFromStore(want, got);
if (!missing.length) return missing;
warn(tag, `${missing.length} of ${want.length} ${what} not in the store's list: ${missing.join(', ')} (${LAG_HINT})`);
if (o.fail) process.exitCode = 1;
return missing;
}

View file

@ -10,10 +10,14 @@
// confirm token. Without one (MCP, CI, serve) those changes are skipped with a warning; listing changes still go.
// Play has no non-renewing type: a `non_renewing` product is a plain one-time product here (your app consumes it
// when the access ends). Products with `platforms` that leave out android are skipped.
// --dry ends with the standard plan table (lib/dry.ts). After a real run the product list is read again: a product
// created a moment ago can be missing from it for a minute, and that gap is named (docs/pitfalls.md).
import { playCodes, sellsOn } from '../lib/config';
import type { Ctx } from '../lib/ctx';
import { confirm, need } from '../lib/ctx';
import { dryPlan } from '../lib/dry';
import { done, log, step, warn } from '../lib/log';
import { LAG_HINT, reportMissing } from '../lib/store-lag';
import { fromMoney, type Money, playRegionConfigs, type RegionConfig, toMoney } from '../lib/money';
import { playClient } from './client';
@ -116,7 +120,15 @@ export async function run(ctx: Ctx): Promise<void> {
log('play', `${tag}: ${what}${dry ? ' (dry)' : ''}`);
plan.push({ p, tag, body, version: conv.regionVersion?.version ?? '2022/02', cur, changes, regions: regions.length, listings: listings.length });
}
if (dry) { done('play', 'products checked (dry run, nothing written)'); return; }
if (dry) {
console.log(dryPlan('play products', plan.map(x => !x.changes.length ? { item: x.p.id, action: 'keep' }
: !x.cur ? { item: x.p.id, action: 'create', detail: `${x.regions} regions, ${x.listings} listings, USD ${x.p.usd}` }
: { item: x.p.id, action: x.changes.some(c => c.owner) ? 'update (owner confirms)' : 'update', detail: x.changes.map(c => c.text).join('; ') })));
const absent = plan.filter(x => !x.cur).map(x => x.p.id);
if (absent.length) log('play', `not on Google Play: ${absent.join(', ')}. If you created them in the last minutes, ${LAG_HINT} before acting on this plan`);
done('play', 'products checked (dry run, nothing written)');
return;
}
// prices, regions and activation of existing products: the owner confirms the diff above first
const gated = plan.filter(x => x.cur && x.changes.some(c => c.owner));
@ -146,5 +158,7 @@ export async function run(ctx: Ctx): Promise<void> {
log('play', `${x.tag}: purchase option activated`);
} catch (e) { warn('play', `${x.tag}: activate failed: ${(e as Error).message}`); }
}
const created = plan.filter(x => !x.cur && x.changes.length).map(x => x.p.id);
if (created.length) reportMissing('play', 'new products', created, (await listOneTimeProducts(play)).map(p => p.productId), { fail: false });
done('play', 'products done');
}