crt-ship 0.1.0: CLI, Claude Code skills and templates for shipping mobile games to Google Play and the App Store

This commit is contained in:
CRTkafa 2026-10-10 12:29:20 +00:00
commit ecb3dc3dc3
64 changed files with 4509 additions and 0 deletions

68
cli/play/client.ts Normal file
View file

@ -0,0 +1,68 @@
// 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';
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?)` : text.slice(0, 1500);
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)`);
}
}
},
};
}

22
cli/play/data-safety.ts Normal file
View file

@ -0,0 +1,22 @@
// Play Data safety form through applications.dataSafety (CSV import; replaces every earlier answer).
// crt-ship play data-safety [--csv out.csv] [--dry]
// Answers come from `dataSafety` in crt-ship.config.ts. --dry only writes / prints the CSV.
import { writeFileSync } from 'node:fs';
import type { Ctx } from '../lib/ctx';
import { need } from '../lib/ctx';
import { dataSafetyCsv } from '../lib/data-safety';
import { done, log } from '../lib/log';
import { playClient } from './client';
export async function run(ctx: Ctx): Promise<void> {
const { config, root, resolve } = ctx.loaded;
const csv = dataSafetyCsv(need(config.dataSafety, 'dataSafety'));
const out = ctx.args.get('csv');
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'));
await play.call('POST', `${play.API}/dataSafety`, { safetyLabels: csv });
done('play', `data safety updated (${csv.split('\n').length - 2} rows)`);
}

72
cli/play/images.ts Normal file
View file

@ -0,0 +1,72 @@
// Play store graphics per language, one edit per language (a Console save in parallel then only costs a retry of that
// language, not of the whole upload).
// crt-ship play images [--dry] [--only en-US,de-DE] [--src store/renders]
// Per Play language, from <renders>/<language id>/: icon (play.icon, 512x512), featureGraphic (feature/1024x500.*),
// phoneScreenshots (play/NN.*), sevenInchScreenshots (tab7/NN.*), tenInchScreenshots (tab10/NN.*). A .jpg next to a
// .png wins (JPEG q92 uploads about 4x faster; `crt-ship shots jpeg` makes them). Each image type is cleared
// before uploading, so re-runs are idempotent. Uploads are slow: run in the background with a log file.
import { existsSync, readdirSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import type { Ctx } from '../lib/ctx';
import { byPlayCode, need } from '../lib/ctx';
import { done, log, step } from '../lib/log';
import { playClient } from './client';
import { readPlayCopy } from './listing';
export const PLAY_IMAGE_DIRS = { phoneScreenshots: 'play', sevenInchScreenshots: 'tab7', tenInchScreenshots: 'tab10' } as const;
/** NN.png / NN.jpg in a dir, sorted, JPEG preferred over PNG of the same number. */
export function numberedImages(dir: string): string[] {
if (!existsSync(dir)) return [];
const files = readdirSync(dir).filter(f => /^\d+\.(png|jpe?g)$/i.test(f));
const byNum = new Map<string, string>();
for (const f of files.sort()) {
const n = f.split('.')[0]!;
const cur = byNum.get(n);
if (!cur || /\.jpe?g$/i.test(f)) byNum.set(n, f);
}
return [...byNum.keys()].sort((a, b) => Number(a) - Number(b)).map(n => join(dir, byNum.get(n)!));
}
export async function run(ctx: Ctx): Promise<void> {
const { config, root, resolve } = ctx.loaded;
const pkg = need(config.play?.packageName, 'play.packageName');
const src = resolve(ctx.args.get('src') ?? config.renders ?? config.shots?.out ?? 'store/renders');
const icon = resolve(config.play?.icon ?? join(config.icons?.out ?? 'store/icons', 'play-512.png'));
const langOf = byPlayCode(config.languages);
const codes = readPlayCopy(ctx).map(c => c.lang);
const sets = new Map<string, [string, string[]][]>();
for (const code of codes) {
const l = langOf.get(code);
if (!l) throw new Error(`${code}: no entry in languages[] has this Play code`);
const dir = join(src, l.id);
const feature = ['jpg', 'jpeg', 'png'].map(e => join(dir, `feature/1024x500.${e}`)).find(existsSync);
const set: [string, string[]][] = [['icon', [icon]], ['featureGraphic', feature ? [feature] : []],
...Object.entries(PLAY_IMAGE_DIRS).map(([type, sub]) => [type, numberedImages(join(dir, sub)).slice(0, 8)] as [string, string[]])];
for (const [type, files] of set) {
if (!files.length || !files.every(existsSync)) throw new Error(`${code}: no ${type} in ${dir} (render first: crt-ship shots render)`);
if (type.endsWith('Screenshots') && files.length < 2) throw new Error(`${code}: ${type} needs at least 2 images`);
}
sets.set(code, set);
}
log('play', `${codes.length} languages, ${[...sets.values()][0]?.reduce((n, [, f]) => n + f.length, 0) ?? 0} images each`);
const play = await playClient(root, pkg);
for (const [i, code] of codes.entries()) {
const set = sets.get(code)!;
await play.edit(async id => {
let n = 0;
await Promise.all(set.map(async ([type, files]) => {
await play.call('DELETE', `${play.API}/edits/${id}/listings/${code}/${type}`);
for (const f of files) {
await play.call('POST', `${play.UPLOAD}/edits/${id}/listings/${code}/${type}?uploadType=media`, new Uint8Array(readFileSync(f)),
{ 'Content-Type': /\.png$/i.test(f) ? 'image/png' : 'image/jpeg' });
n++;
}
}));
log('play', `${step(i + 1, codes.length, code)}: ${n} images`);
}, { dry: ctx.args.has('dry') });
}
done('play', 'images done');
}

36
cli/play/listing.ts Normal file
View file

@ -0,0 +1,36 @@
// Play store listing text + app details in one edit.
// crt-ship play listing [--dry] [--only en-US,de-DE]
// App details: default language, contact email, website (must be the domain that serves app-ads.txt).
// Listings: title, short and full description of every `<!-- play: ... -->` section of the listing file.
import { readFileSync } from 'node:fs';
import { parsePlayListing } from '../lib/copy';
import type { Ctx } from '../lib/ctx';
import { need } from '../lib/ctx';
import { done, log, step } from '../lib/log';
import { playClient } from './client';
export function readPlayCopy(ctx: Ctx) {
const { config, resolve } = ctx.loaded;
const file = resolve(config.play?.listing ?? 'store/listing.md');
const only = ctx.args.list('only');
return parsePlayListing(readFileSync(file, 'utf8'), config.app.name).filter(c => !only.length || only.includes(c.lang));
}
export async function run(ctx: Ctx): Promise<void> {
const { config, root } = ctx.loaded;
const pkg = need(config.play?.packageName, 'play.packageName');
const copy = readPlayCopy(ctx);
const details = { defaultLanguage: config.play?.defaultLanguage ?? 'en-US', contactEmail: config.app.contactEmail, contactWebsite: config.app.website };
if (!copy.some(c => c.lang === details.defaultLanguage) && !ctx.args.has('only')) throw new Error(`listing has no section for the default language ${details.defaultLanguage}`);
log('play', `${copy.length} listings: ${copy.map(c => c.lang).join(', ')}`);
const play = await playClient(root, pkg);
await play.edit(async id => {
await play.call('PUT', `${play.API}/edits/${id}/details`, details);
log('play', `details: ${details.defaultLanguage} · ${details.contactEmail} · ${details.contactWebsite}`);
for (const [i, c] of copy.entries()) {
await play.call('PUT', `${play.API}/edits/${id}/listings/${c.lang}`, { language: c.lang, title: c.title, shortDescription: c.short, fullDescription: c.full });
log('play', step(i + 1, copy.length, c.lang));
}
}, { dry: ctx.args.has('dry') });
done('play', 'listing done');
}

77
cli/play/products.ts Normal file
View file

@ -0,0 +1,77 @@
// In-app products on Google Play through monetization.onetimeproducts (the legacy inappproducts API answers 403
// "Please migrate to the new publishing API" for apps on the new model).
// crt-ship play products [--dry] [--only id1,id2]
// Per product: convertRegionPrices (USD base -> every region at local price points, plus regionsVersion), your
// explicit overrides on top, PATCH ...?allowMissing=true (create or update), then activate the purchase option
// (new options start as DRAFT) with purchaseOptions:batchUpdateStates. Idempotent.
import { playCodes } from '../lib/config';
import type { Ctx } from '../lib/ctx';
import { need } from '../lib/ctx';
import { done, log, step, warn } from '../lib/log';
import { type Money, playRegionConfigs, toMoney } from '../lib/money';
import { playClient } from './client';
const OPTION = 'buy';
interface Converted {
convertedRegionPrices?: Record<string, { regionCode: string; price: Money }>;
convertedOtherRegionsPrice?: { usdPrice: Money; eurPrice: Money };
regionVersion?: { version: string };
}
interface Existing { productId: string; purchaseOptions?: { purchaseOptionId: string; state?: string }[] }
export async function listOneTimeProducts(play: Awaited<ReturnType<typeof playClient>>): Promise<Existing[]> {
const out: Existing[] = [];
let page = '';
do {
// camelCase "oneTimeProducts" here; the lowercase path answers with an HTML 404
const r = await play.call<{ oneTimeProducts?: Existing[]; nextPageToken?: string }>('GET', `${play.API}/oneTimeProducts?pageSize=100${page ? '&pageToken=' + page : ''}`);
out.push(...(r.oneTimeProducts ?? []));
page = r.nextPageToken ?? '';
} while (page);
return out;
}
export async function run(ctx: Ctx): Promise<void> {
const { config, root } = ctx.loaded;
const pkg = need(config.play?.packageName, 'play.packageName');
const only = ctx.args.list('only');
const products = need(config.products, 'products').filter(p => !only.length || only.includes(p.id));
const dry = ctx.args.has('dry');
const play = await playClient(root, pkg);
const existing = new Map((await listOneTimeProducts(play)).map(p => [p.productId, p]));
const langs = new Map(config.languages.map(l => [l.id, l]));
for (const [i, p] of products.entries()) {
const tag = step(i + 1, products.length, p.id);
const conv = await play.call<Converted>('POST', `${play.API}/pricing:convertRegionPrices`, { price: toMoney('USD', p.usd) });
if (!conv.convertedRegionPrices || !conv.convertedOtherRegionsPrice) throw new Error(`${p.id}: convertRegionPrices returned no prices`);
const regions = playRegionConfigs(conv.convertedRegionPrices, p.overrides);
const listings = Object.entries(p.listings).flatMap(([id, l]) =>
playCodes(langs.get(id)!).map(languageCode => ({ languageCode, title: l.title, description: l.description })));
if (!listings.length) throw new Error(`${p.id}: no listing language has a Play code`);
const body = {
packageName: pkg, productId: p.id, listings,
purchaseOptions: [{
purchaseOptionId: OPTION,
buyOption: { legacyCompatible: true, multiQuantityEnabled: false },
regionalPricingAndAvailabilityConfigs: regions,
newRegionsConfig: { usdPrice: conv.convertedOtherRegionsPrice.usdPrice, eurPrice: conv.convertedOtherRegionsPrice.eurPrice, availability: 'AVAILABLE' },
}],
};
const cur = existing.get(p.id);
if (dry) { log('play', `${tag}: ${cur ? 'update' : 'create'} · ${regions.length} regions · ${listings.length} listings (dry)`); continue; }
const v = encodeURIComponent(conv.regionVersion?.version ?? '2022/02');
await play.call('PATCH', `${play.API}/onetimeproducts/${encodeURIComponent(p.id)}?allowMissing=true&regionsVersion.version=${v}&updateMask=listings,purchaseOptions`, body);
log('play', `${tag}: ${cur ? 'updated' : 'created'} · ${regions.length} regions · ${listings.length} listings`);
const active = cur?.purchaseOptions?.find(o => o.purchaseOptionId === OPTION)?.state === 'ACTIVE';
if (active) continue;
try {
await play.call('POST', `${play.API}/oneTimeProducts/${encodeURIComponent(p.id)}/purchaseOptions:batchUpdateStates`, {
requests: [{ activatePurchaseOptionRequest: { packageName: pkg, productId: p.id, purchaseOptionId: OPTION } }],
});
log('play', `${tag}: purchase option activated`);
} catch (e) { warn('play', `${tag}: activate failed: ${(e as Error).message}`); }
}
done('play', dry ? 'products checked (dry run, nothing written)' : 'products done');
}

60
cli/play/release.ts Normal file
View file

@ -0,0 +1,60 @@
// Upload an AAB (or reuse an uploaded versionCode) and put it on one or more tracks in one edit, with the "What's new"
// of every listing language as release notes.
// crt-ship play release app-release.aab [--internal completed] [--production draft] [--name "1.0.0 (3)"] [--dry]
// crt-ship play release --version-code 3 --production draft
// Tracks: internal, alpha (closed), beta (open), production; status completed | draft | inProgress | halted.
// Without a track flag: internal, completed. A production release that is not a draft asks for confirmation.
// Draft app (never published): Play only accepts status "draft" on any track; the first production release is sent
// from the Console (see the play-first-release skill).
import { readFileSync, statSync } from 'node:fs';
import type { Ctx } from '../lib/ctx';
import { confirm, need } from '../lib/ctx';
import { done, log } from '../lib/log';
import { playClient } from './client';
import { readPlayCopy } from './listing';
const TRACKS = ['internal', 'alpha', 'beta', 'production'];
const STATUSES = ['completed', 'draft', 'inProgress', 'halted'];
export async function run(ctx: Ctx): Promise<void> {
const { config, root } = ctx.loaded;
const pkg = need(config.play?.packageName, 'play.packageName');
const a = ctx.args;
const aab = a._.find(x => x.endsWith('.aab'));
const fixed = a.get('version-code');
if (!aab && !fixed) throw new Error('usage: play release <app.aab> | --version-code N [--internal completed] [--production draft] [--name text] [--dry]');
const tracks = TRACKS.filter(t => a.has(t)).map(t => ({ track: t, status: a.get(t) === 'true' ? 'draft' : a.get(t)! }));
if (!tracks.length) tracks.push({ track: 'internal', status: 'completed' });
for (const t of tracks) if (!STATUSES.includes(t.status)) throw new Error(`--${t.track}: status must be one of ${STATUSES.join(', ')}`);
const fraction = a.get('fraction');
const live = tracks.find(t => t.track === 'production' && t.status !== 'draft');
if (live && !a.has('dry') && !(await confirm(ctx, `Release to PRODUCTION as "${live.status}" (public once Google approves)?`))) return;
const notes = readPlayCopy(ctx).filter(c => c.whatsNew).map(c => ({ language: c.lang, text: c.whatsNew }));
const play = await playClient(root, pkg);
try {
await play.edit(async id => {
let code = fixed ?? '';
if (aab) {
log('play', `uploading ${aab} (${(statSync(aab).size / 1048576).toFixed(1)} MB), this can take minutes`);
const b = await play.call<{ versionCode: number }>('POST', `${play.UPLOAD}/edits/${id}/bundles?uploadType=media`,
new Uint8Array(readFileSync(aab)), { 'Content-Type': 'application/octet-stream' });
code = String(b.versionCode);
log('play', `uploaded versionCode ${code}`);
}
for (const t of tracks) {
const release: Record<string, unknown> = { versionCodes: [code], status: t.status };
if (notes.length) release.releaseNotes = notes;
if (a.get('name')) release.name = a.get('name');
if (t.status === 'inProgress') release.userFraction = Number(fraction ?? 0.1);
await play.call('PUT', `${play.API}/edits/${id}/tracks/${t.track}`, { track: t.track, releases: [release] });
log('play', `${t.track} <- ${code} (${t.status}, notes in ${notes.length} languages)`);
}
}, { dry: a.has('dry'), retries: aab ? 0 : 3 });
} catch (e) {
if (/draft app|status draft/i.test(String(e)))
throw new Error(`${(e as Error).message}\n\nThis app has never been published: the API may only create DRAFT releases. Re-run with --production draft, then send it from the Console (skill play-first-release).`);
throw e;
}
done('play', 'release done');
}

31
cli/play/status.ts Normal file
View file

@ -0,0 +1,31 @@
// Read-only overview: tracks and releases, listing languages, one-time products and their purchase option states.
// crt-ship play status [--json]
import type { Ctx } from '../lib/ctx';
import { need } from '../lib/ctx';
import { playClient } from './client';
import { listOneTimeProducts } from './products';
interface Track { track: string; releases?: { name?: string; versionCodes?: string[]; status: string; userFraction?: number }[] }
export async function run(ctx: Ctx): Promise<void> {
const { config, root } = ctx.loaded;
const play = await playClient(root, need(config.play?.packageName, 'play.packageName'));
const e = await play.call<{ id: string }>('POST', `${play.API}/edits`, {});
try {
const tracks = (await play.call<{ tracks?: Track[] }>('GET', `${play.API}/edits/${e.id}/tracks`)).tracks ?? [];
const listings = (await play.call<{ listings?: { language: string }[] }>('GET', `${play.API}/edits/${e.id}/listings`)).listings ?? [];
const details = await play.call<Record<string, string>>('GET', `${play.API}/edits/${e.id}/details`);
const products = await listOneTimeProducts(play);
if (ctx.args.has('json')) { console.log(JSON.stringify({ details, tracks, listings, products }, null, 2)); return; }
console.log(`${play.packageName}\n details: ${details.defaultLanguage} · ${details.contactEmail ?? '-'} · ${details.contactWebsite ?? '-'}`);
console.log(` listings (${listings.length}): ${listings.map(l => l.language).join(', ') || '-'}`);
for (const t of tracks) {
const rs = (t.releases ?? []).map(r => `${r.name ?? '?'} [${r.versionCodes?.join(',') ?? '-'}] ${r.status}${r.userFraction ? ' ' + r.userFraction * 100 + '%' : ''}`);
console.log(` track ${t.track.padEnd(11)} ${rs.join(' | ') || '-'}`);
}
console.log(` products (${products.length}):`);
for (const p of products) console.log(` ${p.productId.padEnd(40)} ${(p.purchaseOptions ?? []).map(o => `${o.purchaseOptionId}:${o.state ?? '?'}`).join(' ')}`);
} finally {
await play.call('DELETE', `${play.API}/edits/${e.id}`).catch(() => {});
}
}