Merge store-ops: TestFlight wait / expire, IAP review submissions, pulls, offers, CPP, events, reports, triage, ASO rank, ads scan

Conflicts resolved for both sides:
- cli/lib/plist.ts, cli/lib/zip.ts: one implementation each. plist reads XML (text or
  bytes, attributes tolerated) and binary plists; ads scan now reads bytes, so a binary
  Info.plist works too. zip gains unzip() for the Play report exports on top of
  zipEntries / zipRead.
- apple upload waits with testflight wait's loop (waitForBuild) instead of its own copy;
  BUILD_DONE removed.
- config, credentials (profiles, keystore, ASC_VENDOR_NUMBER, now also a profile key),
  command table, MCP tools, credentials template, README, CHANGELOG: union.
- MCP: --write stays forbidden; the three pull tools are the listed local-file exception
  (LOCAL_WRITE_TOOLS), so scan --write remains unreachable.
- Adapters and API coverage tables regenerated.
This commit is contained in:
CRTkafa 2026-10-11 16:07:26 +00:00
commit b724cd4043
60 changed files with 4500 additions and 183 deletions

172
cli/lib/adattribution.ts Normal file
View file

@ -0,0 +1,172 @@
// AdAttributionKit / SKAdNetwork checks of an iOS app's Info.plist and sources, as pure rules. The command
// (cli/ads.ts scan) finds the files, parses them (cli/lib/plist.ts) and prints the findings. Text checks only.
// Sources (Apple developer documentation, checked October 2026):
// https://developer.apple.com/documentation/adattributionkit
// Publisher app: "add the ad network IDs" under `AdNetworkIdentifiers` (array of strings); "Lowercase the ad network ID
// string; otherwise, the system doesn't recognize it as a valid network."
// https://developer.apple.com/documentation/adattributionkit/configuring-a-publisher-app
// https://developer.apple.com/documentation/bundleresources/information-property-list/adnetworkidentifiers
// SKAdNetwork: `SKAdNetworkItems`, one dictionary with `SKAdNetworkIdentifier` per network; "Ad network IDs are
// case-sensitive and are in lowercase." `.adattributionkit` and `.skadnetwork` ids work with both frameworks.
// https://developer.apple.com/documentation/bundleresources/information-property-list/skadnetworkitems
// https://developer.apple.com/documentation/adattributionkit/adattributionkit-skadnetwork-interoperability
// Advertised app: copies of winning postbacks with `AttributionCopyEndpoint` (Xcode shows it as "AdAttributionKit -
// Postback Copy URL"; Apple's property list reference lists the key at the top level, Xcode's editor files it under
// an `AdAttributionKit` dictionary: both are read here), "a valid URL in the format of https://example.com"; the
// system uses the registrable domain and posts to https://<domain>/.well-known/appattribution/report-attribution/.
// Re-engagement copies: `EligibleForAdAttributionKitReengagementPostbackCopies` (Boolean YES). The app has to call
// updateConversionValue at least once to start a postback's conversion window.
// https://developer.apple.com/documentation/adattributionkit/configuring-an-advertised-app
// https://developer.apple.com/documentation/bundleresources/information-property-list/attributioncopyendpoint
// SKAdNetwork postback copies and Private Click Measurement: `NSAdvertisingAttributionReportEndpoint`.
// https://developer.apple.com/documentation/bundleresources/information-property-list/nsadvertisingattributionreportendpoint
// Attribution rules: `AdAttributionKitConfigurations` > `AttributionWindows` > `global` | <ad network id> > `install` >
// `click` (1-30 days) / `view` (1-7 days) / `ignoreInteractionType` (view | click; ad network entries only);
// `AttributionCooldown` > `install-cooldown-hours` / `re-engagement-cooldown-hours` (0-720).
// https://developer.apple.com/documentation/adattributionkit/configuring-attribution-rules-for-your-app
// AdAttributionKit needs no App Tracking Transparency prompt.
import type { PlistValue } from './plist';
export type AakLevel = 'blocker' | 'warn' | 'ok' | 'info';
export interface AakFinding { level: AakLevel; code: string; msg: string }
type Dict = { [k: string]: PlistValue };
const isDict = (v: PlistValue | undefined): v is Dict => !!v && typeof v === 'object' && !Array.isArray(v) && !Buffer.isBuffer(v);
const ID_RE = /^[a-z0-9]+\.(skadnetwork|adattributionkit)$/;
export interface SourceSignals {
/** `import AdAttributionKit` (or the framework linked). */
aakImport: boolean;
/** updateConversionValue / updatePostbackConversionValue calls (app code or an attribution SDK). */
conversionUpdates: boolean;
/** Ad SDKs found (Podfile.lock, Package.resolved, frameworks): these show ads, so the app is a publisher. */
adSdks: string[];
/** Mobile measurement SDKs that update conversion values for you (AppsFlyer, Adjust, Branch, Singular, Kochava). */
mmpSdks: string[];
}
export const AD_SDKS: [RegExp, string][] = [
[/Google-Mobile-Ads-SDK|GoogleMobileAds|swift-package-manager-google-mobile-ads/i, 'Google Mobile Ads (AdMob)'], [/AppLovinSDK|applovin-ios-sdk/i, 'AppLovin MAX'],
[/IronSourceSDK|IronSource|LevelPlay/i, 'Unity LevelPlay / ironSource'], [/UnityAds/i, 'Unity Ads'], [/FBAudienceNetwork/i, 'Meta Audience Network'],
[/Vungle|LiftoffMonetize/i, 'Liftoff Monetize'], [/InMobiSDK/i, 'InMobi'], [/MintegralAdSDK/i, 'Mintegral'], [/Pangle|Ads-Global|PAGAdSDK/i, 'Pangle'], [/ChartboostSDK/i, 'Chartboost'],
];
export const MMP_SDKS: [RegExp, string][] = [[/AppsFlyer/i, 'AppsFlyer'], [/\bAdjust(Sdk|Signature)?\b/i, 'Adjust'], [/\bBranch\b|BranchSDK/i, 'Branch'], [/Singular/i, 'Singular'], [/KochavaNetworking|KochavaTracker/i, 'Kochava']];
/** Ad / MMP SDK names and AdAttributionKit signals in dependency lock files and sources. Pure. */
export function sourceSignals(files: { path: string; text: string }[]): SourceSignals {
const deps = files.filter(f => /(Podfile\.lock|Package\.resolved|Cartfile\.resolved|project\.pbxproj)$/.test(f.path)).map(f => f.text).join('\n');
const code = files.filter(f => /\.(swift|m|mm)$/.test(f.path)).map(f => f.text).join('\n');
return {
aakImport: /^\s*import\s+AdAttributionKit\b|@import\s+AdAttributionKit|AdAttributionKit\.framework/m.test(code + deps),
conversionUpdates: /\bupdateConversionValue\s*\(|\bupdatePostbackConversionValue\s*\(/.test(code),
adSdks: AD_SDKS.filter(([re]) => re.test(deps)).map(([, n]) => n),
mmpSdks: MMP_SDKS.filter(([re]) => re.test(deps)).map(([, n]) => n),
};
}
function checkUrl(v: PlistValue | undefined, key: string, f: AakFinding[]): string | null {
if (v === undefined) return null;
if (typeof v !== 'string' || !/^https:\/\/[^\s/]+(\/.*)?$/i.test(v.trim())) { f.push({ level: 'blocker', code: 'endpoint-url', msg: `${key}: "${String(v)}" is not an https URL like https://example.com` }); return null; }
const host = new URL(v.trim()).hostname;
if (new URL(v.trim()).pathname.replace(/\/$/, '')) f.push({ level: 'warn', code: 'endpoint-path', msg: `${key}: the path is ignored; the system only uses the domain (${host})` });
return host;
}
/** Registrable-ish domain (last two labels; good enough to compare two endpoints of one app). */
const domainOf = (host: string): string => host.split('.').slice(-2).join('.');
/** Every finding for one Info.plist (+ the source signals of the project). Pure. */
export function evaluateAdAttribution(plist: Dict, s: SourceSignals): AakFinding[] {
const f: AakFinding[] = [];
// ---- publisher: ad network ids ----
const skItems = plist.SKAdNetworkItems;
const skIds: string[] = [];
if (skItems !== undefined) {
if (!Array.isArray(skItems)) f.push({ level: 'blocker', code: 'skadnetwork-type', msg: 'SKAdNetworkItems must be an array of dictionaries with SKAdNetworkIdentifier' });
else for (const [i, it] of skItems.entries()) {
const id = isDict(it) ? it.SKAdNetworkIdentifier : undefined;
if (typeof id !== 'string') { f.push({ level: 'blocker', code: 'skadnetwork-entry', msg: `SKAdNetworkItems[${i}]: no SKAdNetworkIdentifier string` }); continue; }
skIds.push(id);
}
}
const aak = plist.AdNetworkIdentifiers;
const aakIds: string[] = [];
if (aak !== undefined) {
if (!Array.isArray(aak) || !aak.every(x => typeof x === 'string')) f.push({ level: 'blocker', code: 'aak-ids-type', msg: 'AdNetworkIdentifiers must be an array of strings' });
else aakIds.push(...(aak as string[]));
}
for (const [list, name] of [[skIds, 'SKAdNetworkItems'], [aakIds, 'AdNetworkIdentifiers']] as const) {
const upper = list.filter(id => id !== id.toLowerCase());
if (upper.length) f.push({ level: 'blocker', code: 'id-case', msg: `${name}: ${upper.length} id(s) with capital letters (${upper.slice(0, 3).join(', ')}): the system ignores them; ad network ids are lowercase` });
const odd = list.filter(id => id === id.toLowerCase() && !ID_RE.test(id));
if (odd.length) f.push({ level: 'warn', code: 'id-format', msg: `${name}: ${odd.slice(0, 3).join(', ')} do not look like ad network ids (<id>.skadnetwork / <id>.adattributionkit)` });
const dup = list.filter((id, i) => list.indexOf(id) !== i);
if (dup.length) f.push({ level: 'info', code: 'id-duplicate', msg: `${name}: listed twice: ${[...new Set(dup)].slice(0, 3).join(', ')}` });
}
if (s.adSdks.length && !skIds.length && !aakIds.length)
f.push({ level: 'blocker', code: 'no-network-ids', msg: `ad SDKs (${s.adSdks.join(', ')}) but no SKAdNetworkItems / AdNetworkIdentifiers: installs from those ads cannot be attributed; add each network's ids from its list` });
if (skIds.length && !aakIds.length)
f.push({ level: 'warn', code: 'aak-ids-missing', msg: `SKAdNetworkItems has ${skIds.length} id(s) but there is no AdNetworkIdentifiers: impressions that networks sign with AdAttributionKit are only eligible for networks in AdNetworkIdentifiers (Configuring a publisher app); the same ids work for both` });
else if (aakIds.length && skIds.length) {
const onlySk = skIds.filter(x => !aakIds.includes(x));
if (onlySk.length) f.push({ level: 'info', code: 'aak-ids-partial', msg: `${onlySk.length} id(s) only in SKAdNetworkItems (${onlySk.slice(0, 3).join(', ')}${onlySk.length > 3 ? ', ...' : ''}): add them to AdNetworkIdentifiers too if those networks use AdAttributionKit` });
}
if (skIds.length || aakIds.length) f.push({ level: 'ok', code: 'network-ids', msg: `${new Set([...skIds, ...aakIds]).size} ad network id(s) (SKAdNetworkItems ${skIds.length}, AdNetworkIdentifiers ${aakIds.length})` });
// ---- advertised app: postback copies ----
const group = isDict(plist.AdAttributionKit) ? plist.AdAttributionKit : undefined;
const copyRaw = group?.AttributionCopyEndpoint ?? plist.AttributionCopyEndpoint;
const reRaw = group?.EligibleForAdAttributionKitReengagementPostbackCopies ?? plist.EligibleForAdAttributionKitReengagementPostbackCopies;
const copyHost = checkUrl(copyRaw, 'AttributionCopyEndpoint', f);
if (copyHost) f.push({ level: 'ok', code: 'copy-endpoint', msg: `AdAttributionKit postback copies go to https://${domainOf(copyHost)}/.well-known/appattribution/report-attribution/ (needs a valid TLS certificate and to accept HTTPS POST)` });
if (reRaw !== undefined && typeof reRaw !== 'boolean') f.push({ level: 'blocker', code: 'reengagement-type', msg: 'EligibleForAdAttributionKitReengagementPostbackCopies must be a Boolean (YES)' });
if (reRaw === true && !copyHost) f.push({ level: 'warn', code: 'reengagement-without-endpoint', msg: 'EligibleForAdAttributionKitReengagementPostbackCopies is on but there is no AttributionCopyEndpoint: no copy can be sent' });
const skHost = checkUrl(plist.NSAdvertisingAttributionReportEndpoint, 'NSAdvertisingAttributionReportEndpoint', f);
if (skHost) f.push({ level: 'ok', code: 'skan-endpoint', msg: `SKAdNetwork postback copies (and Private Click Measurement) go to https://${domainOf(skHost)}/.well-known/...` });
if (copyHost && skHost && domainOf(copyHost) !== domainOf(skHost)) f.push({ level: 'info', code: 'endpoint-domains', msg: `AdAttributionKit copies go to ${domainOf(copyHost)}, SKAdNetwork copies to ${domainOf(skHost)}` });
if (skHost && !copyHost && (s.aakImport || aakIds.length)) f.push({ level: 'info', code: 'copy-endpoint-missing', msg: 'SKAdNetwork postback copies are set up but AdAttributionKit ones are not: add AttributionCopyEndpoint for AdAttributionKit copies' });
if ((copyHost || s.aakImport) && !s.conversionUpdates && !s.mmpSdks.length)
f.push({ level: 'warn', code: 'no-conversion-update', msg: 'no updateConversionValue / updatePostbackConversionValue call and no attribution SDK found: the advertised app must update the conversion value at least once (best at first launch) to start the conversion window' });
// ---- attribution rules ----
const conf = plist.AdAttributionKitConfigurations;
if (conf !== undefined) {
if (!isDict(conf)) f.push({ level: 'blocker', code: 'config-type', msg: 'AdAttributionKitConfigurations must be a dictionary' });
else {
const known = new Set([...skIds, ...aakIds]);
const windows = conf.AttributionWindows;
if (windows !== undefined && !isDict(windows)) f.push({ level: 'blocker', code: 'windows-type', msg: 'AttributionWindows must be a dictionary' });
if (isDict(windows)) for (const [who, cfg] of Object.entries(windows)) {
const at = `AttributionWindows.${who}`;
if (who !== 'global') {
if (who !== who.toLowerCase()) f.push({ level: 'blocker', code: 'windows-id-case', msg: `${at}: ad network ids are lowercase` });
else if (known.size && !known.has(who)) f.push({ level: 'warn', code: 'windows-unknown-network', msg: `${at}: not in AdNetworkIdentifiers / SKAdNetworkItems` });
}
const install = isDict(cfg) ? cfg.install : undefined;
if (!isDict(install)) { f.push({ level: 'warn', code: 'windows-install', msg: `${at}: expected an "install" dictionary` }); continue; }
for (const [k, v] of Object.entries(install)) {
if (k === 'click' && !(typeof v === 'number' && Number.isInteger(v) && v >= 1 && v <= 30)) f.push({ level: 'blocker', code: 'window-click', msg: `${at}.install.click: whole days 1-30` });
else if (k === 'view' && !(typeof v === 'number' && Number.isInteger(v) && v >= 1 && v <= 7)) f.push({ level: 'blocker', code: 'window-view', msg: `${at}.install.view: whole days 1-7` });
else if (k === 'ignoreInteractionType') {
if (v !== 'view' && v !== 'click') f.push({ level: 'blocker', code: 'ignore-type', msg: `${at}.install.ignoreInteractionType: view | click` });
if (who === 'global') f.push({ level: 'warn', code: 'ignore-global', msg: `${at}.install.ignoreInteractionType: only read in ad network entries, not in global` });
} else if (!['click', 'view', 'ignoreInteractionType'].includes(k)) f.push({ level: 'info', code: 'window-key', msg: `${at}.install.${k}: not a documented key` });
}
}
const cool = conf.AttributionCooldown;
if (cool !== undefined) {
if (!isDict(cool)) f.push({ level: 'blocker', code: 'cooldown-type', msg: 'AttributionCooldown must be a dictionary' });
else for (const [k, v] of Object.entries(cool)) {
if (k !== 'install-cooldown-hours' && k !== 're-engagement-cooldown-hours') f.push({ level: 'info', code: 'cooldown-key', msg: `AttributionCooldown.${k}: not a documented key` });
else if (!(typeof v === 'number' && v >= 0 && v <= 720)) f.push({ level: 'blocker', code: 'cooldown-range', msg: `AttributionCooldown.${k}: hours 0-720` });
}
}
for (const k of Object.keys(conf)) if (!['AttributionWindows', 'AttributionCooldown'].includes(k)) f.push({ level: 'info', code: 'config-key', msg: `AdAttributionKitConfigurations.${k}: not a documented key` });
}
}
if (!skIds.length && !aakIds.length && !copyHost && !skHost && conf === undefined && !s.aakImport && !s.adSdks.length)
f.push({ level: 'info', code: 'none', msg: 'no ad attribution setup found (fine for an app without ads and without ad campaigns)' });
if (typeof plist.NSUserTrackingUsageDescription === 'string' && !s.adSdks.length && !s.mmpSdks.length)
f.push({ level: 'info', code: 'att-only-for-aak', msg: 'NSUserTrackingUsageDescription is set; AdAttributionKit and SKAdNetwork need no ATT prompt (keep it only if you track across apps)' });
return f;
}

63
cli/lib/aso-rank.ts Normal file
View file

@ -0,0 +1,63 @@
// App Store keyword rank check against Apple's public iTunes Search API, as pure parts. The command (cli/aso.ts rank)
// sends the queries one by one, slower than Apple's limit, and stores a snapshot in .storebound/aso/.
// Source: Apple Search API (Performance Partners), checked October 2026:
// https://itunes.apple.com/search?term=<text>&country=<2-letter>&media=software&entity=software&limit=1..200 (default 50)
// "approximately 20 calls per minute (subject to change)". https://performance-partners.apple.com/search-api
// What this is and is not: the order of the Search API results is close to, but not the same as, App Store search
// (no personalisation, no search ads, no "in-app events" rows), so read ranks as a trend, not a promise. The API returns
// title (trackName), developer (sellerName), bundleId, rating and description, but no subtitle: competitor subtitles
// are not available through a public API, so they are not shown (storebound scrapes nothing).
// Result fields used (as the API returns them; Apple's table lists only the general ones): trackId, trackName,
// bundleId, sellerName, averageUserRating, userRatingCount, primaryGenreName.
export const SEARCH_API = 'https://itunes.apple.com/search';
/** Apple: about 20 calls per minute. One call every 3.5 s stays below it with room for retries. */
export const MIN_DELAY_MS = 3_500;
export const MAX_RESULTS = 200;
export interface SearchApp { trackId: number; trackName: string; bundleId?: string; sellerName?: string; averageUserRating?: number; userRatingCount?: number; primaryGenreName?: string }
export function searchUrl(term: string, country: string, limit = MAX_RESULTS): string {
if (!/^[a-z]{2}$/i.test(country)) throw new Error(`storefront "${country}": a two-letter country code (us, de, tr)`);
return `${SEARCH_API}?${new URLSearchParams({ term, country: country.toLowerCase(), media: 'software', entity: 'software', limit: String(Math.min(MAX_RESULTS, Math.max(1, limit))) })}`;
}
/** Keywords of one App Store locale's keyword field ("a,b,c"), trimmed and de-duplicated, plus extra terms. Pure. */
export function keywordList(field: string | undefined, extra: string[] = []): string[] {
const out: string[] = [];
for (const k of [...(field ?? '').split(','), ...extra].map(s => s.trim()).filter(Boolean)) if (!out.some(x => x.toLowerCase() === k.toLowerCase())) out.push(k);
return out;
}
/** "us=en-US,de=de-DE" or "us,de" -> storefront + listing locale (default locale for the bare ones). Pure. */
export function parseStorefronts(spec: string[], defaultLocale: string): { storefront: string; locale: string }[] {
const list = spec.length ? spec : ['us'];
return list.map(s => { const [sf, loc] = s.split('='); return { storefront: sf!.trim().toLowerCase(), locale: (loc ?? defaultLocale).trim() }; });
}
/** 1-based rank of the app in the results (by Apple ID, else bundle id), or null when not in the first N. Pure. */
export function rankOf(results: SearchApp[], app: { appId?: string; bundleId?: string }): number | null {
const i = results.findIndex(r => (app.appId && String(r.trackId) === app.appId) || (app.bundleId && r.bundleId === app.bundleId));
return i >= 0 ? i + 1 : null;
}
export interface Competitor { rank: number; title: string; developer: string; rating: number | null; ratings: number; genre: string }
/** The first n results that are not the app itself. Pure. */
export function competitors(results: SearchApp[], app: { appId?: string; bundleId?: string }, n = 3): Competitor[] {
return results.map((r, i) => ({ r, i })).filter(({ r }) => !((app.appId && String(r.trackId) === app.appId) || (app.bundleId && r.bundleId === app.bundleId))).slice(0, n)
.map(({ r, i }) => ({ rank: i + 1, title: r.trackName, developer: r.sellerName ?? '', rating: r.averageUserRating ?? null, ratings: r.userRatingCount ?? 0, genre: r.primaryGenreName ?? '' }));
}
export interface RankRow { storefront: string; locale: string; keyword: string; rank: number | null; results: number; competitors: Competitor[] }
/** Rank change between two snapshots: positive = moved up. Pure. */
export function rankDelta(now: RankRow[], before: RankRow[] | undefined): Map<string, number | null> {
const prev = new Map((before ?? []).map(r => [`${r.storefront}|${r.keyword.toLowerCase()}`, r.rank] as const));
const out = new Map<string, number | null>();
for (const r of now) {
const p = prev.get(`${r.storefront}|${r.keyword.toLowerCase()}`);
out.set(`${r.storefront}|${r.keyword.toLowerCase()}`, p === undefined || p === null || r.rank === null ? null : p - r.rank);
}
return out;
}

89
cli/lib/build-ops.ts Normal file
View file

@ -0,0 +1,89 @@
// TestFlight build housekeeping as pure parts: waiting for an uploaded build to finish processing, and expiring old
// builds. The command (cli/apple/testflight.ts wait | expire) reads, calls these and prints / sends.
// API (App Store Connect API 4.5.1 OpenAPI spec and docs, checked October 2026):
// GET /v1/builds filter[app], filter[version], filter[expired], filter[preReleaseVersion.platform], sort=-uploadedDate,
// include=preReleaseVersion,buildBetaDetail,appStoreVersion
// https://developer.apple.com/documentation/appstoreconnectapi/get-v1-builds
// Build.processingState: PROCESSING | FAILED | INVALID | VALID
// PATCH /v1/builds/{id} { expired: true } "Expire a build or change its encryption exemption setting."
// https://developer.apple.com/documentation/appstoreconnectapi/patch-v1-builds-_id_
// Expiring is permanent: testers lose the build, it cannot be un-expired. So `expire` is a dry run first, then a
// terminal confirmation; it is not an MCP tool.
import type { Req } from '../apple/jsonapi';
export type WaitOutcome = 'missing' | 'processing' | 'valid' | 'failed';
export interface BuildSeen { found: boolean; processingState?: string; internal?: string | null; external?: string | null }
/** One poll result -> what it means for the waiter. A build that is not listed yet is normal for some minutes after
* the upload (App Store Connect lists it once processing starts). */
export function waitOutcome(b: BuildSeen): WaitOutcome {
if (!b.found) return 'missing';
if (b.processingState === 'VALID') return 'valid';
if (b.processingState === 'FAILED' || b.processingState === 'INVALID') return 'failed';
return 'processing';
}
/** Poll delay: 20 s at first, x1.5 per poll, at most 2 minutes (processing usually takes 5 to 30 minutes). */
export function waitDelay(prevMs: number | null): number {
return prevMs === null ? 20_000 : Math.min(Math.round(prevMs * 1.5), 120_000);
}
/** Exit codes of `testflight wait`: 0 VALID, 1 FAILED / INVALID, 7 timeout (the same as `apple status --wait-review`). */
export const BUILD_WAIT_EXIT = { valid: 0, failed: 1, timeout: 7 } as const;
/** What the build state means for the next step, one line. */
export function validHint(b: BuildSeen): string {
if (b.internal === 'MISSING_EXPORT_COMPLIANCE' || b.external === 'MISSING_EXPORT_COMPLIANCE')
return 'export compliance missing: storebound apple encryption --build N (from apple.usesNonExemptEncryption)';
return 'ready: storebound apple testflight distribute --build N --group <name>, or apple listing --build N';
}
export interface ExpireCandidate {
id: string; build: string; version?: string; uploaded: string; processingState?: string;
/** Attached to an App Store version (in review, live or being prepared): never expired by storebound. */
attached: boolean;
}
export interface ExpirePlan { expire: ExpireCandidate[]; keep: ExpireCandidate[]; protected: { b: ExpireCandidate; why: string }[]; reqs: Req[] }
/**
* Which builds to expire. `builds` = the app's builds that are not expired yet (any order). keep = keep the newest N
* builds (by upload date; protected builds count as kept), olderThanDays = only builds uploaded before now - D days.
* With both, a build must be beyond the newest N AND older than D days. Builds attached to an App Store version and
* builds still processing are never expired. Pure.
*/
export function planExpire(builds: ExpireCandidate[], o: { keep?: number; olderThanDays?: number; now?: number }): ExpirePlan {
if (o.keep === undefined && o.olderThanDays === undefined) throw new Error('--keep <n> or --older-than <days> (or both)');
if (o.keep !== undefined && !(Number.isInteger(o.keep) && o.keep >= 1)) throw new Error('--keep: a whole number >= 1 (the newest build always stays)');
if (o.olderThanDays !== undefined && !(o.olderThanDays >= 1)) throw new Error('--older-than: days >= 1');
const now = o.now ?? Date.now();
const sorted = [...builds].sort((a, b) => b.uploaded.localeCompare(a.uploaded));
const plan: ExpirePlan = { expire: [], keep: [], protected: [], reqs: [] };
sorted.forEach((b, i) => {
if (b.attached) { plan.protected.push({ b, why: 'attached to an App Store version' }); return; }
if (b.processingState && b.processingState !== 'VALID' && b.processingState !== 'FAILED' && b.processingState !== 'INVALID') { plan.protected.push({ b, why: `still ${b.processingState}` }); return; }
if (i === 0) { plan.keep.push(b); return; }
const beyondKeep = o.keep === undefined || i >= o.keep;
const old = o.olderThanDays === undefined || now - Date.parse(b.uploaded) > o.olderThanDays * 86_400_000;
(beyondKeep && old ? plan.expire : plan.keep).push(b);
});
plan.reqs = plan.expire.map(b => ({ method: 'PATCH', path: `/v1/builds/${b.id}`, note: `expire build ${b.build}${b.version ? ` (${b.version})` : ''}, uploaded ${b.uploaded.slice(0, 10)}`,
body: { data: { type: 'builds', id: b.id, attributes: { expired: true } } } }));
return plan;
}
/** Builds response (include=preReleaseVersion,appStoreVersion) -> expire candidates. Pure. */
export function expireCandidates(pages: { data?: { id: string; attributes?: Record<string, unknown>; relationships?: Record<string, { data?: { id: string } | null }> }[]; included?: { type: string; id: string; attributes?: { version?: string } }[] }[]): ExpireCandidate[] {
const out: ExpireCandidate[] = [];
for (const page of pages) {
const pre = new Map((page.included ?? []).filter(x => x.type === 'preReleaseVersions').map(x => [x.id, x.attributes?.version] as const));
for (const b of page.data ?? []) {
const a = b.attributes ?? {};
if (a.expired === true) continue;
out.push({ id: b.id, build: String(a.version ?? '?'), version: pre.get(b.relationships?.preReleaseVersion?.data?.id ?? ''), uploaded: String(a.uploadedDate ?? ''),
processingState: a.processingState as string | undefined, attached: !!b.relationships?.appStoreVersion?.data });
}
}
return out;
}

View file

@ -3,6 +3,8 @@
import { existsSync } from 'node:fs';
import { dirname, isAbsolute, join, resolve } from 'node:path';
import { validateCapture, validateRecord } from '../shots/devices';
import { type AppEventDef, type CustomProductPageDef, validateCpp, validateEvents } from './cpp-events';
import { type IapOfferCodeDef, type PromotedConfig, validateIapOfferCodes, validatePromoted, validateWinBack, type WinBackDef } from './offers';
import { validateSubscriptions } from './subscriptions';
import { type TfConfig, validateTestflight } from './testflight';
import { type AppleSigning, validateSigning } from './signing';
@ -50,6 +52,8 @@ export interface Product {
familySharable?: boolean;
/** Sell this product only on these platforms (default: all of app.platforms). */
platforms?: Platform[];
/** Apple offer codes for this one-time purchase (`storebound apple offer-codes`). */
offerCodes?: IapOfferCodeDef[];
}
export interface Language {
@ -406,6 +410,8 @@ export interface Subscription {
basePlanId?: string;
/** Play grace period (ISO 8601: P3D, P7D, P14D, P30D). Default: Play's default. */
gracePeriod?: string;
/** Apple win-back offers for lapsed subscribers (`storebound apple win-back`; the subscription must be approved). */
winBack?: WinBackDef[];
}
/** One subscription group. Apple: a subscription group (people can hold one subscription per group and move between
@ -476,6 +482,12 @@ export interface ShipConfig {
signing?: AppleSigning;
/** `storebound apple build`: workspace / project, scheme, configuration, output folder (found automatically when unset). */
build?: AppleBuildConfig;
/** Promoted in-app purchases on the product page, in order (`storebound apple promoted`; at most 20). */
promoted?: PromotedConfig;
/** Custom product pages (`storebound apple cpp`; at most 70). */
customProductPages?: CustomProductPageDef[];
/** In-app events (`storebound apple events`). */
events?: AppEventDef[];
};
products?: Product[];
/** Auto-renewable subscriptions (`storebound apple subscriptions`, `storebound play subscriptions`). */
@ -576,6 +588,10 @@ export function validateConfig(c: unknown): string[] {
if (cfg.apple.screenshotTypes && !cfg.apple.screenshotTypes.every(t => /^APP_[A-Z0-9_]+$/.test(t))) e.push('apple.screenshotTypes: display types like APP_IPHONE_67');
e.push(...validateTestflight(cfg.apple.testflight));
e.push(...validateSigning(cfg.apple.signing), ...validateAppleBuild(cfg.apple.build));
const catalogIds = new Set([...(cfg.products ?? []).map(p => p.id), ...(cfg.subscriptions ?? []).flatMap(g => (g.subscriptions ?? []).map(x => x.id))]);
e.push(...validatePromoted(cfg.apple.promoted, catalogIds));
e.push(...validateCpp(cfg.apple.customProductPages, ids, Object.keys(cfg.shots?.variants ?? {})));
e.push(...validateEvents(cfg.apple.events, ids));
}
if (cfg.appPrivacy) {
if (cfg.appPrivacy.tracking !== undefined && typeof cfg.appPrivacy.tracking !== 'boolean') e.push('appPrivacy.tracking: true | false');
@ -603,6 +619,7 @@ export function validateConfig(c: unknown): string[] {
if ([...(l.title ?? '')].length > 30) e.push(`${at}.listings.${lang}.title: over 30 characters (App Store limit)`);
if (!l.description) e.push(`${at}.listings.${lang}.description: missing`);
}
e.push(...validateIapOfferCodes(at, p.offerCodes, p.type));
for (const o of p.overrides ?? []) {
if (!/^[A-Z]{2}$/.test(o.region)) e.push(`${at}.overrides: region "${o.region}" must be ISO alpha-2 (TR)`);
if (!/^[A-Z]{3}$/.test(o.currency)) e.push(`${at}.overrides: currency "${o.currency}" must be ISO 4217 (TRY)`);
@ -610,6 +627,7 @@ export function validateConfig(c: unknown): string[] {
}
}
e.push(...validateSubscriptions(cfg.subscriptions, ids, seen));
for (const [gi, g] of (cfg.subscriptions ?? []).entries()) for (const [si, sub] of (g.subscriptions ?? []).entries()) e.push(...validateWinBack(`subscriptions[${gi}].subscriptions[${si}]`, sub.winBack));
if (cfg.prices?.baseTerritory && !/^[A-Z]{3}$/.test(cfg.prices.baseTerritory)) e.push('prices.baseTerritory: App Store territory, alpha-3 (USA)');
if (cfg.dataSafety) {
for (const [t, u] of Object.entries(cfg.dataSafety.data ?? {})) {

202
cli/lib/cpp-events.ts Normal file
View file

@ -0,0 +1,202 @@
// App Store custom product pages and in-app events, as pure parts: config checks, the create requests and what to
// change. The commands (cli/apple/cpp.ts, cli/apple/events.ts) read, plan, show the dry run and send. Creating and
// uploading change nothing customers see; sending a page or an event to App Review, and making a page visible, are
// the owner's (terminal, asks first, not MCP tools).
// Sources (App Store Connect API 4.5.1 OpenAPI spec + docs, App Store Connect Help; checked October 2026):
// Custom product pages: POST /v1/appCustomProductPages (name, app, optional appStoreVersionTemplate /
// customProductPageTemplate, inline appCustomProductPageVersions + appCustomProductPageLocalizations with locale and
// promotionalText; Apple's example request), PATCH /v1/appCustomProductPages/{id} (name, visible),
// POST /v1/appCustomProductPageVersions (deepLink), POST /v1/appCustomProductPageLocalizations (locale,
// promotionalText), screenshots: appScreenshotSets with the appCustomProductPageLocalization relationship.
// https://developer.apple.com/documentation/appstoreconnectapi/post-v1-appcustomproductpages
// Help: up to 70 custom product pages per app; each needs App Review (independent of an app update); the deep link
// works from iOS / iPadOS 18 once approved. https://developer.apple.com/app-store/custom-product-pages/
// In-app events: POST /v1/appEvents (referenceName, badge, deepLink, purchaseRequirement, primaryLocale, priority,
// purpose, territorySchedules [{ territories, publishStart, eventStart, eventEnd }]), POST /v1/appEventLocalizations
// (locale, name, shortDescription, longDescription), POST /v1/appEventScreenshots (fileName, fileSize,
// appEventAssetType EVENT_CARD | EVENT_DETAILS_PAGE) + the upload operations.
// Help "Offer In-App Events": reference name up to 64 characters, event name 30, short description 50, long
// description 120; an event lasts 15 minutes to 31 days; it can be published at most 14 days before it starts;
// up to 10 published and 15 approved events per app; events need App Review.
// https://developer.apple.com/help/app-store-connect/offer-in-app-events/offer-in-app-events
// Media: event card 16:9, 1920x1080 to 3840x2160; details page 9:16, 1080x1920 to 2160x3840; .jpg / .png.
// https://developer.apple.com/help/app-store-connect/reference/in-app-events/in-app-event-media-and-audio-specifications
// Sending either to review: a review submission item with appCustomProductPageVersion | appEvent
// (https://developer.apple.com/documentation/appstoreconnectapi/review-submissions).
// Deprecation note (API 4.5.1): screenshot sets and app event screenshots are deprecated in favour of the App Asset
// Library; they still work and storebound uses them until the asset library is the only way.
import type { Req } from '../apple/jsonapi';
import { one } from '../apple/jsonapi';
import type { Language } from './config';
export const CPP_LIMITS = { pages: 70, promotionalText: 170 } as const;
export const EVENT_LIMITS = { referenceName: 64, name: 30, shortDescription: 50, longDescription: 120, published: 10, approved: 15, maxDays: 31, minMinutes: 15, publishLeadDays: 14 } as const;
export const EVENT_BADGES = ['LIVE_EVENT', 'PREMIERE', 'CHALLENGE', 'COMPETITION', 'NEW_SEASON', 'MAJOR_UPDATE', 'SPECIAL_EVENT'] as const;
export const EVENT_PURPOSES = ['APPROPRIATE_FOR_ALL_USERS', 'ATTRACT_NEW_USERS', 'KEEP_ACTIVE_USERS_INFORMED', 'BRING_BACK_LAPSED_USERS'] as const;
/** Event media: [min w, min h, max w, max h]. */
export const EVENT_MEDIA = { EVENT_CARD: [1920, 1080, 3840, 2160], EVENT_DETAILS_PAGE: [1080, 1920, 2160, 3840] } as const;
export interface CustomProductPageDef {
/** Page name (unique per app; shown only in App Store Connect). */
name: string;
/** Screenshots from this shots variant (`storebound shots render --variant <id>`); default: the base renders. */
variant?: string;
/** Universal link or custom URL that "Open" goes to (iOS / iPadOS 18+, after approval). */
deepLink?: string;
/** Language id -> promotional text (170). Every language with an App Store locale gets a localization. */
promotionalText?: Record<string, string>;
}
export interface AppEventDef {
/** Reference name (unique per app, up to 64 characters). */
referenceName: string;
badge: typeof EVENT_BADGES[number];
purpose?: typeof EVENT_PURPOSES[number];
priority?: 'high' | 'normal';
deepLink?: string;
/** Text shown when the event needs a purchase or subscription, e.g. "Pro subscription". */
purchaseRequirement?: string;
/** Language id of the primary locale (default: the first language with an App Store locale). */
primaryLanguage?: string;
/** When and where: ISO date-times; territories (alpha-3) default to every territory of the app. */
schedule: { publishStart: string; eventStart: string; eventEnd: string; territories?: string[] };
/** Language id -> name (30), shortDescription (50), longDescription (120). */
listings: Record<string, { name: string; shortDescription: string; longDescription: string }>;
/** Images (paths from the project root; "{lang}" is replaced by the language id): card 16:9, details 9:16. */
media?: { card?: string; details?: string };
}
const len = (s: string): number => [...s].length;
export function validateCpp(pages: CustomProductPageDef[] | undefined, langIds: Set<string>, variants: string[]): string[] {
const e: string[] = [];
const names = new Set<string>();
if ((pages ?? []).length > CPP_LIMITS.pages) e.push(`apple.customProductPages: at most ${CPP_LIMITS.pages} per app`);
for (const [i, p] of (pages ?? []).entries()) {
const at = `apple.customProductPages[${i}]`;
if (!p.name) e.push(`${at}.name: missing`);
if (names.has(p.name)) e.push(`${at}.name: duplicate "${p.name}"`);
names.add(p.name);
if (p.variant && !variants.includes(p.variant)) e.push(`${at}.variant: "${p.variant}" is not in shots.variants`);
if (p.deepLink && !/^[a-z][a-z0-9+.-]*:\/\/\S+$/i.test(p.deepLink)) e.push(`${at}.deepLink: a universal link (https://...) or custom URL (myapp://...)`);
for (const [l, t] of Object.entries(p.promotionalText ?? {})) {
if (!langIds.has(l)) e.push(`${at}.promotionalText.${l}: not in languages`);
if (len(t) > CPP_LIMITS.promotionalText) e.push(`${at}.promotionalText.${l}: ${len(t)} > ${CPP_LIMITS.promotionalText}`);
}
}
return e;
}
export function validateEvents(events: AppEventDef[] | undefined, langIds: Set<string>): string[] {
const e: string[] = [];
const names = new Set<string>();
for (const [i, ev] of (events ?? []).entries()) {
const at = `apple.events[${i}]`;
if (!ev.referenceName || len(ev.referenceName) > EVENT_LIMITS.referenceName) e.push(`${at}.referenceName: 1-${EVENT_LIMITS.referenceName} characters`);
if (names.has(ev.referenceName)) e.push(`${at}.referenceName: duplicate`);
names.add(ev.referenceName);
if (!EVENT_BADGES.includes(ev.badge)) e.push(`${at}.badge: ${EVENT_BADGES.join(' | ')}`);
if (ev.purpose && !EVENT_PURPOSES.includes(ev.purpose)) e.push(`${at}.purpose: ${EVENT_PURPOSES.join(' | ')}`);
if (ev.priority && ev.priority !== 'high' && ev.priority !== 'normal') e.push(`${at}.priority: high | normal`);
if (ev.primaryLanguage && !langIds.has(ev.primaryLanguage)) e.push(`${at}.primaryLanguage: not in languages`);
const s = ev.schedule;
const t = (x: string | undefined) => (x ? Date.parse(x) : NaN);
if (!s || [s.publishStart, s.eventStart, s.eventEnd].some(x => Number.isNaN(t(x)))) e.push(`${at}.schedule: publishStart, eventStart, eventEnd as ISO date-times`);
else {
const dur = t(s.eventEnd) - t(s.eventStart);
if (dur < EVENT_LIMITS.minMinutes * 60_000) e.push(`${at}.schedule: an event lasts at least ${EVENT_LIMITS.minMinutes} minutes`);
if (dur > EVENT_LIMITS.maxDays * 86_400_000) e.push(`${at}.schedule: an event lasts at most ${EVENT_LIMITS.maxDays} days`);
if (t(s.publishStart) > t(s.eventStart)) e.push(`${at}.schedule: publishStart after eventStart`);
if (t(s.eventStart) - t(s.publishStart) > EVENT_LIMITS.publishLeadDays * 86_400_000) e.push(`${at}.schedule: published at most ${EVENT_LIMITS.publishLeadDays} days before it starts`);
if (s.territories && !s.territories.every(x => /^[A-Z]{3}$/.test(x))) e.push(`${at}.schedule.territories: alpha-3 (USA)`);
}
if (!ev.listings || !Object.keys(ev.listings).length) e.push(`${at}.listings: at least one language`);
for (const [l, x] of Object.entries(ev.listings ?? {})) {
if (!langIds.has(l)) e.push(`${at}.listings.${l}: not in languages`);
for (const k of ['name', 'shortDescription', 'longDescription'] as const) {
if (!x[k]) e.push(`${at}.listings.${l}.${k}: missing`);
else if (len(x[k]) > EVENT_LIMITS[k]) e.push(`${at}.listings.${l}.${k}: ${len(x[k])} > ${EVENT_LIMITS[k]}`);
}
}
}
return e;
}
/** POST /v1/appCustomProductPages with its first version and one localization per locale (Apple's example shape).
* templateVersionId copies the screenshots / previews of an App Store version (optional). */
export function cppCreateBody(appId: string, p: CustomProductPageDef, locales: { locale: string; promotionalText?: string }[], templateVersionId?: string) {
const locIds = locales.map((_, i) => `\${cpp-loc-${i}}`);
return {
data: { type: 'appCustomProductPages', attributes: { name: p.name }, relationships: {
app: one('apps', appId), ...(templateVersionId ? { appStoreVersionTemplate: one('appStoreVersions', templateVersionId) } : {}),
appCustomProductPageVersions: { data: [{ type: 'appCustomProductPageVersions', id: '${cpp-version}' }] } } },
included: [
{ type: 'appCustomProductPageVersions', id: '${cpp-version}', ...(p.deepLink ? { attributes: { deepLink: p.deepLink } } : {}),
relationships: { appCustomProductPageLocalizations: { data: locIds.map(id => ({ type: 'appCustomProductPageLocalizations', id })) } } },
...locales.map((l, i) => ({ type: 'appCustomProductPageLocalizations', id: locIds[i], attributes: { locale: l.locale, ...(l.promotionalText ? { promotionalText: l.promotionalText } : {}) } })),
],
};
}
/** Localizations of an editable page version to add (POST) or change (PATCH promotional text). Pure. */
export function planCppLocales(versionId: string, have: { id: string; locale: string; promotionalText?: string | null }[], want: { locale: string; promotionalText?: string }[]): Req[] {
const out: Req[] = [];
for (const w of want) {
const cur = have.find(h => h.locale === w.locale);
if (!cur) out.push({ method: 'POST', path: '/v1/appCustomProductPageLocalizations', note: w.locale,
body: { data: { type: 'appCustomProductPageLocalizations', attributes: { locale: w.locale, ...(w.promotionalText ? { promotionalText: w.promotionalText } : {}) }, relationships: { appCustomProductPageVersion: one('appCustomProductPageVersions', versionId) } } } });
else if (w.promotionalText !== undefined && (cur.promotionalText ?? '') !== w.promotionalText) out.push({ method: 'PATCH', path: `/v1/appCustomProductPageLocalizations/${cur.id}`, note: `${w.locale} promotional text`,
body: { data: { type: 'appCustomProductPageLocalizations', id: cur.id, attributes: { promotionalText: w.promotionalText } } } });
}
return out;
}
/** Locales of a page from the config: every language with an App Store locale. */
export function cppLocales(p: CustomProductPageDef, langs: Language[]): { locale: string; langId: string; promotionalText?: string }[] {
return langs.filter(l => l.apple).map(l => ({ locale: l.apple!, langId: l.id, ...(p.promotionalText?.[l.id] ? { promotionalText: p.promotionalText[l.id] } : {}) }));
}
/** Editable states of a custom product page version / in-app event (can still be changed and uploaded to). */
export const CPP_EDITABLE = new Set(['PREPARE_FOR_SUBMISSION', 'REJECTED']);
export const EVENT_EDITABLE = new Set(['DRAFT', 'REJECTED']);
/** POST /v1/appEvents. */
export function eventCreateBody(appId: string, ev: AppEventDef, primaryLocale: string, territories: string[]) {
return { data: { type: 'appEvents', attributes: {
referenceName: ev.referenceName, badge: ev.badge, primaryLocale, priority: (ev.priority ?? 'normal').toUpperCase(),
purpose: ev.purpose ?? 'APPROPRIATE_FOR_ALL_USERS', ...(ev.deepLink ? { deepLink: ev.deepLink } : {}), ...(ev.purchaseRequirement ? { purchaseRequirement: ev.purchaseRequirement } : {}),
territorySchedules: [{ territories, publishStart: ev.schedule.publishStart, eventStart: ev.schedule.eventStart, eventEnd: ev.schedule.eventEnd }],
}, relationships: { app: one('apps', appId) } } };
}
/** Event localizations to add or change. Pure. */
export function planEventLocales(eventId: string, have: { id: string; locale: string; name?: string | null; shortDescription?: string | null; longDescription?: string | null }[],
want: { locale: string; name: string; shortDescription: string; longDescription: string }[]): Req[] {
const out: Req[] = [];
for (const w of want) {
const cur = have.find(h => h.locale === w.locale);
const attrs = { name: w.name, shortDescription: w.shortDescription, longDescription: w.longDescription };
if (!cur) out.push({ method: 'POST', path: '/v1/appEventLocalizations', note: w.locale, body: { data: { type: 'appEventLocalizations', attributes: { locale: w.locale, ...attrs }, relationships: { appEvent: one('appEvents', eventId) } } } });
else {
const changed = Object.fromEntries(Object.entries(attrs).filter(([k, v]) => (cur as Record<string, unknown>)[k] !== v));
if (Object.keys(changed).length) out.push({ method: 'PATCH', path: `/v1/appEventLocalizations/${cur.id}`, note: `${w.locale} ${Object.keys(changed).join(', ')}`, body: { data: { type: 'appEventLocalizations', id: cur.id, attributes: changed } } });
}
}
return out;
}
/** Event media size check (card 16:9 landscape, details 9:16 portrait). Pure. */
export function checkEventMedia(kind: keyof typeof EVENT_MEDIA, w: number, h: number, format: string): string[] {
const [minW, minH, maxW, maxH] = EVENT_MEDIA[kind];
const e: string[] = [];
if (format !== 'png' && format !== 'jpeg') e.push('PNG or JPEG only');
if (w < minW || h < minH || w > maxW || h > maxH) e.push(`${w}x${h}: ${minW}x${minH} to ${maxW}x${maxH}`);
if (Math.abs(w / h - minW / minH) > 0.01) e.push(`${w}x${h}: aspect ${kind === 'EVENT_CARD' ? '16:9' : '9:16'}`);
return e;
}
/** POST /v1/reviewSubmissionItems for a custom product page version or an in-app event (into a draft submission). */
export const reviewItemReq = (submissionId: string, kind: 'appCustomProductPageVersion' | 'appEvent', id: string, label: string): Req => ({
method: 'POST', path: '/v1/reviewSubmissionItems', note: label,
body: { data: { type: 'reviewSubmissionItems', relationships: { reviewSubmission: one('reviewSubmissions', submissionId), [kind]: one(kind === 'appEvent' ? 'appEvents' : 'appCustomProductPageVersions', id) } } },
});

View file

@ -27,8 +27,9 @@ function fileStore(root: string): Store {
try { return JSON.parse(readFileSync(p, 'utf8')) as Store; } catch (e) { throw new Error(`${p}: ${(e as Error).message}`); }
}
/** The store credential names a profile holds (the same as the env names). */
export const PROFILE_KEYS = ['PLAY_SERVICE_ACCOUNT', 'ASC_KEY_ID', 'ASC_ISSUER_ID', 'ASC_P8'] as const;
/** The store credential names a profile holds (the same as the env names): per developer account, so the vendor number
* for reports too; an app's Android upload keystore stays in the project. */
export const PROFILE_KEYS = ['PLAY_SERVICE_ACCOUNT', 'ASC_KEY_ID', 'ASC_ISSUER_ID', 'ASC_P8', 'ASC_VENDOR_NUMBER'] as const;
export const PROFILE_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
export const profileDir = (): string => process.env.STOREBOUND_CREDENTIALS_DIR || join(homedir(), '.storebound', 'credentials');
@ -156,3 +157,11 @@ export function androidSigning(root: string): AndroidSigning | null {
const abs = storeFile.replace(/^~(?=\/)/, homedir());
return { storeFile: abs.startsWith('/') ? abs : join(root, abs), storePassword, keyAlias, keyPassword: value(root, 'ANDROID_KEY_PASSWORD') ?? storePassword };
}
/** App Store Connect vendor number for sales and finance reports (Payments and Financial Reports, top left): the
* credential profile, env ASC_VENDOR_NUMBER, else "ASC_VENDOR_NUMBER" in .storebound/credentials.json. An account
* id, so never in the config. */
export function ascVendorNumber(root: string): string | null {
const v = value(root, 'ASC_VENDOR_NUMBER');
return v && /^\d{5,12}$/.test(v.trim()) ? v.trim() : null;
}

32
cli/lib/diff.ts Normal file
View file

@ -0,0 +1,32 @@
// Line diff for "pull" commands (live store text vs the local files). Pure, no dependency: longest common subsequence
// over lines, printed like a unified diff without hunks (" " same, "-" only local, "+" only on the store).
export function lineDiff(before: string, after: string): string[] {
const a = before.split('\n'), b = after.split('\n');
if (a.length * b.length > 4_000_000) return [...a.map(l => `-${l}`), ...b.map(l => `+${l}`)];
const n = a.length, m = b.length;
const lcs: Uint32Array[] = Array.from({ length: n + 1 }, () => new Uint32Array(m + 1));
for (let i = n - 1; i >= 0; i--) for (let j = m - 1; j >= 0; j--) lcs[i]![j] = a[i] === b[j] ? lcs[i + 1]![j + 1]! + 1 : Math.max(lcs[i + 1]![j]!, lcs[i]![j + 1]!);
const out: string[] = [];
let i = 0, j = 0;
while (i < n && j < m) {
if (a[i] === b[j]) { out.push(` ${a[i]}`); i++; j++; }
else if (lcs[i + 1]![j]! >= lcs[i]![j + 1]!) out.push(`-${a[i++]}`);
else out.push(`+${b[j++]}`);
}
while (i < n) out.push(`-${a[i++]}`);
while (j < m) out.push(`+${b[j++]}`);
return out;
}
/** Only the changed lines with `context` unchanged lines around them ("..." between gaps). Empty when equal. */
export function compactDiff(before: string, after: string, context = 2): string[] {
const d = lineDiff(before, after);
if (!d.some(l => l[0] !== ' ')) return [];
const keep = new Set<number>();
d.forEach((l, i) => { if (l[0] !== ' ') for (let k = i - context; k <= i + context; k++) keep.add(k); });
const out: string[] = [];
let last = -1;
d.forEach((l, i) => { if (!keep.has(i)) return; if (last >= 0 && i > last + 1) out.push('...'); out.push(l); last = i; });
return out;
}

164
cli/lib/listing-pull.ts Normal file
View file

@ -0,0 +1,164 @@
// "Pull": the live store texts back into the local sources, as pure merges. The commands (apple listing pull, play
// listing pull, catalog pull) read the stores, call these, print the diff and write only with --write.
// - App Store: appInfoLocalizations (name, subtitle) + appStoreVersionLocalizations (description, keywords,
// promotionalText, whatsNew) -> store/appstore.md, one "## <locale>" section per locale, "### <field>" blocks.
// - Google Play: edits.listings (title, shortDescription, fullDescription) -> store/listing.md sections with
// "<!-- play: <codes> -->". A section serving several Play codes is only changed when they agree on the store.
// - In-app purchases and subscriptions: the store texts as a proposal for storebound.config.ts (a TypeScript file is
// never rewritten by a tool): the diff per product and language, and a JSON proposal file with --write.
// Only fields the store has a value for are written; a local field the store leaves empty is kept.
import type { AppleCopy, AppleField } from './copy';
import { APPLE_LIMITS, len, PLAY_LIMITS } from './copy';
import type { Language, ShipConfig } from './config';
import { playCodes } from './config';
export interface FieldChange { section: string; field: string; from: string | null; to: string }
export interface MergeResult { md: string; changes: FieldChange[]; added: string[]; conflicts: string[] }
const fence = (t: string): string => '```\n' + t + '\n```';
const BLOCK = (heading: RegExp) => new RegExp(`(^### (?:${heading.source})[^\\n]*\\n)\`\`\`[^\\n]*\\n([\\s\\S]*?)\\n?\`\`\``, 'm' + (heading.flags.includes('i') ? 'i' : ''));
/** Replace (or append) the fenced block under the first "### " heading matching `heading` in one section. */
function setBlock(sec: string, heading: RegExp, newHeading: string, text: string): { sec: string; from: string | null } {
const re = BLOCK(heading);
const m = re.exec(sec);
if (m) return { sec: sec.replace(re, (_a, h: string) => h + fence(text)), from: m[2]!.trim() };
const body = sec.replace(/\s*$/, '');
return { sec: `${body}\n\n### ${newHeading}\n${fence(text)}\n\n`, from: null };
}
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 {
const parts = md.split(/^(?=## )/m);
const res: MergeResult = { md: '', changes: [], added: [], conflicts: [] };
const seen = new Set<string>();
const out = parts.map(sec => {
if (!sec.startsWith('## ')) return sec;
const loc = sec.slice(3).split(/[\s·]/)[0]!.trim();
const r = remote[loc];
if (!r) return sec;
seen.add(loc);
for (const f of APPLE_ORDER) {
const v = r[f];
if (v === undefined || v === null || v === '') 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;
}
return sec;
});
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]);
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';
for (const f of fields) res.changes.push({ section: loc, field: f, from: null, to: r[f]! });
}
res.md = text.endsWith('\n') ? text : text + '\n';
return res;
}
export interface PlayRemote { language: string; title?: string; shortDescription?: string; fullDescription?: string }
const PLAY_FIELDS: { key: keyof PlayRemote; re: RegExp; heading: string; limit: number }[] = [
{ key: 'title', re: /[^\n]*\btitle\b/i, heading: `Title (max ${PLAY_LIMITS.title})`, limit: PLAY_LIMITS.title },
{ key: 'shortDescription', re: /[^\n]*\bshort\b/i, heading: `Short description (max ${PLAY_LIMITS.short})`, limit: PLAY_LIMITS.short },
{ key: 'fullDescription', re: /[^\n]*\bfull\b/i, heading: `Full description (max ${PLAY_LIMITS.full})`, limit: PLAY_LIMITS.full },
];
/** Live Play listings merged into the Play listing file. A title equal to `defaultTitle` (app.name) is only written
* where the section already has a title block. Pure. */
export function mergePlayListing(md: string, remote: PlayRemote[], defaultTitle: string): MergeResult {
const byLang = new Map(remote.map(l => [l.language, l] as const));
const res: MergeResult = { md: '', changes: [], added: [], conflicts: [] };
const seen = new Set<string>();
const parts = md.split(/^(?=## )/m).map(sec => {
const m = /^<!--\s*play:\s*([^>]+?)\s*-->$/m.exec(sec);
if (!m) return sec;
const codes = m[1]!.split(',').map(s => s.trim()).filter(Boolean);
const hits = codes.map(c => byLang.get(c)).filter((x): x is PlayRemote => !!x);
for (const c of codes) if (byLang.has(c)) seen.add(c);
if (!hits.length) return sec;
for (const f of PLAY_FIELDS) {
const values = [...new Set(hits.map(h => (h[f.key] ?? '').trim()).filter(Boolean))];
if (!values.length) continue;
if (values.length > 1) { res.conflicts.push(`${codes.join(', ')}: ${f.key} differs between these Play languages on the store; left as it is (give each its own section)`); continue; }
const v = values[0]!;
const has = BLOCK(f.re).test(sec);
if (f.key === 'title' && !has && v === defaultTitle) continue;
const { sec: next, from } = setBlock(sec, f.re, f.heading, v);
if (from !== v) res.changes.push({ section: codes.join(', '), field: f.key, from, to: v });
sec = next;
}
return sec;
});
let text = parts.join('');
for (const l of [...remote].sort((a, b) => a.language.localeCompare(b.language))) {
if (seen.has(l.language)) continue;
res.added.push(l.language);
const blocks = PLAY_FIELDS.filter(f => l[f.key] && !(f.key === 'title' && l.title === defaultTitle)).map(f => `### ${f.heading}\n${fence(String(l[f.key]))}`);
text = text.replace(/\s*$/, '') + `\n\n## ${l.language}\n<!-- play: ${l.language} -->\n\n${blocks.join('\n\n')}\n`;
for (const f of PLAY_FIELDS) if (l[f.key]) res.changes.push({ section: l.language, field: f.key, from: null, to: String(l[f.key]) });
}
res.md = text.endsWith('\n') ? text : text + '\n';
return res;
}
/** Store values over a store limit (the pull still writes them; `check` will flag them). */
export function overLimits(changes: FieldChange[], store: 'apple' | 'play'): string[] {
const lim: Record<string, number> = store === 'apple' ? APPLE_LIMITS : { title: PLAY_LIMITS.title, shortDescription: PLAY_LIMITS.short, fullDescription: PLAY_LIMITS.full };
return changes.filter(c => lim[c.field] !== undefined && len(c.to) > lim[c.field]!).map(c => `${c.section} ${c.field}: ${len(c.to)} > ${lim[c.field]}`);
}
// ---- in-app purchases and subscriptions -> config proposal ----
export interface RemoteText { title: string; description: string; benefits?: string[] }
/** Store texts per product id and store language code (App Store locale or Play language code). */
export type RemoteCatalog = Record<string, Record<string, RemoteText>>;
export interface CatalogProposal {
/** product id -> language id -> the store's texts (only where they differ from the config or are missing there). */
listings: Record<string, Record<string, { title: string; description: string; benefits?: string[] }>>;
changes: { id: string; lang: string; field: string; from: string | null; to: string; store: 'apple' | 'play' }[];
/** Store languages the config has no language entry for (not mapped). */
unmapped: string[];
/** Products on the store that are not in the config. */
unknown: string[];
}
/** Store language code -> config language id (App Store locale or any Play code of the entry). */
export function langIdOf(langs: Language[], store: 'apple' | 'play', code: string): string | undefined {
return langs.find(l => (store === 'apple' ? l.apple === code : playCodes(l).includes(code)))?.id;
}
/** The store texts of in-app purchases and subscriptions against the config's listings. Apple wins over Play when
* both differ for the same language (shown as two changes). Pure. */
export function catalogProposal(config: Pick<ShipConfig, 'languages' | 'products' | 'subscriptions'>, remote: { apple?: RemoteCatalog; play?: RemoteCatalog }): CatalogProposal {
const local = new Map<string, Record<string, { title: string; description: string; benefits?: string[] }>>();
for (const p of config.products ?? []) local.set(p.id, p.listings);
for (const g of config.subscriptions ?? []) for (const s of g.subscriptions) local.set(s.id, s.listings);
const out: CatalogProposal = { listings: {}, changes: [], unmapped: [], unknown: [] };
for (const store of ['play', 'apple'] as const) {
for (const [id, byCode] of Object.entries(remote[store] ?? {})) {
const mine = local.get(id);
if (!mine) { if (!out.unknown.includes(id)) out.unknown.push(id); continue; }
for (const [code, t] of Object.entries(byCode)) {
const lang = langIdOf(config.languages, store, code);
if (!lang) { const u = `${store}:${code}`; if (!out.unmapped.includes(u)) out.unmapped.push(u); continue; }
const cur = mine[lang];
const fields: [string, string | null, string][] = [['title', cur?.title ?? null, t.title], ['description', cur?.description ?? null, t.description]];
if (store === 'play' && t.benefits?.length) fields.push(['benefits', cur?.benefits?.join(' | ') ?? null, t.benefits.join(' | ')]);
const diff = fields.filter(([, from, to]) => to && from !== to);
if (!diff.length) continue;
for (const [field, from, to] of diff) out.changes.push({ id, lang, field, from, to, store });
const prev = out.listings[id]?.[lang] ?? { title: cur?.title ?? t.title, description: cur?.description ?? t.description, ...(cur?.benefits ? { benefits: cur.benefits } : {}) };
out.listings[id] = { ...out.listings[id], [lang]: { ...prev, title: t.title || prev.title, description: t.description || prev.description, ...(store === 'play' && t.benefits?.length ? { benefits: t.benefits } : {}) } };
}
}
}
return out;
}

301
cli/lib/offers.ts Normal file
View file

@ -0,0 +1,301 @@
// App Store offers beyond introductory / promotional offers, as pure parts: offer codes for one-time purchases,
// win-back offers for subscriptions, promoted in-app purchases and app pre-orders. The commands (cli/apple/offers.ts)
// read, plan, print the dry run and send; everything that becomes visible to customers asks first and none of it is
// an MCP tool.
// Sources (App Store Connect API 4.5.1 OpenAPI spec + docs, App Store Connect Help; checked October 2026):
// In-app purchase offer codes: POST /v1/inAppPurchaseOfferCodes (name, customerEligibilities NON_SPENDER |
// ACTIVE_SPENDER | CHURNED_SPENDER, inAppPurchase, prices = inAppPurchaseOfferPrices: territory + pricePoint),
// POST /v1/inAppPurchaseOfferCodeCustomCodes (customCode, numberOfCodes, expirationDate?),
// POST /v1/inAppPurchaseOfferCodeOneTimeUseCodes (numberOfCodes, expirationDate, environment PRODUCTION | SANDBOX),
// GET /v1/inAppPurchaseOfferCodeOneTimeUseCodes/{id}/values (the codes), GET /v2/inAppPurchases/{id}/offerCodes.
// Help "Create offer codes for In-App Purchases": up to 10 active offers per app, 1 million codes per app per
// quarter, one-time-use batches of 500-25,000 valid at most 6 months, custom codes up to 64 characters without
// special characters and up to 25,000 redemptions, paid or free offers. Consumables, non-consumables and
// non-renewing subscriptions (iOS 16.3+).
// https://developer.apple.com/help/app-store-connect/manage-in-app-purchases/create-offer-codes-for-in-app-purchases
// Win-back offers: POST /v1/winBackOffers (referenceName, offerId, duration, offerMode, periodCount,
// customerEligibilityPaidSubscriptionDurationInMonths, customerEligibilityTimeSinceLastSubscribedInMonths {minimum,
// maximum}, customerEligibilityWaitBetweenOffersInMonths?, startDate, endDate?, priority HIGH | NORMAL,
// promotionIntent NOT_PROMOTED | USE_AUTO_GENERATED_ASSETS; subscription; prices = winBackOfferPrices with a
// subscriptionPricePoint), GET /v1/subscriptions/{id}/winBackOffers.
// https://developer.apple.com/documentation/appstoreconnectapi/post-v1-winbackoffers
// Help "Set up win-back offers": the subscription must be approved first; paid duration 1-24 months or 3, 4, 5
// years; time since last subscribed 1-24 months (min and max required); wait between offers 2-24 months; start at
// the earliest tomorrow, run at least 3 days; at most 350 per subscription and 5 at a time per storefront; reference
// name, offer id and price cannot be changed later; an offer id must not be reused in the group.
// https://developer.apple.com/help/app-store-connect/manage-subscriptions/set-up-win-back-offers
// Promoted purchases: POST /v1/promotedPurchases (visibleForAllUsers, enabled?, app, inAppPurchaseV2 | subscription),
// PATCH /v1/promotedPurchases/{id} (visibleForAllUsers, enabled), GET /v1/apps/{id}/promotedPurchases,
// PATCH /v1/apps/{id}/relationships/promotedPurchases (the order). Help "Promote In-App Purchases": up to 20
// promoted at a time, each needs its promotional image, the app must handle purchases started on the App Store
// (PurchaseIntent). https://developer.apple.com/help/app-store-connect/configure-in-app-purchase-settings/promote-in-app-purchases
// Pre-orders: GET /v1/apps/{id}/appAvailabilityV2, GET /v2/appAvailabilities/{id}/territoryAvailabilities
// (available, releaseDate, preOrderEnabled, preOrderPublishDate, contentStatuses), PATCH
// /v1/territoryAvailabilities/{id} (available, releaseDate, preOrderEnabled), POST /v1/endAppAvailabilityPreOrders
// ("End the pre-order for your app and release to store immediately"). Help "Publish for pre-order": a version
// must be approved first; release date 2-180 days ahead (Apple's pre-orders page: up to 365 days for an existing
// app in a new region); not possible where the app is already released.
// https://developer.apple.com/help/app-store-connect/manage-your-apps-availability/publish-for-pre-order
// Google Play pre-registration has no API (androidpublisher v3 lists no such resource): Play Console only.
import type { Req } from '../apple/jsonapi';
import { many, one } from '../apple/jsonapi';
import { APPLE_OFFER_DURATION, APPLE_OFFER_MODE } from './subscriptions';
// ---- config ----
/** Offer code campaign for a one-time purchase (consumable, non-consumable, non-renewing). */
export interface IapOfferCodeDef {
/** Reference name of the campaign (unique per product). */
name: string;
/** NON_SPENDER = never purchased in the app, ACTIVE_SPENDER = purchased in the last 30 days, CHURNED_SPENDER =
* purchased more than 30 days ago. All three = everyone. */
eligibility: ('NON_SPENDER' | 'ACTIVE_SPENDER' | 'CHURNED_SPENDER')[];
/** Free offer (no price) or a paid one in USD (the USA price point and its equalizations). */
free?: boolean;
usd?: number;
/** Limit the offer to these App Store territories (alpha-3). Default: every territory. */
territories?: string[];
/** Custom codes (anyone with the code; created only from a terminal run with --codes that confirms). */
customCodes?: { code: string; count: number; expires?: string }[];
/** One-time-use code batches (500-25,000, expiry at most 6 months; --codes, confirms; the codes are saved to
* .storebound/offer-codes/). */
oneTimeCodes?: { count: number; expires: string; sandbox?: boolean }[];
}
/** Win-back offer for lapsed subscribers of one subscription. */
export interface WinBackDef {
/** Offer identifier (unique in the subscription group, never reused; cannot change later). */
id: string;
/** Reference name (default: the id; cannot change later). */
name?: string;
type: 'free' | 'pay-as-you-go' | 'pay-up-front';
/** free / pay-up-front: P3D ... P1Y; pay-as-you-go: the subscription period (default). */
duration?: string;
/** pay-as-you-go: number of periods (default 1). */
periods?: number;
/** USD price (per period for pay-as-you-go, total for pay-up-front); fixed after creation. */
usd?: number;
/** Customers who paid at least this many months: 1-24, 36, 48 or 60. */
paidMonths: number;
/** Lapsed between min and max months ago (1-24). */
lapsedMonths: { min: number; max: number };
/** Months between two win-back offers for one customer (2-24, optional). */
waitMonths?: number;
/** YYYY-MM-DD, at the earliest tomorrow. */
start: string;
/** YYYY-MM-DD, at least 3 days after start (optional). */
end?: string;
priority?: 'high' | 'normal';
/** Promote on the App Store with auto-generated assets (needs an approved subscription image). */
promote?: boolean;
}
export interface PromotedConfig {
/** Product / subscription ids in display order (at most 20). */
products: string[];
/** Shown to every user (true) or only to users your app makes it visible for (false). Default true. */
visibleForAllUsers?: boolean;
}
const DAY = 86_400_000;
const isDate = (s: unknown): s is string => typeof s === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(s) && !Number.isNaN(Date.parse(s));
const ELIG = ['NON_SPENDER', 'ACTIVE_SPENDER', 'CHURNED_SPENDER'];
const PAID_MONTHS = new Set([...Array.from({ length: 24 }, (_, i) => i + 1), 36, 48, 60]);
/** Problems with products[].offerCodes. With `today` (when codes are about to be created) also the 6-month expiry
* rule; the config check leaves dates relative to today out, so an old campaign never breaks the config. Pure. */
export function validateIapOfferCodes(at: string, codes: IapOfferCodeDef[] | undefined, type: string, today?: string): string[] {
const e: string[] = [];
const names = new Set<string>();
const max = today ? new Date(Date.parse(today) + 183 * DAY).toISOString().slice(0, 10) : '9999-12-31';
for (const [i, c] of (codes ?? []).entries()) {
const p = `${at}.offerCodes[${i}]`;
if (!c.name || [...c.name].length > 64) e.push(`${p}.name: 1-64 characters`);
if (names.has(c.name)) e.push(`${p}.name: duplicate "${c.name}"`);
names.add(c.name);
if (!Array.isArray(c.eligibility) || !c.eligibility.length || !c.eligibility.every(x => ELIG.includes(x))) e.push(`${p}.eligibility: some of ${ELIG.join(', ')}`);
if (!!c.free === (c.usd !== undefined)) e.push(`${p}: free: true or usd (one of them)`);
if (c.usd !== undefined && !(c.usd > 0)) e.push(`${p}.usd: positive`);
if (c.territories && !c.territories.every(t => /^[A-Z]{3}$/.test(t))) e.push(`${p}.territories: App Store territories, alpha-3 (USA)`);
for (const [k, cc] of (c.customCodes ?? []).entries()) {
if (!/^[A-Za-z0-9]{1,64}$/.test(cc.code ?? '')) e.push(`${p}.customCodes[${k}].code: letters and digits, up to 64`);
if (!(Number.isInteger(cc.count) && cc.count >= 1 && cc.count <= 25000)) e.push(`${p}.customCodes[${k}].count: 1-25000`);
if (cc.expires !== undefined && (!isDate(cc.expires) || cc.expires > max)) e.push(`${p}.customCodes[${k}].expires: YYYY-MM-DD within 6 months`);
}
for (const [k, b] of (c.oneTimeCodes ?? []).entries()) {
const lo = b.sandbox ? 10 : 500, hi = b.sandbox ? 10000 : 25000;
if (!(Number.isInteger(b.count) && b.count >= lo && b.count <= hi)) e.push(`${p}.oneTimeCodes[${k}].count: ${lo}-${hi}`);
if (!isDate(b.expires) || b.expires > max) e.push(`${p}.oneTimeCodes[${k}].expires: YYYY-MM-DD within 6 months (required)`);
}
}
if ((codes ?? []).length && !['consumable', 'non_consumable', 'non_renewing'].includes(type)) e.push(`${at}.offerCodes: one-time purchases only`);
return e;
}
/** Problems with subscriptions[].winBack. With `today` (right before creating) also "start at the earliest
* tomorrow". Pure. */
export function validateWinBack(at: string, offers: WinBackDef[] | undefined, today?: string): string[] {
const e: string[] = [];
const ids = new Set<string>();
for (const [i, o] of (offers ?? []).entries()) {
const p = `${at}.winBack[${i}]`;
if (!/^[A-Za-z0-9._-]{1,64}$/.test(o.id ?? '')) e.push(`${p}.id: letters, digits, ".", "_", "-"`);
if (ids.has(o.id)) e.push(`${p}.id: duplicate "${o.id}"`);
ids.add(o.id);
if (!(o.type in APPLE_OFFER_MODE)) e.push(`${p}.type: free | pay-as-you-go | pay-up-front`);
if (o.type !== 'pay-as-you-go' && !(o.duration && o.duration in APPLE_OFFER_DURATION)) e.push(`${p}.duration: ${Object.keys(APPLE_OFFER_DURATION).join(', ')}`);
if (o.type !== 'free' && !(typeof o.usd === 'number' && o.usd > 0)) e.push(`${p}.usd: positive (a paid offer)`);
if (o.type === 'free' && o.usd !== undefined) e.push(`${p}.usd: not for a free offer`);
if (o.periods !== undefined && !(Number.isInteger(o.periods) && o.periods >= 1 && o.periods <= 12)) e.push(`${p}.periods: 1-12`);
if (!PAID_MONTHS.has(o.paidMonths)) e.push(`${p}.paidMonths: 1-24, 36, 48 or 60`);
const l = o.lapsedMonths;
if (!l || !(Number.isInteger(l.min) && Number.isInteger(l.max) && l.min >= 1 && l.max <= 24 && l.min <= l.max)) e.push(`${p}.lapsedMonths: { min, max } within 1-24`);
if (o.waitMonths !== undefined && !(Number.isInteger(o.waitMonths) && o.waitMonths >= 2 && o.waitMonths <= 24)) e.push(`${p}.waitMonths: 2-24`);
if (!isDate(o.start)) e.push(`${p}.start: YYYY-MM-DD`);
else if (today && o.start <= today) e.push(`${p}.start: at the earliest tomorrow`);
if (o.end !== undefined && (!isDate(o.end) || (isDate(o.start) && Date.parse(o.end) - Date.parse(o.start) < 3 * DAY))) e.push(`${p}.end: YYYY-MM-DD, at least 3 days after start`);
if (o.priority !== undefined && o.priority !== 'high' && o.priority !== 'normal') e.push(`${p}.priority: high | normal`);
}
return e;
}
export function validatePromoted(p: PromotedConfig | undefined, ids: Set<string>): string[] {
if (!p) return [];
const e: string[] = [];
if (!Array.isArray(p.products) || !p.products.length) e.push('apple.promoted.products: at least one product id');
if ((p.products ?? []).length > 20) e.push('apple.promoted.products: at most 20 (App Store limit)');
for (const id of p.products ?? []) if (!ids.has(id)) e.push(`apple.promoted.products: "${id}" is not a product or subscription of the config`);
if (new Set(p.products).size !== (p.products ?? []).length) e.push('apple.promoted.products: duplicates');
return e;
}
// ---- request bodies ----
export interface TerritoryPoint { territory: string; pointId?: string }
/** POST /v1/inAppPurchaseOfferCodes. A free offer sends the territories without a price point (the schema marks the
* price point optional; not verified against a live account). */
export function iapOfferCodeBody(iapId: string, c: IapOfferCodeDef, prices: TerritoryPoint[]) {
const ids = prices.map((_, i) => `\${iapcode-${i}}`);
return {
data: { type: 'inAppPurchaseOfferCodes', attributes: { name: c.name, customerEligibilities: c.eligibility },
relationships: { inAppPurchase: one('inAppPurchases', iapId), prices: { data: ids.map(id => ({ type: 'inAppPurchaseOfferPrices', id })) } } },
included: prices.map((p, i) => {
if (!c.free && !p.pointId) throw new Error(`${c.name}: paid offer in ${p.territory} needs a price point`);
return { type: 'inAppPurchaseOfferPrices', id: ids[i], relationships: { territory: one('territories', p.territory), ...(p.pointId ? { pricePoint: one('inAppPurchasePricePoints', p.pointId) } : {}) } };
}),
};
}
export const iapCustomCodeReq = (offerCodeId: string, cc: { code: string; count: number; expires?: string }): Req => ({ method: 'POST', path: '/v1/inAppPurchaseOfferCodeCustomCodes',
note: `custom code ${cc.code} (${cc.count} redemptions${cc.expires ? `, until ${cc.expires}` : ''})`,
body: { data: { type: 'inAppPurchaseOfferCodeCustomCodes', attributes: { customCode: cc.code, numberOfCodes: cc.count, ...(cc.expires ? { expirationDate: cc.expires } : {}) },
relationships: { offerCode: one('inAppPurchaseOfferCodes', offerCodeId) } } } });
export const iapOneTimeCodesReq = (offerCodeId: string, b: { count: number; expires: string; sandbox?: boolean }): Req => ({ method: 'POST', path: '/v1/inAppPurchaseOfferCodeOneTimeUseCodes',
note: `${b.count} one-time-use ${b.sandbox ? 'sandbox ' : ''}codes until ${b.expires}`,
body: { data: { type: 'inAppPurchaseOfferCodeOneTimeUseCodes', attributes: { numberOfCodes: b.count, expirationDate: b.expires, environment: b.sandbox ? 'SANDBOX' : 'PRODUCTION' },
relationships: { offerCode: one('inAppPurchaseOfferCodes', offerCodeId) } } } });
/** POST /v1/winBackOffers. `subPeriod` = the subscription's period (pay-as-you-go duration). Paid prices: one
* subscriptionPricePoint per territory (the point carries its territory, as in Apple's example request). A free offer
* sends the territories without a price point (not verified against a live account). */
export function winBackBody(subId: string, subPeriod: string, o: WinBackDef, prices: TerritoryPoint[]) {
const ids = prices.map((_, i) => `\${winback-${i}}`);
const duration = o.type === 'pay-as-you-go' ? (o.duration ?? subPeriod) : o.duration!;
return {
data: { type: 'winBackOffers', attributes: {
referenceName: o.name ?? o.id, offerId: o.id, duration: APPLE_OFFER_DURATION[duration], offerMode: APPLE_OFFER_MODE[o.type],
periodCount: o.type === 'pay-as-you-go' ? (o.periods ?? 1) : 1,
customerEligibilityPaidSubscriptionDurationInMonths: o.paidMonths,
customerEligibilityTimeSinceLastSubscribedInMonths: { minimum: o.lapsedMonths.min, maximum: o.lapsedMonths.max },
...(o.waitMonths !== undefined ? { customerEligibilityWaitBetweenOffersInMonths: o.waitMonths } : {}),
startDate: o.start, ...(o.end ? { endDate: o.end } : {}), priority: (o.priority ?? 'normal').toUpperCase(),
promotionIntent: o.promote ? 'USE_AUTO_GENERATED_ASSETS' : 'NOT_PROMOTED',
}, relationships: { subscription: one('subscriptions', subId), prices: { data: ids.map(id => ({ type: 'winBackOfferPrices', id })) } } },
included: prices.map((p, i) => {
if (o.type !== 'free' && !p.pointId) throw new Error(`${o.id}: paid win-back offer in ${p.territory} needs a price point`);
return { type: 'winBackOfferPrices', id: ids[i], relationships: p.pointId ? { subscriptionPricePoint: one('subscriptionPricePoints', p.pointId) } : { territory: one('territories', p.territory) } };
}),
};
}
// ---- promoted purchases ----
export interface PromotedNow { id: string; productId: string; enabled: boolean; visibleForAllUsers: boolean; state?: string }
export interface PromotedPlan { create: Req[]; update: Req[]; order: Req | null; unknown: string[]; extra: string[] }
/** Wanted promoted purchases vs the current ones. New ones are created disabled unless enable; `enable` also turns on
* existing ones. The order request lists the configured ones first, then the others as they are. Pure. */
export function planPromoted(appId: string, cfg: PromotedConfig, now: PromotedNow[], products: Map<string, { apiId: string; kind: 'iap' | 'sub' }>, o: { enable?: boolean } = {}): PromotedPlan {
const plan: PromotedPlan = { create: [], update: [], order: null, unknown: [], extra: [] };
const visible = cfg.visibleForAllUsers ?? true;
const have = new Map(now.map(p => [p.productId, p] as const));
for (const id of cfg.products) {
const cur = have.get(id);
if (cur) {
const attrs: Record<string, boolean> = {};
if (cur.visibleForAllUsers !== visible) attrs.visibleForAllUsers = visible;
if (o.enable && !cur.enabled) attrs.enabled = true;
if (Object.keys(attrs).length) plan.update.push({ method: 'PATCH', path: `/v1/promotedPurchases/${cur.id}`, note: `${id}: ${Object.entries(attrs).map(([k, v]) => `${k}=${v}`).join(', ')}`,
body: { data: { type: 'promotedPurchases', id: cur.id, attributes: attrs } } });
continue;
}
const p = products.get(id);
if (!p) { plan.unknown.push(id); continue; }
plan.create.push({ method: 'POST', path: '/v1/promotedPurchases', note: `promote ${id}${o.enable ? ' (enabled)' : ' (not enabled yet)'}`,
body: { data: { type: 'promotedPurchases', attributes: { visibleForAllUsers: visible, enabled: !!o.enable },
relationships: { app: one('apps', appId), ...(p.kind === 'iap' ? { inAppPurchaseV2: one('inAppPurchases', p.apiId) } : { subscription: one('subscriptions', p.apiId) }) } } } });
}
plan.extra = now.filter(p => !cfg.products.includes(p.productId)).map(p => p.productId);
return plan;
}
/** PATCH /v1/apps/{id}/relationships/promotedPurchases: the display order (configured first, then the rest). */
export function promotedOrderReq(appId: string, cfg: PromotedConfig, now: PromotedNow[]): Req | null {
const byProduct = new Map(now.map(p => [p.productId, p.id] as const));
const ordered = [...cfg.products.map(id => byProduct.get(id)).filter((x): x is string => !!x), ...now.filter(p => !cfg.products.includes(p.productId)).map(p => p.id)];
if (!ordered.length || ordered.join() === now.map(p => p.id).join()) return null;
return { method: 'PATCH', path: `/v1/apps/${appId}/relationships/promotedPurchases`, note: 'promoted purchase order', body: many('promotedPurchases', ordered) };
}
// ---- pre-orders ----
export interface TerritoryAvail { id: string; territory: string; available?: boolean; releaseDate?: string | null; preOrderEnabled?: boolean; preOrderPublishDate?: string | null; contentStatuses?: string[] }
/** Territory availabilities response(s) (include=territory) -> rows. Pure. */
export function territoryRows(pages: { data?: { id: string; attributes?: Record<string, unknown>; relationships?: { territory?: { data?: { id: string } } } }[] }[]): TerritoryAvail[] {
return pages.flatMap(p => (p.data ?? []).map(t => ({ id: t.id, territory: t.relationships?.territory?.data?.id ?? '?', available: t.attributes?.available as boolean | undefined,
releaseDate: (t.attributes?.releaseDate as string | null | undefined) ?? null, preOrderEnabled: t.attributes?.preOrderEnabled as boolean | undefined,
preOrderPublishDate: (t.attributes?.preOrderPublishDate as string | null | undefined) ?? null, contentStatuses: t.attributes?.contentStatuses as string[] | undefined })));
}
/** PATCH requests that put the chosen territories on pre-order with this release date. Territories where the app is
* already out (AVAILABLE) cannot go on pre-order. Pure. */
export function planPreOrder(rows: TerritoryAvail[], releaseDate: string, territories: string[] | null, today = new Date().toISOString().slice(0, 10)): { reqs: Req[]; problems: string[]; warnings: string[] } {
const problems: string[] = [], warnings: string[] = [];
if (!isDate(releaseDate)) problems.push('--release-date: YYYY-MM-DD');
const days = (Date.parse(releaseDate) - Date.parse(today)) / DAY;
if (isDate(releaseDate) && days < 2) problems.push('--release-date: at least 2 days ahead');
if (isDate(releaseDate) && days > 365) problems.push('--release-date: at most 365 days ahead (180 for a new app)');
else if (isDate(releaseDate) && days > 180) warnings.push('more than 180 days ahead: only allowed for an existing app in a new region');
const pick = territories ? rows.filter(r => territories.includes(r.territory)) : rows;
if (territories) for (const t of territories) if (!rows.some(r => r.territory === t)) problems.push(`territory ${t}: not in the app's availability`);
const reqs: Req[] = [];
for (const r of pick) {
if (r.contentStatuses?.includes('AVAILABLE')) { warnings.push(`${r.territory}: already released there, no pre-order possible`); continue; }
if (r.preOrderEnabled && r.releaseDate === releaseDate && r.available) continue;
reqs.push({ method: 'PATCH', path: `/v1/territoryAvailabilities/${r.id}`, note: `${r.territory}: pre-order, release ${releaseDate}`,
body: { data: { type: 'territoryAvailabilities', id: r.id, attributes: { available: true, preOrderEnabled: true, releaseDate } } } });
}
return { reqs, problems, warnings };
}
/** POST /v1/endAppAvailabilityPreOrders: end the pre-order in these territories and release there now. */
export function endPreOrderReq(rows: TerritoryAvail[], territories: string[] | null): Req | null {
const pick = rows.filter(r => r.preOrderEnabled && (!territories || territories.includes(r.territory)));
if (!pick.length) return null;
return { method: 'POST', path: '/v1/endAppAvailabilityPreOrders', note: `end the pre-order and release now in ${pick.map(r => r.territory).join(', ')}`,
body: { data: { type: 'endAppAvailabilityPreOrders', relationships: { territoryAvailabilities: many('territoryAvailabilities', pick.map(r => r.id)) } } } };
}

View file

@ -1,6 +1,6 @@
// Property lists without dependencies: write XML plists (ExportOptions.plist), read XML and binary plists (an IPA's
// Info.plist, the plist inside a .mobileprovision). Only the types those files use: dict, array, string, integer,
// real, true / false, date (as an ISO string) and data (as a Buffer).
// Property lists without dependencies: write XML plists (ExportOptions.plist), read XML and binary plists (a source or
// IPA Info.plist, the plist inside a .mobileprovision). Only the types those files use: dict, array, string, integer,
// real, true / false, date (as an ISO string) and data (as a Buffer). Pure.
export type PlistValue = string | number | boolean | Buffer | PlistValue[] | { [k: string]: PlistValue };
const esc = (s: string): string => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
@ -27,9 +27,11 @@ const unesc = (s: string): string => s.replace(/&lt;/g, '<').replace(/&gt;/g, '>
/** Parses an XML plist (tolerant of comments and whitespace). Throws on anything it does not understand. */
export function parseXmlPlist(text: string): PlistValue {
const body = /<plist[^>]*>([\s\S]*)<\/plist>/.exec(text);
if (!body) throw new Error('not an XML plist');
const toks = [...body[1]!.replace(/<!--[\s\S]*?-->/g, '').matchAll(/<(\/?)([a-zA-Z]+)(\/?)>|([^<]+)/g)];
if (text.startsWith('bplist')) throw new Error('binary plist: read the file as bytes (parsePlist(Buffer)) or convert it with `plutil -convert xml1`');
const body = /<plist[^>]*>([\s\S]*)<\/plist>/.exec(text)?.[1] ?? text.replace(/<\?xml[^>]*\?>|<!DOCTYPE[^>]*>/g, '');
if (!/<(dict|array|string|integer|real|true|false|date|data)\b/.test(body)) throw new Error('not an XML plist');
// tags may carry attributes or a space before "/>" (hand-edited files)
const toks = [...body.replace(/<!--[\s\S]*?-->/g, '').matchAll(/<(\/?)([a-zA-Z]+)(?:\s[^>]*?)?\s*(\/?)>|([^<]+)/g)];
let i = 0;
const skipWs = () => { while (i < toks.length && toks[i]![4] !== undefined && !toks[i]![4]!.trim()) i++; };
const text_ = (tag: string): string => {
@ -111,8 +113,9 @@ export function parseBinaryPlist(b: Buffer): PlistValue {
return obj(top);
}
/** XML or binary plist bytes. */
export function parsePlist(b: Buffer): PlistValue {
/** XML or binary plist bytes, or XML plist text. */
export function parsePlist(b: Buffer | string): PlistValue {
if (typeof b === 'string') return parseXmlPlist(b);
return b.subarray(0, 8).toString('latin1') === 'bplist00' ? parseBinaryPlist(b) : parseXmlPlist(b.toString('utf8'));
}

150
cli/lib/reports.ts Normal file
View file

@ -0,0 +1,150 @@
// Sales and finance reports, as pure parts: request paths, file names and the summaries. The command
// (cli/reports.ts) downloads into .storebound/reports/ (gitignored: these files hold per-order and per-buyer-location
// rows) and prints / exports only aggregates.
// Sources (checked October 2026):
// Apple: GET /v1/salesReports (filter[vendorNumber], filter[reportType], filter[reportSubType], filter[frequency],
// filter[reportDate], filter[version]; answer application/a-gzip, tab-separated text) and GET /v1/financeReports
// (filter[vendorNumber], filter[reportType] FINANCIAL | FINANCE_DETAIL, filter[regionCode], filter[reportDate] =
// fiscal month YYYY-MM). Team key only, not an individual key.
// https://developer.apple.com/documentation/appstoreconnectapi/get-v1-salesreports
// https://developer.apple.com/documentation/appstoreconnectapi/get-v1-financereports
// Allowed combinations (docs table): SALES SUMMARY DAILY|WEEKLY|MONTHLY|YEARLY 1_0; SUBSCRIPTION SUMMARY DAILY 1_3;
// SUBSCRIPTION_EVENT SUMMARY DAILY 1_3; SUBSCRIBER DETAILED DAILY 1_3; PRE_ORDER SUMMARY ... 1_0;
// SUBSCRIPTION_OFFER_CODE_REDEMPTION SUMMARY DAILY 1_0; WIN_BACK_ELIGIBILITY SUMMARY DAILY 1_0; INSTALLS ...
// Region codes (Help, "Financial report regions and currencies"): ZZ = all regions consolidated (FINANCIAL),
// Z1 = the Financial Detail report (FINANCE_DETAIL).
// Summary Sales Report columns (Help): Provider, Provider Country, SKU, Developer, Title, Version, Product Type
// Identifier, Units, Developer Proceeds, Begin Date, End Date, Customer Currency, Country Code, Currency of Proceeds,
// Apple Identifier, Customer Price, ...
// Google Play: Cloud Storage bucket of the developer account (play.reportsBucket), read-only scope
// devstorage.read_only: earnings/earnings_YYYYMM*.zip and sales/salesreport_YYYYMM*.zip, one CSV inside each.
// Earnings columns: Description, Transaction Date, Transaction Time, Tax Type, Transaction Type, Refund Type,
// Product Title, Package ID, Product Type, SKU ID, Hardware, Buyer Country, ..., Merchant Currency, Amount
// (Merchant Currency), ... Estimated sales columns: Order Number, Order Charged Date, ..., Financial Status, ...,
// Product Title, Package ID, Product Type, SKU ID, Currency of Sale, Item Price, Taxes Collected, Charged Amount,
// ..., Country of Buyer, ... The service account needs "View financial data" in Play Console.
// https://support.google.com/googleplay/android-developer/answer/6135870
import { parseCsv } from './csv';
export const APPLE_SALES_COMBOS: Record<string, { subType: string; frequencies: string[]; version: string }> = {
SALES: { subType: 'SUMMARY', frequencies: ['DAILY', 'WEEKLY', 'MONTHLY', 'YEARLY'], version: '1_0' },
PRE_ORDER: { subType: 'SUMMARY', frequencies: ['DAILY', 'WEEKLY', 'MONTHLY', 'YEARLY'], version: '1_0' },
SUBSCRIPTION: { subType: 'SUMMARY', frequencies: ['DAILY'], version: '1_3' },
SUBSCRIPTION_EVENT: { subType: 'SUMMARY', frequencies: ['DAILY'], version: '1_3' },
SUBSCRIBER: { subType: 'DETAILED', frequencies: ['DAILY'], version: '1_3' },
SUBSCRIPTION_OFFER_CODE_REDEMPTION: { subType: 'SUMMARY', frequencies: ['DAILY'], version: '1_0' },
WIN_BACK_ELIGIBILITY: { subType: 'SUMMARY', frequencies: ['DAILY'], version: '1_0' },
};
/** The report date for a frequency: DAILY / WEEKLY YYYY-MM-DD, MONTHLY YYYY-MM, YEARLY YYYY. Default: the newest that
* is usually there (yesterday minus one day, last month, last year). */
export function appleReportDate(frequency: string, given: string | undefined, now = new Date()): string {
if (given) {
const ok = frequency === 'YEARLY' ? /^\d{4}$/ : frequency === 'MONTHLY' ? /^\d{4}-\d{2}$/ : /^\d{4}-\d{2}-\d{2}$/;
if (!ok.test(given)) throw new Error(`--date for ${frequency}: ${frequency === 'YEARLY' ? 'YYYY' : frequency === 'MONTHLY' ? 'YYYY-MM' : 'YYYY-MM-DD'}`);
return given;
}
const d = new Date(now);
if (frequency === 'YEARLY') return String(d.getUTCFullYear() - 1);
if (frequency === 'MONTHLY') { d.setUTCDate(1); d.setUTCMonth(d.getUTCMonth() - 1); return d.toISOString().slice(0, 7); }
d.setUTCDate(d.getUTCDate() - 2);
return d.toISOString().slice(0, 10);
}
export function appleSalesPath(vendor: string, o: { type: string; frequency: string; date: string; subType?: string; version?: string }): string {
const combo = APPLE_SALES_COMBOS[o.type];
if (!combo) throw new Error(`--type: one of ${Object.keys(APPLE_SALES_COMBOS).join(', ')}`);
if (!combo.frequencies.includes(o.frequency)) throw new Error(`${o.type} reports come ${combo.frequencies.join(' / ')} only`);
const q = new URLSearchParams({ 'filter[vendorNumber]': vendor, 'filter[reportType]': o.type, 'filter[reportSubType]': o.subType ?? combo.subType,
'filter[frequency]': o.frequency, 'filter[reportDate]': o.date, 'filter[version]': o.version ?? combo.version });
return `/v1/salesReports?${q}`;
}
export function appleFinancePath(vendor: string, month: string, o: { type?: 'FINANCIAL' | 'FINANCE_DETAIL'; region?: string } = {}): string {
if (!/^\d{4}-\d{2}$/.test(month)) throw new Error('--month YYYY-MM (Apple fiscal month)');
const type = o.type ?? 'FINANCIAL';
const region = o.region ?? (type === 'FINANCE_DETAIL' ? 'Z1' : 'ZZ');
return `/v1/financeReports?${new URLSearchParams({ 'filter[vendorNumber]': vendor, 'filter[reportType]': type, 'filter[regionCode]': region, 'filter[reportDate]': month })}`;
}
/** Tab-separated report text -> records (header row first). Apple's finance reports end with total lines after a
* blank line; rows without the first header column are dropped. Pure. */
export function parseTsv(text: string): Record<string, string>[] {
const lines = text.replace(/^/, '').split(/\r?\n/);
const head = (lines[0] ?? '').split('\t').map(h => h.trim());
const out: Record<string, string>[] = [];
for (const l of lines.slice(1)) {
if (!l.trim()) break;
const cells = l.split('\t');
out.push(Object.fromEntries(head.map((h, i) => [h, (cells[i] ?? '').trim()])));
}
return out;
}
export interface SummaryRow { key: string; title: string; currency: string; units: number; amount: number; rows: number }
const num = (s: string | undefined): number => { const n = Number(String(s ?? '').replace(/,/g, '')); return Number.isFinite(n) ? n : 0; };
const round2 = (n: number): number => Math.round(n * 100) / 100;
function group(rows: Record<string, string>[], keyOf: (r: Record<string, string>) => [string, string, string], unitsOf: (r: Record<string, string>) => number, amountOf: (r: Record<string, string>) => number): SummaryRow[] {
const m = new Map<string, SummaryRow>();
for (const r of rows) {
const [key, title, currency] = keyOf(r);
const id = `${key}\u0000${currency}`;
const cur = m.get(id) ?? { key, title, currency, units: 0, amount: 0, rows: 0 };
cur.units += unitsOf(r); cur.amount += amountOf(r); cur.rows++;
m.set(id, cur);
}
return [...m.values()].map(x => ({ ...x, amount: round2(x.amount) })).sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : a.currency < b.currency ? -1 : a.currency > b.currency ? 1 : 0));
}
/** Summary Sales Report: units and proceeds (units x Developer Proceeds) per SKU and proceeds currency. Pure. */
export function summarizeAppleSales(rows: Record<string, string>[]): SummaryRow[] {
return group(rows, r => [r.SKU || r['Apple Identifier'] || '?', r.Title ?? '', r['Currency of Proceeds'] ?? ''], r => num(r.Units), r => num(r.Units) * num(r['Developer Proceeds']));
}
/** Financial report: quantity and Extended Partner Share per Vendor Identifier and currency. Pure. */
export function summarizeAppleFinance(rows: Record<string, string>[]): SummaryRow[] {
return group(rows.filter(r => r['Vendor Identifier'] !== undefined && r['Vendor Identifier'] !== ''),
r => [r['Vendor Identifier']!, r.Title ?? '', r['Partner Share Currency'] ?? ''], r => num(r.Quantity), r => num(r['Extended Partner Share']));
}
/** Play earnings: amount in the merchant currency per SKU, transaction type and currency. Pure. */
export function summarizePlayEarnings(rows: Record<string, string>[]): SummaryRow[] {
return group(rows, r => [`${r['SKU ID'] || r['Product Type'] || '?'} · ${r['Transaction Type'] ?? ''}`, r['Product Title'] ?? '', r['Merchant Currency'] ?? ''],
r => (/^charge$/i.test(r['Transaction Type'] ?? '') ? 1 : 0), r => num(r['Amount (Merchant Currency)']));
}
/** Play estimated sales: charged amount per SKU, financial status and currency of sale. Pure. */
export function summarizePlaySales(rows: Record<string, string>[]): SummaryRow[] {
return group(rows, r => [`${r['SKU ID'] || '?'} · ${r['Financial Status'] ?? ''}`, r['Product Title'] ?? '', r['Currency of Sale'] ?? ''], () => 1, r => num(r['Charged Amount']));
}
/** Total per currency (summaries are never added across currencies). */
export function totalsByCurrency(rows: SummaryRow[]): { currency: string; units: number; amount: number }[] {
const m = new Map<string, { currency: string; units: number; amount: number }>();
for (const r of rows) { const t = m.get(r.currency) ?? { currency: r.currency, units: 0, amount: 0 }; t.units += r.units; t.amount = round2(t.amount + r.amount); m.set(r.currency, t); }
return [...m.values()].sort((a, b) => (a.currency < b.currency ? -1 : a.currency > b.currency ? 1 : 0));
}
export const summaryCsvRows = (rows: SummaryRow[]): (string | number)[][] => [['key', 'title', 'currency', 'units', 'amount', 'rows'], ...rows.map(r => [r.key, r.title, r.currency, r.units, r.amount, r.rows])];
/** Play month -> object name prefix in the bucket. */
export const playReportPrefix = (kind: 'earnings' | 'sales', month: string): string => {
if (!/^\d{4}-\d{2}$/.test(month)) throw new Error('--month YYYY-MM');
return kind === 'earnings' ? `earnings/earnings_${month.replace('-', '')}` : `sales/salesreport_${month.replace('-', '')}`;
};
/** CSV text of a Play report (they are UTF-8, some exports UTF-16 with a BOM). Pure. */
export function decodeReport(b: Uint8Array): string {
if (b[0] === 0xff && b[1] === 0xfe) return new TextDecoder('utf-16le').decode(b.subarray(2));
return new TextDecoder().decode(b).replace(/^/, '');
}
/** Play report CSV -> records keyed by the original header names. Pure. */
export const parsePlayCsv = (text: string): Record<string, string>[] => {
const [head, ...rest] = parseCsv(text);
if (!head) return [];
const keys = head.map(h => h.trim());
return rest.map(r => Object.fromEntries(keys.map((k, i) => [k, (r[i] ?? '').trim()])));
};

166
cli/lib/review-submit.ts Normal file
View file

@ -0,0 +1,166 @@
// Sending in-app purchases and subscriptions to App Review through review submissions, as a pure planner. The command
// (cli/apple/iap-submit.ts) reads the state, calls `planIapSubmission`, prints the plan and only sends it after the
// owner says yes in a terminal. Never an MCP tool: submitting for review is the owner's action.
//
// How App Store Connect does it (API 4.4.1+, OpenAPI spec 4.5.1, checked October 2026):
// - Every in-app purchase, subscription and subscription group has versions (inAppPurchaseVersions,
// subscriptionVersions, subscriptionGroupVersions; GET /v2/inAppPurchases/{id}/versions, /v1/subscriptions/{id}/versions,
// /v1/subscriptionGroups/{id}/versions). "Use the In-App Purchase version for submitting to review."
// - A version goes to App Review as an item of a review submission: POST /v1/reviewSubmissions (app; platform
// optional), POST /v1/reviewSubmissionItems with inAppPurchaseVersion | subscriptionVersion | subscriptionGroupVersion
// (or appStoreVersion), then PATCH /v1/reviewSubmissions/{id} { submitted: true }.
// The older inAppPurchaseSubmissions / subscriptionSubmissions / subscriptionGroupSubmissions are deprecated.
// https://developer.apple.com/documentation/appstoreconnectapi/app-store-connect-api-4-4-1-release-notes
// https://developer.apple.com/documentation/appstoreconnectapi/review-submissions
// https://developer.apple.com/documentation/appstoreconnectapi/in-app-purchase-versions
// The rules (App Store Connect Help, "Submit an In-App Purchase", checked October 2026):
// - "The first consumable, non-consumable, auto-renewable subscription, and non-renewing subscription In-App
// Purchase of each type must be submitted with a new app version."
// - Later items of an approved type go without an app version "as long as your app has at least one approved app
// version at the time of submission".
// - A new subscription goes together with its subscription group while the group is not approved; "each new
// subscription group must be submitted with at least one of its subscriptions".
// - Everything reviewed together goes into the same draft submission; up to 200 items per submission.
// - In-App Purchases with content hosting can no longer be submitted. In-app purchases are not supported on Apple Watch.
// https://developer.apple.com/help/app-store-connect/manage-submissions-to-app-review/submit-an-in-app-purchase
import type { Req } from '../apple/jsonapi';
import { one } from '../apple/jsonapi';
export const MAX_SUBMISSION_ITEMS = 200;
/** App Store version states after which the app counts as having an approved version. */
const APPROVED_APP = new Set(['READY_FOR_DISTRIBUTION', 'READY_FOR_SALE', 'PENDING_DEVELOPER_RELEASE', 'PENDING_APPLE_RELEASE', 'PROCESSING_FOR_DISTRIBUTION',
'PROCESSING_FOR_APP_STORE', 'REPLACED_WITH_NEW_VERSION', 'ACCEPTED', 'DEVELOPER_REMOVED_FROM_SALE', 'REMOVED_FROM_SALE']);
/** Product states (InAppPurchaseState / Subscription.state) that mean the product was approved once. */
const APPROVED_PRODUCT = new Set(['APPROVED', 'DEVELOPER_REMOVED_FROM_SALE', 'REMOVED_FROM_SALE']);
/** Version states that can still go into a draft submission. */
const SUBMITTABLE = new Set(['PREPARE_FOR_SUBMISSION', 'READY_FOR_REVIEW']);
const IN_REVIEW = new Set(['WAITING_FOR_REVIEW', 'IN_REVIEW']);
export type ItemKind = 'inAppPurchaseVersion' | 'subscriptionVersion' | 'subscriptionGroupVersion' | 'appStoreVersion';
const ITEM_TYPE: Record<ItemKind, string> = {
inAppPurchaseVersion: 'inAppPurchaseVersions', subscriptionVersion: 'subscriptionVersions', subscriptionGroupVersion: 'subscriptionGroupVersions', appStoreVersion: 'appStoreVersions',
};
export interface PVersion { id: string; version?: number; state: string }
export interface PIap { id: string; productId: string; type: string; state: string; versions: PVersion[] }
export interface PSub { id: string; productId: string; groupId: string; state: string; versions: PVersion[] }
export interface PGroup { id: string; name: string; versions: PVersion[] }
export interface PAppVersion { id: string; versionString: string; state: string }
export interface SubmitState {
appVersions: PAppVersion[];
iaps: PIap[];
subs: PSub[];
groups: PGroup[];
/** The app's draft review submission (state READY_FOR_REVIEW), if one exists, and the version ids already in it. */
draft?: { id: string; itemVersionIds: string[] } | null;
}
export interface PlanItem { kind: ItemKind; versionId: string; label: string }
export interface SubmitPlan {
items: PlanItem[];
/** Product ids that are left out, with the reason. */
skipped: { id: string; why: string }[];
/** Types submitted for the first time (need an app version in the same submission). */
firstOfType: string[];
hasApprovedVersion: boolean;
/** An app version must be in this submission (first of a type, or no approved app version yet). */
needsAppVersion: boolean;
/** The editable app version that would go in (with withVersion). */
appVersion?: PAppVersion;
/** Problems that stop the submission (nothing is sent while any is left). */
blockers: string[];
/** Requests up to and including adding the items (a draft the owner can also submit in App Store Connect). */
prepare: Req[];
/** The submit request itself (the owner's action). Uses the placeholder id "${submission}" when the draft is new. */
submit: Req;
}
const typeLabel = (t: string): string => ({ CONSUMABLE: 'consumable', NON_CONSUMABLE: 'non-consumable', NON_RENEWING_SUBSCRIPTION: 'non-renewing subscription', AUTO_RENEWABLE: 'auto-renewable subscription' }[t] ?? t);
/** The newest version of a product (highest `version`, else the last listed). */
export function latestVersion(vs: PVersion[]): PVersion | undefined {
return [...vs].sort((a, b) => (a.version ?? 0) - (b.version ?? 0)).at(-1);
}
/**
* Plan for submitting `want` (product ids of in-app purchases and subscriptions). withVersion: put the editable app
* version into the same submission (needed for the first item of a type, or while the app has no approved version).
*/
export function planIapSubmission(s: SubmitState, want: string[], o: { withVersion?: boolean } = {}): SubmitPlan {
const plan: SubmitPlan = { items: [], skipped: [], firstOfType: [], hasApprovedVersion: s.appVersions.some(v => APPROVED_APP.has(v.state)), needsAppVersion: false, blockers: [], prepare: [],
submit: { method: 'PATCH', path: '/v1/reviewSubmissions/${submission}', note: 'submit for App Review', body: {} } };
const approvedTypes = new Set([...s.iaps.filter(p => APPROVED_PRODUCT.has(p.state)).map(p => p.type), ...(s.subs.some(x => APPROVED_PRODUCT.has(x.state)) ? ['AUTO_RENEWABLE'] : [])]);
const firstTypes = new Set<string>();
const already = new Set(s.draft?.itemVersionIds ?? []);
const groupsNeeded = new Set<string>();
const pick = (id: string, productState: string, versions: PVersion[], kind: ItemKind, type: string): void => {
if (productState === 'MISSING_METADATA') { plan.skipped.push({ id, why: 'missing metadata (price, localization or review screenshot): storebound apple iap / apple subscriptions / apple iap-review' }); return; }
if (productState === 'WAITING_FOR_UPLOAD' || productState === 'PROCESSING_CONTENT') { plan.skipped.push({ id, why: `hosted content ${productState}: content-hosted purchases can no longer be submitted` }); return; }
const v = latestVersion(versions);
if (!v) { plan.skipped.push({ id, why: 'no version on App Store Connect yet (create the product first: storebound apple iap / apple subscriptions)' }); return; }
if (IN_REVIEW.has(v.state)) { plan.skipped.push({ id, why: `already ${v.state}` }); return; }
if (!SUBMITTABLE.has(v.state)) { plan.skipped.push({ id, why: `latest version is ${v.state}: change it in App Store Connect (or --new-version) to send a new version` }); return; }
if (already.has(v.id)) { plan.skipped.push({ id, why: 'already in the draft submission' }); return; }
plan.items.push({ kind, versionId: v.id, label: `${id} (${typeLabel(type)}, version ${v.version ?? '?'})` });
if (!approvedTypes.has(type)) firstTypes.add(type);
};
for (const id of want) {
const iap = s.iaps.find(p => p.productId === id);
const sub = s.subs.find(p => p.productId === id);
if (iap) pick(id, iap.state, iap.versions, 'inAppPurchaseVersion', iap.type);
else if (sub) {
const before = plan.items.length;
pick(id, sub.state, sub.versions, 'subscriptionVersion', 'AUTO_RENEWABLE');
if (plan.items.length > before) groupsNeeded.add(sub.groupId);
} else plan.skipped.push({ id, why: 'not on App Store Connect (storebound apple iap / apple subscriptions creates it)' });
}
for (const gid of groupsNeeded) {
const g = s.groups.find(x => x.id === gid);
if (!g) continue;
if (g.versions.some(v => v.state === 'APPROVED') || s.subs.some(x => x.groupId === gid && APPROVED_PRODUCT.has(x.state))) continue;
const v = latestVersion(g.versions);
if (!v) { plan.blockers.push(`subscription group "${g.name}" has no version to submit`); continue; }
if (IN_REVIEW.has(v.state) || already.has(v.id)) continue;
if (!SUBMITTABLE.has(v.state)) { plan.blockers.push(`subscription group "${g.name}": version is ${v.state}`); continue; }
plan.items.push({ kind: 'subscriptionGroupVersion', versionId: v.id, label: `subscription group "${g.name}" (not approved yet, goes with its subscriptions)` });
}
plan.firstOfType = [...firstTypes].map(typeLabel);
plan.needsAppVersion = plan.items.length > 0 && (firstTypes.size > 0 || !plan.hasApprovedVersion);
if (plan.needsAppVersion) {
const editable = s.appVersions.find(v => ['PREPARE_FOR_SUBMISSION', 'DEVELOPER_REJECTED', 'REJECTED', 'METADATA_REJECTED', 'INVALID_BINARY', 'READY_FOR_REVIEW'].includes(v.state));
const why = firstTypes.size ? `first ${plan.firstOfType.join(' / ')} of this app: Apple reviews it only together with a new app version`
: 'the app has no approved version yet: in-app purchases go together with an app version';
if (!o.withVersion) plan.blockers.push(`${why}. Add --with-version (the editable version ${editable ? editable.versionString : '(none yet: storebound apple listing --version x.y.z --build N)'} goes into the same submission; submitting it submits the app)`);
else if (!editable) plan.blockers.push(`${why}, and there is no editable app version: storebound apple listing --version x.y.z --build N first`);
else if (!already.has(editable.id)) { plan.appVersion = editable; plan.items.unshift({ kind: 'appStoreVersion', versionId: editable.id, label: `app version ${editable.versionString}` }); }
}
if (plan.items.length + (s.draft?.itemVersionIds.length ?? 0) > MAX_SUBMISSION_ITEMS) plan.blockers.push(`more than ${MAX_SUBMISSION_ITEMS} items in one submission: use --only for a part`);
const sid = s.draft?.id ?? '${submission}';
if (!s.draft && plan.items.length) plan.prepare.push({ method: 'POST', path: '/v1/reviewSubmissions', note: 'new draft review submission', body: { data: { type: 'reviewSubmissions', attributes: { platform: 'IOS' }, relationships: { app: one('apps', '${app}') } } } });
for (const it of plan.items) plan.prepare.push({ method: 'POST', path: '/v1/reviewSubmissionItems', note: it.label,
body: { data: { type: 'reviewSubmissionItems', relationships: { reviewSubmission: one('reviewSubmissions', sid), [it.kind]: one(ITEM_TYPE[it.kind], it.versionId) } } } });
plan.submit = { method: 'PATCH', path: `/v1/reviewSubmissions/${sid}`, note: 'submit for App Review', body: { data: { type: 'reviewSubmissions', id: sid, attributes: { submitted: true } } } };
return plan;
}
/** Fills the placeholders of a planned request (app id, the id of the draft created a moment ago). Pure. */
export function bindIds(r: Req, ids: { app?: string; submission?: string }): Req {
const text = JSON.stringify(r).replaceAll('${app}', ids.app ?? '${app}').replaceAll('${submission}', ids.submission ?? '${submission}');
return JSON.parse(text) as Req;
}
/** POST /v1/inAppPurchaseVersions | /v1/subscriptionVersions: a new draft version of an approved (or rejected)
* product, "capturing its current localized metadata and review images for App Review submission". */
export function newVersionReq(kind: 'iap' | 'sub', productApiId: string, label: string): Req {
return kind === 'iap'
? { method: 'POST', path: '/v1/inAppPurchaseVersions', note: `new version of ${label}`, body: { data: { type: 'inAppPurchaseVersions', relationships: { inAppPurchase: one('inAppPurchases', productApiId) } } } }
: { method: 'POST', path: '/v1/subscriptionVersions', note: `new version of ${label}`, body: { data: { type: 'subscriptionVersions', relationships: { subscription: one('subscriptions', productApiId) } } } };
}
/** Versions response -> PVersion list. Pure. */
export const versionsOf = (data: { id: string; attributes?: { version?: number; state?: string } }[]): PVersion[] =>
data.map(v => ({ id: v.id, version: v.attributes?.version, state: v.attributes?.state ?? '?' }));

122
cli/lib/triage.ts Normal file
View file

@ -0,0 +1,122 @@
// Crash and feedback triage, as pure parts: crash signatures from TestFlight crash logs, and clusters by signature,
// device and OS version for TestFlight feedback and Google Play vitals error reports. The command (cli/triage.ts)
// reads (GET only), groups and prints a table or --json. Tester emails are never read into the output (the feedback
// requests ask only for the fields listed below).
// Sources (checked October 2026):
// TestFlight feedback (App Store Connect API 4.0+, OpenAPI 4.5.1): GET /v1/apps/{id}/betaFeedbackCrashSubmissions,
// GET /v1/apps/{id}/betaFeedbackScreenshotSubmissions (createdDate, comment, deviceModel, osVersion, locale,
// appPlatform, deviceFamily, build relationship; filter[build], sort=-createdDate, fields[...]),
// GET /v1/betaFeedbackCrashSubmissions/{id}/crashLog -> BetaCrashLog.logText.
// https://developer.apple.com/documentation/appstoreconnectapi/prerelease-versions-and-beta-testers
// Google Play Developer Reporting API v1beta1: errorIssues:search (issues = Play's own clusters: type, cause,
// location, errorReportCount, distinctUsers) and errorReports:search (filter "errorIssueId = <id>", interval
// hour-aligned UTC, pageSize <= 100; ErrorReport: name, type, reportText, issue, eventTime, deviceModel
// {deviceId {buildBrand, buildDevice}, marketingName}, osVersion {apiLevel}, appVersion {versionCode}).
// https://developers.google.com/play/developer/reporting/reference/rest/v1beta1/vitals.errors.reports/search
// https://developers.google.com/play/developer/reporting/reference/rest/v1beta1/vitals.errors.reports
/** Fields read for feedback (no email, no tester relationship). */
export const FEEDBACK_FIELDS = 'createdDate,comment,deviceModel,osVersion,locale,appPlatform,deviceFamily,build';
export const CRASH_FIELDS = 'createdDate,comment,deviceModel,osVersion,locale,appPlatform,deviceFamily,build,crashLog';
const cleanFrame = (s: string): string => s.replace(/\s+\+\s+\d+$/, '').replace(/0x[0-9a-f]+/gi, '').replace(/\s+/g, ' ').trim();
/**
* One crash signature from a crash log: "<exception type> @ <first frame of the crashed thread in the app>" (else the
* first frame). Handles the text crash report format and the JSON .ips format (header line + body). Pure.
*/
export function crashSignature(log: string): string {
const text = log.trim();
// .ips: first line is a JSON header, the rest a JSON body
const nl = text.indexOf('\n');
if (text.startsWith('{') && nl > 0) {
try {
const head = JSON.parse(text.slice(0, nl)) as { app_name?: string; name?: string };
const body = JSON.parse(text.slice(nl + 1)) as { exception?: { type?: string; signal?: string }; faultingThread?: number; threads?: { triggered?: boolean; frames?: { imageIndex?: number; symbol?: string; imageOffset?: number }[] }[]; usedImages?: { name?: string }[]; procName?: string };
const ex = [body.exception?.type, body.exception?.signal].filter(Boolean).join(' ') || 'crash';
const t = body.threads?.[body.faultingThread ?? -1] ?? body.threads?.find(x => x.triggered);
const app = body.procName ?? head.app_name ?? head.name;
const frames = (t?.frames ?? []).map(f => ({ image: body.usedImages?.[f.imageIndex ?? -1]?.name ?? '?', symbol: f.symbol ?? `+${f.imageOffset ?? '?'}` }));
const f = frames.find(x => app && x.image === app) ?? frames[0];
return f ? `${ex} @ ${f.image} ${cleanFrame(f.symbol)}` : ex;
} catch { /* fall through to the text format */ }
}
const ex = /^Exception Type:\s*(.+)$/m.exec(text)?.[1]?.trim() ?? /^Termination Reason:\s*(.+)$/m.exec(text)?.[1]?.trim() ?? 'crash';
const proc = /^Process:\s*([^\s\[]+)/m.exec(text)?.[1];
const crashed = /^Crashed Thread:\s*(\d+)/m.exec(text)?.[1];
const lines = text.split(/\r?\n/);
const at = lines.findIndex(l => (crashed !== undefined ? new RegExp(`^Thread ${crashed} Crashed`) : /^Thread \d+ Crashed/).test(l));
const block: string[] = [];
if (at >= 0) for (const l of lines.slice(at + 1)) { if (!l.trim()) break; block.push(l); }
const frames = block.map(l => /^\d+\s+(\S+)\s+0x[0-9a-f]+\s+(.+)$/i.exec(l.trim())).filter((m): m is RegExpExecArray => !!m).map(m => ({ image: m[1]!, symbol: m[2]! }));
const f = frames.find(x => proc && x.image === proc) ?? frames[0];
return f ? `${ex} @ ${f.image} ${cleanFrame(f.symbol)}` : ex;
}
export interface TriageItem { signature: string; device: string; os: string; build?: string; date?: string; comment?: string }
export interface Cluster { signature: string; count: number; devices: [string, number][]; os: [string, number][]; builds: [string, number][]; first?: string; last?: string; comments?: string[] }
const top = (xs: string[], n = 3): [string, number][] => {
const m = new Map<string, number>();
for (const x of xs) m.set(x, (m.get(x) ?? 0) + 1);
return [...m.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, n);
};
/** Items -> clusters by signature, most frequent first, each with its top devices, OS versions and builds. Pure. */
export function cluster(items: TriageItem[], o: { comments?: number } = {}): Cluster[] {
const by = new Map<string, TriageItem[]>();
for (const i of items) by.set(i.signature, [...(by.get(i.signature) ?? []), i]);
return [...by.entries()].map(([signature, xs]) => {
const dates = xs.map(x => x.date ?? '').filter(Boolean).sort();
const comments = o.comments ? xs.map(x => (x.comment ?? '').replace(/\s+/g, ' ').trim()).filter(Boolean).slice(0, o.comments).map(c => c.slice(0, 120)) : undefined;
return { signature, count: xs.length, devices: top(xs.map(x => x.device)), os: top(xs.map(x => x.os)), builds: top(xs.map(x => x.build ?? '?')),
...(dates.length ? { first: dates[0], last: dates.at(-1) } : {}), ...(comments?.length ? { comments } : {}) };
}).sort((a, b) => b.count - a.count || a.signature.localeCompare(b.signature));
}
/** TestFlight feedback (crash or screenshot submissions) -> items. Screenshot feedback has no crash: its signature is
* "feedback". Pure. */
export function feedbackItems(subs: { id: string; attributes?: Record<string, unknown>; relationships?: { build?: { data?: { id: string } | null } } }[], builds: Map<string, string>, signatures: Map<string, string> = new Map()): TriageItem[] {
return subs.map(s => {
const a = s.attributes ?? {};
return { signature: signatures.get(s.id) ?? 'feedback', device: String(a.deviceModel ?? '?'), os: String(a.osVersion ?? '?'),
build: builds.get(s.relationships?.build?.data?.id ?? '') ?? undefined, date: typeof a.createdDate === 'string' ? a.createdDate : undefined,
comment: typeof a.comment === 'string' ? a.comment : undefined };
});
}
export interface PlayIssueRef { id: string; type: string; cause: string; location: string; reports: number; users: number }
/** errorIssues:search -> issue refs with their id (the last part of `name`). Pure. */
export function playIssues(resp: { errorIssues?: { name?: string; type?: string; cause?: string; location?: string; errorReportCount?: string; distinctUsers?: string }[] }): PlayIssueRef[] {
return (resp.errorIssues ?? []).map(i => ({ id: (i.name ?? '').split('/').pop() ?? '', type: i.type === 'APPLICATION_NOT_RESPONDING' ? 'ANR' : i.type ?? '?', cause: i.cause ?? '',
location: i.location ?? '', reports: Number(i.errorReportCount ?? 0), users: Number(i.distinctUsers ?? 0) })).filter(i => i.id);
}
/** errorReports:search -> items with the signature of their issue. Pure. */
export function playReportItems(resp: { errorReports?: { issue?: string; type?: string; eventTime?: string; deviceModel?: { marketingName?: string; deviceId?: { buildBrand?: string; buildDevice?: string } }; osVersion?: { apiLevel?: string }; appVersion?: { versionCode?: string } }[] }, issues: PlayIssueRef[]): TriageItem[] {
const sig = new Map(issues.map(i => [i.id, `${i.type} ${i.cause}${i.location ? ` @ ${i.location}` : ''}`] as const));
return (resp.errorReports ?? []).map(r => {
const id = (r.issue ?? '').split('/').pop() ?? '';
const dev = r.deviceModel?.marketingName || [r.deviceModel?.deviceId?.buildBrand, r.deviceModel?.deviceId?.buildDevice].filter(Boolean).join('/') || '?';
return { signature: sig.get(id) ?? `${r.type ?? '?'} issue ${id}`, device: dev, os: r.osVersion?.apiLevel ? `API ${r.osVersion.apiLevel}` : '?', build: r.appVersion?.versionCode, date: r.eventTime };
});
}
/** errorReports:search query string for one issue (UTC, hour-aligned interval, newest window). Pure. */
export function reportsQuery(issueId: string, start: Date, end: Date, pageSize = 100): string {
const p = new URLSearchParams();
for (const [k, d] of [['start', start], ['end', end]] as const) {
p.set(`interval.${k}Time.year`, String(d.getUTCFullYear())); p.set(`interval.${k}Time.month`, String(d.getUTCMonth() + 1)); p.set(`interval.${k}Time.day`, String(d.getUTCDate()));
p.set(`interval.${k}Time.hours`, '0'); p.set(`interval.${k}Time.timeZone.id`, 'UTC');
}
p.set('filter', `errorIssueId = ${issueId}`);
p.set('pageSize', String(Math.min(100, pageSize)));
return p.toString();
}
/** Table rows for a cluster list. Pure. */
export function clusterRows(cs: Cluster[]): (string | number)[][] {
const fmt = (xs: [string, number][]) => xs.map(([k, n]) => `${k} (${n})`).join(', ');
return cs.map(c => [c.count, c.signature.slice(0, 70), fmt(c.devices), fmt(c.os), fmt(c.builds)]);
}

View file

@ -1,5 +1,7 @@
// User-facing release notes from commit subjects, and writing them into the two listing files. Pure.
// The draft is a starting point for a human: commit messages are written for developers, notes are for users.
import type { Language } from './config';
import { playCodes } from './config';
import { len, PLAY_LIMITS } from './copy';
export const NOTES_LIMITS = { play: PLAY_LIMITS.whatsNew, apple: 4000 } as const;
@ -98,3 +100,69 @@ export function setAppleWhatsNew(md: string, locale: string, text: string): { md
});
return { md: out.join(''), changed };
}
// ---- many languages: one file per language, translated by your agent (whats-new skill) or a provider hook ----
// Limits per store (what each store enforces for the release-notes field):
// Google Play "What's new" (edits.tracks releaseNotes / Play Console): 500 characters per language.
// App Store "What's New in This Version" (appStoreVersionLocalizations.whatsNew): 4000 characters.
export type NotesStatus = 'source' | 'translate' | 'translated';
export interface NotesFile { lang: string; source: string; status: NotesStatus; text: string }
const HEAD_RE = /^<!--\s*whats-new\s+lang=(\S+)\s+source=(\S+)\s+status=(source|translate|translated)\s*-->\n?/;
/** One language file: a header line the tools read, then the text. Pure. */
export function notesFileText(f: NotesFile): string {
return `<!-- whats-new lang=${f.lang} source=${f.source} status=${f.status} -->\n${f.text.trim()}\n`;
}
/** Parses a language file; a file without the header is taken as translated text. Pure. */
export function parseNotesFile(text: string, lang: string): NotesFile {
const m = HEAD_RE.exec(text);
if (!m) return { lang, source: '', status: 'translated', text: text.trim() };
return { lang: m[1]!, source: m[2]!, status: m[3] as NotesStatus, text: text.slice(m[0].length).trim() };
}
/** --languages values (config language ids, App Store locales or Play codes) -> language entries, in that order. */
export function resolveLanguages(langs: Language[], wanted: string[]): Language[] {
const out: Language[] = [];
for (const w of wanted) {
const l = langs.find(x => x.id === w) ?? langs.find(x => x.apple === w) ?? langs.find(x => playCodes(x).includes(w));
if (!l) throw new Error(`--languages: "${w}" is not a language of the config (ids: ${langs.map(x => x.id).join(', ')})`);
if (!out.includes(l)) out.push(l);
}
return out;
}
export interface LangCheck { lang: string; chars: number; play?: { limit: number; ok: boolean }; apple?: { limit: number; ok: boolean }; problems: string[] }
/** Limits and wording of one language's notes, for the stores that language is listed on. Pure. */
export function checkLanguageNotes(l: Language, f: NotesFile, sourceText?: string): LangCheck {
const chars = len(f.text);
const c: LangCheck = { lang: l.id, chars, problems: [] };
if (playCodes(l).length) { c.play = { limit: NOTES_LIMITS.play, ok: chars <= NOTES_LIMITS.play }; if (!c.play.ok) c.problems.push(`Google Play: ${chars} > ${NOTES_LIMITS.play} characters`); }
if (l.apple) { c.apple = { limit: NOTES_LIMITS.apple, ok: chars <= NOTES_LIMITS.apple }; if (!c.apple.ok) c.problems.push(`App Store: ${chars} > ${NOTES_LIMITS.apple} characters`); }
if (!f.text) c.problems.push('empty');
if (f.status === 'translate') c.problems.push('not translated yet (status=translate)');
else if (sourceText !== undefined && f.status !== 'source' && f.text === sourceText.trim()) c.problems.push('identical to the source language: translate it');
const hook = f.text.split('\n')[0] ?? '';
if (len(hook) > HOOK_CHARS) c.problems.push(`first line is ${len(hook)} characters; about ${HOOK_CHARS} show before "more"`);
return c;
}
/** Writes one language's notes into the listing files (every Play code of the language, its App Store locale). Pure. */
export function applyLanguageNotes(md: { play?: string; apple?: string }, l: Language, text: string): { play?: string; apple?: string; changed: string[] } {
const out: { play?: string; apple?: string; changed: string[] } = { ...md, changed: [] };
if (md.play !== undefined) for (const code of playCodes(l)) {
const r = setPlayWhatsNew(out.play!, code, text);
out.play = r.md;
out.changed.push(...r.changed.map(x => `play:${x}`));
}
if (md.apple !== undefined && l.apple) {
const r = setAppleWhatsNew(out.apple!, l.apple, text);
out.apple = r.md;
out.changed.push(...r.changed.map(x => `apple:${x}`));
}
out.changed = [...new Set(out.changed)];
return out;
}

View file

@ -160,9 +160,8 @@ export function ipaInfo(ipa: string | Buffer): IpaInfo {
return { bundleId, version, build, minOs: str('MinimumOSVersion'), name: str('CFBundleDisplayName') ?? str('CFBundleName'), platform: (p.CFBundleSupportedPlatforms as string[] | undefined)?.[0] };
}
/** States of an App Store Connect build upload (BuildUploadState) and of a processed build (processingState). */
/** End states of an App Store Connect build upload (BuildUploadState); processing is polled by apple testflight wait. */
export const UPLOAD_DONE = new Set(['COMPLETE', 'FAILED']);
export const BUILD_DONE = new Set(['VALID', 'INVALID', 'FAILED']);
/** Requests of an App Store Connect API build upload (Build Uploads, API 4.1): the upload, then the file reservation. */
export function buildUploadReqs(appId: string, info: IpaInfo, fileName: string, fileSize: number) {

View file

@ -1,5 +1,6 @@
// Reads entries of a ZIP archive (an .ipa) without dependencies: the central directory, then one entry, stored or
// deflated (node:zlib). Enough to read Payload/<App>.app/Info.plist; ZIP64 archives (> 4 GB) are not supported.
// Reads entries of a ZIP archive without dependencies: the central directory, then one entry, stored or deflated
// (node:zlib, built into Bun). Used for an .ipa / .aab (Payload/<App>.app/Info.plist, the manifest) and the Play
// financial report exports (earnings_YYYYMM.zip, salesreport_YYYYMM.zip: one CSV inside). No ZIP64, no encryption.
import { closeSync, fstatSync, openSync, readSync } from 'node:fs';
import { inflateRawSync } from 'node:zlib';
@ -50,3 +51,9 @@ export function zipRead(src: string | Buffer, e: ZipEntry): Buffer {
throw new Error(`ZIP: compression method ${e.method} not supported (${e.name})`);
} finally { if (fd >= 0) closeSync(fd); }
}
/** Every file entry with its uncompressed bytes, from an in-memory archive (a Play report export). */
export function unzip(buf: Uint8Array): { name: string; data: Uint8Array }[] {
const b = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
return zipEntries(b).filter(e => !e.name.endsWith('/')).map(e => ({ name: e.name, data: new Uint8Array(zipRead(b, e)) }));
}