storebound/cli/play/client.ts
CRT b8da75e519 apps / health / catalog / validate: fixes from a read-only run against live store accounts
- API error bodies on one line (errorBody): Google and App Store Connect pretty-print errors, which hid
  SERVICE_DISABLED from the Play account check (reported permission instead of api-disabled), broke tables
  and turned serve's apps.list error into a JSON fragment
- apps list: failure says the reason and the fix (same words as apps check)
- newest App Store version by createdDate, iOS first (the API groups versions by platform); all versions
  read so no platform is missed; per-app reads four at a time
- apps check (apple): team app count from meta.paging.total with a one-app read
- Play Money without units (prices under 1.00) read as 0.xx, not NaN (catalog diff, subscription diffs)
- health: App Store Connect 404 for perfPowerMetrics / diagnosticSignatures means no field data yet;
  Play vitals behind a disabled Reporting API say so with the fix
- validate: gracRatingClassificationNumber optional, socialMediaAgeRestricted only when socialMedia is yes,
  socialMedia unanswered is a warning
- tests with sanitized recorded responses (tests/store-real-shapes.test.ts)
2026-10-10 20:50:26 +00:00

69 lines
3.5 KiB
TypeScript

// Google Play Developer API (androidpublisher v3) client: JSON + media calls with retry, and the edit lifecycle.
import { playServiceAccount } from '../lib/credentials';
import { tokenSource } from '../lib/google-auth';
import { log } from '../lib/log';
import { errorBody } from '../lib/http';
export type PlayClient = Awaited<ReturnType<typeof playClient>>;
export async function playClient(root: string, packageName: string) {
const token = tokenSource(playServiceAccount(root));
const API = `https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${packageName}`;
const UPLOAD = `https://androidpublisher.googleapis.com/upload/androidpublisher/v3/applications/${packageName}`;
/** JSON call (object body) or media upload (Uint8Array body + Content-Type). Throws with the API's text. */
async function call<T = unknown>(method: string, url: string, body?: unknown, headers: Record<string, string> = {}): Promise<T> {
const bin = body instanceof Uint8Array;
for (let attempt = 0; ; attempt++) {
const r = await fetch(url, {
method,
headers: { Authorization: 'Bearer ' + (await token()), ...(body === undefined || bin ? {} : { 'Content-Type': 'application/json' }), ...headers },
body: body === undefined ? undefined : bin ? (body as unknown as BodyInit) : JSON.stringify(body),
});
const text = await r.text();
if (r.ok) return (text ? JSON.parse(text) : {}) as T;
if ((r.status === 429 || r.status >= 500) && attempt < 4) { await Bun.sleep(2000 * (attempt + 1)); continue; }
const short = url.replace(API, '').replace(UPLOAD, '');
// A wrong path casing answers with an HTML 404 page, not JSON: say so instead of dumping the HTML.
const msg = /^\s*</.test(text) ? `(HTML ${r.status} page: wrong path or casing?)` : errorBody(text);
throw new Error(`${method} ${short} -> ${r.status} ${msg}`);
}
}
async function editOnce<T>(fn: (id: string) => Promise<T>, o: { dry?: boolean; commitQuery?: string }): Promise<T> {
const e = await call<{ id: string }>('POST', `${API}/edits`, {});
log('play', `edit ${e.id} opened`);
try {
const out = await fn(e.id);
if (o.dry) {
await call('POST', `${API}/edits/${e.id}:validate`);
log('play', 'dry run: edit validated, discarding');
await call('DELETE', `${API}/edits/${e.id}`);
} else {
await call('POST', `${API}/edits/${e.id}:commit${o.commitQuery ?? ''}`);
log('play', `edit ${e.id} committed`);
}
return out;
} catch (err) {
await call('DELETE', `${API}/edits/${e.id}`).catch(() => {});
throw err;
}
}
return {
API, UPLOAD, packageName, call,
/**
* Opens an edit, runs fn, then commits (or validates and discards when dry). Any Console save or other edit commit
* invalidates an open edit ("A change was made to the application outside of this Edit"); then the whole edit is
* redone, up to `retries` times. Keep edits small (e.g. one per language for images) so a retry is cheap.
*/
async edit<T>(fn: (id: string) => Promise<T>, o: { dry?: boolean; commitQuery?: string; retries?: number } = {}): Promise<T> {
for (let left = o.retries ?? 3; ; left--) {
try { return await editOnce(fn, o); } catch (err) {
if (left <= 0 || !/outside of this Edit|Edit has been deleted|edit.*(expired|not found)/i.test(String(err))) throw err;
log('play', `app changed outside the edit (Console?), redoing it (${left} retries left)`);
}
}
},
};
}