Merge remote-tracking branch 'origin/main' into shots-liga

# Conflicts:
#	CHANGELOG.md
#	cli/index.ts
This commit is contained in:
CRTkafa 2026-10-11 21:24:19 +00:00
commit f0eda4bc5b
57 changed files with 3202 additions and 222 deletions

View file

@ -60,6 +60,7 @@ export const WRAPPED: { apple: Record<string, string>; play: Record<string, stri
'appStoreVersions_build_getToOneRelated': 'apple/listing validate',
'appStoreVersions_build_updateToOneRelationship': 'apple/listing',
'appStoreVersions_createInstance': 'apple/listing',
'appStoreVersions_getInstance': 'apple/listing',
'appStoreVersions_updateInstance': 'apple/listing',
'apps_analyticsReportRequests_getToManyRelated': 'analytics',
'apps_appAvailabilityV2_getToOneRelated': 'apple/appinfo apple/preorder validate',

View file

@ -16,12 +16,13 @@ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { type AppleCopy, parseAppStoreListing } from '../lib/copy';
import { compactDiff } from '../lib/diff';
import { mergeAppleListing, overLimits } from '../lib/listing-pull';
import { counts, draftReason, draftSections, type ItemPlan, itemLines, planLocales, planVersion, short, type Skipped, type VersionPlan } from '../lib/listing-plan';
import { counts, draftReason, draftSections, type ItemPlan, itemLines, planItem, planLocales, planVersion, short, type Skipped, type VersionPlan } from '../lib/listing-plan';
import { createOnce, findOrCreate, getById } from '../lib/upsert';
import { appleName } from '../lib/config';
import type { Ctx } from '../lib/ctx';
import { confirm, need } from '../lib/ctx';
import { done, log, printJson, warn } from '../lib/log';
import { ascClient, type J } from './asc';
import { ascClient, EDITABLE, type J } from './asc';
export function readAppleCopy(ctx: Ctx) {
const { config, resolve } = ctx.loaded;
@ -156,15 +157,21 @@ export function listingPlanLines(p: AppleListingPlan): string[] {
return out;
}
async function applyLocales(c: Asc, type: string, parentRel: string, parentType: string, parentId: string, plan: ItemPlan[]): Promise<void> {
async function applyLocales(c: Asc, type: string, parentRel: string, parentType: string, parentId: string, listPath: string, plan: ItemPlan[]): Promise<void> {
const patch = async (key: string, id: string, changes: ItemPlan['changes']) => {
await c.asc('PATCH', `/v1/${type}/${id}`, { data: { type, id, attributes: Object.fromEntries(changes.map(ch => [ch.field, ch.to ?? ''])) } });
log('apple', `${type} ${key}: updated ${changes.map(ch => ch.field).join(', ')}`);
};
for (const l of plan) {
if (l.action === 'create') {
await c.asc('POST', `/v1/${type}`, { data: { type, attributes: { locale: l.key, ...l.attributes }, relationships: { [parentRel]: { data: { type: parentType, id: parentId } } } } });
log('apple', `${type} ${l.key}: created`);
} else if (l.action === 'update') {
await c.asc('PATCH', `/v1/${type}/${l.id}`, { data: { type, id: l.id, attributes: Object.fromEntries(l.changes.map(ch => [ch.field, ch.to ?? ''])) } });
log('apple', `${type} ${l.key}: updated ${l.changes.map(ch => ch.field).join(', ')}`);
}
// a locale is unique per parent: a 409 (or a lost answer) finds the existing one, which is then updated, never created twice
const made = await createOnce<J>({ what: `${type} ${l.key}`, tag: 'apple', unique: true,
find: async () => (await c.all(`${listPath}?limit=200`)).find((x: J) => x.attributes.locale === l.key) ?? null,
create: async () => (await c.asc('POST', `/v1/${type}`, { data: { type, attributes: { locale: l.key, ...l.attributes }, relationships: { [parentRel]: { data: { type: parentType, id: parentId } } } } })).data });
if (made.created) { log('apple', `${type} ${l.key}: created`); continue; }
const again = planItem(l.key, { id: made.value.id, attributes: made.value.attributes ?? {} }, l.attributes);
if (again.action === 'update') await patch(l.key, made.value.id, again.changes);
} else if (l.action === 'update') await patch(l.key, l.id!, l.changes);
}
}
@ -189,9 +196,21 @@ export async function run(ctx: Ctx): Promise<void> {
const vp = p.versionPlan;
let versionId = vp.id;
if (vp.action === 'create') {
versionId = (await c.asc('POST', '/v1/appStoreVersions', { data: { type: 'appStoreVersions',
attributes: Object.fromEntries(Object.entries(vp.attributes)), relationships: { app: { data: { type: 'apps', id: appId } } } } })).data.id;
log('apple', `version ${version} created`);
// look again right before the create (another run, or a lost answer), then the journal for the list lag
const made = await findOrCreate<J>({ what: `App Store version ${version}`, tag: 'apple', unique: true,
find: async () => (await c.all(`/v1/apps/${appId}/appStoreVersions?filter[platform]=IOS&limit=50`))
.find((x: J) => x.attributes.versionString === version && EDITABLE.has(x.attributes.appVersionState ?? x.attributes.appStoreState)) ?? null,
journal: { root, key: `apple:${appId}:version:IOS:${version}`, byId: id => getById(c.asc, `/v1/appStoreVersions/${id}`) as Promise<J | null>, idOf: v => v.id },
create: async () => (await c.asc('POST', '/v1/appStoreVersions', { data: { type: 'appStoreVersions',
attributes: Object.fromEntries(Object.entries(vp.attributes)), relationships: { app: { data: { type: 'apps', id: appId } } } } })).data });
versionId = made.value.id;
if (made.created) log('apple', `version ${version} created`);
else {
const { platform: _p, ...want } = vp.attributes;
const again = planItem(version, { id: versionId!, attributes: made.value.attributes ?? {} }, want);
if (again.action === 'update') await c.asc('PATCH', `/v1/appStoreVersions/${versionId}`, { data: { type: 'appStoreVersions', id: versionId, attributes: Object.fromEntries(again.changes.map(ch => [ch.field, ch.to])) } });
log('apple', `version ${version} exists already (an earlier run made it): using it${again.action === 'update' ? `, updated ${again.changes.map(ch => ch.field).join(', ')}` : ''}`);
}
} else if (vp.action === 'update') {
await c.asc('PATCH', `/v1/appStoreVersions/${versionId}`, { data: { type: 'appStoreVersions', id: versionId, attributes: Object.fromEntries(vp.changes.map(ch => [ch.field, ch.to])) } });
log('apple', `version: ${vp.changes.map(ch => `${ch.field} ${ch.from ?? '(none)'} -> ${ch.to}`).join(', ')}`);
@ -200,8 +219,9 @@ export async function run(ctx: Ctx): Promise<void> {
await c.asc('PATCH', `/v1/appStoreVersions/${versionId}/relationships/build`, { data: { type: 'builds', id: p.build.id } });
log('apple', `build ${version} (${p.build.number}) attached`);
}
await applyLocales(c, 'appInfoLocalizations', 'appInfo', 'appInfos', p.appInfo.id, p.appInfo.locales);
const vl = p.versionLocales ?? planLocales(await c.all(`/v1/appStoreVersions/${versionId}/appStoreVersionLocalizations?limit=200`), p.wanted);
await applyLocales(c, 'appStoreVersionLocalizations', 'appStoreVersion', 'appStoreVersions', versionId!, vl);
await applyLocales(c, 'appInfoLocalizations', 'appInfo', 'appInfos', p.appInfo.id, `/v1/appInfos/${p.appInfo.id}/appInfoLocalizations`, p.appInfo.locales);
const vlPath = `/v1/appStoreVersions/${versionId}/appStoreVersionLocalizations`;
const vl = p.versionLocales ?? planLocales(await c.all(`${vlPath}?limit=200`), p.wanted);
await applyLocales(c, 'appStoreVersionLocalizations', 'appStoreVersion', 'appStoreVersions', versionId!, vlPath, vl);
done('apple', 'listing done');
}

View file

@ -1,32 +1,86 @@
// App Store keyword rank check through Apple's public iTunes Search API (no account, no scraping).
// App Store keyword work from official / public data only (no scraping, no third-party ASO services).
// storebound aso rank [--storefronts us,de=de-DE] [--keywords "a,b"] [--only-keywords] [--competitors 3] [--limit 200]
// [--delay 3500] [--dry] [--json]
// Keywords: the keyword field of each storefront's locale in store/appstore.md (us -> the primary locale unless
// storebound aso competitors [--term <kw>]... [--storefront us,tr] [--only-terms] [--top 10] [--delay 3500] [--no-save] [--dry] [--json]
// storebound aso suggest [--locale en-US,tr] [--fresh] [--offline] [--write] [--json]
// storebound aso audit [--storefront US] [--json]
// rank: keywords = the keyword field of each storefront's locale in store/appstore.md (us -> the primary locale unless
// "us=en-GB"), plus --keywords (--only-keywords: just those). One request per keyword and storefront, at most one
// every 3.5 s (Apple allows about 20 a minute); a 403 / 429 stops the run with what was read. Rank = position of the
// app (apple.appId, else the bundle id) in the first --limit results, "-" when not there; plus the first competitors
// (title, developer, rating). Subtitles are not in the public API and are not shown. Writes
// .storebound/aso/<date>.json (and compares with the previous one) unless --dry. Pure parts: cli/lib/aso-rank.ts.
// (title, developer, rating). Writes .storebound/aso/<date>.json (and compares with the previous one) unless --dry.
// competitors: the same queries and rate limit; per term the top N other apps (name, developer, rating count, first
// release, last update, genre) and the words in their names that our name / subtitle / keywords do not cover. Saves
// .storebound/aso/competitors/<date>.json unless --dry / --no-save; names the apps new in a term's top N since the
// previous snapshot. Competitor subtitles are not in any public API and are not shown.
// suggest: keyword candidates per App Store locale from our own name / subtitle / description, the latest competitor
// snapshot, the localized category names (from the Search API's genres) and, when Apple Ads credentials exist (and
// not --offline), Apple Ads keyword suggestions with their relative popularity (0-100). Prints the ranked candidates
// and a 100-byte keyword field per locale as a diff against store/appstore.md; --write puts it there with a draft
// line above it (review, then delete the line). Never invents a popularity.
// audit: one offline report (cli/lib/aso-audit.ts) with experiment ideas and the next 3 actions. Never writes.
// Pure parts: cli/lib/aso-rank.ts, cli/lib/aso-intel.ts, cli/lib/aso-audit.ts.
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { adsClient } from './ads/client';
import type { Snapshot } from './lib/analytics';
import { mergeSeries } from './lib/analytics';
import { auditAso } from './lib/aso';
import { auditText, buildAudit, type RankSnap } from './lib/aso-audit';
import {
ADS_KEYWORD_SUGGESTIONS, type AdsSuggestion, candidates, categoryNames, competitorRow, type CompetitorRow, type CompetitorSnapshot, coverageGaps, draftLocales,
draftMark, fitKeywordField, keywordSuggestionBody, newEntrants, parseKeywordSuggestions, setKeywords, storefrontOf, tokens,
} from './lib/aso-intel';
import { competitors, keywordList, MIN_DELAY_MS, parseStorefronts, rankDelta, rankOf, type RankRow, type SearchApp, searchUrl } from './lib/aso-rank';
import { appleName } from './lib/config';
import { parseAppStoreListing, parsePlayListing } from './lib/copy';
import type { Ctx } from './lib/ctx';
import { done, log, printJson, warn } from './lib/log';
import { competitors, keywordList, MIN_DELAY_MS, parseStorefronts, rankDelta, rankOf, type RankRow, type SearchApp, searchUrl } from './lib/aso-rank';
import { appleSections } from './lib/project-files';
import { textTable } from './lib/table';
const TAG = 'aso';
const SUBS = ['rank', 'competitors', 'suggest', 'audit'];
const SNAP_RE = /^\d{4}-\d{2}-\d{2}\.json$/;
const today = () => new Date().toISOString().slice(0, 10);
export async function run(ctx: Ctx): Promise<void> {
function listingOf(ctx: Ctx): { file: string; md: string; sections: Map<string, Record<string, string | undefined>> } {
const { config, resolve } = ctx.loaded;
const file = resolve(config.apple?.listing ?? 'store/appstore.md');
const md = existsSync(file) ? readFileSync(file, 'utf8') : '';
return { file, md, sections: appleSections(md) };
}
const primaryLocale = (ctx: Ctx): string => ctx.loaded.config.apple?.primaryLocale ?? ctx.loaded.config.languages.find(l => l.apple)?.apple ?? 'en-US';
function snapshots<T>(dir: string): { file: string; data: T }[] {
if (!existsSync(dir)) return [];
return readdirSync(dir).filter(f => SNAP_RE.test(f)).sort().map(f => {
try { return { file: f, data: JSON.parse(readFileSync(join(dir, f), 'utf8')) as T }; } catch { return null; }
}).filter((x): x is { file: string; data: T } => x !== null);
}
/** One Search API call per item, one every `delay` ms; stops on 403 / 429 with what was read. */
async function searchAll<P extends { storefront: string; keyword: string }>(plan: P[], limit: number, delay: number, each: (p: P, results: SearchApp[], i: number) => void): Promise<number> {
let read = 0;
for (const [i, p] of plan.entries()) {
if (i) await Bun.sleep(delay);
const r = await fetch(searchUrl(p.keyword, p.storefront, limit), { headers: { Accept: 'application/json' } });
if (r.status === 403 || r.status === 429) { warn(TAG, `Search API answered ${r.status} (rate limit): stopped after ${read} of ${plan.length}; try later or with a larger --delay`); break; }
if (!r.ok) { warn(TAG, `${p.storefront} "${p.keyword}": HTTP ${r.status}`); continue; }
each(p, ((await r.json()) as { results?: SearchApp[] }).results ?? [], i);
read++;
}
return read;
}
async function rank(ctx: Ctx): Promise<void> {
const { config, resolve } = ctx.loaded;
const a = ctx.args;
if (a._[0] !== 'rank') throw new Error('usage: storebound aso rank [--storefronts us,de=de-DE] [--keywords "a,b"] [--dry] [--json]');
if (!config.apple) throw new Error('aso rank checks App Store search: the config has no apple section');
const primary = config.apple.primaryLocale ?? config.languages.find(l => l.apple)?.apple ?? 'en-US';
const listingFile = resolve(config.apple.listing ?? 'store/appstore.md');
const listing = existsSync(listingFile) ? appleSections(readFileSync(listingFile, 'utf8')) : new Map<string, Record<string, string | undefined>>();
const { file: listingFile, sections: listing } = listingOf(ctx);
const extra = a.list('keywords');
const fronts = parseStorefronts(a.list('storefronts'), primary);
const fronts = parseStorefronts(a.list('storefronts'), primaryLocale(ctx));
const n = a.num('competitors', 3);
const limit = a.num('limit', 200);
const delay = Math.max(MIN_DELAY_MS, a.num('delay', MIN_DELAY_MS));
@ -40,21 +94,16 @@ export async function run(ctx: Ctx): Promise<void> {
return;
}
const rows: RankRow[] = [];
for (const [i, p] of plan.entries()) {
if (i) await Bun.sleep(delay);
const r = await fetch(searchUrl(p.keyword, p.storefront, limit), { headers: { Accept: 'application/json' } });
if (r.status === 403 || r.status === 429) { warn(TAG, `Search API answered ${r.status} (rate limit): stopped after ${rows.length} of ${plan.length}; try later or with a larger --delay`); break; }
if (!r.ok) { warn(TAG, `${p.storefront} "${p.keyword}": HTTP ${r.status}`); continue; }
const results = ((await r.json()) as { results?: SearchApp[] }).results ?? [];
await searchAll(plan, limit, delay, (p, results, i) => {
const row: RankRow = { storefront: p.storefront, locale: p.locale, keyword: p.keyword, rank: rankOf(results, app), results: results.length, competitors: competitors(results, app, n) };
rows.push(row);
log(TAG, `${i + 1}/${plan.length} ${p.storefront} "${p.keyword}": ${row.rank ?? `not in the first ${results.length}`}`);
}
});
const dir = resolve('.storebound/aso');
const prevFile = existsSync(dir) ? readdirSync(dir).filter(f => /^\d{4}-\d{2}-\d{2}\.json$/.test(f)).sort().at(-1) : undefined;
const prevFile = snapshots<unknown>(dir).at(-1)?.file;
const prev = prevFile ? (JSON.parse(readFileSync(join(dir, prevFile), 'utf8')) as { rows?: RankRow[] }).rows : undefined;
const delta = rankDelta(rows, prev);
const date = new Date().toISOString().slice(0, 10);
const date = today();
if (a.has('json')) printJson({ date, previous: prevFile ?? null, rows: rows.map(r => ({ ...r, change: delta.get(`${r.storefront}|${r.keyword.toLowerCase()}`) ?? null })) });
else console.log(textTable(['store', 'keyword', 'rank', 'change', 'top competitors'], rows.map(r => {
const d = delta.get(`${r.storefront}|${r.keyword.toLowerCase()}`);
@ -64,3 +113,148 @@ export async function run(ctx: Ctx): Promise<void> {
writeFileSync(join(dir, `${date}.json`), JSON.stringify({ date, app: { appId: app.appId ?? null, bundleId: app.bundleId }, rows }, null, 2) + '\n');
done(TAG, `${rows.length} rank(s) saved to ${join(dir, `${date}.json`)}${prevFile ? ` (change vs ${prevFile})` : ''}; Search API order is close to App Store search, read it as a trend`);
}
async function competitorsCmd(ctx: Ctx): Promise<void> {
const { config, resolve } = ctx.loaded;
const a = ctx.args;
if (!config.apple) throw new Error('aso competitors reads App Store search: the config has no apple section');
const { file, sections } = listingOf(ctx);
const terms = a.many('term').flatMap(t => t.split(',')).map(t => t.trim()).filter(Boolean);
const fronts = parseStorefronts([...a.list('storefront'), ...a.list('storefronts')], primaryLocale(ctx));
const top = Math.max(1, Math.min(50, a.num('top', 10)));
const delay = Math.max(MIN_DELAY_MS, a.num('delay', MIN_DELAY_MS));
const app = { appId: config.apple.appId, bundleId: config.apple.bundleId };
const plan = fronts.flatMap(f => keywordList(a.has('only-terms') ? '' : sections.get(f.locale)?.keywords, terms).map(k => ({ ...f, keyword: k })));
if (!plan.length) throw new Error(`no terms: ${file} has no keywords for ${fronts.map(f => f.locale).join(', ')}; pass --term <keyword>`);
const limit = top + 1;
const save = !a.has('dry') && !a.has('no-save');
if (!a.has('json')) log(TAG, `${plan.length} quer${plan.length === 1 ? 'y' : 'ies'} (${fronts.map(f => f.storefront).join(', ')}), top ${top} each, one every ${delay / 1000}s: about ${Math.ceil(plan.length * delay / 60_000)} min`);
if (a.has('dry')) {
if (a.has('json')) printJson({ dryRun: true, top, queries: plan.map(p => ({ storefront: p.storefront, locale: p.locale, term: p.keyword, url: searchUrl(p.keyword, p.storefront, limit) })) });
else for (const p of plan) log(TAG, `would GET ${searchUrl(p.keyword, p.storefront, limit)}`);
return;
}
const rows: CompetitorRow[] = [];
await searchAll(plan, limit, delay, (p, results, i) => {
rows.push(competitorRow(results, app, { storefront: p.storefront, locale: p.locale, term: p.keyword }, top));
if (!a.has('json')) log(TAG, `${i + 1}/${plan.length} ${p.storefront} "${p.keyword}": ${results.length} result(s)`);
});
const dir = resolve('.storebound/aso/competitors');
const prev = snapshots<CompetitorSnapshot>(dir).filter(s => s.file !== `${today()}.json`).at(-1);
const fresh = newEntrants(rows, prev?.data.rows);
const gaps = fronts.map(f => {
const s = sections.get(f.locale) ?? {};
const covered = [...tokens(s.name ?? appleName(config), f.locale), ...tokens(s.subtitle ?? '', f.locale), ...(s.keywords ?? '').split(',').flatMap(t => tokens(t, f.locale))];
return { storefront: f.storefront, locale: f.locale, gaps: coverageGaps(rows.filter(r => r.storefront === f.storefront && r.locale === f.locale), covered, f.locale) };
});
const snap: CompetitorSnapshot = { date: today(), app: { appId: app.appId ?? null, bundleId: app.bundleId }, top, rows };
if (a.has('json')) printJson({ ...snap, previous: prev?.file ?? null, newEntrants: Object.fromEntries(fresh), gaps, saved: save,
notes: ['Search API order is close to, not equal to, App Store search', 'competitor subtitles are not in any public API'] });
else {
for (const r of rows) {
console.log(`\n${r.storefront} "${r.term}"${r.ourRank ? ` (you: #${r.ourRank})` : ''}`);
console.log(textTable(['#', 'app', 'developer', 'ratings', 'released', 'updated', 'genre'],
r.apps.map(x => [x.rank, x.name.slice(0, 40), x.developer.slice(0, 24), x.ratings, x.released ?? '-', x.updated ?? '-', x.genres[0]?.name || x.genre])));
const n = fresh.get(`${r.storefront}|${r.term.toLowerCase()}`);
if (n?.length) log(TAG, `new in the top ${top} since ${prev!.data.date}: ${n.join(', ')}`);
}
for (const g of gaps) console.log(`\n${g.storefront} ${g.locale}: words in competitors' names you do not cover: ${g.gaps.length ? g.gaps.map(x => `${x.word} (${x.apps} apps, ${x.developers} developers)`).join(', ') : 'none'}`);
log(TAG, 'subtitles are not in any public API, so they are not shown; words one developer uses are left out (likely a brand); never put other apps\' names into your keywords');
}
if (save) {
mkdirSync(dir, { recursive: true });
writeFileSync(join(dir, `${snap.date}.json`), JSON.stringify(snap, null, 2) + '\n');
if (!a.has('json')) done(TAG, `${rows.length} term(s) saved to ${join(dir, `${snap.date}.json`)}`);
}
}
async function suggest(ctx: Ctx): Promise<void> {
const { config, resolve, root } = ctx.loaded;
const a = ctx.args;
const json = a.has('json');
if (!config.apple) throw new Error('aso suggest proposes App Store keyword fields: the config has no apple section');
const { file, md } = listingOf(ctx);
if (!md) throw new Error(`${file} not found`);
const listing = parseAppStoreListing(md);
const locales = a.list('locale').length ? a.list('locale') : Object.keys(listing);
for (const l of locales) if (!listing[l]) throw new Error(`--locale ${l}: no "## ${l}" section in ${file}`);
const comp = snapshots<CompetitorSnapshot>(resolve('.storebound/aso/competitors')).at(-1)?.data ?? null;
const cats = Object.values(config.apple.info?.categories ?? {}).filter((x): x is string => typeof x === 'string');
// Apple Ads keyword suggestions: only with the owner's credentials and an Apple ID; never estimated without them
let ads: ReturnType<typeof adsClient> | null = null;
let adsNote = '';
if (a.has('offline')) adsNote = '--offline: Apple Ads not asked; popularity unknown';
else if (!config.apple.appId) adsNote = 'no apple.appId in the config: Apple Ads suggestions need the app\'s Apple ID; popularity unknown';
else {
try { ads = adsClient(root); if (!ads.accountId) { ads = null; adsNote = 'APPLE_ADS_ACCOUNT_ID is not set: popularity unknown'; } } catch (e) { adsNote = `no Apple Ads credentials (${(e as Error).message.split(';')[0]}): popularity unknown`; }
}
const results: { locale: string; storefront: string; ads: string; competitors: string | null; candidates: ReturnType<typeof candidates>; proposal: ReturnType<typeof fitKeywordField> }[] = [];
for (const locale of locales) {
const c = listing[locale]!;
const sf = storefrontOf(locale);
const rows = (comp?.rows ?? []).filter(r => r.locale === locale);
const name = c.name ?? appleName(config);
let sugg: AdsSuggestion[] = [];
let adsState = adsNote;
if (ads) {
const seeds = [...new Set([...tokens(name, locale), ...tokens(c.subtitle ?? '', locale), ...(c.keywords ?? '').split(',').map(t => t.trim()).filter(Boolean)])].slice(0, 20);
try {
sugg = parseKeywordSuggestions(await ads.post(ADS_KEYWORD_SUGGESTIONS, keywordSuggestionBody(config.apple.appId!, seeds, [sf])));
adsState = `Apple Ads keyword suggestions (${sf.toUpperCase()}): ${sugg.length}; popularity is Apple's relative 0-100 score, not a search volume`;
} catch (e) { adsState = `Apple Ads keyword suggestions failed (${(e as Error).message.slice(0, 160)}): popularity unknown`; }
}
const cands = candidates({ locale, name, subtitle: c.subtitle ?? '', keywords: c.keywords ?? '', description: c.description ?? '', competitors: rows, categories: categoryNames(rows, cats), ads: sugg });
const proposal = fitKeywordField({ locale, current: c.keywords ?? '', name, subtitle: c.subtitle ?? '', ranked: cands, fresh: a.has('fresh') });
results.push({ locale, storefront: sf, ads: adsState, competitors: rows.length ? `${comp!.date}: ${rows.length} term(s)` : null, candidates: cands, proposal });
}
const write = a.has('write') && !a.has('dry');
const changed = results.filter(r => r.proposal.after !== r.proposal.before);
if (json) printJson({ file, written: write && changed.length > 0, results: results.map(r => ({ ...r, candidates: r.candidates.slice(0, 60) })) });
else {
for (const r of results) {
console.log(`\n== ${r.locale} (storefront ${r.storefront}) · competitors: ${r.competitors ?? 'no snapshot (storebound aso competitors)'} · ${r.ads}`);
const shown = r.candidates.filter(c => c.status === 'candidate').slice(0, 25);
console.log(textTable(['candidate', 'from', 'relevance', 'in names', 'popularity'], shown.map(c => [c.term, c.sources.join('+'), `${c.relevance}/2`, `${c.inNames}/${c.ofApps}`,
c.popularity === null ? 'unknown' : `${c.popularity}${c.popularityFrom === 'phrase' ? ' (phrase)' : ''}`])));
const skipped = r.candidates.filter(c => c.status !== 'candidate' && c.kind === 'word').slice(0, 12);
if (skipped.length) log(TAG, `left out: ${skipped.map(c => `${c.term} (${c.why})`).join(', ')}`);
const p = r.proposal;
if (p.after === p.before) { log(TAG, `${r.locale}: keyword field unchanged (${p.bytes}/100 bytes)`); continue; }
console.log(`--- ${r.locale} keywords (store/appstore.md)\n- ${p.before || '(empty)'}\n+ ${p.after}\n ${p.bytes}/100 bytes · kept ${p.kept.length} · added ${p.added.join(', ') || 'none'}${p.dropped.length ? ` · dropped ${p.dropped.map(d => `${d.term} (${d.why})`).join(', ')}` : ''}`);
}
log(TAG, 'relevance: in your own text (+1) and in competitors\' names (+1); "in names": top apps that already have the word in their name; popularity only from Apple Ads, never estimated');
}
if (!changed.length) return;
if (!write) { if (!json) log(TAG, `dry run: nothing written; --write puts the ${changed.length} proposal(s) into ${file} as drafts for review`); return; }
let next = md;
for (const r of changed) next = setKeywords(next, r.locale, r.proposal.after, draftMark(today()));
writeFileSync(file, next);
if (!json) done(TAG, `wrote ${changed.length} draft keyword field(s) to ${file}: review them, delete the draft lines, then storebound check --aso`);
}
function audit(ctx: Ctx): void {
const { config, resolve } = ctx.loaded;
const a = ctx.args;
const storefront = (a.get('storefront') ?? 'US').toUpperCase();
const { file, md } = listingOf(ctx);
const apple = config.apple && md ? parseAppStoreListing(md) : undefined;
const playFile = resolve(config.play?.listing ?? 'store/listing.md');
const play = config.play && existsSync(playFile) ? parsePlayListing(readFileSync(playFile, 'utf8'), config.app.name) : undefined;
const findings = auditAso({ apple, play, appName: appleName(config), storefront });
const ranks = snapshots<RankSnap>(resolve('.storebound/aso')).map(s => ({ date: s.data.date, rows: s.data.rows ?? [] }));
const comp = snapshots<CompetitorSnapshot>(resolve('.storebound/aso/competitors')).at(-1)?.data ?? null;
const analytics = mergeSeries(snapshots<Snapshot>(resolve('.storebound/analytics')).map(s => s.data)).apple;
const r = buildAudit({ today: today(), storefront, findings, drafts: md ? draftLocales(md) : [], apple, appName: appleName(config), play, ranks, competitors: comp, analytics,
variants: Object.keys(config.shots?.variants ?? {}) });
if (a.has('json')) return printJson({ ...r, files: { appstore: apple ? file : null, play: play ? playFile : null } });
console.log(auditText(r));
}
export async function run(ctx: Ctx): Promise<void> {
const sub = ctx.args._[0];
if (!sub || !SUBS.includes(sub)) throw new Error('usage: storebound aso rank | competitors | suggest | audit (see the aso-basics skill)');
if (sub === 'rank') return rank(ctx);
if (sub === 'competitors') return competitorsCmd(ctx);
if (sub === 'suggest') return suggest(ctx);
return audit(ctx);
}

View file

@ -7,6 +7,7 @@
import { existsSync, readFileSync } from 'node:fs';
import { relative } from 'node:path';
import { type AsoFinding, auditAso } from './lib/aso';
import { draftLocales } from './lib/aso-intel';
import { appleName, playCodes } from './lib/config';
import { APPLE_IAP_LIMITS, appleNameIssues, len, parseAppStoreListing, parsePlayListing } from './lib/copy';
import type { Ctx } from './lib/ctx';
@ -20,9 +21,11 @@ import { type CopyFile, validateCopy } from './shots/lib';
function aso(ctx: Ctx): void {
const { config, resolve } = ctx.loaded;
const apple = config.apple ? parseAppStoreListing(readFileSync(resolve(config.apple.listing ?? 'store/appstore.md'), 'utf8')) : undefined;
const appleMd = config.apple ? readFileSync(resolve(config.apple.listing ?? 'store/appstore.md'), 'utf8') : '';
const apple = config.apple ? parseAppStoreListing(appleMd) : undefined;
const play = config.play ? parsePlayListing(readFileSync(resolve(config.play.listing ?? 'store/listing.md'), 'utf8'), config.app.name) : undefined;
const f: AsoFinding[] = auditAso({ apple, play, appName: appleName(config), storefront: ctx.args.get('storefront') ?? 'US' });
for (const l of draftLocales(appleMd)) f.push({ level: 'warn', where: `apple ${l}`, msg: 'keywords: draft from `aso suggest`, not reviewed yet (review, then delete the storebound-aso draft line)' });
if (ctx.args.has('json')) { const errors = f.filter(x => x.level === 'error').length; printJson({ findings: f, errors }); if (errors) process.exitCode = 1; return; }
const tag = { error: 'ERROR', warn: 'warn ', info: 'info ' } as const;
for (const x of f) console.log(`${tag[x.level]} [${x.where}] ${x.msg}`);

View file

@ -32,7 +32,7 @@ export const COMMANDS: Record<string, [() => Promise<Mod>, string]> = {
'catalog': [() => import('./catalog'), 'diff: cross-store parity of products + subscriptions (missing / extra / mismatched, prices per region, offers); read-only, exit 1 on mismatches | pull [--write]: store texts of IAPs + subscriptions as a config proposal'],
'reports': [() => import('./reports'), 'apple-sales | apple-finance --month | play-earnings --month | play-sales --month: download to .storebound/reports/, summary table + CSV; read-only'],
'triage': [() => import('./triage'), 'TestFlight crash / screenshot feedback and Play error reports grouped by signature, device, OS version, build; read-only, --json'],
'aso': [() => import('./aso'), 'rank [--storefronts us,de] [--keywords a,b]: App Store rank per keyword and storefront + competitors from the public iTunes Search API (rate limited) -> .storebound/aso/'],
'aso': [() => import('./aso'), 'rank | competitors | suggest | audit: App Store ranks, top apps per keyword, keyword field proposals (Apple Ads popularity with credentials) and one ASO report, from the public iTunes Search API -> .storebound/aso/'],
'prices': [() => import('./prices'), 'export | import a CSV of product x store x region prices (diff first, asks before writing; Apple future-dated changes) | ppp --base <USD> (purchasing power price sheet, snapped to store price points)'],
'ads apple': [() => import('./ads/apple'), 'Apple Ads (Search Ads): status | campaigns | report (spend, taps, installs, CPA per campaign / keyword, --csv); bid | budget | pause (dry run, asks first; never via MCP)'],
'web': [() => import('./web'), 'init (apple-app-site-association, assetlinks.json, Smart App Banner tag, optional landing page) | check <domain> (live files: content type, no redirects, ids match)'],
@ -46,7 +46,7 @@ export const COMMANDS: Record<string, [() => Promise<Mod>, string]> = {
'play subscriptions': [() => import('./play/subscriptions'), 'auto-renewable subscriptions: listings, base plan, regional prices, intro offer, activate (--csv prices sheet; asks first)'],
'play listing': [() => import('./play/listing'), 'app details + title / short / full description per language; pull [--write]: live listings back into the listing file (diff first)'],
'play images': [() => import('./play/images'), 'icon, feature graphic, phone / 7" / 10" screenshots per language; --variant <id>'],
'play data-safety': [() => import('./play/data-safety'), 'Data safety form (CSV import through the API)'],
'play data-safety': [() => import('./play/data-safety'), '[--force] Data safety form (CSV import through the API; skipped when unchanged since the last upload)'],
'play release': [() => import('./play/release'), 'upload an AAB and put it on tracks with release notes'],
'play build': [() => import('./play/build'), 'gradle bundleRelease (Flutter: flutter build appbundle) with the next free versionCode and the upload key from env / .storebound; --dry'],
'play upload': [() => import('./play/upload'), 'upload an AAB to a testing track (--track internal|alpha|beta), versionCode checked first; --dry read-only, asks first'],

View file

@ -168,6 +168,8 @@ export interface OpenOpts {
hosts?: string[];
headless?: boolean;
platform?: string;
/** Tests: Playwright's launch timeout for modes (b) and (c) (default: Playwright's 30 s). */
launchTimeoutMs?: number;
say: (m: string) => void;
}
@ -233,7 +235,7 @@ export async function openConsoleBrowser(root: string, o: OpenOpts): Promise<Con
copy = await copySession(chromeDir, { ...(o.chromeProfile ? { profile: o.chromeProfile } : {}), ...(o.hosts ? { hosts: o.hosts } : {}) });
const c = await chromiumFor(root);
const context = await c.launchPersistentContext(copy.dir, {
channel: 'chrome', headless: o.headless ?? false, viewport: null, args: KEEP_SESSION_ARGS,
channel: 'chrome', headless: o.headless ?? false, viewport: null, args: KEEP_SESSION_ARGS, ...(o.launchTimeoutMs ? { timeout: o.launchTimeoutMs } : {}),
// Playwright's mock keychain would hide Chrome's own key, and the cookies could not be read
ignoreDefaultArgs: ['--use-mock-keychain', '--password-store=basic'],
});
@ -251,7 +253,7 @@ export async function openConsoleBrowser(root: string, o: OpenOpts): Promise<Con
}
// (c) storebound's persistent profile, the owner signs in there
mkdirSync(o.profileDir, { recursive: true });
const context = await launchPersistent(root, o.profileDir, { headless: o.headless ?? false, viewport: null, args: KEEP_SESSION_ARGS });
const context = await launchPersistent(root, o.profileDir, { headless: o.headless ?? false, viewport: null, args: KEEP_SESSION_ARGS, ...(o.launchTimeoutMs ? { timeout: o.launchTimeoutMs } : {}) });
o.say(`browser: storebound's own profile (${o.profileDir}); sign in there once, it is kept for the next run`);
const page = await ownTab(context);
return wrapContext('profile', context, page, () => { /* kept on purpose */ });

View file

@ -238,10 +238,19 @@
"aso": [
"competitors",
"delay",
"fresh",
"keywords",
"limit",
"locale",
"no-save",
"offline",
"only-keywords",
"storefronts"
"only-terms",
"storefront",
"storefronts",
"term",
"top",
"write"
],
"catalog": [
"all",
@ -343,7 +352,8 @@
"version-name"
],
"play data-safety": [
"csv"
"csv",
"force"
],
"play images": [
"include-drafts",
@ -665,6 +675,7 @@
"format",
"fraction",
"frequency",
"fresh",
"fresh-profile",
"from",
"godot",
@ -708,6 +719,7 @@
"no-install",
"no-local",
"no-mcp",
"no-save",
"no-scan",
"no-sheet",
"no-skills",
@ -721,6 +733,7 @@
"older-than",
"only-keywords",
"only-missing",
"only-terms",
"originality",
"out",
"param",
@ -762,11 +775,13 @@
"storefronts",
"submit-review",
"target",
"term",
"territories",
"text",
"threshold",
"timeout",
"to",
"top",
"track",
"traffic",
"translate",
@ -927,7 +942,10 @@
"storebound apps check [--store apple|play] [--json] auth OK / permission missing / key revoked, with the fix"
],
"aso": [
"storebound aso rank [--storefronts us,de=de-DE] [--keywords \"a,b\"] [--only-keywords] [--competitors 3] [--limit 200]"
"storebound aso rank [--storefronts us,de=de-DE] [--keywords \"a,b\"] [--only-keywords] [--competitors 3] [--limit 200]",
"storebound aso competitors [--term <kw>]... [--storefront us,tr] [--only-terms] [--top 10] [--delay 3500] [--no-save] [--dry] [--json]",
"storebound aso suggest [--locale en-US,tr] [--fresh] [--offline] [--write] [--json]",
"storebound aso audit [--storefront US] [--json]"
],
"catalog": [
"storebound catalog diff [--store apple|play] [--threshold 10] [--json]",
@ -991,7 +1009,7 @@
"storebound play build [--version-code N] [--version-name 1.2.0] [--flavor prod] [--dir android] [--module app]"
],
"play data-safety": [
"storebound play data-safety [--csv out.csv] [--dry]"
"storebound play data-safety [--csv out.csv] [--dry] [--force]"
],
"play images": [
"storebound play images [--dry] [--only en-US,de-DE] [--src store/renders] [--variant b]"

221
cli/lib/aso-audit.ts Normal file
View file

@ -0,0 +1,221 @@
// `aso audit`: one offline report over everything storebound already keeps, as pure parts. Inputs: the `check --aso`
// findings and the cross-locale free-keyword-room hint (cli/lib/aso.ts), the rank snapshots of `aso rank`
// (.storebound/aso/<date>.json, trend arrows), the latest competitor snapshot of `aso competitors`
// (.storebound/aso/competitors/<date>.json, coverage gaps), the Play listing (keyword density, short description use),
// the App Store analytics snapshots (.storebound/analytics, impressions / downloads / conversion) and the screenshot
// variants of the config. Output: the report, experiment ideas (suggestions only: nothing is started) and the next 3
// concrete actions. No network, no writes.
import type { AppleDay } from './analytics';
import type { AsoFinding } from './aso';
import { words } from './aso';
import { type CompetitorSnapshot, coverageGaps, type Gap, isStop, tokens } from './aso-intel';
import type { RankRow } from './aso-rank';
import type { AppleCopy, PlayCopy } from './copy';
import { len } from './copy';
import { textTable } from './table';
export interface RankSnap { date: string; rows: RankRow[] }
export type Arrow = '↑' | '↓' | '→' | 'new' | 'lost' | '·';
export interface TrendRow { storefront: string; keyword: string; rank: number | null; previous: number | null; change: number | null; arrow: Arrow; best: number | null; snapshots: number }
const k = (r: { storefront: string; keyword: string }) => `${r.storefront}|${r.keyword.toLowerCase()}`;
/** Latest rank per storefront + keyword against the snapshot before it (positive change = moved up). Pure. */
export function rankTrend(snaps: RankSnap[]): { rows: TrendRow[]; dates: string[]; series: { storefront: string; keyword: string; ranks: (number | null)[] }[] } {
const sorted = [...snaps].sort((a, b) => a.date.localeCompare(b.date));
const dates = sorted.map(s => s.date);
const hist = new Map<string, { storefront: string; keyword: string; ranks: (number | null | undefined)[] }>();
sorted.forEach((s, i) => {
for (const r of s.rows) {
const h = hist.get(k(r)) ?? { storefront: r.storefront, keyword: r.keyword, ranks: Array(sorted.length).fill(undefined) };
h.ranks[i] = r.rank;
hist.set(k(r), h);
}
});
const rows: TrendRow[] = [];
for (const h of hist.values()) {
const seen = h.ranks.map((v, i) => ({ v, i })).filter(x => x.v !== undefined) as { v: number | null; i: number }[];
const last = seen.at(-1)!, prev = seen.at(-2);
const rank = last.v, previous = prev ? prev.v : null;
const arrow: Arrow = !prev ? (rank === null ? '·' : 'new') : rank === null ? (previous === null ? '·' : 'lost') : previous === null ? 'new'
: rank < previous ? '↑' : rank > previous ? '↓' : '→';
const known = seen.map(x => x.v).filter((v): v is number => v !== null);
rows.push({ storefront: h.storefront, keyword: h.keyword, rank, previous, change: rank !== null && previous !== null ? previous - rank : null, arrow,
best: known.length ? Math.min(...known) : null, snapshots: seen.length });
}
rows.sort((a, b) => a.storefront.localeCompare(b.storefront) || (a.rank ?? 999) - (b.rank ?? 999) || a.keyword.localeCompare(b.keyword));
const series = [...hist.values()].map(h => ({ storefront: h.storefront, keyword: h.keyword, ranks: h.ranks.map(v => v ?? null) }));
return { rows, dates, series };
}
export interface PlayUse { lang: string; title: string; shortChars: number; shortRoom: number; titleWordsInShort: boolean; shortWordsInOpening: boolean; top: { word: string; count: number; density: number }[]; stuffed: string[] }
/** Play: how the short description is used and which words the full description leans on (density). Pure. */
export function playUse(c: PlayCopy): PlayUse {
const L = c.lang;
const full = words(c.full, L);
const counts = new Map<string, number>();
for (const w of full) if (w.length > 3 && !isStop(w, L)) counts.set(w, (counts.get(w) ?? 0) + 1);
const top = [...counts.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, 5)
.map(([word, count]) => ({ word, count, density: full.length ? count / full.length : 0 }));
const titleWords = tokens(c.title, L).filter(w => w.length > 2);
const shortWords = new Set(tokens(c.short, L));
const opening = new Set(words(c.full.split('\n').slice(0, 3).join(' '), L));
return {
lang: L, title: c.title, shortChars: len(c.short), shortRoom: 80 - len(c.short),
titleWordsInShort: titleWords.some(w => shortWords.has(w)),
shortWordsInOpening: [...shortWords].some(w => w.length > 3 && opening.has(w)),
top, stuffed: top.filter(t => full.length >= 80 && t.count >= 6 && t.density > 0.03).map(t => t.word),
};
}
export interface Experiment { store: 'apple' | 'play'; what: string; why: string; how: string }
export interface Action { what: string; why: string; command?: string }
export interface AuditInput {
today: string;
storefront: string;
findings: AsoFinding[];
drafts: string[];
apple?: Record<string, AppleCopy>;
appName: string;
play?: PlayCopy[];
ranks: RankSnap[];
competitors: CompetitorSnapshot | null;
analytics: AppleDay[];
variants: string[];
}
export interface AsoAudit {
generated: string; storefront: string;
keywordField: { errors: number; warnings: number; hints: number; findings: AsoFinding[] };
crossLocale: string | null;
drafts: string[];
ranks: { snapshots: number; latest: string | null; rows: TrendRow[]; dates: string[]; series: { storefront: string; keyword: string; ranks: (number | null)[] }[] };
competitors: { date: string | null; gaps: { storefront: string; locale: string; gaps: Gap[] }[] };
play: PlayUse[];
/** check --aso findings of the Play listing (stuffing, claims, caps, emoji, short description room). */
playFindings: AsoFinding[];
analytics: { days: number; start: string; end: string; impressions: number; pageViews: number; downloads: number; conversion: number | null } | null;
experiments: Experiment[];
next: Action[];
}
const daysBetween = (a: string, b: string) => Math.round((Date.parse(b) - Date.parse(a)) / 86_400_000);
/** The whole audit. Pure. */
export function buildAudit(i: AuditInput): AsoAudit {
const kwFindings = i.findings.filter(f => f.where.startsWith('apple ') && !/storefront$/.test(f.where));
const playFindings = i.findings.filter(f => f.where.startsWith('play '));
const cross = i.findings.find(f => /storefront$/.test(f.where))?.msg ?? null;
const trend = rankTrend(i.ranks);
const gaps: AsoAudit['competitors']['gaps'] = [];
if (i.competitors) {
const groups = new Map<string, CompetitorSnapshot['rows']>();
for (const r of i.competitors.rows) groups.set(`${r.storefront}|${r.locale}`, [...(groups.get(`${r.storefront}|${r.locale}`) ?? []), r]);
for (const [g, rows] of groups) {
const [storefront, locale] = g.split('|') as [string, string];
const c = i.apple?.[locale];
const covered = [...words(c?.name ?? i.appName, locale), ...words(c?.subtitle ?? '', locale), ...(c?.keywords ?? '').split(',').flatMap(t => words(t, locale))];
gaps.push({ storefront, locale, gaps: coverageGaps(rows, covered, locale, 8) });
}
}
const play = (i.play ?? []).map(playUse);
const last = i.analytics.slice(-28);
const sum = (f: (d: AppleDay) => number) => last.reduce((n, d) => n + f(d), 0);
const analytics = last.length ? { days: last.length, start: last[0]!.date, end: last.at(-1)!.date, impressions: sum(d => d.uniqueImpressions || d.impressions),
pageViews: sum(d => d.uniquePageViews || d.pageViews), downloads: sum(d => d.firstTimeDownloads || d.downloads), conversion: null as number | null } : null;
if (analytics) analytics.conversion = analytics.impressions ? analytics.downloads / analytics.impressions : null;
const a: AsoAudit = {
generated: i.today, storefront: i.storefront,
keywordField: { errors: kwFindings.filter(f => f.level === 'error').length, warnings: kwFindings.filter(f => f.level === 'warn').length, hints: kwFindings.filter(f => f.level === 'info').length, findings: kwFindings },
crossLocale: cross, drafts: i.drafts,
ranks: { snapshots: i.ranks.length, latest: trend.dates.at(-1) ?? null, rows: trend.rows, dates: trend.dates, series: trend.series },
competitors: { date: i.competitors?.date ?? null, gaps },
play, playFindings, analytics, experiments: [], next: [],
};
a.experiments = experimentIdeas(a, i);
a.next = nextActions(a, i);
return a;
}
/** Product Page Optimization (Apple) and store listing experiment (Play) ideas from the audit. Suggestions only. Pure. */
export function experimentIdeas(a: AsoAudit, i: AuditInput): Experiment[] {
const out: Experiment[] = [];
if (i.apple) {
const v = i.variants[0];
out.push({ store: 'apple', what: 'first screenshot caption: lead with the search phrase people use for the app\'s main job',
why: a.analytics?.conversion !== null && a.analytics ? `App Store conversion (first-time downloads / unique impressions, last ${a.analytics.days} days) is ${(a.analytics.conversion! * 100).toFixed(1)}%: the first screenshot is what search results show` : 'the first screenshot is what search results show; PPO measures it against the original',
how: v ? `variant "${v}" exists: storebound shots render --variant ${v}, then storebound apple ppo create --variant ${v} --dry and apple ppo upload --variant ${v} --dry (starting the test is the owner's step: apple ppo start)`
: 'add a shots.variants entry with the new caption, storebound shots render --variant b, then storebound apple ppo create --variant b --dry (starting the test is the owner\'s step: apple ppo start)' });
out.push({ store: 'apple', what: 'subtitle variant',
why: 'PPO tests only icons, screenshots and app previews: the subtitle cannot be A/B tested on the App Store',
how: 'change it with the next version and compare before / after with storebound analytics compare (one change at a time)' });
}
for (const p of a.play.slice(0, 1)) {
out.push({ store: 'play', what: `short description variant (${p.lang})`,
why: p.shortRoom > 30 ? `the short description uses ${p.shortChars}/80 characters` : !p.titleWordsInShort ? 'the short description shares no word with the title' : 'the short description is the first text on the listing',
how: 'Play Console > Grow users > Store listing experiments (no API: storebound only prepares the text; the store-screenshots skill has the steps)' });
if (i.variants.length) out.push({ store: 'play', what: `screenshot variant "${i.variants[0]}"`, why: 'graphics experiments need no new version',
how: `storebound shots render --variant ${i.variants[0]} --size play, then upload it as the experiment's variant in Play Console` });
}
return out;
}
/** The next 3 concrete actions, most important first. Pure. */
export function nextActions(a: AsoAudit, i: AuditInput): Action[] {
const out: Action[] = [];
const f = a.keywordField.findings;
const err = f.find(x => x.level === 'error');
if (err) out.push({ what: `fix ${err.where}: ${err.msg}`, why: 'App Store Connect refuses the keyword field as it is', command: 'storebound check --aso' });
if (a.drafts.length) out.push({ what: `review the draft keywords of ${a.drafts.join(', ')} in store/appstore.md and delete the draft line`, why: 'they were proposed by aso suggest, not reviewed yet' });
const room = f.find(x => /bytes used; fill/.test(x.msg));
if (room) out.push({ what: `fill the keyword field of ${room.where.replace('apple ', '')} (${room.msg.replace(/^keywords: /, '')})`, why: 'unused bytes are unused search reach', command: `storebound aso suggest --locale ${room.where.replace('apple ', '')}` });
const rep = f.find(x => /repeat words from the name/.test(x.msg));
if (rep) out.push({ what: `${rep.where}: replace the words the name / subtitle already index (${rep.msg.split(': ').at(-1)})`, why: 'they take bytes without adding reach', command: `storebound aso suggest --locale ${rep.where.replace('apple ', '')}` });
const gap = a.competitors.gaps.find(g => g.gaps.length);
if (gap) out.push({ what: `consider "${gap.gaps.slice(0, 3).map(g => g.word).join('", "')}" for ${gap.locale} (in the names of ${gap.gaps[0]!.developers} developers' top apps, not in your name / subtitle / keywords)`, why: 'words the top apps lead with; only if they describe your app', command: `storebound aso suggest --locale ${gap.locale}` });
const lost = a.ranks.rows.filter(r => r.arrow === '↓' || r.arrow === 'lost');
if (lost.length) out.push({ what: `look at the keywords that dropped: ${lost.slice(0, 3).map(r => `${r.storefront} "${r.keyword}" ${r.previous ?? '-'} -> ${r.rank ?? '-'}`).join(', ')}`, why: 'a drop after a listing change is the signal to revert or adjust it' });
if (!a.ranks.latest) out.push({ what: 'take a first rank snapshot', why: 'trends need a baseline before the next listing change', command: 'storebound aso rank --dry, then storebound aso rank' });
else if (daysBetween(a.ranks.latest, i.today) > 14) out.push({ what: `take a new rank snapshot (the last is from ${a.ranks.latest})`, why: 'trend arrows compare the last two snapshots', command: 'storebound aso rank' });
if (!a.competitors.date) out.push({ what: 'read the competitors for your keywords', why: 'coverage gaps and suggest need the top apps per term', command: 'storebound aso competitors --dry, then storebound aso competitors' });
for (const p of a.play) {
if (p.stuffed.length) out.push({ what: `Play ${p.lang}: use "${p.stuffed.join('", "')}" less often in the full description`, why: 'reads as keyword stuffing (Play metadata policy)' });
else if (p.shortRoom > 30) out.push({ what: `Play ${p.lang}: put the core phrase into the short description (${p.shortChars}/80 used)`, why: 'Play indexes the short description' });
}
if (!a.analytics) out.push({ what: 'start App Store analytics snapshots', why: 'conversion before / after each listing change is the real measure', command: 'storebound analytics setup --dry, then storebound analytics snapshot' });
return out.slice(0, 3);
}
const signed = (n: number | null) => (n === null ? '' : n > 0 ? `+${n}` : String(n));
/** The report as text. Pure. */
export function auditText(a: AsoAudit): string {
const o: string[] = [];
const kf = a.keywordField;
o.push(`ASO audit ${a.generated} (offline: listing files, .storebound/aso snapshots, .storebound/analytics)`, '');
o.push(`1. Keyword field (check --aso): ${kf.errors} errors, ${kf.warnings} warnings, ${kf.hints} hints`);
for (const f of kf.findings.filter(x => x.level !== 'info').slice(0, 8)) o.push(` ${f.level === 'error' ? 'ERROR' : 'warn '} [${f.where}] ${f.msg}`);
if (a.drafts.length) o.push(` draft keywords (from aso suggest, not reviewed): ${a.drafts.join(', ')}`);
if (a.crossLocale) o.push(` ${a.storefront} storefront: ${a.crossLocale}`);
o.push('', `2. Ranks (aso rank, iTunes Search API order; a trend, not App Store search itself): ${a.ranks.snapshots} snapshot(s)${a.ranks.latest ? `, latest ${a.ranks.latest}` : ''}`);
if (a.ranks.rows.length) o.push(indent(textTable(['store', 'keyword', 'rank', '', 'change', 'best'], a.ranks.rows.map(r => [r.storefront, r.keyword, r.rank ?? '-', r.arrow, signed(r.change), r.best ?? '-']))));
else o.push(' none yet: storebound aso rank');
o.push('', `3. Competitor coverage (aso competitors${a.competitors.date ? `, ${a.competitors.date}` : ''}): words in the top apps' names you do not cover`);
if (!a.competitors.date) o.push(' no snapshot yet: storebound aso competitors');
for (const g of a.competitors.gaps) o.push(` ${g.storefront} ${g.locale}: ${g.gaps.length ? g.gaps.map(x => `${x.word} (${x.apps} apps, ${x.developers} devs)`).join(', ') : 'none'}`);
o.push('', '4. Google Play listing');
if (!a.play.length) o.push(' no Play listing');
for (const f of a.playFindings.filter(x => x.level !== 'info')) o.push(` warn [${f.where}] ${f.msg}`);
for (const p of a.play) o.push(` ${p.lang}: short ${p.shortChars}/80${p.titleWordsInShort ? '' : ', no title word in it'}${p.shortWordsInOpening ? '' : ', opening lines share no word with it'}; top words ${p.top.map(t => `${t.word} ${t.count}x (${(t.density * 100).toFixed(1)}%)`).join(', ') || '-'}${p.stuffed.length ? `; STUFFING: ${p.stuffed.join(', ')}` : ''}`);
o.push('', '5. App Store analytics (analytics snapshot)');
o.push(a.analytics ? ` ${a.analytics.start} .. ${a.analytics.end} (${a.analytics.days} days): ${a.analytics.impressions} unique impressions, ${a.analytics.pageViews} product page views, ${a.analytics.downloads} first-time downloads, conversion ${a.analytics.conversion === null ? 'n/a' : `${(a.analytics.conversion * 100).toFixed(2)}%`}` : ' no snapshots: storebound analytics snapshot');
o.push('', '6. Experiment ideas (suggestions only; nothing is started)');
for (const e of a.experiments) o.push(` [${e.store === 'apple' ? 'App Store PPO' : 'Play experiment'}] ${e.what}`, ` why: ${e.why}`, ` how: ${e.how}`);
o.push('', 'Next 3 actions');
a.next.forEach((x, n) => o.push(` ${n + 1}. ${x.what}`, ` why: ${x.why}${x.command ? `; run: ${x.command}` : ''}`));
return o.join('\n');
}
const indent = (s: string) => s.split('\n').map(l => ` ${l}`).join('\n');

366
cli/lib/aso-intel.ts Normal file
View file

@ -0,0 +1,366 @@
// ASO keyword research from official and public data only, as pure parts. The commands are in cli/aso.ts
// (`aso competitors`, `aso suggest`); the audit report is cli/lib/aso-audit.ts.
//
// Data sources and what each number is (and is not):
// - iTunes Search API (public, no account; https://performance-partners.apple.com/search-api): the top N apps for a
// term in one storefront, with name (trackName), developer, rating count, first release date, last update, genre
// and the genre names localized to that storefront ("genres": "Produktivität" for country=de). Its order is close
// to, not equal to, App Store search. It has no subtitle field, so competitor subtitles are never shown.
// - Apple Ads Platform API, POST /v1/suggestions/keywords/query (only with the owner's Apple Ads credentials):
// keyword suggestions for the app (promotedObjectId = Apple ID, promotedObjectType APPSTORE_APP), seeded with
// `terms` and scoped with `countriesOrRegions`; each KeywordSuggestion is { text, popularity } where popularity is
// "a relative popularity score (not an absolute volume)" on a 0-100 scale. That is the only popularity signal
// storebound shows; without credentials popularity stays "unknown" (never estimated).
// https://developer.apple.com/documentation/apple-ads-platform-api/query-keyword-suggestions
// https://developer.apple.com/documentation/apple-ads-platform-api/keywordsuggestion
// https://developer.apple.com/documentation/apple-ads-platform-api/recommendationqueryrequest (pageSize 1..1000)
// (The Recommendations endpoints are budget / target CPA only; Insights has search term popularity 1-5 by genre,
// not used here.)
// - The app's own listing (store/appstore.md): name, subtitle, keyword field and description.
// Nothing here scrapes a store web page or calls a third-party ASO service.
import { FILLER, words } from './aso';
import type { SearchApp } from './aso-rank';
// ---------------------------------------------------------------------------------------------------------------
// Words
/** Function words that never make a keyword (a few languages; extend as needed). FILLER (app, game, free ...) too. */
const STOP: Record<string, string[]> = {
en: ['to', 'in', 'on', 'at', 'by', 'or', 'is', 'it', 'its', 'you', 'your', 'our', 'we', 'my', 'me', 'all', 'one', 'new', 'more', 'from', 'that', 'this', 'are', 'be', 'can', 'get', 'up', 'out', 'as', 'so', 'no', 'not', 'any', 'every', 'each', 'just', 'into', 'than', 'then', 'also', 'will', 'has', 'have', 'only', 'when', 'what', 'who', 'how', 'way', 'like', 'use', 'make', 'keep', 'see'],
de: ['der', 'die', 'das', 'und', 'mit', 'für', 'von', 'zu', 'ein', 'eine', 'ist', 'im', 'in', 'auf', 'den', 'dem', 'des', 'sie', 'du', 'dein', 'deine', 'alle', 'oder', 'auch'],
fr: ['le', 'la', 'les', 'et', 'de', 'des', 'du', 'un', 'une', 'pour', 'avec', 'en', 'au', 'aux', 'vos', 'votre', 'est', 'dans', 'sur', 'ou', 'tout', 'tous'],
es: ['el', 'la', 'los', 'las', 'y', 'de', 'del', 'un', 'una', 'para', 'con', 'en', 'tu', 'tus', 'es', 'por', 'o', 'que', 'todo', 'todos'],
pt: ['o', 'a', 'os', 'as', 'e', 'de', 'do', 'da', 'um', 'uma', 'para', 'com', 'em', 'seu', 'sua', 'no', 'na', 'ou', 'que', 'todo', 'todos'],
it: ['il', 'lo', 'la', 'le', 'gli', 'e', 'di', 'del', 'un', 'una', 'per', 'con', 'in', 'tuo', 'tua', 'che', 'tutti'],
tr: ['ve', 'ile', 'için', 'göre', 'kadar', 'sonra', 'önce', 'olan', 'olarak', 'bir', 'bu', 'şu', 'da', 'de', 'mi', 'en', 'çok', 'her', 'tüm', 'gibi', 'daha', 'sen', 'senin'],
};
/** Words of listing boilerplate (account, settings, privacy ...): they describe the store page, not the app's job. */
const BOILER = new Set(['account', 'accounts', 'settings', 'sign', 'signin', 'login', 'delete', 'privacy', 'policy', 'terms', 'support', 'contact', 'feature', 'features',
'update', 'updates', 'version', 'subscription', 'purchase', 'purchases', 'time', 'any', 'back', 'between', 'off', 'next', 'keeps', 'keep', 'item', 'items',
'change', 'changes', 'show', 'shows', 'work', 'works', 'people', 'phone', 'phones', 'here', 'there', 'about', 'want', 'need', 'help', 'day', 'days', 'even', 'much', 'many']);
const lang = (locale: string): string => locale.split('-')[0]!.toLowerCase();
export const isStop = (w: string, locale: string): boolean => FILLER.has(w) || BOILER.has(w) || (STOP[lang(locale)] ?? []).includes(w) || STOP.en!.includes(w) || /^\d+$/.test(w);
/** "Ayarlar'dan" -> "Ayarlar", "it's" -> "it": the suffix after an apostrophe is not a word of its own. */
const unApostrophe = (s: string): string => s.replace(/['’]\p{L}+/gu, '');
/** Content words of a text (lowercased for the locale, function words, boilerplate and numbers left out). Pure. */
export const tokens = (s: string, locale: string): string[] => words(unApostrophe(s), locale).filter(w => !isStop(w, locale));
/** Two-word phrases of content words that stand next to each other in the text. Pure. */
export function bigrams(s: string, locale: string): string[] {
const out: string[] = [];
for (const seg of unApostrophe(s).split(/[.!?\n:;,()"“”«»•·|/–—-]+/)) {
const ws = words(seg, locale);
for (let i = 0; i + 1 < ws.length; i++) if (!isStop(ws[i]!, locale) && !isStop(ws[i + 1]!, locale)) out.push(`${ws[i]} ${ws[i + 1]}`);
}
return out;
}
/** Plural-insensitive key: languages whose plural is mostly "-s" fold "lists" and "list" together. Pure. */
export function stem(w: string, locale: string): string {
const l = lang(locale);
if (l === 'en' && w.length > 4 && w.endsWith('ies')) return w.slice(0, -3) + 'y'; // groceries -> grocery
return ['en', 'fr', 'es', 'pt'].includes(l) && w.length > 3 && w.endsWith('s') && !w.endsWith('ss') ? w.slice(0, -1) : w;
}
/** Languages that add suffixes to a word ("listeler", "listelerini"): one word starts with the other. */
const SUFFIXING = new Set(['tr', 'fi', 'hu', 'et', 'az', 'kk', 'uz']);
/** The same keyword for search: plural-insensitive, and in suffixing languages a word that only adds a short suffix
* (up to 5 letters) to a word of at least 4. A heuristic: it errs on the side of not repeating a word. Pure. */
export function sameWord(a: string, b: string, locale: string): boolean {
const x = stem(a, locale), y = stem(b, locale);
if (x === y) return true;
if (!SUFFIXING.has(lang(locale))) return false;
const [s, l] = x.length <= y.length ? [x, y] : [y, x];
return s.length >= 4 && l.startsWith(s) && l.length - s.length <= 5;
}
const coveredBy = (w: string, set: Iterable<string>, locale: string): boolean => { for (const s of set) if (sameWord(w, s, locale)) return true; return false; };
// ---------------------------------------------------------------------------------------------------------------
// Competitors (iTunes Search API)
/** App Store Connect category id -> iTunes genre id (the "genreIds" of Search API results). Apple's genre ids. */
export const GENRE_IDS: Record<string, string> = {
BOOKS: '6018', BUSINESS: '6000', DEVELOPER_TOOLS: '6026', EDUCATION: '6017', ENTERTAINMENT: '6016', FINANCE: '6015', FOOD_AND_DRINK: '6023', GAMES: '6014',
GRAPHICS_AND_DESIGN: '6027', HEALTH_AND_FITNESS: '6013', LIFESTYLE: '6012', MAGAZINES_AND_NEWSPAPERS: '6021', MEDICAL: '6020', MUSIC: '6011', NAVIGATION: '6010',
NEWS: '6009', PHOTO_AND_VIDEO: '6008', PRODUCTIVITY: '6007', REFERENCE: '6006', SHOPPING: '6024', SOCIAL_NETWORKING: '6005', SPORTS: '6004', STICKERS: '6025',
TRAVEL: '6003', UTILITIES: '6002', WEATHER: '6001',
GAMES_ACTION: '7001', GAMES_ADVENTURE: '7002', GAMES_CASUAL: '7003', GAMES_BOARD: '7004', GAMES_CARD: '7005', GAMES_CASINO: '7006', GAMES_FAMILY: '7009',
GAMES_MUSIC: '7011', GAMES_PUZZLE: '7012', GAMES_RACING: '7013', GAMES_ROLE_PLAYING: '7014', GAMES_SIMULATION: '7015', GAMES_SPORTS: '7016',
GAMES_STRATEGY: '7017', GAMES_TRIVIA: '7018', GAMES_WORD: '7019',
};
export interface CompetitorApp {
rank: number; id: string; name: string; developer: string; ratings: number; rating: number | null;
/** First release (releaseDate) and the current version's release (currentVersionReleaseDate), YYYY-MM-DD. */
released: string | null; updated: string | null;
genre: string;
/** Genre ids with their names localized to the storefront. */
genres: { id: string; name: string }[];
}
export interface CompetitorRow { storefront: string; locale: string; term: string; results: number; ourRank: number | null; apps: CompetitorApp[] }
export interface CompetitorSnapshot { date: string; app: { appId: string | null; bundleId: string }; top: number; rows: CompetitorRow[] }
const isUs = (r: SearchApp, app: { appId?: string; bundleId?: string }) => !!((app.appId && String(r.trackId) === app.appId) || (app.bundleId && r.bundleId === app.bundleId));
/** One term's Search API results -> the top n other apps (and our own position among the results read). Pure. */
export function competitorRow(results: SearchApp[], app: { appId?: string; bundleId?: string }, q: { storefront: string; locale: string; term: string }, n: number): CompetitorRow {
const i = results.findIndex(r => isUs(r, app));
const apps = results.map((r, k) => ({ r, k })).filter(({ r }) => !isUs(r, app)).slice(0, n).map(({ r, k }): CompetitorApp => ({
rank: k + 1, id: String(r.trackId), name: r.trackName, developer: r.sellerName ?? '', ratings: r.userRatingCount ?? 0, rating: r.averageUserRating ?? null,
released: r.releaseDate?.slice(0, 10) ?? null, updated: r.currentVersionReleaseDate?.slice(0, 10) ?? null, genre: r.primaryGenreName ?? '',
genres: (r.genreIds ?? []).map((id, j) => ({ id: String(id), name: r.genres?.[j] ?? '' })).filter(g => g.name),
}));
return { ...q, results: results.length, ourRank: i >= 0 ? i + 1 : null, apps };
}
/** Distinct apps of the rows (one storefront / locale), first seen first. Pure. */
export function distinctApps(rows: CompetitorRow[]): CompetitorApp[] {
const seen = new Map<string, CompetitorApp>();
for (const r of rows) for (const a of r.apps) if (!seen.has(a.id)) seen.set(a.id, a);
return [...seen.values()];
}
export interface Gap { word: string; apps: number; developers: number; terms: string[]; examples: string[] }
/**
* Words in competitors' names that our name, subtitle and keyword field do not cover. A word only counts when apps of at
* least two different developers use it: a word one developer uses is most likely a brand (and other apps' names and
* trademarks must never go into a keyword field). Pure.
*/
export function coverageGaps(rows: CompetitorRow[], covered: Iterable<string>, locale: string, max = 15): Gap[] {
const have = [...covered];
const by = new Map<string, { apps: Set<string>; devs: Set<string>; terms: Set<string>; examples: string[] }>();
for (const r of rows) for (const a of r.apps) for (const w of new Set(tokens(a.name, locale))) {
if (w.length < 3 || coveredBy(w, have, locale)) continue;
const k = stem(w, locale);
const g = by.get(k) ?? { apps: new Set(), devs: new Set(), terms: new Set(), examples: [] };
if (!g.apps.has(a.id) && g.examples.length < 3) g.examples.push(a.name);
g.apps.add(a.id); g.devs.add(a.developer.toLowerCase()); g.terms.add(r.term);
by.set(k, g);
}
return [...by.entries()].filter(([, g]) => g.devs.size >= 2)
.map(([word, g]) => ({ word, apps: g.apps.size, developers: g.devs.size, terms: [...g.terms], examples: g.examples }))
.sort((a, b) => b.developers - a.developers || b.apps - a.apps || a.word.localeCompare(b.word)).slice(0, max);
}
/** Apps in the top N now that were not there in the previous snapshot, per storefront + term. Pure. */
export function newEntrants(now: CompetitorRow[], before: CompetitorRow[] | undefined): Map<string, string[]> {
const out = new Map<string, string[]>();
if (!before) return out;
const prev = new Map(before.map(r => [`${r.storefront}|${r.term.toLowerCase()}`, new Set(r.apps.map(a => a.id))] as const));
for (const r of now) {
const p = prev.get(`${r.storefront}|${r.term.toLowerCase()}`);
if (p) out.set(`${r.storefront}|${r.term.toLowerCase()}`, r.apps.filter(a => !p.has(a.id)).map(a => a.name));
}
return out;
}
/** The category names of the app in one storefront's language, read from the Search API results' localized genres. Pure. */
export function categoryNames(rows: CompetitorRow[], categoryIds: string[]): string[] {
const ids = new Set(categoryIds.map(c => GENRE_IDS[c]).filter(Boolean));
const names = new Set<string>();
for (const a of distinctApps(rows)) for (const g of a.genres) if (ids.has(g.id)) names.add(g.name);
return [...names];
}
// ---------------------------------------------------------------------------------------------------------------
// Apple Ads keyword suggestions
export const ADS_KEYWORD_SUGGESTIONS = '/suggestions/keywords/query';
/** RecommendationQueryRequest for keyword suggestions: the two required filters, seed terms, countries. Pure. */
export function keywordSuggestionBody(adamId: string, terms: string[], countries: string[], pageSize = 200): Record<string, unknown> {
const filters: Record<string, unknown>[] = [
{ field: 'promotedObjectId', operator: 'EQUALS', value: [adamId] },
{ field: 'promotedObjectType', operator: 'EQUALS', value: ['APPSTORE_APP'] },
];
if (terms.length) filters.push({ field: 'terms', operator: 'IN', value: terms });
if (countries.length) filters.push({ field: 'countriesOrRegions', operator: 'IN', value: countries.map(c => c.toUpperCase()) });
return { filters, sorting: [{ field: 'popularity', order: 'DESC' }], pagination: { offset: 0, pageSize: Math.min(1000, Math.max(1, pageSize)) } };
}
export interface AdsSuggestion { text: string; popularity: number }
/** `result` of the keyword suggestions answer -> { text, popularity } (0-100), invalid rows left out. Pure. */
export function parseKeywordSuggestions(res: unknown): AdsSuggestion[] {
const rows = (res as { result?: unknown })?.result;
if (!Array.isArray(rows)) return [];
return rows.filter((r): r is { text: string; popularity: number } => typeof r?.text === 'string' && typeof r?.popularity === 'number')
.map(r => ({ text: r.text.trim(), popularity: Math.max(0, Math.min(100, Math.round(r.popularity))) })).filter(r => r.text);
}
// ---------------------------------------------------------------------------------------------------------------
// Candidates and scoring
export type CandSource = 'name' | 'subtitle' | 'keywords' | 'description' | 'competitors' | 'category' | 'apple-ads';
export type CandStatus = 'candidate' | 'indexed' | 'category' | 'filler';
export interface Candidate {
term: string;
kind: 'word' | 'phrase';
sources: CandSource[];
/** Times in our own name / subtitle / description. */
ours: number;
/** relevance 0-2: +1 in our own text (name, subtitle, description, keywords), +1 in competitor names (the top apps). */
relevance: number;
/** Competition: how many of the distinct top apps already have it in their name, of how many read. */
inNames: number; ofApps: number;
/** Apple Ads relative popularity 0-100, null = unknown (no credentials, or Apple returned nothing for it). */
popularity: number | null;
/** exact: Apple Ads suggested this exact word; phrase: the highest score of a suggested phrase that contains it. */
popularityFrom: 'exact' | 'phrase' | null;
status: CandStatus;
why?: string;
}
export interface CandidateInput {
locale: string;
name: string; subtitle: string; keywords: string; description: string;
/** The competitor rows of this locale's storefront (latest `aso competitors` snapshot), may be empty. */
competitors: CompetitorRow[];
/** Category names in this language (categoryNames); matched by Apple anyway, so never put into the field. */
categories: string[];
ads: AdsSuggestion[];
}
/** Every keyword candidate of one locale with its signals. Sorted: candidates first, by relevance, popularity (known
* first), lower competition, then how often our own text uses it. Pure. */
export function candidates(i: CandidateInput): Candidate[] {
const L = i.locale;
const m = new Map<string, Candidate>();
const key = (t: string) => t.split(' ').map(w => stem(w, L)).join(' ');
const add = (term: string, kind: Candidate['kind'], src: CandSource, n = 1) => {
const k = key(term);
const c = m.get(k) ?? { term, kind, sources: [], ours: 0, relevance: 0, inNames: 0, ofApps: 0, popularity: null, popularityFrom: null, status: 'candidate' as CandStatus };
if (!c.sources.includes(src)) c.sources.push(src);
if (src === 'name' || src === 'subtitle' || src === 'description') c.ours += n;
m.set(k, c);
};
for (const [src, text] of [['name', i.name], ['subtitle', i.subtitle], ['description', i.description]] as const) for (const w of tokens(text, L)) if (w.length > 2) add(w, 'word', src);
for (const w of i.keywords.split(',').flatMap(t => tokens(t, L))) if (w.length > 1) add(w, 'word', 'keywords');
// phrases: only the ones our own text uses at least twice, or that stand in the name / subtitle
const phraseCount = new Map<string, number>();
for (const b of [...bigrams(i.name, L), ...bigrams(i.subtitle, L), ...bigrams(i.subtitle, L), ...bigrams(i.description, L)]) phraseCount.set(b, (phraseCount.get(b) ?? 0) + 1);
for (const [b, n] of phraseCount) if (n >= 2) add(b, 'phrase', 'description', n);
const apps = distinctApps(i.competitors);
const nameWords = apps.map(a => new Set(tokens(a.name, L).map(w => stem(w, L))));
for (const g of coverageGaps(i.competitors, [], L, 200)) add(g.word, 'word', 'competitors');
const catWords = [...new Set(i.categories.flatMap(c => words(c, L)))];
const cats = new Set(catWords.map(w => stem(w, L)));
for (const c of catWords) add(c, 'word', 'category');
for (const s of i.ads) {
const ws = tokens(s.text, L);
if (ws.length === 1) add(ws[0]!, 'word', 'apple-ads');
}
const indexed = [...tokens(i.name, L), ...tokens(i.subtitle, L)];
for (const c of m.values()) {
const ws = c.term.split(' ').map(w => stem(w, L));
const inOurs = c.ours > 0 || c.sources.includes('keywords');
c.inNames = nameWords.filter(n => ws.every(w => n.has(w))).length;
c.ofApps = apps.length;
c.relevance = (inOurs ? 1 : 0) + (c.inNames > 0 ? 1 : 0);
const exact = i.ads.find(s => key(s.text.toLocaleLowerCase(L)) === key(c.term));
const phrases = i.ads.filter(s => ws.every(w => tokens(s.text, L).map(x => stem(x, L)).includes(w)));
if (exact) { c.popularity = exact.popularity; c.popularityFrom = 'exact'; }
else if (phrases.length) { c.popularity = Math.max(...phrases.map(s => s.popularity)); c.popularityFrom = 'phrase'; }
if (ws.some(w => cats.has(w)) && ws.length === 1) { c.status = 'category'; c.why = 'category name: matched by Apple anyway'; }
else if (ws.every(w => coveredBy(w, indexed, L))) { c.status = 'indexed'; c.why = 'already in the name / subtitle (indexed)'; }
else if (ws.some(w => FILLER.has(w))) { c.status = 'filler'; c.why = 'filler word'; }
}
const order = (c: Candidate) => (c.status === 'candidate' ? 0 : 1);
// a word only the description uses once is noise, unless competitors or Apple Ads bring it up too
const weak = (c: Candidate) => c.sources.length === 1 && c.sources[0] === 'description' && c.ours < 2;
return [...m.values()].filter(c => !weak(c)).sort((a, b) => order(a) - order(b) || b.relevance - a.relevance || (b.popularity ?? -1) - (a.popularity ?? -1)
|| a.inNames - b.inNames || b.ours - a.ours || a.term.localeCompare(b.term));
}
// ---------------------------------------------------------------------------------------------------------------
// The 100-byte keyword field
export interface FieldProposal { locale: string; before: string; after: string; bytes: number; kept: string[]; added: string[]; dropped: { term: string; why: string }[] }
const bytes = (s: string) => Buffer.byteLength(s, 'utf8');
/**
* A keyword field for one locale that fits 100 bytes (UTF-8) with the existing rules: commas without spaces, no
* duplicates (plural-insensitive), no words of the name / subtitle, no filler or category words, single words. Current
* terms that are still valid are kept first (change a few terms per release, not all), unless `fresh`; then the best
* candidates fill the room. Pure.
*/
export function fitKeywordField(o: { locale: string; current: string; name: string; subtitle: string; ranked: Candidate[]; fresh?: boolean; limit?: number }): FieldProposal {
const L = o.locale, limit = o.limit ?? 100;
const indexed = [...tokens(o.name, L), ...tokens(o.subtitle, L)];
const blocked = new Map(o.ranked.filter(c => c.status !== 'candidate' && c.kind === 'word').map(c => [stem(c.term, L), c.why ?? c.status] as const));
const out: string[] = [], kept: string[] = [], added: string[] = [], dropped: { term: string; why: string }[] = [];
const seen: string[] = [];
const fits = (t: string) => bytes([...out, t].join(',')) <= limit;
const tryAdd = (t: string, into: string[]): string | null => {
const ws = words(t, L);
if (!ws.length) return 'empty';
if (ws.every(w => coveredBy(w, indexed, L))) return 'already in the name / subtitle (indexed)';
if (ws.some(w => FILLER.has(w))) return 'filler word';
if (ws.length === 1 ? coveredBy(ws[0]!, seen, L) : seen.includes(ws.join(' '))) return 'duplicate';
const b = ws.length === 1 ? blocked.get(stem(ws[0]!, L)) : undefined;
if (b) return b;
if (!fits(t)) return 'no room in 100 bytes';
seen.push(ws.length === 1 ? ws[0]! : ws.join(' ')); out.push(t); into.push(t);
return null;
};
if (!o.fresh) for (const t of o.current.split(',').map(s => s.trim().toLocaleLowerCase(L)).filter(Boolean)) {
// keep a current phrase as the words it is made of: single words combine on their own and save bytes
const parts = /\s/.test(t) ? tokens(t, L) : [t];
for (const p of parts) { const why = tryAdd(p, kept); if (why && why !== 'duplicate') dropped.push({ term: p, why }); }
}
for (const c of o.ranked) {
if (c.status !== 'candidate' || c.kind !== 'word') continue;
tryAdd(c.term, added);
}
const after = out.join(',');
return { locale: L, before: o.current, after, bytes: bytes(after), kept, added, dropped };
}
// ---------------------------------------------------------------------------------------------------------------
// Writing the proposal into store/appstore.md (only with --write; marked as a draft for review)
export const DRAFT_RE = /^<!--\s*storebound-aso:\s*draft\b[^>]*-->\s*$/m;
export const draftMark = (date: string): string => `<!-- storebound-aso: draft keywords from \`aso suggest\` ${date}; review them, then delete this line -->`;
/** Locales of store/appstore.md whose keywords carry the draft line. Pure. */
export function draftLocales(md: string): string[] {
const out: string[] = [];
for (const sec of md.split(/^(?=## )/m)) {
if (!sec.startsWith('## ')) continue;
const kw = sec.split(/^(?=### )/m).find(p => /^### keywords\s*$/m.test(p.split('\n')[0]!));
if (kw && DRAFT_RE.test(kw)) out.push(sec.slice(3).split(/[\s·]/)[0]!.trim());
}
return out;
}
/** store/appstore.md with the keywords block of `locale` set to `value` and the draft line above it. Pure. */
export function setKeywords(md: string, locale: string, value: string, mark: string): string {
const secs = md.split(/^(?=## )/m);
const i = secs.findIndex(s => s.startsWith('## ') && s.slice(3).split(/[\s·]/)[0]!.trim() === locale);
if (i < 0) throw new Error(`no "## ${locale}" section in the App Store listing`);
const parts = secs[i]!.split(/^(?=### )/m);
const block = `### keywords\n${mark}\n\`\`\`\n${value}\n\`\`\`\n`;
const k = parts.findIndex(p => /^### keywords\s*$/.test(p.split('\n')[0]!));
if (k >= 0) {
const old = parts[k]!;
const fence = /^```[^\n]*\n[\s\S]*?\n```[^\n]*\n?/m.exec(old);
const tail = fence ? old.slice(fence.index + fence[0].length) : old.split('\n').slice(1).join('\n');
parts[k] = block + tail.replace(DRAFT_RE, '').replace(/^\n+/, '\n');
if (!/\n$/.test(parts[k]!)) parts[k] += '\n';
} else {
const last = parts.length - 1;
parts[last] = parts[last]!.replace(/\n*$/, '\n\n') + block + (i < secs.length - 1 ? '\n' : '');
}
secs[i] = parts.join('');
return secs.join('');
}
/** "us" for en-US, "tr" for tr, "jp" for ja ... : the storefront a locale is most likely meant for. Pure. */
export function storefrontOf(locale: string): string {
const [l, r] = locale.split('-');
if (r && /^[A-Za-z]{2}$/.test(r)) return r.toLowerCase();
const map: Record<string, string> = { ja: 'jp', ko: 'kr', zh: locale === 'zh-Hant' ? 'tw' : 'cn', el: 'gr', he: 'il', hi: 'in', uk: 'ua', vi: 'vn', cs: 'cz', da: 'dk', sv: 'se', nb: 'no', ms: 'my', ca: 'es', en: 'us', ar: 'sa' };
return map[l!.toLowerCase()] ?? l!.toLowerCase();
}

View file

@ -8,14 +8,18 @@
// 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.
// bundleId, sellerName, averageUserRating, userRatingCount, primaryGenreName; `aso competitors` also releaseDate,
// currentVersionReleaseDate, genres (localized to the storefront, e.g. "Produktivität" for country=de) and genreIds.
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 interface SearchApp {
trackId: number; trackName: string; bundleId?: string; sellerName?: string; averageUserRating?: number; userRatingCount?: number; primaryGenreName?: string;
releaseDate?: string; currentVersionReleaseDate?: string; genres?: string[]; genreIds?: string[]; primaryGenreId?: number;
}
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)`);

View file

@ -16,9 +16,9 @@ export const CROSS_LOCALES: Record<string, string[]> = {
};
/** Words that add nothing in the keyword field (Apple: the category name and "app" are matched anyway). */
const FILLER = new Set(['app', 'apps', 'game', 'games', 'free', 'the', 'and', 'for', 'with', 'a', 'an', 'of', 'iphone', 'ipad', 'ios']);
export const FILLER = new Set(['app', 'apps', 'game', 'games', 'free', 'the', 'and', 'for', 'with', 'a', 'an', 'of', 'iphone', 'ipad', 'ios']);
const words = (s: string, locale: string): string[] =>
export const words = (s: string, locale: string): string[] =>
s.toLocaleLowerCase(locale).split(/[^\p{L}\p{N}]+/u).filter(w => w.length > 1);
/** One locale of the App Store listing: keyword field rules. */

View file

@ -322,6 +322,17 @@ export interface AnalyticsCompare {
/** Per store with no days in any snapshot: why the newest snapshot has none (no report request yet, no bucket). */
errors?: { apple?: string; play?: string };
}
/** aso.audit (`aso audit --json`, offline, cli/lib/aso-audit.ts AsoAudit): the parts the Growth tab's ASO card shows. */
export interface AsoTrendRow { storefront: string; keyword: string; rank: number | null; previous: number | null; change: number | null; arrow: '↑' | '↓' | '→' | 'new' | 'lost' | '·'; best: number | null; snapshots: number }
export interface AsoAuditView {
generated: string;
keywordField: { errors: number; warnings: number; hints: number; findings: { level: 'error' | 'warn' | 'info'; where: string; msg: string }[] };
drafts: string[];
ranks: { snapshots: number; latest: string | null; rows: AsoTrendRow[]; dates: string[]; series: { storefront: string; keyword: string; ranks: (number | null)[] }[] };
competitors: { date: string | null; gaps: { storefront: string; locale: string; gaps: { word: string; apps: number; developers: number }[] }[] };
experiments: { store: 'apple' | 'play'; what: string; why: string; how: string }[];
next: { what: string; why: string; command?: string }[];
}
/** console.fill (`console fill <form> --json`, cli/console/fill.ts): the answers it types into one console form. The
* dry run has the answers only; the real run (it ends when the owner closes the browser) adds what happened. */
export type ConsoleForm = 'apple-app-record' | 'apple-age-rating' | 'apple-app-privacy' | 'play-content-rating' | 'play-target-audience';

View file

@ -116,7 +116,10 @@ const COMPETITORS = ['instagram', 'tiktok', 'whatsapp', 'facebook', 'snapchat',
'amazon', 'chatgpt', 'openai', 'minecraft', 'roblox', 'fortnite', 'pubg', 'candy crush', 'clash of clans', 'pokemon', 'pokémon', 'among us', 'subway surfers', 'temple run',
'angry birds', 'tetris', 'wordle', 'duolingo', 'zoom', 'gmail', 'google maps', 'waze', 'shazam', 'tinder', 'notion', 'evernote', 'photoshop', 'canva', 'capcut', 'iphone', 'ipad', 'apple'];
const OTHER_PLATFORMS = /\b(Android|Google Play|Play Store|Galaxy Store|AppGallery|Huawei|Windows Phone|BlackBerry|Amazon Appstore)\b/;
const PLACEHOLDER = /lorem ipsum|\bTODO\b|\bTBD\b|\bFIXME\b|\bplaceholder\b|\bXXX\b|your app (name|description) here|coming soon|First paragraph:|Short hook under the name|One or two sentences you can change|İsmin altındaki kısa kanca|Yeni sürüm göndermeden istediğin zaman|\bExample (Game|App|Pro|Studio)\b/i;
// Developer markers count only in capitals ("TODO:", "FIXME"): "todo" is a real word and keyword (a to-do app).
const PLACEHOLDER_MARKERS = /\bTODO\b|\bTBD\b|\bFIXME\b|\bXXX\b/;
const PLACEHOLDER_TEXT = /lorem ipsum|\bplaceholder\b|your app (name|description) here|coming soon|First paragraph:|Short hook under the name|One or two sentences you can change|İsmin altındaki kısa kanca|Yeni sürüm göndermeden istediğin zaman|\bExample (Game|App|Pro|Studio)\b/i;
const PLACEHOLDER = { test: (l: string) => PLACEHOLDER_MARKERS.test(l) || PLACEHOLDER_TEXT.test(l) } as RegExp;
const FGS_PERMISSION: Record<string, string> = {
camera: 'CAMERA', connectedDevice: 'CONNECTED_DEVICE', dataSync: 'DATA_SYNC', health: 'HEALTH', location: 'LOCATION', mediaPlayback: 'MEDIA_PLAYBACK',
mediaProjection: 'MEDIA_PROJECTION', microphone: 'MICROPHONE', phoneCall: 'PHONE_CALL', remoteMessaging: 'REMOTE_MESSAGING', specialUse: 'SPECIAL_USE',

View file

@ -163,7 +163,8 @@ export const TOOLS: ToolDef[] = [
props: { only, csv: { type: 'string', description: 'Prices CSV with rows for subscription ids' } },
args: i => [...opt('only', i.only), ...opt('csv', i.csv)] },
{ name: 'play_data_safety', title: 'Push Play Data safety', command: ['play', 'data-safety'], write: true, destructive: true, network: true, idempotent: true,
description: 'Replace the whole Play Data safety form with the answers from the config (CSV import). dry_run prints the CSV.' },
description: 'Replace the whole Play Data safety form with the answers from the config (CSV import). Skipped when the CSV equals the last upload of this project (hash in .storebound/; force: true sends it anyway). dry_run prints the CSV.',
props: { force: { type: 'boolean', default: false, description: 'Upload even when the CSV equals the last upload (after a manual change in Play Console)' } }, args: i => flag('force', i.force) },
{ name: 'play_release_testing', title: 'Release to a Play testing track', command: ['play', 'release'], write: true, network: true,
description: 'Upload an AAB (or reuse a versionCode) to a TESTING track (internal, alpha, beta) with release notes. Production is not available here.',
props: { aab: { type: 'string', description: 'Path to the .aab' }, version_code: { type: 'integer', minimum: 1 },
@ -356,6 +357,20 @@ export const TOOLS: ToolDef[] = [
props: { storefronts: { type: 'string', pattern: '^[a-z]{2}(=[A-Za-z-]+)?(,[a-z]{2}(=[A-Za-z-]+)?)*$', description: 'e.g. us,de=de-DE (default us)' }, keywords: { type: 'string', description: 'Extra keywords, comma-separated' },
competitors: { type: 'integer', minimum: 0, maximum: 10, default: 3 } },
args: i => [...opt('storefronts', i.storefronts), ...opt('keywords', i.keywords), ...opt('competitors', i.competitors), '--json'] },
{ name: 'aso_competitors', title: 'App Store competitors per keyword', command: ['aso', 'competitors'], write: false, network: true,
description: 'Read-only: for each keyword of the locale\'s keyword field (plus terms) and storefront, the top apps in Apple\'s public iTunes Search API (name, developer, rating count, first release, last update, localized genre) and the words in their names that your name / subtitle / keywords do not cover (only words of at least two developers: a one-developer word is likely a brand). One request every 3.5 s. Saves no snapshot (the terminal run `storebound aso competitors` does). Search API order is close to, not equal to, App Store search; competitor subtitles are not in any public API.',
props: { storefront: { type: 'string', pattern: '^[a-z]{2}(=[A-Za-z-]+)?(,[a-z]{2}(=[A-Za-z-]+)?)*$', description: 'e.g. us,tr (default us)' },
terms: { type: 'string', description: 'Extra terms, comma-separated' }, top: { type: 'integer', minimum: 1, maximum: 50, default: 10 } },
args: i => [...opt('storefront', i.storefront), ...opt('term', i.terms), ...opt('top', i.top), '--no-save', '--json'] },
{ name: 'aso_suggest', title: 'Keyword field proposal', command: ['aso', 'suggest'], write: false, network: true,
description: 'Read-only proposal: keyword candidates per App Store locale from your own name / subtitle / description, the latest `aso competitors` snapshot, the localized category names and, when Apple Ads credentials exist, Apple Ads keyword suggestions (relative popularity 0-100; without credentials popularity is "unknown", never estimated). Scores relevance (own text, competitor names) and competition (top apps with the word in their name) and returns a 100-byte keyword field per locale as old -> new. Never writes: the owner runs `storebound aso suggest --write` in a terminal, which marks the result as a draft for review.',
props: { locale: { type: 'string', description: 'Comma-separated App Store locales (default: every locale of store/appstore.md)' },
fresh: { type: 'boolean', default: false, description: 'Do not keep the current keywords first' }, offline: { type: 'boolean', default: false, description: 'Skip Apple Ads' } },
args: i => [...opt('locale', i.locale), ...flag('fresh', i.fresh), ...flag('offline', i.offline), '--json'] },
{ name: 'aso_audit', title: 'ASO audit', command: ['aso', 'audit'], write: false, network: false,
description: 'Offline ASO report: keyword field findings (check --aso), cross-locale free keyword room, rank trend from the `aso rank` snapshots, competitor coverage gaps, Play short description use and keyword density, App Store analytics conversion from the snapshots, Product Page Optimization / Play experiment ideas (suggestions only) and the next 3 actions.',
props: { storefront: { type: 'string', description: 'App Store storefront for the cross-locale hint', default: 'US' } },
args: i => [...opt('storefront', i.storefront), '--json'] },
{ name: 'ads_scan', title: 'AdAttributionKit scan', command: ['ads', 'scan'], write: false, network: false,
description: 'Local scan of an iOS project for AdAttributionKit and SKAdNetwork: ad network ids (SKAdNetworkItems, AdNetworkIdentifiers, lowercase), postback copy endpoints (AttributionCopyEndpoint, re-engagement copies, NSAdvertisingAttributionReportEndpoint), attribution windows and cooldown, conversion value updates in code, ad SDKs without ids.',
props: { ios: { type: 'string', description: 'Path of the iOS project folder, e.g. ios/App' } }, required: ['ios'], args: i => [...opt('ios', i.ios), '--json'] },

View file

@ -1,7 +1,10 @@
// Play Data safety form through applications.dataSafety (CSV import; replaces every earlier answer).
// storebound play data-safety [--csv out.csv] [--dry]
// storebound play data-safety [--csv out.csv] [--dry] [--force]
// Answers come from `dataSafety` in storebound.config.ts. --dry only writes / prints the CSV.
import { mkdirSync, writeFileSync } from 'node:fs';
// Play cannot read the form back, so a run compares with what this project uploaded last: the sha256 of that CSV
// (per package) is kept in .storebound/data-safety.sha256 (gitignored). The same CSV is not sent again; --force sends it
// anyway (e.g. after the form was changed in Play Console by hand).
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import type { Ctx } from '../lib/ctx';
import { need } from '../lib/ctx';
@ -10,6 +13,27 @@ import { DATA_SAFETY_UPLOADED } from '../lib/declarations';
import { done, log } from '../lib/log';
import { playClient } from './client';
export const DATA_SAFETY_HASH = '.storebound/data-safety.sha256';
/** sha256 of the CSV for one package. Pure. */
export const dataSafetyHash = (pkg: string, csv: string): string => new Bun.CryptoHasher('sha256').update(`${pkg}\n${csv}`).digest('hex');
/** The hash of the last upload of this package, null when none is recorded. */
export function lastUpload(root: string, pkg: string): { sha256: string; at: string } | null {
const f = join(root, DATA_SAFETY_HASH);
if (!existsSync(f)) return null;
try { return (JSON.parse(readFileSync(f, 'utf8')) as Record<string, { sha256: string; at: string }>)[pkg] ?? null; } catch { return null; }
}
function rememberUpload(root: string, pkg: string, sha256: string): void {
const f = join(root, DATA_SAFETY_HASH);
let all: Record<string, { sha256: string; at: string }> = {};
try { if (existsSync(f)) all = JSON.parse(readFileSync(f, 'utf8')); } catch { all = {}; }
all[pkg] = { sha256, at: new Date().toISOString() };
mkdirSync(join(root, '.storebound'), { recursive: true });
writeFileSync(f, JSON.stringify(all, null, 2) + '\n');
}
export async function run(ctx: Ctx): Promise<void> {
const { config, root, resolve } = ctx.loaded;
const csv = dataSafetyCsv(need(config.dataSafety, 'dataSafety'));
@ -17,10 +41,25 @@ export async function run(ctx: Ctx): Promise<void> {
if (out) { writeFileSync(resolve(out), csv); log('play', `wrote ${out}`); }
const types = Object.keys(config.dataSafety!.data);
log('play', `data safety: ${types.length} data types declared (${types.join(', ') || 'none'})`);
if (ctx.args.has('dry')) { if (!out) process.stdout.write(csv); return; }
const play = await playClient(root, need(config.play?.packageName, 'play.packageName'));
const pkg = need(config.play?.packageName, 'play.packageName');
const hash = dataSafetyHash(pkg, csv);
const last = lastUpload(root, pkg);
const same = last?.sha256 === hash;
if (ctx.args.has('dry')) {
if (!out) process.stdout.write(csv);
log('play', same ? `the same CSV was uploaded ${last!.at.slice(0, 16).replace('T', ' ')} UTC: a real run sends nothing (--force sends it again)` : 'a real run uploads it (it differs from the last upload, or none is recorded)');
return;
}
if (same && !ctx.args.has('force')) {
done('play', `data safety unchanged since the upload of ${last!.at.slice(0, 16).replace('T', ' ')} UTC: nothing sent (--force sends it again, e.g. after a change in Play Console)`);
return;
}
const play = await playClient(root, pkg);
await play.call('POST', `${play.API}/dataSafety`, { safetyLabels: csv });
// Play cannot read the form back: keep what went up, so the desktop app can show what changed since (gitignored).
try { mkdirSync(join(root, '.storebound'), { recursive: true }); writeFileSync(join(root, DATA_SAFETY_UPLOADED), csv); } catch { /* the upload itself worked */ }
// keep what went up: the hash skips the next identical upload, the CSV lets the desktop app show what changed since
try {
rememberUpload(root, pkg, hash);
writeFileSync(join(root, DATA_SAFETY_UPLOADED), csv);
} catch { /* the upload itself worked */ }
done('play', `data safety updated (${csv.split('\n').length - 2} rows)`);
}

View file

@ -140,16 +140,24 @@ export async function run(ctx: Ctx): Promise<void> {
if (dry) { done('play', `dry run: ${p.changes ? `${p.changes} change(s)` : 'nothing to change'}; read-only, nothing written`); return; }
if (!p.changes) { done('play', 'listing already up to date'); return; }
if (process.stdin.isTTY && !(await confirm(ctx, `Apply these ${p.changes} change(s) to Google Play (one edit, committed)?`))) { warn('play', 'nothing written'); return; }
const todo = p.listings.filter(l => l.action !== 'same').map(l => bodies.find(b => b.language === l.key)!);
await play.edit(async id => {
if (p.details.action !== 'same') {
// The edit compares again with what it holds (a Console save or another run since the plan): only differing details
// and languages are PUT; nothing left to change = the edit is deleted, not committed. Commit only after every PUT worked.
let sent = 0;
await play.edit(async (id, ctl) => {
const cur = await play.call<Record<string, string>>('GET', `${play.API}/edits/${id}/details`);
const now = (await play.call<{ listings?: PlayListing[] }>('GET', `${play.API}/edits/${id}/listings`)).listings ?? [];
const q = playPlan(cur, details, now, bodies, { only: a.has('only') });
const todo = q.listings.filter(l => l.action !== 'same').map(l => bodies.find(b => b.language === l.key)!);
sent = q.changes;
if (!q.changes) { ctl.unchanged(); return; }
if (q.details.action !== 'same') {
await play.call('PUT', `${play.API}/edits/${id}/details`, details);
log('play', `details: ${p.details.changes.map(ch => ch.field).join(', ')}`);
log('play', `details: ${q.details.changes.map(ch => ch.field).join(', ')}`);
}
for (const [i, b] of todo.entries()) {
await play.call('PUT', `${play.API}/edits/${id}/listings/${b.language}`, b);
log('play', step(i + 1, todo.length, b.language!));
}
});
done('play', 'listing done');
done('play', sent ? 'listing done' : 'listing already up to date (the edit was deleted, nothing committed)');
}

View file

@ -45,7 +45,7 @@ export const DESKTOP_EXCLUDED = new Set(['play_release_testing', 'apple_phased_r
export const FORBIDDEN_METHOD_WORDS = /submit|release|publish|rollout|resume|complete|send|start|stop|cancel|delete|remove|invite/i;
/** Read tools whose command prints a structured result with --json. */
export const JSON_TOOLS = new Set(['check', 'check_aso', 'scan', 'validate', 'health', 'reviews_list', 'prices_diff', 'analytics_compare', 'apple_status',
export const JSON_TOOLS = new Set(['check', 'check_aso', 'aso_audit', 'aso_suggest', 'aso_competitors', 'scan', 'validate', 'health', 'reviews_list', 'prices_diff', 'analytics_compare', 'apple_status',
'apple_next_build', 'play_status', 'play_next_version_code', 'shots_check', 'apple_testflight_status', 'apple_ppo_status', 'catalog_diff',
'project_icon', 'project_listings', 'reviews_drafts', 'project_declarations', 'project_listing_text', 'project_renders', 'project_render', 'prices_current']);