Merge origin/main into shots-speed

# Conflicts:
#	CHANGELOG.md
This commit is contained in:
CRTkafa 2026-10-11 19:49:58 +00:00
commit 91b0284df5
46 changed files with 1313 additions and 185 deletions

View file

@ -26,8 +26,9 @@ export const WRAPPED: { apple: Record<string, string>; play: Record<string, stri
'appEventScreenshots_updateInstance': 'apple/events',
'appEvents_createInstance': 'apple/events',
'appEvents_localizations_getToManyRelated': 'apple/events',
'appInfos_ageRatingDeclaration_getToOneRelated': 'validate',
'appInfos_ageRatingDeclaration_getToOneRelated': 'apple/appinfo validate',
'appInfos_appInfoLocalizations_getToManyRelated': 'apple/listing validate',
'appInfos_getInstance': 'apple/appinfo',
'appInfos_updateInstance': 'apple/appinfo',
'appPreviewSets_appPreviews_getToManyRelated': 'apple/previews',
'appPreviewSets_createInstance': 'apple/previews',
@ -57,7 +58,7 @@ export const WRAPPED: { apple: Record<string, string>; play: Record<string, stri
'appStoreVersions_appStoreReviewDetail_getToOneRelated': 'apple/review-details validate',
'appStoreVersions_appStoreVersionLocalizations_getToManyRelated': 'apple/listing apple/previews apple/screenshots validate',
'appStoreVersions_appStoreVersionPhasedRelease_getToOneRelated': 'apple/release apple/status',
'appStoreVersions_build_getToOneRelated': 'validate',
'appStoreVersions_build_getToOneRelated': 'apple/listing validate',
'appStoreVersions_build_updateToOneRelationship': 'apple/listing',
'appStoreVersions_createInstance': 'apple/listing',
'appStoreVersions_updateInstance': 'apple/listing',
@ -76,7 +77,7 @@ export const WRAPPED: { apple: Record<string, string>; play: Record<string, stri
'apps_betaGroups_getToManyRelated': 'apple/testflight',
'apps_customerReviews_getToManyRelated': 'reviews',
'apps_getCollection': 'apple/asc apple/bundle apps lib/store-apps',
'apps_getInstance': 'apple/status',
'apps_getInstance': 'apple/appinfo apple/status',
'apps_inAppPurchasesV2_getToManyRelated': 'apple/iap apple/iap-review apple/iap-submit apple/offer-codes apple/promoted apple/status catalog prices validate',
'apps_perfPowerMetrics_getToManyRelated': 'health',
'apps_promotedPurchases_getToManyRelated': 'apple/promoted',
@ -140,9 +141,9 @@ export const WRAPPED: { apple: Record<string, string>; play: Record<string, stri
'inAppPurchaseVersions_createInstance': 'lib/review-submit',
'inAppPurchasesV2_appStoreReviewScreenshot_getToOneRelated': 'apple/iap-review validate',
'inAppPurchasesV2_createInstance': 'apple/iap',
'inAppPurchasesV2_iapPriceSchedule_getToOneRelated': 'apple/iap catalog',
'inAppPurchasesV2_inAppPurchaseAvailability_getToOneRelated': 'apple/iap',
'inAppPurchasesV2_inAppPurchaseLocalizations_getToManyRelated': 'apple/iap catalog',
'inAppPurchasesV2_iapPriceSchedule_getToOneRelated': 'apple/iap apple/iap-review catalog',
'inAppPurchasesV2_inAppPurchaseAvailability_getToOneRelated': 'apple/iap apple/iap-review',
'inAppPurchasesV2_inAppPurchaseLocalizations_getToManyRelated': 'apple/iap apple/iap-review catalog',
'inAppPurchasesV2_offerCodes_getToManyRelated': 'apple/offer-codes',
'inAppPurchasesV2_pricePoints_getToManyRelated': 'apple/iap apple/offer-codes prices prices-ppp',
'inAppPurchasesV2_versions_getToManyRelated': 'apple/iap-submit',

View file

@ -1,13 +1,16 @@
// App-level App Store settings (idempotent), from apple.info in storebound.config.ts:
// storebound apple appinfo [--dry]
// storebound apple appinfo [--dry] [--json]
// Every run first reads the current values and prints the plan (old -> new per field); --dry stops there, the real run
// asks in a terminal and changes only what differs.
// - categories (primary + up to two subcategories for games, secondary)
// - age rating declaration: every content question NONE / false unless overridden in apple.info.ageRating
// - content rights declaration
// - price Free (USA base) and availability in every territory + new ones (when apple.info.free !== false)
// App Privacy ("nutrition label") has no API: web UI only (store-declarations skill).
import type { Ctx } from '../lib/ctx';
import { need } from '../lib/ctx';
import { done, log } from '../lib/log';
import { confirm, need } from '../lib/ctx';
import { type ItemPlan, itemLines, planItem } from '../lib/listing-plan';
import { done, log, printJson, warn } from '../lib/log';
import { ascClient } from './asc';
/** Every question of the current age rating declaration at its "nothing" answer. */
@ -20,52 +23,97 @@ export const AGE_RATING_NONE: Record<string, string | boolean | null> = {
violenceRealisticProlongedGraphicOrSadistic: 'NONE', kidsAgeBand: null,
};
const CATEGORY_RELS = ['primaryCategory', 'primarySubcategoryOne', 'primarySubcategoryTwo', 'secondaryCategory'] as const;
const str = (v: unknown): string => (v === null || v === undefined ? '' : String(v));
/** The plan of one `apple appinfo` run, from read-only GETs. */
export interface AppInfoPlan { appInfoId: string; items: ItemPlan[]; freePricePointId: string | null; territories: string[]; changes: number }
/** The plan as text lines. Pure. */
export function appInfoPlanLines(p: AppInfoPlan): string[] {
return p.items.flatMap(i => itemLines(i.key, i, ''));
}
async function planAppInfo(ctx: Ctx, c: Awaited<ReturnType<typeof ascClient>>, appId: string): Promise<AppInfoPlan> {
const info = ctx.loaded.config.apple?.info ?? {};
const appInfo = await c.editableAppInfo();
const items: ItemPlan[] = [];
if (info.categories) {
const k = info.categories;
const cur = await c.maybe(`/v1/appInfos/${appInfo.id}?include=${CATEGORY_RELS.join(',')}`);
const rel = cur?.data?.relationships ?? appInfo.relationships ?? {};
const want = { primaryCategory: k.primary, primarySubcategoryOne: k.primarySubOne ?? '', primarySubcategoryTwo: k.primarySubTwo ?? '', secondaryCategory: k.secondary ?? '' };
items.push(planItem('categories', { attributes: Object.fromEntries(CATEGORY_RELS.map(r => [r, str(rel[r]?.data?.id)])) }, want));
}
const attributes = { ...AGE_RATING_NONE, ...(info.ageRating ?? {}) };
const age = await c.maybe(`/v1/appInfos/${appInfo.id}/ageRatingDeclaration`);
items.push(planItem('age rating declaration', age?.data ? { attributes: Object.fromEntries(Object.keys(attributes).map(q => [q, str(age.data.attributes?.[q])])) } : null,
Object.fromEntries(Object.entries(attributes).map(([q, v]) => [q, str(v)]))));
if (info.contentRights) {
const app = await c.maybe(`/v1/apps/${appId}`);
items.push(planItem('content rights', { attributes: { contentRightsDeclaration: str(app?.data?.attributes?.contentRightsDeclaration) } }, { contentRightsDeclaration: info.contentRights }));
}
let freePricePointId: string | null = null, territories: string[] = [];
if (info.free !== false) {
const sched = await c.maybe(`/v1/apps/${appId}/appPriceSchedule?include=manualPrices`);
if (!sched?.included?.some((x: { type: string }) => x.type === 'appPrices')) {
const free = (await c.all(`/v1/apps/${appId}/appPricePoints?filter[territory]=USA&limit=200`)).find(p => Number(p.attributes.customerPrice) === 0);
if (!free) throw new Error('no free price point for USA');
freePricePointId = free.id;
items.push(planItem('price', null, { price: 'Free', baseTerritory: 'USA' }));
} else items.push(planItem('price', { attributes: { schedule: 'exists' } }, { schedule: 'exists' }));
const avail = await c.maybe(`/v1/apps/${appId}/appAvailabilityV2`);
if (!avail?.data) {
territories = (await c.all('/v1/territories?limit=200')).map(t => t.id);
items.push(planItem('availability', null, { territories: `${territories.length} (all)`, availableInNewTerritories: 'true' }));
} else items.push(planItem('availability', { attributes: { availability: 'exists' } }, { availability: 'exists' }));
}
return { appInfoId: appInfo.id, items, freePricePointId, territories, changes: items.filter(i => i.action !== 'same').length };
}
export async function run(ctx: Ctx): Promise<void> {
const { config, root } = ctx.loaded;
const info = config.apple?.info ?? {};
const dry = ctx.args.has('dry');
const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId);
const appId = await c.app();
const appInfo = await c.editableAppInfo();
const say = (m: string) => log('apple', dry ? `${m} (dry)` : m);
const p = await planAppInfo(ctx, c, appId);
if (ctx.args.has('json')) printJson({ dry, ...p });
else for (const line of appInfoPlanLines(p)) console.log(line);
if (dry) { done('apple', `dry run: ${p.changes ? `${p.changes} change(s)` : 'nothing to change'}; read-only, nothing written`); return; }
if (!p.changes) { done('apple', 'appinfo already up to date (App Privacy is UI-only: store-declarations skill)'); return; }
if (process.stdin.isTTY && !(await confirm(ctx, `Apply these ${p.changes} change(s) to App Store Connect?`))) { warn('apple', 'nothing written'); return; }
const changed = (key: string) => p.items.some(i => i.key === key && i.action !== 'same');
if (info.categories) {
if (info.categories && changed('categories')) {
const k = info.categories;
const rel = (id?: string) => ({ data: id ? { type: 'appCategories', id } : null });
if (!dry) await c.asc('PATCH', `/v1/appInfos/${appInfo.id}`, { data: { type: 'appInfos', id: appInfo.id, relationships: {
await c.asc('PATCH', `/v1/appInfos/${p.appInfoId}`, { data: { type: 'appInfos', id: p.appInfoId, relationships: {
primaryCategory: rel(k.primary), primarySubcategoryOne: rel(k.primarySubOne), primarySubcategoryTwo: rel(k.primarySubTwo), secondaryCategory: rel(k.secondary) } } });
say(`categories: ${[k.primary, k.primarySubOne, k.primarySubTwo].filter(Boolean).join(' / ')}${k.secondary ? `, secondary ${k.secondary}` : ''}`);
log('apple', `categories: ${[k.primary, k.primarySubOne, k.primarySubTwo].filter(Boolean).join(' / ')}${k.secondary ? `, secondary ${k.secondary}` : ''}`);
}
const attributes = { ...AGE_RATING_NONE, ...(info.ageRating ?? {}) };
if (!dry) await c.asc('PATCH', `/v1/ageRatingDeclarations/${appInfo.id}`, { data: { type: 'ageRatingDeclarations', id: appInfo.id, attributes } });
say(`age rating declaration: ${Object.entries(info.ageRating ?? {}).map(([q, v]) => `${q}=${v}`).join(', ') || 'all NONE'}`);
if (info.contentRights) {
if (!dry) await c.asc('PATCH', `/v1/apps/${appId}`, { data: { type: 'apps', id: appId, attributes: { contentRightsDeclaration: info.contentRights } } });
say(`content rights: ${info.contentRights}`);
if (changed('age rating declaration')) {
const attributes = { ...AGE_RATING_NONE, ...(info.ageRating ?? {}) };
await c.asc('PATCH', `/v1/ageRatingDeclarations/${p.appInfoId}`, { data: { type: 'ageRatingDeclarations', id: p.appInfoId, attributes } });
log('apple', `age rating declaration: ${Object.entries(info.ageRating ?? {}).map(([q, v]) => `${q}=${v}`).join(', ') || 'all NONE'}`);
}
if (info.free !== false) {
const sched = await c.maybe(`/v1/apps/${appId}/appPriceSchedule?include=manualPrices`);
if (!sched?.included?.some((x: { type: string }) => x.type === 'appPrices')) {
const free = (await c.all(`/v1/apps/${appId}/appPricePoints?filter[territory]=USA&limit=200`)).find(p => Number(p.attributes.customerPrice) === 0);
if (!free) throw new Error('no free price point for USA');
if (!dry) await c.asc('POST', '/v1/appPriceSchedules', { data: { type: 'appPriceSchedules', relationships: {
app: { data: { type: 'apps', id: appId } }, baseTerritory: { data: { type: 'territories', id: 'USA' } },
manualPrices: { data: [{ type: 'appPrices', id: '${free}' }] } } },
included: [{ type: 'appPrices', id: '${free}', attributes: { startDate: null }, relationships: { appPricePoint: { data: { type: 'appPricePoints', id: free.id } } } }] });
say('price: Free (USA base)');
} else log('apple', 'price schedule exists');
const avail = await c.maybe(`/v1/apps/${appId}/appAvailabilityV2`);
if (!avail?.data) {
const ts: string[] = (await c.all('/v1/territories?limit=200')).map(t => t.id);
if (!dry) await c.asc('POST', '/v2/appAvailabilities', { data: { type: 'appAvailabilities', attributes: { availableInNewTerritories: true },
relationships: { app: { data: { type: 'apps', id: appId } }, territoryAvailabilities: { data: ts.map(t => ({ type: 'territoryAvailabilities', id: '${' + t + '}' })) } } },
included: ts.map(t => ({ type: 'territoryAvailabilities', id: '${' + t + '}', attributes: { available: true }, relationships: { territory: { data: { type: 'territories', id: t } } } })) });
say(`availability: ${ts.length} territories + new ones`);
} else log('apple', 'availability exists');
if (info.contentRights && changed('content rights')) {
await c.asc('PATCH', `/v1/apps/${appId}`, { data: { type: 'apps', id: appId, attributes: { contentRightsDeclaration: info.contentRights } } });
log('apple', `content rights: ${info.contentRights}`);
}
if (p.freePricePointId) {
await c.asc('POST', '/v1/appPriceSchedules', { data: { type: 'appPriceSchedules', relationships: {
app: { data: { type: 'apps', id: appId } }, baseTerritory: { data: { type: 'territories', id: 'USA' } },
manualPrices: { data: [{ type: 'appPrices', id: '${free}' }] } } },
included: [{ type: 'appPrices', id: '${free}', attributes: { startDate: null }, relationships: { appPricePoint: { data: { type: 'appPricePoints', id: p.freePricePointId } } } }] });
log('apple', 'price: Free (USA base)');
}
if (p.territories.length) {
const ts = p.territories;
await c.asc('POST', '/v2/appAvailabilities', { data: { type: 'appAvailabilities', attributes: { availableInNewTerritories: true },
relationships: { app: { data: { type: 'apps', id: appId } }, territoryAvailabilities: { data: ts.map(t => ({ type: 'territoryAvailabilities', id: '${' + t + '}' })) } } },
included: ts.map(t => ({ type: 'territoryAvailabilities', id: '${' + t + '}', attributes: { available: true }, relationships: { territory: { data: { type: 'territories', id: t } } } })) });
log('apple', `availability: ${ts.length} territories + new ones`);
}
done('apple', 'appinfo done (App Privacy is UI-only: store-declarations skill)');
}

View file

@ -1,35 +1,100 @@
// Upload the App Review screenshot of every in-app purchase (idempotent: a screenshot whose MD5 matches is kept) and
// print each product's state. Nothing is submitted.
// Upload the App Review screenshot of every in-app purchase (idempotent: a screenshot whose MD5 matches and that
// Apple processed is kept) and print each product's state with what is still missing. Nothing is submitted.
// storebound apple iap-review [--dry]
// Screenshot per product: products[].reviewScreenshot, else apple.reviewShots/<product id>.(png|jpg).
// Size: a real device screenshot size (e.g. 1290 x 2796); other sizes fail with IMAGE_INCORRECT_DIMENSIONS.
// 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 } from 'node:path';
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';
/** Every iPhone / iPad screenshot size App Store Connect accepts (portrait and landscape). */
export const REVIEW_SHOT_SIZES: [number, number][] = Object.values(IMAGE_SPECS)
.filter(s => s.store === 'apple' && /^APP_(IPHONE|IPAD)/.test(s.type))
.flatMap(s => s.sizes.flatMap(([w, h]) => [[w, h], [h, w]] as [number, number][]));
/** null when the image can be used as an App Review screenshot, else why not. Pure. */
export function reviewShotProblem(buf: Uint8Array): string | null {
const i = imageInfo(buf);
if (i.format === 'unknown') return 'not a PNG or JPEG';
if (!REVIEW_SHOT_SIZES.some(([w, h]) => w === i.w && h === i.h))
return `${i.w} x ${i.h} is not an App Store screenshot size (use e.g. 1320 x 2868 or 1290 x 2796 for iPhone, 2064 x 2752 for iPad; Apple fails other sizes with IMAGE_INCORRECT_DIMENSIONS)`;
return null;
}
type Shot = { id: string; attributes: { sourceFileChecksum?: string; fileName?: string; assetDeliveryState?: { state?: string; errors?: { code?: string; description?: string }[] } } };
const stateOf = (s: Shot | undefined): string => s?.attributes.assetDeliveryState?.state ?? 'NONE';
const errorsOf = (s: Shot | undefined): string => (s?.attributes.assetDeliveryState?.errors ?? []).map(e => e.code ?? e.description).filter(Boolean).join(', ');
export async function run(ctx: Ctx): Promise<void> {
const { config, root, resolve } = ctx.loaded;
const dry = ctx.args.has('dry');
const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId);
const appId = await c.app();
const defs = new Map((config.products ?? []).map(p => [p.id, p]));
for (const p of await c.all(`/v1/apps/${appId}/inAppPurchasesV2?limit=200`)) {
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 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)`); 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 cur = (await c.maybe(`/v2/inAppPurchases/${p.id}/appStoreReviewScreenshot`))?.data;
if (cur && cur.attributes.sourceFileChecksum === md5(buf) && cur.attributes.assetDeliveryState?.state !== 'FAILED') { log('apple', `${sku}: screenshot up to date`); continue; }
if (ctx.args.has('dry')) { log('apple', `${sku}: would upload ${file}`); continue; }
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)})` : ''}` : ''}`);
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})`); 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})`); 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);
log('apple', `${sku}: screenshot uploaded`);
// Apple processes the asset after the commit: read the state back (COMPLETE, or FAILED with the reason)
let after: Shot | undefined, state = 'UPLOAD_COMPLETE';
for (let i = 0; i < 10; i++) {
await Bun.sleep(i ? 3000 : 1500);
after = await shotOf(p.id); state = stateOf(after);
if (state === 'COMPLETE' || state === 'FAILED') break;
}
if (state === 'FAILED') { warn('apple', `${sku}: Apple rejected the screenshot: ${errorsOf(after) || 'FAILED'}`); problems++; }
else log('apple', `${sku}: screenshot uploaded (${state})`);
}
await Bun.sleep(3000);
for (const p of await c.all(`/v1/apps/${appId}/inAppPurchasesV2?limit=200`)) log('apple', `${p.attributes.productId}: ${p.attributes.state}`);
done('apple', 'iap-review done (READY_TO_SUBMIT = complete; first IAPs go to review with a version, from the IAP page)');
// what keeps a product in MISSING_METADATA (Apple's rule: a localization, a price, availability and the screenshot)
for (const p of await c.all(`/v1/apps/${appId}/inAppPurchasesV2?limit=200`)) {
const state: string = p.attributes.state;
if (state !== 'MISSING_METADATA') { log('apple', `${p.attributes.productId}: ${state}`); continue; }
const lack: string[] = [];
const locs = await c.maybe(`/v2/inAppPurchases/${p.id}/inAppPurchaseLocalizations?limit=50`);
if (!locs?.data?.length) lack.push('a localization (name + description)');
const price = await c.maybe(`/v2/inAppPurchases/${p.id}/iapPriceSchedule`);
if (!price?.data) lack.push('a price');
const avail = await c.maybe(`/v2/inAppPurchases/${p.id}/inAppPurchaseAvailability`);
if (!avail?.data) lack.push('availability (territories)');
const shot = await shotOf(p.id);
if (!shot) lack.push('the review screenshot');
else if (stateOf(shot) === 'FAILED') lack.push(`a working review screenshot (FAILED: ${errorsOf(shot) || 'unknown'})`);
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' };
}
}

View file

@ -1,5 +1,9 @@
// App Store version + listing text (idempotent; re-run after editing the App Store listing file).
// storebound apple listing --version 1.0.0 [--build 3] [--dry]
// storebound apple listing --version 1.0.0 [--build 3] [--include-drafts] [--dry] [--json]
// Every run first reads App Store Connect and prints the plan: the version (keep, update the editable one, create, or
// refuse with the reason), the build, and per locale create / update with old -> new per field. --dry stops there
// (read-only); the real run asks in a terminal and applies exactly that plan. Locales marked status=draft or
// status=translate (listing translate) are skipped unless --include-drafts.
// - the editable iOS version: versionString, copyright, release type MANUAL; with --build that processed build is attached
// - appInfoLocalizations: name, subtitle, privacy policy URL per locale
// - appStoreVersionLocalizations: description, keywords, promotional text, what's new (not on a first version),
@ -12,8 +16,10 @@ 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 { counts, draftReason, draftSections, type ItemPlan, itemLines, planLocales, planVersion, short, type Skipped, type VersionPlan } from '../lib/listing-plan';
import { appleName } from '../lib/config';
import type { Ctx } from '../lib/ctx';
import { need } from '../lib/ctx';
import { confirm, need } from '../lib/ctx';
import { done, log, printJson, warn } from '../lib/log';
import { ascClient, type J } from './asc';
@ -24,22 +30,6 @@ export function readAppleCopy(ctx: Ctx) {
return Object.fromEntries(Object.entries(all).filter(([l]) => !only.length || only.includes(l)));
}
async function upsertLocs(c: Awaited<ReturnType<typeof ascClient>>, list: string, type: string, parentRel: string, parentType: string, parentId: string,
want: Record<string, Record<string, string | undefined>>): Promise<void> {
const have = new Map((await c.all(`${list}?limit=200`)).map((l: J) => [l.attributes.locale, l] as const));
for (const [locale, raw] of Object.entries(want)) {
const attributes = Object.fromEntries(Object.entries(raw).filter(([, v]) => v !== undefined));
const cur = have.get(locale);
if (!cur) {
await c.asc('POST', `/v1/${type}`, { data: { type, attributes: { locale, ...attributes }, relationships: { [parentRel]: { data: { type: parentType, id: parentId } } } } });
log('apple', `${type} ${locale}: created`);
} else if (Object.entries(attributes).some(([k, v]) => cur.attributes[k] !== v)) {
await c.asc('PATCH', `/v1/${type}/${cur.id}`, { data: { type, id: cur.id, attributes } });
log('apple', `${type} ${locale}: updated`);
} else log('apple', `${type} ${locale}: up to date`);
}
}
/** 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;
@ -65,7 +55,7 @@ async function pull(ctx: Ctx): Promise<void> {
}
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 r = mergeAppleListing(before, remote, appleName(config));
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 });
@ -81,45 +71,137 @@ async function pull(ctx: Ctx): Promise<void> {
done('apple', `${file}: ${r.changes.length} change(s) written${r.added.length ? `, new locales ${r.added.join(', ')}` : ''}`);
}
/** The plan of one `apple listing --version` run, from read-only GETs. */
export interface AppleListingPlan {
version: string;
versionPlan: VersionPlan;
build: { number: string; id: string | null; current: string | null; action: 'attach' | 'same' | 'refuse'; reason: string } | null;
appInfo: { id: string; state: string; locales: ItemPlan[] };
/** null: the version is created first; App Store Connect copies the previous version's texts, then these are applied. */
versionLocales: ItemPlan[] | null;
wanted: Record<string, Record<string, string | undefined>>;
skipped: Skipped[];
notes: string[];
changes: number;
}
type Asc = Awaited<ReturnType<typeof ascClient>>;
async function planListing(ctx: Ctx, c: Asc, appId: string, version: string): Promise<AppleListingPlan> {
const { config, resolve } = ctx.loaded;
const app = config.app;
const listing = readAppleCopy(ctx);
const md = readFileSync(resolve(config.apple?.listing ?? 'store/appstore.md'), 'utf8');
const drafts = draftSections(md, 'apple');
const include = ctx.args.has('include-drafts');
const skipped: Skipped[] = [];
const notes: string[] = [];
for (const l of Object.keys(listing)) {
const st = drafts.get(l);
if (!st) continue;
if (include) notes.push(`${l}: ${st === 'draft' ? 'machine-translated draft' : 'untranslated (status=translate)'} included (--include-drafts)`);
else { skipped.push({ key: l, reason: draftReason(st) }); delete listing[l]; }
}
const copyright = app.copyright ?? `${new Date().getFullYear()} ${app.name}`;
const rows = await c.all(`/v1/apps/${appId}/appStoreVersions?filter[platform]=IOS&limit=50`);
const versionPlan = planVersion(rows, version, { copyright, releaseType: 'MANUAL' });
let build: AppleListingPlan['build'] = null;
const number = ctx.args.get('build');
if (number) {
const b = (await c.all(`/v1/builds?filter[app]=${appId}&filter[version]=${number}&filter[preReleaseVersion.version]=${version}&filter[preReleaseVersion.platform]=IOS`))[0];
const cur = versionPlan.id ? (await c.maybe(`/v1/appStoreVersions/${versionPlan.id}/build`))?.data : null;
const current = cur ? String(cur.attributes?.version ?? cur.id) : null;
build = !b ? { number, id: null, current, action: 'refuse', reason: `build ${version} (${number}) not found (still uploading? check TestFlight)` }
: b.attributes.processingState !== 'VALID' ? { number, id: b.id, current, action: 'refuse', reason: `build ${number} is ${b.attributes.processingState}; wait until VALID` }
: cur?.id === b.id ? { number, id: b.id, current, action: 'same', reason: `build ${number} is already attached` }
: { number, id: b.id, current, action: 'attach', reason: `attach build ${version} (${number})${current ? ` instead of ${current}` : ''}` };
}
const info = await c.editableAppInfo();
const infoWant = Object.fromEntries(Object.entries(listing).map(([l, f]) => [l, { name: f.name ?? appleName(config), subtitle: f.subtitle, privacyPolicyUrl: app.privacyPolicyUrl }]));
const infoLocs = planLocales(await c.all(`/v1/appInfos/${info.id}/appInfoLocalizations?limit=200`), infoWant);
if (versionPlan.first && Object.values(listing).some(f => f.whatsNew)) notes.push('what\'s new is left out: App Store Connect has no what\'s new on the first version');
const wanted = Object.fromEntries(Object.entries(listing).map(([l, f]) => [l, { description: f.description, keywords: f.keywords, promotionalText: f.promotionalText,
whatsNew: versionPlan.first ? undefined : f.whatsNew, supportUrl: app.supportUrl, marketingUrl: app.marketingUrl ?? app.website }]));
const versionLocales = versionPlan.id ? planLocales(await c.all(`/v1/appStoreVersions/${versionPlan.id}/appStoreVersionLocalizations?limit=200`), wanted) : null;
if (!versionLocales && versionPlan.action === 'create') notes.push('the new version gets the previous version\'s texts from App Store Connect; the version texts below are applied after it is created');
const changes = (versionPlan.action === 'create' || versionPlan.action === 'update' ? 1 : 0) + (build?.action === 'attach' ? 1 : 0)
+ infoLocs.filter(x => x.action !== 'same').length + (versionLocales ? versionLocales.filter(x => x.action !== 'same').length : Object.keys(wanted).length);
return { version, versionPlan, build, appInfo: { id: info.id, state: String(info.attributes?.state ?? info.attributes?.appStoreState ?? ''), locales: infoLocs },
versionLocales, wanted, skipped, notes, changes };
}
/** The plan as text lines. Pure. */
export function listingPlanLines(p: AppleListingPlan): string[] {
const v = p.versionPlan;
const out = [`Version (App Store Connect has: ${v.existing.length ? v.existing.map(x => `${x.versionString} ${x.state} ${x.platform}`).join(', ') : 'no iOS version yet'})`];
out.push(` ${v.action === 'refuse' ? 'REFUSE' : v.action.toUpperCase()}: ${v.reason}`);
for (const ch of v.changes) out.push(` ${ch.field}: ${v.action === 'create' ? short(ch.to) : `${short(ch.from)} -> ${short(ch.to)}`}`);
if (p.build) out.push(`Build: ${p.build.action === 'refuse' ? 'REFUSE: ' : ''}${p.build.reason}`);
out.push(`App info ${p.appInfo.state ? `(${p.appInfo.state})` : ''}: name, subtitle, privacy policy URL per locale · ${counts(p.appInfo.locales)}`);
for (const l of p.appInfo.locales) out.push(...itemLines(l.key, l));
if (p.versionLocales) {
out.push(`Version texts: description, keywords, promotional text, what's new, support / marketing URL · ${counts(p.versionLocales)}`);
for (const l of p.versionLocales) out.push(...itemLines(l.key, l));
} else if (v.action === 'refuse') {
out.push('Version texts: not planned (the version is refused)');
} else {
out.push(`Version texts (applied after the version is created): ${Object.keys(p.wanted).join(', ')}`);
}
for (const s of p.skipped) out.push(`Skipped ${s.key}: ${s.reason}`);
for (const n of p.notes) out.push(`Note: ${n}`);
return out;
}
async function applyLocales(c: Asc, type: string, parentRel: string, parentType: string, parentId: string, plan: ItemPlan[]): Promise<void> {
for (const l of plan) {
if (l.action === 'create') {
await c.asc('POST', `/v1/${type}`, { data: { type, attributes: { locale: l.key, ...l.attributes }, relationships: { [parentRel]: { data: { type: parentType, id: parentId } } } } });
log('apple', `${type} ${l.key}: created`);
} else if (l.action === 'update') {
await c.asc('PATCH', `/v1/${type}/${l.id}`, { data: { type, id: l.id, attributes: Object.fromEntries(l.changes.map(ch => [ch.field, ch.to ?? ''])) } });
log('apple', `${type} ${l.key}: updated ${l.changes.map(ch => ch.field).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);
log('apple', `listing: ${Object.keys(listing).length} locales (${Object.keys(listing).join(', ')})`);
if (a.has('dry')) return;
const app = config.app;
const copyright = app.copyright ?? `${new Date().getFullYear()} ${app.name}`;
if (!version) throw new Error('usage: apple listing --version 1.0.0 [--build N] [--include-drafts] [--dry] [--json]');
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 p = await planListing(ctx, c, appId, version);
const refused = [p.versionPlan.action === 'refuse' ? p.versionPlan.reason : '', p.build?.action === 'refuse' ? p.build.reason : ''].filter(Boolean);
if (a.has('json')) printJson({ dry, ...p, refused });
else for (const line of listingPlanLines(p)) console.log(line);
if (refused.length) { if (dry) { process.exitCode = 1; warn('apple', `dry run: would refuse: ${refused.join('; ')}`); return; } throw new Error(refused.join('; ')); }
if (dry) { done('apple', `dry run: ${p.changes ? `${p.changes} change(s)` : 'nothing to change'}; read-only, nothing written`); return; }
if (!p.changes) { done('apple', 'listing already up to date'); return; }
if (process.stdin.isTTY && !(await confirm(ctx, `Apply these ${p.changes} change(s) to App Store Connect?`))) { warn('apple', 'nothing written'); return; }
let v = await c.editableVersion();
if (!v) {
v = (await c.asc('POST', '/v1/appStoreVersions', { data: { type: 'appStoreVersions',
attributes: { platform: 'IOS', versionString: version, copyright, releaseType: 'MANUAL' },
relationships: { app: { data: { type: 'apps', id: appId } } } } })).data;
const vp = p.versionPlan;
let versionId = vp.id;
if (vp.action === 'create') {
versionId = (await c.asc('POST', '/v1/appStoreVersions', { data: { type: 'appStoreVersions',
attributes: Object.fromEntries(Object.entries(vp.attributes)), relationships: { app: { data: { type: 'apps', id: appId } } } } })).data.id;
log('apple', `version ${version} created`);
} else if (v.attributes.versionString !== version || v.attributes.copyright !== copyright || v.attributes.releaseType !== 'MANUAL') {
await c.asc('PATCH', `/v1/appStoreVersions/${v.id}`, { data: { type: 'appStoreVersions', id: v.id, attributes: { versionString: version, copyright, releaseType: 'MANUAL' } } });
log('apple', `version ${v.attributes.versionString} -> ${version}, copyright, release MANUAL`);
} else if (vp.action === 'update') {
await c.asc('PATCH', `/v1/appStoreVersions/${versionId}`, { data: { type: 'appStoreVersions', id: versionId, attributes: Object.fromEntries(vp.changes.map(ch => [ch.field, ch.to])) } });
log('apple', `version: ${vp.changes.map(ch => `${ch.field} ${ch.from ?? '(none)'} -> ${ch.to}`).join(', ')}`);
}
const build = a.get('build');
if (build) {
const b = (await c.all(`/v1/builds?filter[app]=${appId}&filter[version]=${build}&filter[preReleaseVersion.version]=${version}&filter[preReleaseVersion.platform]=IOS`))[0];
if (!b) throw new Error(`build ${version} (${build}) not found (still uploading? check TestFlight)`);
if (b.attributes.processingState !== 'VALID') throw new Error(`build ${build} is ${b.attributes.processingState}; wait until VALID`);
await c.asc('PATCH', `/v1/appStoreVersions/${v.id}/relationships/build`, { data: { type: 'builds', id: b.id } });
log('apple', `build ${version} (${build}) attached`);
if (p.build?.action === 'attach') {
await c.asc('PATCH', `/v1/appStoreVersions/${versionId}/relationships/build`, { data: { type: 'builds', id: p.build.id } });
log('apple', `build ${version} (${p.build.number}) attached`);
}
const info = await c.editableAppInfo();
await upsertLocs(c, `/v1/appInfos/${info.id}/appInfoLocalizations`, 'appInfoLocalizations', 'appInfo', 'appInfos', info.id,
Object.fromEntries(Object.entries(listing).map(([l, f]) => [l, { name: f.name ?? app.name, subtitle: f.subtitle, privacyPolicyUrl: app.privacyPolicyUrl }])));
await upsertLocs(c, `/v1/appStoreVersions/${v.id}/appStoreVersionLocalizations`, 'appStoreVersionLocalizations', 'appStoreVersion', 'appStoreVersions', v.id,
Object.fromEntries(Object.entries(listing).map(([l, f]) => [l, { description: f.description, keywords: f.keywords, promotionalText: f.promotionalText,
whatsNew: f.whatsNew, supportUrl: app.supportUrl, marketingUrl: app.marketingUrl ?? app.website }])));
await applyLocales(c, 'appInfoLocalizations', 'appInfo', 'appInfos', p.appInfo.id, p.appInfo.locales);
const vl = p.versionLocales ?? planLocales(await c.all(`/v1/appStoreVersions/${versionId}/appStoreVersionLocalizations?limit=200`), p.wanted);
await applyLocales(c, 'appStoreVersionLocalizations', 'appStoreVersion', 'appStoreVersions', versionId!, vl);
done('apple', 'listing done');
}

View file

@ -3,17 +3,18 @@
// subscriptions + terms URL) and the files the config points at. No network; credentials are only checked for presence.
// storebound check everything above
// storebound check --aso keyword audit of both listing files (App Store keyword field, Play stuffing); exit 1 on errors
// --json structured result ({ ok, items, warnings, problems } or { findings, errors }), exit 1 on problems
// --json structured result ({ ok, items, warnings, hints, problems } or { findings, errors }), exit 1 on problems
import { existsSync, readFileSync } from 'node:fs';
import { relative } from 'node:path';
import { type AsoFinding, auditAso } from './lib/aso';
import { playCodes } from './lib/config';
import { APPLE_IAP_LIMITS, len, parseAppStoreListing, parsePlayListing } from './lib/copy';
import { appleName, playCodes } from './lib/config';
import { APPLE_IAP_LIMITS, appleNameIssues, len, parseAppStoreListing, parsePlayListing } from './lib/copy';
import type { Ctx } from './lib/ctx';
import { dataSafetyRows } from './lib/data-safety';
import { reviewDemoAccount } from './lib/credentials';
import { log, printJson, warn } from './lib/log';
import { profileIssues } from './lib/profile';
import { reviewShotProblem } from './apple/iap-review';
import { allSubscriptions } from './lib/subscriptions';
import { type CopyFile, validateCopy } from './shots/lib';
@ -21,7 +22,7 @@ function aso(ctx: Ctx): void {
const { config, resolve } = ctx.loaded;
const apple = config.apple ? parseAppStoreListing(readFileSync(resolve(config.apple.listing ?? 'store/appstore.md'), 'utf8')) : undefined;
const play = config.play ? parsePlayListing(readFileSync(resolve(config.play.listing ?? 'store/listing.md'), 'utf8'), config.app.name) : undefined;
const f: AsoFinding[] = auditAso({ apple, play, appName: config.app.name, storefront: ctx.args.get('storefront') ?? 'US' });
const f: AsoFinding[] = auditAso({ apple, play, appName: appleName(config), storefront: ctx.args.get('storefront') ?? 'US' });
if (ctx.args.has('json')) { const errors = f.filter(x => x.level === 'error').length; printJson({ findings: f, errors }); if (errors) process.exitCode = 1; return; }
const tag = { error: 'ERROR', warn: 'warn ', info: 'info ' } as const;
for (const x of f) console.log(`${tag[x.level]} [${x.where}] ${x.msg}`);
@ -37,6 +38,7 @@ export async function run(ctx: Ctx): Promise<void> {
const problems: string[] = [];
const items: { what: string; detail: string }[] = [];
const warnings: string[] = [];
const hints: string[] = [];
const note = (msg: string): void => { warnings.push(msg); warn('check', msg); };
const tryDo = (what: string, fn: () => string): void => {
try { const detail = fn(); items.push({ what, detail }); log('check', `${what}: ${detail}`); } catch (e) {
@ -63,6 +65,9 @@ export async function run(ctx: Ctx): Promise<void> {
const copy = parseAppStoreListing(readFileSync(f, 'utf8'));
const missing = config.languages.filter(l => l.apple && !copy[l.apple]).map(l => l.apple);
if (missing.length) note(`appstore listing has no section for ${missing.join(', ')}`);
for (const i of appleNameIssues(copy, config.languages.flatMap(l => l.apple ? [l.apple] : []), appleName(config), config.app.name)) {
if (i.level === 'error') problems.push(i.msg); else { hints.push(i.msg); log('check', `hint: ${i.msg}`); }
}
return `${Object.keys(copy).length} locales`;
});
// listing translation drafts (storebound listing translate): fine to keep working on, not to push unreviewed
@ -78,6 +83,13 @@ export async function run(ctx: Ctx): Promise<void> {
if (config.apple && len(l.description) > APPLE_IAP_LIMITS.description) problems.push(`product ${p.id} ${lang}: description ${len(l.description)} > ${APPLE_IAP_LIMITS.description} (App Store limit)`);
if (len(l.description) > 200) problems.push(`product ${p.id} ${lang}: description ${len(l.description)} > 200 (Play limit)`);
}
// App Review screenshots of in-app purchases: Apple fails any non-screenshot size after upload (IMAGE_INCORRECT_DIMENSIONS)
if (config.apple) for (const f of new Set((config.products ?? []).map(p => p.reviewScreenshot).filter((x): x is string => !!x))) {
const file = resolve(f);
if (!existsSync(file)) continue; // reported with the other missing files below
const bad = reviewShotProblem(readFileSync(file));
if (bad) problems.push(`products[].reviewScreenshot ${f}: ${bad}`);
}
if (config.shots) tryDo('shots copy', () => {
const copy = JSON.parse(readFileSync(resolve(config.shots!.copy), 'utf8')) as CopyFile;
const e = validateCopy(copy, config.shots!, config.languages.map(l => l.id));
@ -95,7 +107,7 @@ export async function run(ctx: Ctx): Promise<void> {
if (existsSync(resolve('.gitignore')) && !/^\/?\.storebound\/?$/m.test(readFileSync(resolve('.gitignore'), 'utf8')))
problems.push('.gitignore does not ignore .storebound/ (credentials live there)');
if (ctx.args.has('json')) { printJson({ config: path, ok: !problems.length, items, warnings, problems }); if (problems.length) process.exitCode = 1; return; }
if (ctx.args.has('json')) { printJson({ config: path, ok: !problems.length, items, warnings, hints, problems }); if (problems.length) process.exitCode = 1; return; }
if (problems.length) { for (const p of problems) console.error(` - ${p}`); throw new Error(`${problems.length} problems`); }
log('check', 'all good');
}

View file

@ -15,7 +15,7 @@ export function parseArgs(argv: string[], booleans: string[] = []): Args {
const repeated = new Map<string, string[]>();
const set = (k: string, v: string) => { flags.set(k, v); repeated.set(k, [...(repeated.get(k) ?? []), v]); };
const _: string[] = [];
const bool = new Set(['dry', 'yes', 'help', 'json', 'verbose', 'all-pages', 'apply', 'resume', 'force', ...booleans]);
const bool = new Set(['dry', 'yes', 'help', 'json', 'verbose', 'all-pages', 'apply', 'resume', 'force', 'include-drafts', ...booleans]);
for (let i = 0; i < argv.length; i++) {
const a = argv[i]!;
if (!a.startsWith('--')) { _.push(a); continue; }

View file

@ -509,6 +509,10 @@ export interface ShipConfig {
};
apple?: {
bundleId: string; appId?: string; primaryLocale?: string; listing?: string; info?: AppleAppInfo; reviewShots?: string;
/** App Store name in the primary locale (at most 30 characters) when it differs from app.name, e.g. because the plain
* name is taken on the App Store ("STAR DASH: Stone Age to 2100"). Default app.name. A `### name` block in the
* App Store listing file wins for its locale. app.name stays the Play / on-device name. */
name?: string;
/** Apple Developer Team ID (10 characters, Membership details). apple-app-site-association and ad-hoc export use it. */
teamId?: string;
/** Ad-hoc / release-testing export (`storebound apple adhoc`). */
@ -700,6 +704,12 @@ function validateConsole(c: ConsoleConfig): string[] {
}
/** Platforms of the app (app identity): app.platforms, else from the store sections. */
/** App Store name limit (characters). */
export const APPLE_NAME_MAX = 30;
/** The App Store name in the primary locale: apple.name, else app.name. Per-locale `### name` blocks win over it. */
export const appleName = (c: Pick<ShipConfig, 'app' | 'apple'>): string => c.apple?.name?.trim() || c.app.name;
export const platformsOf = (c: Pick<ShipConfig, 'app' | 'apple' | 'play'>): Platform[] =>
c.app.platforms ?? [...(c.apple ? ['ios' as const] : []), ...(c.play ? ['android' as const] : [])];
@ -773,6 +783,9 @@ export function validateConfig(c: unknown): string[] {
e.push(`play.billingPrograms: a list of ${PLAY_BILLING_PROGRAMS.join(' | ')}`);
if (cfg.apple) {
if (!ID_RE.test(cfg.apple.bundleId ?? '')) e.push('apple.bundleId: not a bundle id (com.example.game)');
const an = cfg.apple.name;
if (an !== undefined && (typeof an !== 'string' || !an.trim())) e.push('apple.name: the App Store name (text), or leave it out to use app.name');
else if (an !== undefined && [...an].length > APPLE_NAME_MAX) e.push(`apple.name: ${[...an].length} characters > ${APPLE_NAME_MAX} (App Store limit)`);
if (cfg.apple.appId && !/^\d+$/.test(cfg.apple.appId)) e.push('apple.appId: numeric Apple ID of the app (App Store Connect > App Information)');
const enc = cfg.apple.usesNonExemptEncryption;
if (enc !== undefined && typeof enc !== 'boolean') e.push('apple.usesNonExemptEncryption: true | false');

View file

@ -14,7 +14,7 @@
// https://support.google.com/googleplay/android-developer/answer/9859655 (content ratings)
// https://support.google.com/googleplay/android-developer/answer/9867159 (target audience and content)
import { AGE_RATING_NONE } from '../apple/appinfo';
import { type AgeGroup, AGE_GROUPS, IARC_QUESTIONS, type IarcQuestion, profileOf, type ShipConfig } from './config';
import { type AgeGroup, AGE_GROUPS, appleName, IARC_QUESTIONS, type IarcQuestion, profileOf, type ShipConfig } from './config';
import { APPLE_PRIVACY, applePurpose } from './declarations';
import { maskUser } from './credentials';
@ -86,7 +86,8 @@ function appRecord(config: ShipConfig): Answer[] {
const lang = locale ? LANGUAGE_NAMES[locale] : undefined;
return [
a ? ok('platform:ios', 'Platforms: iOS', true, 'apple section') : ask('platform:ios', 'Platforms: iOS', 'config', 'The config has no apple section.'),
ok('name', 'Name', config.app.name, 'app.name', 'Must be unique on the App Store; App Store Connect says so when it is taken.'),
ok('name', 'Name', appleName(config), a?.name?.trim() ? 'apple.name' : 'app.name',
`Must be unique on the App Store (at most 30 characters); when App Store Connect says it is already being used, set apple.name (e.g. "${config.app.name}: <short tagline>") and fill again.`),
lang ? ok('language', 'Primary Language', lang, a?.primaryLocale ? 'apple.primaryLocale' : 'languages[0].apple')
: ask('language', 'Primary Language', 'apple.primaryLocale', locale ? `Pick the language of locale "${locale}".` : 'Set apple.primaryLocale (e.g. en-US).'),
a?.bundleId ? ok('bundleId', 'Bundle ID', a.bundleId, 'apple.bundleId', 'Register it first if it is not in the list: storebound apple bundle.')

View file

@ -5,7 +5,7 @@
// The names are modeled on Apple's and Google's public help pages (sources in console-answers.ts), not recorded from a
// signed-in console: the exact App Privacy dialog titles, the IARC question wording and the Play category names could
// not be verified without an account, which is why every field has candidates and the engine falls back on a miss.
import { AGE_GROUPS, type ShipConfig } from './config';
import { AGE_GROUPS, appleName, type ShipConfig } from './config';
import { AGE_LABELS, type Answer, APPLE_PURPOSES, type FormId } from './console-answers';
/** An accessible name: a string matches exactly, a RegExp matches the name. */
@ -188,12 +188,13 @@ const POLICY: Name[] = ['Policy and programs', 'Policy', 'Politika ve programlar
/**
* The steps that open a form after sign-in, built from the config only (apple.appId, apple.bundleId, play.packageName,
* app.name). The last step waits for the form itself. Pure.
* apple.name / app.name). The last step waits for the form itself. Pure.
*/
export function navPlan(id: FormId, config: ShipConfig, bases: NavBases = NAV_BASES): NavStep[] {
const asc = bases.asc.replace(/\/$/, ''), play = bases.play.replace(/\/$/, '');
const name = config.app?.name;
const named = name ? { name } : {};
const appleNamed = name ? { name: appleName(config) } : {};
switch (id) {
case 'apple-app-record': return [
{ kind: 'goto', label: 'open Apps', url: `${asc}/apps` },
@ -206,7 +207,7 @@ export function navPlan(id: FormId, config: ShipConfig, bases: NavBases = NAV_BA
const appId = config.apple?.appId;
const open: NavStep[] = appId ? [{ kind: 'goto', label: 'open App Privacy of the app (apple.appId)', url: `${asc}/apps/${encodeURIComponent(appId)}/distribution/privacy` }] : [
{ kind: 'goto', label: 'open Apps', url: `${asc}/apps` },
{ kind: 'pickApp', label: 'the app in the list', tokens: config.apple?.bundleId ? [config.apple.bundleId] : [], ...named },
{ kind: 'pickApp', label: 'the app in the list', tokens: config.apple?.bundleId ? [config.apple.bundleId] : [], ...appleNamed },
{ kind: 'click', label: 'App Privacy in the sidebar', roles: ['link', 'tab'], names: ['App Privacy', 'Uygulama Gizliliği', /^app privacy$/i] },
];
return [...open, { kind: 'wait', label: 'the App Privacy page', roles: ['heading'], names: ['App Privacy', 'Uygulama Gizliliği', /^app privacy$/i] }];

View file

@ -83,3 +83,21 @@ export function parseAppStoreListing(md: string): Record<string, AppleCopy> {
if (errors.length) throw new Error('appstore listing: ' + errors.join('; '));
return out;
}
export interface NameIssue { level: 'error' | 'info'; msg: string }
/**
* The App Store name per locale (a `### name` block, else `fallback` = apple.name, else app.name) against the 30-char
* limit, plus a hint when every locale uses the plain app.name: App Store names are unique, so a taken name stops the
* app record ("already being used"). Pure.
*/
export function appleNameIssues(copy: Record<string, AppleCopy>, locales: string[], fallback: string, appName: string): NameIssue[] {
const out: NameIssue[] = [];
const all = [...new Set([...locales, ...Object.keys(copy)])];
const names = all.map(l => ({ l, name: (copy[l]?.name ?? fallback).trim(), own: !!copy[l]?.name }));
for (const n of names) if (len(n.name) > APPLE_LIMITS.name)
out.push({ level: 'error', msg: `App Store name of ${n.l} is ${len(n.name)} > ${APPLE_LIMITS.name} characters: "${n.name}" (${n.own ? 'its ### name block' : fallback === appName ? 'app.name; set apple.name' : 'apple.name'})` });
if (names.length && names.every(n => n.name === appName))
out.push({ level: 'info', msg: `the App Store name is "${appName}" in every locale: App Store names are unique, so if it is taken App Store Connect refuses the record ("already being used"). Then set apple.name with a short suffix, e.g. "${appName}: <tagline>" (30 characters at most); app.name stays the Play and on-device name` });
return out;
}

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;
}

View file

@ -471,7 +471,7 @@ export function planImport(scan: FastlaneScan, o: PlanOptions): ImportPlan {
const md = `# ${appName} · App Store listing copy
Imported from fastlane deliver (\`storebound import fastlane\`). Source for \`storebound apple listing\`. One
\`## <ASC locale>\` section per locale, one fenced block per \`### <field>\`: \`name\` (optional, defaults to \`app.name\`),
\`## <ASC locale>\` section per locale, one fenced block per \`### <field>\`: \`name\` (optional, defaults to \`apple.name\`, else \`app.name\`),
\`subtitle\` (30), \`promotionalText\` (170), \`keywords\` (100 bytes, comma separated, no spaces after commas),
\`description\` (4000), \`whatsNew\` (optional). Privacy policy, support and marketing URL come from
\`storebound.config.ts\`.

137
cli/lib/listing-plan.ts Normal file
View file

@ -0,0 +1,137 @@
// Write plans for the listing commands (apple listing, play listing, apple appinfo): what the store has now, what a
// run would send, field by field (old -> new). The dry run prints the plan; the real run applies exactly that plan.
// Pure: the commands read the store, this file decides and formats.
import { EDITABLE } from '../apple/asc';
import { appleLocaleOf, markerOf, playCodesOf, sections, type TStatus } from './listing-translate';
export interface FieldDiff { field: string; from: string | null; to: string | null }
/** One localization (or one settings object): create, update the changed fields, or leave it. */
export interface ItemPlan { key: string; action: 'create' | 'update' | 'same'; id?: string; changes: FieldDiff[]; unchanged: string[]; attributes: Record<string, string> }
export interface Skipped { key: string; reason: string }
const norm = (v: unknown): string | null => (v === undefined || v === null || v === '' ? null : String(v));
/** Create / update / same for one wanted attribute set against the current one (null when it does not exist). Only
* defined wanted values count; an empty and a missing value are the same. Pure. */
export function planItem(key: string, current: { id?: string; attributes: Record<string, unknown> } | null, want: Record<string, string | undefined>): ItemPlan {
const attributes = Object.fromEntries(Object.entries(want).filter((e): e is [string, string] => e[1] !== undefined));
if (!current) return { key, action: 'create', changes: Object.entries(attributes).map(([field, to]) => ({ field, from: null, to })), unchanged: [], attributes };
const changes: FieldDiff[] = [], unchanged: string[] = [];
for (const [field, to] of Object.entries(attributes)) {
const from = norm(current.attributes[field]);
if (from === norm(to)) unchanged.push(field); else changes.push({ field, from, to });
}
return { key, action: changes.length ? 'update' : 'same', ...(current.id ? { id: current.id } : {}), changes, unchanged, attributes };
}
/** Localizations: every wanted locale against the ones the store has (by `locale`). Pure. */
export function planLocales(have: { id: string; attributes: Record<string, unknown> }[], want: Record<string, Record<string, string | undefined>>): ItemPlan[] {
const byLocale = new Map(have.map(h => [String(h.attributes.locale), h] as const));
return Object.entries(want).map(([locale, w]) => planItem(locale, byLocale.get(locale) ?? null, w));
}
// ---- App Store version ----
export interface VersionInfo { id: string; versionString: string; state: string; platform: string }
export interface VersionPlan {
action: 'create' | 'update' | 'keep' | 'refuse';
/** The editable version that is kept or updated. */
id?: string;
reason: string;
existing: VersionInfo[];
changes: FieldDiff[];
attributes: Record<string, string>;
/** No version of the app went through review before: what's new cannot be set on the first version. */
first: boolean;
}
/** Versions App Store Connect still lets you edit (texts, build, version string). */
export const EDITABLE_STATES = EDITABLE;
/** A version in these states blocks a new one (App Store Connect allows one version in progress). */
const IN_PROGRESS = new Set(['WAITING_FOR_REVIEW', 'IN_REVIEW', 'READY_FOR_REVIEW', 'WAITING_FOR_EXPORT_COMPLIANCE', 'PENDING_APPLE_RELEASE',
'PENDING_DEVELOPER_RELEASE', 'PROCESSING_FOR_APP_STORE', 'PROCESSING_FOR_DISTRIBUTION', 'ACCEPTED']);
/** -1 / 0 / 1 by numeric segments ("1.0" < "1.0.1", "1.10" > "1.9"). */
export function compareVersions(a: string, b: string): number {
const x = a.split('.').map(Number), y = b.split('.').map(Number);
for (let i = 0; i < Math.max(x.length, y.length); i++) { const d = (x[i] ?? 0) - (y[i] ?? 0); if (d) return d < 0 ? -1 : 1; }
return 0;
}
/** Version rows of GET /v1/apps/{id}/appStoreVersions. */
export const versionInfos = (rows: { id: string; attributes: Record<string, unknown> }[]): VersionInfo[] =>
rows.map(r => ({ id: r.id, versionString: String(r.attributes.versionString ?? ''), state: String(r.attributes.appVersionState ?? r.attributes.appStoreState ?? ''), platform: String(r.attributes.platform ?? 'IOS') }));
/**
* What `apple listing --version <want>` does with the app's iOS versions: keep / update the editable one (its version
* string changes only while PREPARE_FOR_SUBMISSION), create a new one, or refuse (the number exists, is not higher than
* a version that went through review, or another version is in review / pending release). Pure.
*/
export function planVersion(rows: { id: string; attributes: Record<string, unknown> }[], want: string, attrs: { copyright: string; releaseType: string }): VersionPlan {
const existing = versionInfos(rows);
const editable = existing.find(v => EDITABLE_STATES.has(v.state));
const others = existing.filter(v => v !== editable);
const first = !others.length;
const base = { existing, first, changes: [] as FieldDiff[], attributes: {} as Record<string, string> };
const refuse = (reason: string): VersionPlan => ({ ...base, action: 'refuse', reason });
const taken = others.find(v => v.versionString === want);
if (taken) return refuse(`version ${want} already exists (${taken.state}); a new version needs a higher number`);
const higher = others.filter(v => compareVersions(v.versionString, want) >= 0).sort((a, b) => compareVersions(b.versionString, a.versionString))[0];
if (higher && (!editable || editable.versionString !== want))
return refuse(`version ${want} is not higher than ${higher.versionString} (${higher.state}); App Store versions only go up`);
if (editable) {
const cur = rows.find(r => r.id === editable.id)!.attributes;
const wantAttrs = { versionString: want, copyright: attrs.copyright, releaseType: attrs.releaseType };
const p = planItem(editable.id, { id: editable.id, attributes: cur }, wantAttrs);
if (editable.versionString !== want && editable.state !== 'PREPARE_FOR_SUBMISSION')
return refuse(`the editable version ${editable.versionString} is ${editable.state}; its version string changes only while PREPARE_FOR_SUBMISSION (use --version ${editable.versionString}, or change it in App Store Connect)`);
if (editable.versionString !== want) return { ...base, action: 'update', id: editable.id, changes: p.changes, attributes: p.attributes,
reason: `update the editable version ${editable.versionString} (${editable.state}) to ${want}` };
return { ...base, action: p.changes.length ? 'update' : 'keep', id: editable.id, changes: p.changes, attributes: p.attributes,
reason: p.changes.length ? `update version ${want} (${editable.state}): ${p.changes.map(c => c.field).join(', ')}` : `version ${want} (${editable.state}) is up to date` };
}
const busy = others.find(v => IN_PROGRESS.has(v.state));
if (busy) return refuse(`version ${busy.versionString} is ${busy.state}; App Store Connect allows one version in progress (wait for its release or remove it from review)`);
const attributes = { platform: 'IOS', versionString: want, copyright: attrs.copyright, releaseType: attrs.releaseType };
return { ...base, action: 'create', reason: `create version ${want} (no editable iOS version)`, changes: Object.entries(attributes).map(([field, to]) => ({ field, from: null, to })), attributes };
}
// ---- translation drafts ----
/** Locales (App Store) or Play language codes whose section is a translation draft or still untranslated, with why. */
export function draftSections(md: string, store: 'apple' | 'play'): Map<string, TStatus> {
const out = new Map<string, TStatus>();
for (const sec of sections(md)) {
const m = markerOf(sec);
if (!m) continue;
const keys = store === 'apple' ? [appleLocaleOf(sec)].filter((x): x is string => !!x) : playCodesOf(sec);
for (const k of keys) out.set(k, m.status);
}
return out;
}
export const draftReason = (s: TStatus): string => s === 'draft'
? 'machine-translated draft, not reviewed (storebound listing check, then listing reviewed --lang <id>; or --include-drafts)'
: 'not translated yet (status=translate: still the source text; translate it, or --include-drafts)';
// ---- formatting ----
/** One value for a plan line: quoted, long text cut with its length. */
export function short(v: string | null, max = 60): string {
if (v === null) return '(none)';
const flat = v.replace(/\s*\n\s*/g, ' ⏎ ');
const n = [...v].length;
return [...flat].length > max ? `"${[...flat].slice(0, max).join('')}…" (${n} chars)` : `"${flat}"`;
}
/** Plan lines of one item: a header and one line per changed field; unchanged fields summarized. */
export function itemLines(label: string, p: ItemPlan, indent = ' '): string[] {
if (p.action === 'same') return [`${indent}${label}: unchanged (${p.unchanged.length} field${p.unchanged.length === 1 ? '' : 's'})`];
const head = `${indent}${label}: ${p.action === 'create' ? 'create' : 'update'}${p.unchanged.length ? ` (${p.unchanged.length} unchanged: ${p.unchanged.join(', ')})` : ''}`;
return [head, ...p.changes.map(c => `${indent} ${c.field}: ${p.action === 'create' ? short(c.to) : `${short(c.from)} -> ${short(c.to)}`}`)];
}
export const counts = (items: ItemPlan[]): string => {
const n = (a: ItemPlan['action']) => items.filter(i => i.action === a).length;
return `${n('create')} create, ${n('update')} update, ${n('same')} unchanged`;
};

View file

@ -29,8 +29,9 @@ function setBlock(sec: string, heading: RegExp, newHeading: string, text: string
const APPLE_ORDER: AppleField[] = ['name', 'subtitle', 'promotionalText', 'keywords', 'description', 'whatsNew'];
/** Live App Store texts per locale merged into the App Store listing file. Pure. */
export function mergeAppleListing(md: string, remote: Record<string, AppleCopy>): MergeResult {
/** Live App Store texts per locale merged into the App Store listing file. A name equal to `defaultName` (apple.name,
* else app.name) is only written where the section already has a name block. Pure. */
export function mergeAppleListing(md: string, remote: Record<string, AppleCopy>, defaultName?: string): MergeResult {
const parts = md.split(/^(?=## )/m);
const res: MergeResult = { md: '', changes: [], added: [], conflicts: [] };
const seen = new Set<string>();
@ -43,6 +44,7 @@ export function mergeAppleListing(md: string, remote: Record<string, AppleCopy>)
for (const f of APPLE_ORDER) {
const v = r[f];
if (v === undefined || v === null || v === '') continue;
if (f === 'name' && v === defaultName && !BLOCK(/name\b/).test(sec)) continue;
const { sec: next, from } = setBlock(sec, new RegExp(`${f}\\b`), f, v);
if (from !== v.trim()) res.changes.push({ section: loc, field: f, from, to: v });
sec = next;
@ -52,7 +54,7 @@ export function mergeAppleListing(md: string, remote: Record<string, AppleCopy>)
let text = out.join('');
for (const [loc, r] of Object.entries(remote).sort(([a], [b]) => a.localeCompare(b))) {
if (seen.has(loc)) continue;
const fields = APPLE_ORDER.filter(f => r[f]);
const fields = APPLE_ORDER.filter(f => r[f] && !(f === 'name' && r[f] === defaultName));
if (!fields.length) continue;
res.added.push(loc);
text = text.replace(/\s*$/, '') + `\n\n## ${loc}\n\n` + fields.map(f => `### ${f}\n${fence(r[f]!)}`).join('\n\n') + '\n';

View file

@ -3,7 +3,7 @@
// line, never an exception, so one bad section does not hide the rest ("unknown, never false").
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
import { extname, isAbsolute, join, resolve } from 'node:path';
import { type ShipConfig, playCodes } from './config';
import { appleName, type ShipConfig, playCodes } from './config';
import { APPLE_LIMITS, len, PLAY_LIMITS } from './copy';
import type { DraftsResult, IconResult, ListingField, ListingLocale, ListingsResult, ListingText, RenderImage, ReplyDraft } from './desktop-protocol';
import { parseFrontMatter, stringifyFrontMatter } from './frontmatter';
@ -136,7 +136,7 @@ export function listingCompleteness(config: ShipConfig, root: string): ListingsR
const applePart = config.apple ? {
code: ac,
fields: tally([
field('name', as?.name ?? (as ? config.app.name : undefined), APPLE_LIMITS.name, true),
field('name', as?.name ?? (as ? appleName(config) : undefined), APPLE_LIMITS.name, true),
field('subtitle', as?.subtitle, APPLE_LIMITS.subtitle, true),
field('promotionalText', as?.promotionalText, APPLE_LIMITS.promotionalText, true),
field('keywords', as?.keywords, APPLE_LIMITS.keywords, true),

View file

@ -333,6 +333,7 @@ export function scanRules(inp: ScanInput): ScanFinding[] {
const BETA = /\b(beta|demo|trial version|test (version|build|app)|testing build|early access|prototype|preview (build|version)|alpha (build|version))\b/i;
const betaName: Hit[] = [];
if (c?.app?.name && BETA.test(c.app.name)) betaName.push(...cfg(c.app.name, `app.name: ${c.app.name}`));
if (c?.apple?.name && c.apple.name !== c.app?.name && BETA.test(c.apple.name)) betaName.push(...cfg(c.apple.name, `apple.name: ${c.apple.name}`));
for (const k of ['CFBundleDisplayName', 'CFBundleName']) {
const v = plistVal(k);
if (typeof v?.value === 'string' && BETA.test(v.value) && !/\$\(/.test(v.value)) betaName.push({ ...v.at, text: `${k}: ${v.value}` });

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

@ -150,7 +150,7 @@ export const TOOLS: ToolDef[] = [
props: { since: { type: 'string', description: 'Git tag or ref (default: latest tag)' }, lang: { type: 'string' }, all_languages: { type: 'boolean', default: false } },
args: i => [...opt('since', i.since), ...opt('lang', i.lang), ...flag('all', i.all_languages)] },
{ name: 'play_listing', title: 'Push Play listing text', command: ['play', 'listing'], write: true, network: true, idempotent: true,
description: 'Google Play app details + title / short / full description per language from the listing file. Not public until the next review / publish.',
description: 'Google Play app details + title / short / full description per language from the listing file. dry_run prints the plan (old -> new per field); draft languages are skipped (owner terminal run with --include-drafts). Not public until the next review / publish.',
props: { only }, args: i => opt('only', i.only) },
{ name: 'play_images', title: 'Upload Play graphics', command: ['play', 'images'], write: true, destructive: true, network: true, idempotent: true,
description: 'Replace icon, feature graphic and screenshots per Play language from the renders folder (or an A/B variant folder). Slow (minutes): prefer the terminal with a log for many languages.',
@ -181,7 +181,7 @@ export const TOOLS: ToolDef[] = [
{ name: 'apple_iap_review', title: 'IAP review screenshots', command: ['apple', 'iap-review'], write: true, destructive: true, network: true, idempotent: true,
description: 'Upload (replace when changed) the App Review screenshot of every in-app purchase. Never submits.' },
{ name: 'apple_listing', title: 'Push App Store version + text', command: ['apple', 'listing'], write: true, network: true, idempotent: true,
description: 'Create / update the editable version (manual release), attach a build by explicit number, and push name / subtitle / description / keywords / promo / what\'s new per locale.',
description: 'Create / update the editable version (manual release), attach a build by explicit number, and push name / subtitle / description / keywords / promo / what\'s new per locale. dry_run prints the plan: version keep / update / create / refuse with the reason, per locale old -> new per field; draft locales are skipped (owner terminal run with --include-drafts).',
props: { version: { type: 'string', pattern: '^\\d+(\\.\\d+){0,2}$' }, build: { type: 'string', description: 'Exact build number to attach (use the number you just uploaded, never "latest")' }, only },
required: ['version'], args: i => [...opt('version', i.version), ...opt('build', i.build), ...opt('only', i.only)] },
{ name: 'apple_screenshots', title: 'Upload App Store screenshots', command: ['apple', 'screenshots'], write: true, destructive: true, network: true, idempotent: true,

View file

@ -1,7 +1,9 @@
// Play store listing text + app details in one edit.
// storebound play listing [--dry] [--only en-US,de-DE]
// --dry is read-only: a throwaway edit is opened, the current details and listings are read and compared with the file,
// and the edit is deleted. Nothing is written, not even into that edit.
// storebound play listing [--dry] [--json] [--only en-US,de-DE] [--include-drafts]
// Every run first reads Play in a throwaway edit (deleted again) and prints the plan: app details and per language
// create / update with old -> new per field. --dry stops there (nothing is written, not even into that edit); the real
// run asks in a terminal and PUTs only what the plan changes, in one committed edit. Languages whose section is
// status=draft or status=translate (listing translate) are skipped unless --include-drafts.
// App details: default language, contact email, website (must be the domain that serves app-ads.txt).
// Listings: title, short and full description of every `<!-- play: ... -->` section of the listing file, plus the promo
// video (play.video, a YouTube URL) on every language. Play has no video upload: make the video with
@ -12,8 +14,9 @@ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { parsePlayListing } from '../lib/copy';
import { compactDiff } from '../lib/diff';
import { mergePlayListing, overLimits } from '../lib/listing-pull';
import { counts, draftReason, draftSections, type ItemPlan, itemLines, planItem, type Skipped } from '../lib/listing-plan';
import type { Ctx } from '../lib/ctx';
import { need } from '../lib/ctx';
import { confirm, need } from '../lib/ctx';
import { done, log, printJson, step, warn } from '../lib/log';
import { playClient } from './client';
@ -75,36 +78,77 @@ async function pull(ctx: Ctx): Promise<void> {
done('play', `${file}: ${r.changes.length} change(s) written${r.added.length ? `, new languages ${r.added.join(', ')}` : ''}`);
}
/** The plan of one `play listing` run, from a read-only edit. */
export interface PlayListingPlan { details: ItemPlan; listings: ItemPlan[]; other: string[]; skipped: Skipped[]; notes: string[]; changes: number }
/** Plan from what Play has now. The listing PUT replaces the whole listing: a promo video on Play that play.video leaves
* out is shown as cleared. Pure. */
export function playPlan(curDetails: Record<string, unknown>, details: Record<string, string | undefined>, now: PlayListing[], bodies: Record<string, string>[],
o: { skipped?: Skipped[]; notes?: string[]; only?: boolean } = {}): PlayListingPlan {
const d = planItem('details', { attributes: curDetails }, details);
const byLang = new Map(now.map(l => [l.language, l]));
const listings = bodies.map(b => {
const cur = byLang.get(b.language!);
const { language, ...want } = b;
const w: Record<string, string | undefined> = { ...want, video: want.video ?? (cur?.video ? '' : undefined) };
return planItem(language!, cur ? { attributes: cur as unknown as Record<string, unknown> } : null, w);
});
const other = o.only ? [] : now.filter(l => !bodies.some(b => b.language === l.language)).map(l => l.language);
const changes = (d.action === 'same' ? 0 : 1) + listings.filter(l => l.action !== 'same').length;
return { details: d, listings, other, skipped: o.skipped ?? [], notes: o.notes ?? [], changes };
}
/** The plan as text lines. Pure. */
export function playPlanLines(p: PlayListingPlan): string[] {
const out = [...itemLines('App details (default language, contact email, website)', p.details, '')];
out.push(`Listings: title, short and full description, promo video · ${counts(p.listings)}`);
for (const l of p.listings) out.push(...itemLines(l.key, l));
if (p.other.length) out.push(`Left as they are (on Play, not in the listing file): ${p.other.join(', ')}`);
for (const s of p.skipped) out.push(`Skipped ${s.key}: ${s.reason}`);
for (const n of p.notes) out.push(`Note: ${n}`);
return out;
}
export async function run(ctx: Ctx): Promise<void> {
const { config, root } = ctx.loaded;
if (ctx.args._[0] === 'pull') return pull(ctx);
const { config, root, resolve } = ctx.loaded;
const a = ctx.args;
if (a._[0] === 'pull') return pull(ctx);
const pkg = need(config.play?.packageName, 'play.packageName');
const copy = readPlayCopy(ctx);
const all = readPlayCopy(ctx);
const drafts = draftSections(readFileSync(resolve(config.play?.listing ?? 'store/listing.md'), 'utf8'), 'play');
const skipped: Skipped[] = [], notes: string[] = [];
const copy = all.filter(c => {
const st = drafts.get(c.lang);
if (!st) return true;
if (a.has('include-drafts')) { notes.push(`${c.lang}: ${st === 'draft' ? 'machine-translated draft' : 'untranslated (status=translate)'} included (--include-drafts)`); return true; }
skipped.push({ key: c.lang, reason: draftReason(st) });
return false;
});
const details = { defaultLanguage: config.play?.defaultLanguage ?? 'en-US', contactEmail: config.app.contactEmail, contactWebsite: config.app.website };
if (!copy.some(c => c.lang === details.defaultLanguage) && !ctx.args.has('only')) throw new Error(`listing has no section for the default language ${details.defaultLanguage}`);
log('play', `${copy.length} listings: ${copy.map(c => c.lang).join(', ')}${config.play?.video ? ` · promo video ${config.play.video}` : ''}`);
if (!all.some(c => c.lang === details.defaultLanguage) && !a.has('only')) throw new Error(`listing has no section for the default language ${details.defaultLanguage}`);
if (!a.has('json')) log('play', `${copy.length} listings: ${copy.map(c => c.lang).join(', ')}${config.play?.video ? ` · promo video ${config.play.video}` : ''}`);
const play = await playClient(root, pkg);
if (ctx.args.has('dry')) {
await play.read(async id => {
const cur = await play.call<Record<string, string>>('GET', `${play.API}/edits/${id}/details`);
const dc = detailsChanges(cur, details);
log('play', `details: ${dc.length ? 'would change ' + dc.join(', ') : 'unchanged'}`);
const now = (await play.call<{ listings?: PlayListing[] }>('GET', `${play.API}/edits/${id}/listings`)).listings ?? [];
const changes = listingChanges(now, copy.map(c => listingBody(c, config.play?.video)));
for (const c of changes) log('play', `${c.lang}: ${c.change === 'update' ? 'would update ' + c.fields.join(', ') : c.change === 'new' ? 'would add (new language)' : 'unchanged'}`);
const other = now.filter(l => !copy.some(c => c.lang === l.language)).map(l => l.language);
if (other.length && !ctx.args.has('only')) log('play', `${other.length} languages on Play not in the listing file (left as they are): ${other.join(', ')}`);
const n = changes.filter(c => c.change !== 'same').length + (dc.length ? 1 : 0);
done('play', `dry run: ${n ? n + ' change(s)' : 'nothing to change'}; read-only, nothing written`);
});
return;
}
const bodies = copy.map(c => listingBody(c, config.play?.video));
const p = await play.read(async id => {
const cur = await play.call<Record<string, string>>('GET', `${play.API}/edits/${id}/details`);
const now = (await play.call<{ listings?: PlayListing[] }>('GET', `${play.API}/edits/${id}/listings`)).listings ?? [];
return playPlan(cur, details, now, bodies, { skipped, notes, only: a.has('only') });
});
const dry = a.has('dry');
if (a.has('json')) printJson({ dry, ...p });
else for (const line of playPlanLines(p)) console.log(line);
if (dry) { done('play', `dry run: ${p.changes ? `${p.changes} change(s)` : 'nothing to change'}; read-only, nothing written`); return; }
if (!p.changes) { done('play', 'listing already up to date'); return; }
if (process.stdin.isTTY && !(await confirm(ctx, `Apply these ${p.changes} change(s) to Google Play (one edit, committed)?`))) { warn('play', 'nothing written'); return; }
const todo = p.listings.filter(l => l.action !== 'same').map(l => bodies.find(b => b.language === l.key)!);
await play.edit(async id => {
await play.call('PUT', `${play.API}/edits/${id}/details`, details);
log('play', `details: ${details.defaultLanguage} · ${details.contactEmail} · ${details.contactWebsite}`);
for (const [i, c] of copy.entries()) {
await play.call('PUT', `${play.API}/edits/${id}/listings/${c.lang}`, listingBody(c, config.play?.video));
log('play', step(i + 1, copy.length, c.lang));
if (p.details.action !== 'same') {
await play.call('PUT', `${play.API}/edits/${id}/details`, details);
log('play', `details: ${p.details.changes.map(ch => ch.field).join(', ')}`);
}
for (const [i, b] of todo.entries()) {
await play.call('PUT', `${play.API}/edits/${id}/listings/${b.language}`, b);
log('play', step(i + 1, todo.length, b.language!));
}
});
done('play', 'listing done');

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');
}