Analytics snapshots: storebound analytics setup | snapshot | compare, store-analytics skill

App Store Connect Analytics Reports API (ONGOING request, Discovery and Engagement + Downloads Standard reports,
daily instances, md5-checked gzip segments, newest processing per day) and the Play statistics exports in the
pubsite_prod_rev_ Cloud Storage bucket (UTF-16 CSV, store listing visitors / acquisitions, daily user installs;
play.reportsBucket). Snapshots in .storebound/analytics/<date>.json; compare lines them up with the git history of the
store files (7 days before vs after each change). MCP: analytics_snapshot, analytics_compare, analytics_setup.
This commit is contained in:
CRTkafa 2026-10-10 15:21:39 +00:00
parent f7d0c41374
commit 117540912c
12 changed files with 512 additions and 1 deletions

153
cli/analytics.ts Normal file
View file

@ -0,0 +1,153 @@
// Store analytics snapshots next to the listing changes.
// storebound analytics setup [--dry] App Store: create the ONGOING analytics report request (Admin key; once)
// storebound analytics snapshot [--days 28] [--store apple|play] [--dry] -> .storebound/analytics/<date>.json
// storebound analytics compare [--days 7] [--paths store,storebound.config.ts] [--md]
// App Store: Analytics Reports API (Discovery and Engagement: impressions, product page views; Downloads: first-time
// downloads and redownloads), every segment checked against its md5 checksum. Google Play has no statistics API:
// the monthly CSV exports in your Cloud Storage bucket (play.reportsBucket = "pubsite_prod_rev_<id>", Play Console >
// Download reports > Statistics > Copy Cloud Storage URI) are read with the service account (store listing visitors,
// acquisitions, daily user installs). compare lines the snapshots up with the git history of the store files (listing
// text, screenshots, config): the days before vs after each change. Read-only on both stores except `setup`.
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { ascClient, type Asc, type J } from './apple/asc';
import type { Ctx } from './lib/ctx';
import {
type AppleDay, APPLE_REPORTS, appleDaily, appleTotals, bucketName, checksumOk, compareAroundEvents, decodeText, effectMarkdown, effectTable, inWindow,
latestPerDate, mergeSeries, monthsBetween, parseGitLog, parseReport, pickReport, type PlayDay, playDaily, playObjects, playTotals, type Snapshot,
} from './lib/analytics';
import { STORAGE_READ_SCOPE } from './lib/google-auth';
import { done, log, warn } from './lib/log';
import { pct, textTable } from './lib/table';
import { googleClient } from './play/google';
const TAG = 'analytics';
const day = (d: Date) => d.toISOString().slice(0, 10);
async function ongoingRequest(c: Asc, appId: string): Promise<J | null> {
const reqs = await c.all(`/v1/apps/${appId}/analyticsReportRequests?filter[accessType]=ONGOING&limit=50`);
return reqs.find(r => !r.attributes?.stoppedDueToInactivity) ?? null;
}
async function reportRows(c: Asc, report: J, start: string, tag: string): Promise<Record<string, string>[]> {
const instances = (await c.all(`/v1/analyticsReports/${report.id}/instances?filter[granularity]=DAILY&limit=200`))
.filter(i => (i.attributes?.processingDate ?? '') >= start).sort((a, b) => a.attributes.processingDate.localeCompare(b.attributes.processingDate));
log(TAG, `apple: ${tag}: ${instances.length} daily instance(s) since ${start}`);
const parts: { processingDate: string; rows: Record<string, string>[] }[] = [];
for (const inst of instances) {
const rows: Record<string, string>[] = [];
for (const seg of await c.all(`/v1/analyticsReportInstances/${inst.id}/segments?limit=200`)) {
// Segment URLs are pre-signed (valid 5 minutes): fetched without the API token.
const r = await fetch(seg.attributes.url);
if (!r.ok) throw new Error(`segment ${seg.id}: HTTP ${r.status}`);
const gz = new Uint8Array(await r.arrayBuffer());
const raw = gz[0] === 0x1f && gz[1] === 0x8b ? Bun.gunzipSync(gz) : gz;
// Apple documents an md5 checksum per segment without saying of which bytes: accept the file or its content.
if (seg.attributes.checksum && !checksumOk(gz, seg.attributes.checksum) && !checksumOk(raw, seg.attributes.checksum)) throw new Error(`segment ${seg.id}: md5 checksum mismatch`);
rows.push(...parseReport(decodeText(raw)));
}
parts.push({ processingDate: inst.attributes.processingDate, rows });
}
return latestPerDate(parts);
}
async function appleSnapshot(ctx: Ctx, start: string, end: string): Promise<{ daily: AppleDay[] }> {
const { config, root } = ctx.loaded;
const c = await ascClient(root, config.apple!.bundleId, config.apple?.appId);
const appId = await c.app();
const req = await ongoingRequest(c, appId);
if (!req) throw new Error('no active ONGOING analytics report request: run storebound analytics setup (Admin key), data starts 1-2 days later');
const reports = await c.all(`/v1/analyticsReportRequests/${req.id}/reports?limit=200`);
const eng = pickReport(reports.filter(r => r.attributes?.category === APPLE_REPORTS.engagement.category), APPLE_REPORTS.engagement.match);
const dl = pickReport(reports.filter(r => r.attributes?.category === APPLE_REPORTS.downloads.category), APPLE_REPORTS.downloads.match);
if (!eng || !dl) throw new Error(`reports not found yet (${reports.length} listed): wait a day after setup`);
const daily = appleDaily(await reportRows(c, eng, start, eng.attributes.name), await reportRows(c, dl, start, dl.attributes.name));
return { daily: inWindow(daily, start, end) };
}
async function playSnapshot(ctx: Ctx, start: string, end: string): Promise<{ daily: PlayDay[] }> {
const { config, root } = ctx.loaded;
const bucket = config.play?.reportsBucket;
if (!bucket) throw new Error('play.reportsBucket is not set (Play Console > Download reports > Statistics > Copy Cloud Storage URI)');
const g = googleClient(root, STORAGE_READ_SCOPE);
const sp: Record<string, string>[] = [], inst: Record<string, string>[] = [];
for (const month of monthsBetween(start, end)) {
const o = playObjects(config.play!.packageName, month);
for (const [name, into] of [[o.storePerformance, sp], [o.installs, inst]] as const) {
const url = `https://storage.googleapis.com/storage/v1/b/${encodeURIComponent(bucketName(bucket))}/o/${encodeURIComponent(name)}?alt=media`;
try { into.push(...parseReport(decodeText(await g.bytes(url)))); log(TAG, `play: ${name}`); }
catch (e) { if (/-> 404/.test(String(e))) warn(TAG, `play: ${name} not there (yet)`); else throw e; }
}
}
return { daily: inWindow(playDaily(sp, inst), start, end) };
}
function readSnapshots(dir: string): Snapshot[] {
if (!existsSync(dir)) return [];
return readdirSync(dir).filter(n => /^\d{4}-\d{2}-\d{2}\.json$/.test(n)).sort().map(n => JSON.parse(readFileSync(join(dir, n), 'utf8')) as Snapshot);
}
export async function run(ctx: Ctx): Promise<void> {
const { config, root, resolve } = ctx.loaded;
const a = ctx.args;
const sub = a._[0];
const dir = resolve(a.get('dir') ?? '.storebound/analytics');
const dry = a.has('dry');
if (sub === 'setup') {
if (!config.apple) throw new Error('no apple section in the config (Google Play needs no setup: set play.reportsBucket)');
const c = await ascClient(root, config.apple.bundleId, config.apple.appId);
const appId = await c.app();
const cur = await ongoingRequest(c, appId);
if (cur) { done(TAG, `apple: ONGOING report request exists (${cur.id})`); return; }
const body = { data: { type: 'analyticsReportRequests', attributes: { accessType: 'ONGOING' }, relationships: { app: { data: { type: 'apps', id: appId } } } } };
if (dry) { log(TAG, 'would POST /v1/analyticsReportRequests {accessType=ONGOING} (dry)'); return; }
await c.asc('POST', '/v1/analyticsReportRequests', body);
done(TAG, 'apple: ONGOING report request created; the first reports appear after 1-2 days, then daily');
return;
}
if (sub === 'snapshot') {
const days = a.num('days', 28);
if (!(days >= 1 && days <= 120)) throw new Error('--days: 1-120');
const store = a.get('store');
const now = new Date();
const end = day(new Date(now.getTime() - 86_400_000)), start = day(new Date(now.getTime() - days * 86_400_000));
const snap: Snapshot = { date: day(now), window: { start, end, days } };
if ((!store || store === 'apple') && config.apple) {
try { const r = await appleSnapshot(ctx, start, end); snap.apple = { daily: r.daily, totals: appleTotals(r.daily) }; }
catch (e) { snap.apple = { error: (e as Error).message.slice(0, 400) }; warn(TAG, `apple: ${snap.apple.error}`); }
}
if ((!store || store === 'play') && config.play) {
try { const r = await playSnapshot(ctx, start, end); snap.play = { daily: r.daily, totals: playTotals(r.daily) }; }
catch (e) { snap.play = { error: (e as Error).message.slice(0, 400) }; warn(TAG, `play: ${snap.play.error}`); }
}
const rows: (string | number)[][] = [];
if (snap.apple && !('error' in snap.apple)) { const t = snap.apple.totals; rows.push(['apple', `${t.impressions} impressions`, `${t.pageViews} page views`, `${t.downloads} downloads`, pct(t.conversion ?? null)]); }
if (snap.play && !('error' in snap.play)) { const t = snap.play.totals; rows.push(['play', `${t.visitors} visitors`, `${t.acquisitions} acquisitions`, `${t.installs} installs`, pct(t.conversion ?? null)]); }
if (rows.length) console.log(textTable(['store', 'reach', 'interest', 'installs', 'conversion'], rows));
const file = join(dir, `${snap.date}.json`);
if (dry) { done(TAG, `dry run: would write ${file} (${start} to ${end})`); return; }
mkdirSync(dir, { recursive: true });
writeFileSync(file, JSON.stringify(snap, null, 2) + '\n');
done(TAG, `snapshot ${file} (${start} to ${end})`);
return;
}
if (sub === 'compare') {
const snaps = readSnapshots(dir);
if (!snaps.length) throw new Error(`no snapshots in ${dir} (storebound analytics snapshot)`);
const series = mergeSeries(snaps);
const first = [series.apple[0]?.date, series.play[0]?.date].filter(Boolean).sort()[0] ?? snaps[0]!.window.start;
const paths = a.list('paths').length ? a.list('paths') : ['store', 'storebound.config.ts', ...(config.shots?.copy ? [config.shots.copy] : [])];
const g = Bun.spawnSync(['git', 'log', `--since=${first}`, '--date=short', '--format=%x1e%h%x1f%ad%x1f%s', '--name-only', '--', ...paths], { cwd: root, stdout: 'pipe', stderr: 'pipe' });
if (g.exitCode !== 0) throw new Error(`git log: ${g.stderr.toString().trim()}`);
const events = parseGitLog(g.stdout.toString()).reverse();
log(TAG, `${snaps.length} snapshot(s), ${series.apple.length} App Store day(s), ${series.play.length} Play day(s), ${events.length} store change(s) since ${first}`);
const fx = compareAroundEvents(series, events, a.num('days', 7));
console.log(a.has('md') ? effectMarkdown(fx) : effectTable(fx));
log(TAG, 'reading: a change needs several days on both sides and enough traffic; seasonality, featuring and ads move these numbers too');
return;
}
throw new Error('usage: storebound analytics setup | snapshot | compare');
}

View file

@ -17,6 +17,7 @@ const PLAIN: Record<string, [() => Promise<Plain>, string]> = {
const COMMANDS: Record<string, [() => Promise<Mod>, string]> = {
'check': [() => import('./check'), 'validate config, copy files, data safety answers and products (offline); --aso keyword audit'],
'validate': [() => import('./validate'), 'read-only store readiness report with ordered blockers (--apple / --play), plus local renders checks (--no-local skips); exit 1 on blockers'],
'analytics': [() => import('./analytics'), 'setup (App Store report request) | snapshot (impressions, page views, installs, conversion -> .storebound/analytics) | compare (vs listing changes in git)'],
'health': [() => import('./health'), 'crash / ANR vitals (Play) and diagnostics (App Store), read-only; --weekly writes a markdown report; exit 1 over a threshold'],
'prices': [() => import('./prices'), 'export | import a CSV of product x store x region prices (diff first, asks before writing; Apple future-dated changes)'],
'reviews': [() => import('./reviews'), 'list | draft (local reply drafts in .storebound/replies) | send (approved drafts only, asks first)'],

186
cli/lib/analytics.ts Normal file
View file

@ -0,0 +1,186 @@
// Store analytics snapshots (impressions, product page views, downloads / installs, conversion) and their comparison
// with listing changes, as pure parts. `storebound analytics` downloads the data (read-only) and writes the snapshots.
// Sources (checked October 2026):
// App Store Connect Analytics Reports API: an ONGOING analyticsReportRequest (Admin creates it once; first data after
// 1-2 days, then daily; instances kept 35 days; a request stops after long inactivity: stoppedDueToInactivity),
// reports -> instances (DAILY) -> segments (url valid 5 minutes, md5 checksum, gzip text files; every segment of
// an instance is needed). A later processingDate replaces rows of the same Date: never sum one Date across instances.
// https://developer.apple.com/documentation/appstoreconnectapi/downloading-analytics-reports
// https://developer.apple.com/documentation/analytics-reports/app-store-discovery-and-engagement
// https://developer.apple.com/documentation/analytics-reports/app-download
// Google Play: no API for store listing statistics (the Reporting API has vitals only). Monthly CSV exports in the
// developer's Cloud Storage bucket gs://pubsite_prod_rev_<id> (Play Console > Download reports > Statistics, "Copy
// Cloud Storage URI"), UTF-16, read with the service account (Play Console permission "View app information and
// download bulk reports", scope devstorage.read_only):
// stats/store_performance/store_performance_<package>_<yyyyMM>_country.csv (Store listing acquisitions / visitors)
// stats/installs/installs_<package>_<yyyyMM>_country.csv (Daily User Installs, ...)
// https://support.google.com/googleplay/android-developer/answer/6135870
import { createHash } from 'node:crypto';
import { parseCsvRecords } from './csv';
import { mdTable, pct, textTable } from './table';
export const APPLE_REPORTS = {
engagement: { category: 'APP_STORE_ENGAGEMENT', match: /discovery and engagement/i },
downloads: { category: 'COMMERCE', match: /download/i },
} as const;
/** Standard over Detailed (Detailed adds noise for privacy and splits by campaign). */
export function pickReport<T extends { attributes?: { name?: string } }>(reports: T[], match: RegExp): T | null {
const hits = reports.filter(r => match.test(r.attributes?.name ?? ''));
return hits.find(r => /standard/i.test(r.attributes?.name ?? '')) ?? hits[0] ?? null;
}
/** Bytes of a downloaded segment vs its md5 checksum. */
export const checksumOk = (b: Uint8Array, checksum: string): boolean => createHash('md5').update(b).digest('hex').toLowerCase() === checksum.toLowerCase();
/** Text of a report file: UTF-16 with a BOM (Play exports), else UTF-8. */
export function decodeText(b: Uint8Array): string {
if (b[0] === 0xff && b[1] === 0xfe) return new TextDecoder('utf-16le').decode(b.subarray(2));
if (b[0] === 0xfe && b[1] === 0xff) return new TextDecoder('utf-16be').decode(b.subarray(2));
return new TextDecoder('utf-8').decode(b);
}
/** Tab- or comma-separated report text -> records keyed by lower-case column name (by name: Apple may reorder). */
export function parseReport(text: string): Record<string, string>[] {
const first = text.replace(/^/, '').split(/\r?\n/, 1)[0] ?? '';
return parseCsvRecords(text, first.includes('\t') ? '\t' : ',');
}
/** Rows of several instances: per Date only the rows of the newest processingDate (later instances restate days). */
export function latestPerDate(instances: { processingDate: string; rows: Record<string, string>[] }[]): Record<string, string>[] {
const best = new Map<string, string>();
for (const i of instances) for (const r of i.rows) { const d = r.date ?? ''; if (!best.has(d) || best.get(d)! < i.processingDate) best.set(d, i.processingDate); }
return instances.flatMap(i => i.rows.filter(r => best.get(r.date ?? '') === i.processingDate));
}
export interface AppleDay { date: string; impressions: number; uniqueImpressions: number; pageViews: number; uniquePageViews: number; downloads: number; firstTimeDownloads: number }
export interface PlayDay { date: string; visitors: number; acquisitions: number; installs: number }
const num = (v: string | undefined) => { const n = Number((v ?? '').replace(/,/g, '')); return Number.isFinite(n) ? n : 0; };
/** Discovery and Engagement + Downloads rows -> one line per day (App Store, every territory and source summed). */
export function appleDaily(engagement: Record<string, string>[], downloads: Record<string, string>[]): AppleDay[] {
const days = new Map<string, AppleDay>();
const day = (d: string) => days.get(d) ?? days.set(d, { date: d, impressions: 0, uniqueImpressions: 0, pageViews: 0, uniquePageViews: 0, downloads: 0, firstTimeDownloads: 0 }).get(d)!;
for (const r of engagement) {
if (!r.date) continue;
const ev = (r.event ?? '').toLowerCase();
const x = day(r.date);
if (ev === 'impression') { x.impressions += num(r.counts); x.uniqueImpressions += num(r.unique_counts); }
else if (ev === 'page view') { x.pageViews += num(r.counts); x.uniquePageViews += num(r.unique_counts); }
}
for (const r of downloads) {
if (!r.date) continue;
const t = (r.download_type ?? '').toLowerCase();
const x = day(r.date);
if (t === 'first-time download') { x.firstTimeDownloads += num(r.counts); x.downloads += num(r.counts); }
else if (t === 'redownload') x.downloads += num(r.counts);
}
return [...days.values()].sort((a, b) => a.date.localeCompare(b.date));
}
/** Play store performance + installs CSV rows (country files) -> one line per day. Dates are YYYY-MM-DD. */
export function playDaily(storePerformance: Record<string, string>[], installs: Record<string, string>[]): PlayDay[] {
const days = new Map<string, PlayDay>();
const day = (d: string) => days.get(d) ?? days.set(d, { date: d, visitors: 0, acquisitions: 0, installs: 0 }).get(d)!;
for (const r of storePerformance) if (r.date) { const x = day(r.date); x.visitors += num(r.store_listing_visitors); x.acquisitions += num(r.store_listing_acquisitions); }
for (const r of installs) if (r.date) day(r.date).installs += num(r.daily_user_installs);
return [...days.values()].sort((a, b) => a.date.localeCompare(b.date));
}
/** Months (yyyyMM) a date window touches, for the Play file names. */
export function monthsBetween(start: string, end: string): string[] {
const out: string[] = [];
let y = Number(start.slice(0, 4)), m = Number(start.slice(5, 7));
const ey = Number(end.slice(0, 4)), em = Number(end.slice(5, 7));
while (y < ey || (y === ey && m <= em)) { out.push(`${y}${String(m).padStart(2, '0')}`); if (++m > 12) { m = 1; y++; } }
return out;
}
export const playObjects = (pkg: string, month: string) => ({
storePerformance: `stats/store_performance/store_performance_${pkg}_${month}_country.csv`,
installs: `stats/installs/installs_${pkg}_${month}_country.csv`,
});
/** "gs://pubsite_prod_rev_123/" or "pubsite_prod_rev_123" -> bucket name. */
export const bucketName = (b: string): string => b.replace(/^gs:\/\//, '').replace(/\/.*$/, '');
export interface Totals { impressions?: number; pageViews?: number; downloads?: number; conversion?: number | null; visitors?: number; acquisitions?: number; installs?: number }
export function appleTotals(days: AppleDay[]): Totals {
const s = (k: keyof AppleDay) => days.reduce((n, d) => n + (d[k] as number), 0);
const uniq = s('uniqueImpressions');
return { impressions: s('impressions'), pageViews: s('pageViews'), downloads: s('downloads'), conversion: uniq ? s('downloads') / uniq : null };
}
export function playTotals(days: PlayDay[]): Totals {
const s = (k: keyof PlayDay) => days.reduce((n, d) => n + (d[k] as number), 0);
const v = s('visitors');
return { visitors: v, acquisitions: s('acquisitions'), installs: s('installs'), conversion: v ? s('acquisitions') / v : null };
}
export interface Snapshot {
date: string;
window: { start: string; end: string; days: number };
apple?: { daily: AppleDay[]; totals: Totals } | { error: string };
play?: { daily: PlayDay[]; totals: Totals } | { error: string };
}
export const inWindow = <T extends { date: string }>(rows: T[], start: string, end: string): T[] => rows.filter(r => r.date >= start && r.date <= end);
// ---- compare with listing changes ----
export interface Event { date: string; commit: string; subject: string; files: string[] }
/** `git log --date=short --format=%x1e%h%x1f%ad%x1f%s --name-only -- <paths>` -> events. */
export function parseGitLog(out: string): Event[] {
return out.split('\x1e').map(s => s.trim()).filter(Boolean).map(block => {
const [head, ...files] = block.split('\n');
const [commit = '', date = '', subject = ''] = (head ?? '').split('\x1f');
return { date, commit, subject, files: files.map(f => f.trim()).filter(Boolean) };
}).filter(e => /^\d{4}-\d{2}-\d{2}$/.test(e.date));
}
/** Snapshots -> one series per store (newest snapshot wins for a date). */
export function mergeSeries(snaps: Snapshot[]): { apple: AppleDay[]; play: PlayDay[] } {
const a = new Map<string, AppleDay>(), p = new Map<string, PlayDay>();
for (const s of [...snaps].sort((x, y) => x.date.localeCompare(y.date))) {
if (s.apple && !('error' in s.apple)) for (const d of s.apple.daily) a.set(d.date, d);
if (s.play && !('error' in s.play)) for (const d of s.play.daily) p.set(d.date, d);
}
return { apple: [...a.values()].sort((x, y) => x.date.localeCompare(y.date)), play: [...p.values()].sort((x, y) => x.date.localeCompare(y.date)) };
}
const addDays = (d: string, n: number) => new Date(Date.parse(d + 'T00:00:00Z') + n * 86_400_000).toISOString().slice(0, 10);
export interface EventEffect { event: Event; store: 'apple' | 'play'; before: Totals; after: Totals; daysBefore: number; daysAfter: number }
/** For every event: the `days` before it (excluding the event day) vs the `days` from it, per store, where data exists. */
export function compareAroundEvents(series: { apple: AppleDay[]; play: PlayDay[] }, events: Event[], days = 7): EventEffect[] {
const out: EventEffect[] = [];
for (const e of events) {
const bs = addDays(e.date, -days), be = addDays(e.date, -1), as = e.date, ae = addDays(e.date, days - 1);
const ab = inWindow(series.apple, bs, be), aa = inWindow(series.apple, as, ae);
if (ab.length || aa.length) out.push({ event: e, store: 'apple', before: appleTotals(ab), after: appleTotals(aa), daysBefore: ab.length, daysAfter: aa.length });
const pb = inWindow(series.play, bs, be), pa = inWindow(series.play, as, ae);
if (pb.length || pa.length) out.push({ event: e, store: 'play', before: playTotals(pb), after: playTotals(pa), daysBefore: pb.length, daysAfter: pa.length });
}
return out;
}
const perDay = (v: number | undefined, n: number) => (v === undefined || !n ? null : v / n);
const fmtN = (v: number | null) => (v === null ? 'n/a' : v >= 100 ? Math.round(v).toString() : v.toFixed(1));
const delta = (a: number | null | undefined, b: number | null | undefined) => (a == null || b == null || a === 0 ? '' : `${b >= a ? '+' : ''}${(((b - a) / a) * 100).toFixed(0)}%`);
/** Rows for the comparison table: per event and store, daily averages before / after and the conversion change. */
export function effectRows(fx: EventEffect[]): (string | number)[][] {
return fx.map(f => {
const top = f.store === 'apple' ? 'impressions' : 'visitors';
const b = perDay(f.before[top], f.daysBefore), a = perDay(f.after[top], f.daysAfter);
return [f.event.date, f.store, f.event.subject.slice(0, 48), `${fmtN(b)} -> ${fmtN(a)} ${delta(b, a)}`.trim(),
`${pct(f.before.conversion ?? null)} -> ${pct(f.after.conversion ?? null)}`, `${f.daysBefore}/${f.daysAfter}`];
});
}
export const EFFECT_HEAD = ['date', 'store', 'change', 'impressions or visitors / day', 'conversion', 'days before/after'];
export const effectTable = (fx: EventEffect[]): string => (fx.length ? textTable(EFFECT_HEAD, effectRows(fx)) : 'no listing changes inside the snapshot data yet');
export const effectMarkdown = (fx: EventEffect[]): string => mdTable(EFFECT_HEAD, effectRows(fx));

View file

@ -271,6 +271,9 @@ export interface ShipConfig {
packageName: string; defaultLanguage?: string; listing?: string; icon?: string;
/** Promo video: a YouTube URL (public or unlisted, ads off, embeddable). Play takes no video upload. Sent by `play listing`. */
video?: string;
/** Cloud Storage bucket of the Play Console report exports, e.g. "pubsite_prod_rev_<number>" (Play Console >
* Download reports > Statistics > Copy Cloud Storage URI). Used by `storebound analytics snapshot`. */
reportsBucket?: string;
};
apple?: {
bundleId: string; appId?: string; primaryLocale?: string; listing?: string; info?: AppleAppInfo; reviewShots?: string;
@ -335,6 +338,8 @@ export function validateConfig(c: unknown): string[] {
if (cfg.play && !ID_RE.test(cfg.play.packageName ?? '')) e.push('play.packageName: not a package name (com.example.game)');
if (cfg.play?.video && !/^https:\/\/(www\.youtube\.com\/watch\?v=[\w-]{6,}|youtu\.be\/[\w-]{6,})$/.test(cfg.play.video))
e.push('play.video: a plain YouTube video URL (https://www.youtube.com/watch?v=... or https://youtu.be/...), no playlist, channel or extra parameters');
if (cfg.play?.reportsBucket && !/^(gs:\/\/)?pubsite_prod(_rev)?_\d+\/?$/.test(cfg.play.reportsBucket))
e.push('play.reportsBucket: the Play reports bucket, e.g. "pubsite_prod_rev_<number>" (Play Console > Download reports > Copy Cloud Storage URI)');
if (cfg.apple) {
if (!ID_RE.test(cfg.apple.bundleId ?? '')) e.push('apple.bundleId: not a bundle id (com.example.game)');
if (cfg.apple.appId && !/^\d+$/.test(cfg.apple.appId)) e.push('apple.appId: numeric Apple ID of the app (App Store Connect > App Information)');

View file

@ -68,6 +68,16 @@ export const TOOLS: ToolDef[] = [
description: 'Read the current prices of every product on both stores and write them as the prices CSV (local file only; Apple equalized prices with with_automatic, marked kind=auto). dry_run prints the CSV.',
props: { out: { type: 'string', description: 'CSV path' }, store: { type: 'string', enum: ['apple', 'play'] }, only, with_automatic: { type: 'boolean', default: false } },
args: i => [...opt('out', i.out), ...opt('store', i.store), ...opt('only', i.only), ...flag('with-automatic', i.with_automatic)] },
{ name: 'analytics_snapshot', title: 'Store analytics snapshot', command: ['analytics', 'snapshot'], write: true, network: true, idempotent: true,
description: 'Read store analytics (App Store: impressions, product page views, downloads via the Analytics Reports API; Google Play: store listing visitors, acquisitions, installs from the Play reports bucket) and write .storebound/analytics/<date>.json. Local file only; dry_run reads and prints the totals.',
props: { days: { type: 'integer', minimum: 1, maximum: 120, default: 28 }, store: { type: 'string', enum: ['apple', 'play'] } },
args: i => [...opt('days', i.days), ...opt('store', i.store)] },
{ name: 'analytics_compare', title: 'Analytics vs listing changes', command: ['analytics', 'compare'], write: false, network: false,
description: 'Offline: line the analytics snapshots up with the git history of the store files (listing text, screenshots, config) and show daily impressions / visitors and conversion in the days before vs after each change.',
props: { days: { type: 'integer', minimum: 1, maximum: 60, default: 7 }, md: { type: 'boolean', default: false, description: 'Markdown table' } },
args: i => [...opt('days', i.days), ...flag('md', i.md)] },
{ name: 'analytics_setup', title: 'Start App Store analytics reports', command: ['analytics', 'setup'], write: true, network: true, idempotent: true,
description: 'Create the ONGOING App Store Connect analytics report request once (needs an Admin key; reports start 1-2 days later). Changes nothing public.' },
{ name: 'apple_status', title: 'App Store status', command: ['apple', 'status'], write: false, network: true,
description: 'Read-only App Store Connect overview: versions and their states, recent builds, in-app purchases, review submissions.' },
{ name: 'apple_next_build', title: 'Next iOS build number', command: ['apple', 'next-build'], write: false, network: true,