CLI for desktop D2: doctor, inspect --icon / --listings, reviews drafts / approve, init --dry from embedded templates, iOS phased release share, playwright as optional peer (sidecar bundles playwright-core)

This commit is contained in:
CRTkafa 2026-10-10 19:34:45 +00:00
parent 9320d64f46
commit 3f7cf446be
22 changed files with 808 additions and 40 deletions

View file

@ -54,7 +54,17 @@ export async function run(ctx: Ctx): Promise<void> {
const builds = (await c.asc('GET', `/v1/builds?filter[app]=${appId}&sort=-uploadedDate&limit=5&include=preReleaseVersion`));
const iaps = await c.all(`/v1/apps/${appId}/inAppPurchasesV2?limit=200`);
const subs = await c.all(`/v1/reviewSubmissions?filter[app]=${appId}&limit=20`);
if (ctx.args.has('json')) { printJson({ app, versions, builds: builds.data, iaps, subs }); return; }
if (ctx.args.has('json')) {
// phased release of the newest versions that are live or close to it (rollout share on the desktop timeline)
const phased: Record<string, unknown> = {};
for (const v of versions.slice(0, 3)) {
const st = String(v.attributes.appVersionState ?? v.attributes.appStoreState ?? '');
if (!/READY_FOR_SALE|READY_FOR_DISTRIBUTION|PENDING_DEVELOPER_RELEASE|PENDING_APPLE_RELEASE|ACCEPTED/.test(st)) continue;
phased[v.id] = (await c.maybe(`/v1/appStoreVersions/${v.id}/appStoreVersionPhasedRelease`))?.data ?? null;
}
printJson({ app, versions, builds: builds.data, iaps, subs, phased });
return;
}
console.log(`${app.attributes.name} · ${app.attributes.bundleId} · Apple ID ${appId}`);
for (const v of versions) console.log(` version ${v.attributes.versionString.padEnd(8)} ${v.attributes.appVersionState ?? v.attributes.appStoreState}${v.relationships?.build?.data ? ' (build attached)' : ''}`);

52
cli/doctor.ts Normal file
View file

@ -0,0 +1,52 @@
// What this machine has for storebound, and how to get what is missing. The same detection as the desktop app's
// Dependencies screen (lib/tools.ts). Store work (listings, products, releases, reviews) needs none of these tools;
// screenshots, app previews, icons and simulator / emulator captures do. Read-only: it prints commands, it runs none.
// storebound doctor [--dir .] [--json]
import { existsSync } from 'node:fs';
import { join, resolve } from 'node:path';
import pkg from '../package.json' with { type: 'json' };
import type { Args } from './lib/args';
import { CONFIG_NAMES } from './lib/config';
import { log } from './lib/log';
import { textTable } from './lib/table';
import { detectTools, findPlaywright, installCommands, type ToolStatus } from './lib/tools';
export interface DoctorRow {
id: ToolStatus['id'] | 'playwright';
name: string;
found: boolean;
version: string | null;
path: string | null;
source: ToolStatus['source'];
usedFor: string;
/** Install commands for this OS (empty when found). */
install: string[];
url: string | null;
}
export interface DoctorResult { storebound: string; bun: string; platform: string; project: string | null; tools: DoctorRow[]; missing: number }
export function doctor(cwd: string, env: Record<string, string | undefined> = process.env): DoctorResult {
const tools: DoctorRow[] = detectTools(env).map(t => ({ id: t.id, name: t.name, found: t.found, version: t.version, path: t.path, source: t.source, usedFor: t.usedFor,
install: t.found ? [] : installCommands(t.id), url: t.install.url }));
const pw = findPlaywright([cwd, join(import.meta.dir, '..')]);
tools.splice(3, 0, { id: 'playwright', name: 'playwright', found: !!pw, version: null, path: pw, source: pw ? 'system' : null,
usedFor: 'screenshot renders and web captures from a terminal (the desktop app brings its own)', install: pw ? [] : installCommands('playwright'), url: 'https://playwright.dev/docs/intro' });
const project = CONFIG_NAMES.some(n => existsSync(join(cwd, n))) ? cwd : null;
return { storebound: pkg.version, bun: Bun.version, platform: `${process.platform}-${process.arch}`, project, tools, missing: tools.filter(t => !t.found).length };
}
export async function run(args: Args): Promise<void> {
const r = doctor(resolve(args.str('dir', '.')));
if (args.has('json')) { console.log(JSON.stringify(r, null, 2)); return; }
log('doctor', `storebound ${r.storebound} · bun ${r.bun} · ${r.platform}${r.project ? ' · project config found' : ''}`);
console.log(textTable(['tool', 'status', 'version', 'used for'], r.tools.map(t => [t.name, t.found ? (t.source === 'app' ? 'ok (app copy)' : 'ok') : 'missing', t.version ?? '', t.usedFor])));
const missing = r.tools.filter(t => !t.found);
if (!missing.length) { log('doctor', 'everything storebound can use is here'); return; }
console.log('\nTo install what is missing (pick one per tool; storebound never runs these for you):');
for (const t of missing) {
console.log(` ${t.name}`);
for (const c of t.install) console.log(` ${c}`);
if (t.url) console.log(` ${t.url}`);
}
log('doctor', `${missing.length} missing. Store work needs none of them; screenshots, previews, icons and captures do.`);
}

View file

@ -13,6 +13,7 @@ const PLAIN: Record<string, [() => Promise<Plain>, string]> = {
'install': [() => import('./install'), 'skills + MCP server for --agent claude|codex|cursor|copilot|windsurf|gemini|opencode'],
'mcp': [async () => ({ run: async () => (await import('./mcp')).serve() }), 'stdio MCP server wrapping these commands (for any MCP-capable AI tool)'],
'serve': [() => import('./serve'), '--stdio: JSON-RPC session for the storebound desktop app (dry runs; writes need a host confirm token)'],
'doctor': [() => import('./doctor'), 'local tools for screenshots, previews, icons and captures (ffmpeg, Chrome, playwright, Xcode, adb, git) and how to install what is missing; --json'],
'privacy-manifest': [() => import('./privacy-manifest'), 'iOS PrivacyInfo.xcprivacy + required-reason API + SDK manifest scan (--ios <path>)'],
};
const COMMANDS: Record<string, [() => Promise<Mod>, string]> = {

View file

@ -1,15 +1,16 @@
// Copies the templates into the current project without overwriting anything, and makes sure .storebound/ is ignored.
// storebound init [--dir .] [--profile app|game|subscription-app]
// storebound init [--dir .] [--profile app|game|subscription-app] [--dry]
// Profiles (default app): app = utility / productivity app with an optional account and analytics, no ads;
// game = free-to-play game with ads and in-app purchases (the templates storebound shipped before 0.5.0);
// subscription-app = accounts plus auto-renewable subscriptions. Each profile has its own config, declarations,
// App Privacy answers, Data safety section, listing copy and screenshot copy; every answer is a starting point to edit.
// Lookup per file: templates/profiles/<profile>/<file>, then the profile it builds on, then templates/<file>.
import { appendFileSync, copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, join, relative, resolve } from 'node:path';
import type { Args } from './lib/args';
import { type AppProfile, PROFILES } from './lib/config';
import { log } from './lib/log';
import { TEMPLATE_TEXT } from './lib/template-files';
const T = join(import.meta.dir, '..', 'templates');
export const FILES: [string, string][] = [
@ -24,33 +25,43 @@ export const FILES: [string, string][] = [
['testers.csv', '.storebound/testers.csv'],
];
/** Template folders a profile reads from, most specific first. game = the root templates. */
/** Template folders a profile reads from (relative to templates/), most specific first. game = the root templates. */
const CHAIN: Record<AppProfile, string[]> = {
'game': [T],
'app': [join(T, 'profiles', 'app'), T],
'subscription-app': [join(T, 'profiles', 'subscription-app'), join(T, 'profiles', 'app'), T],
'game': [''],
'app': ['profiles/app/', ''],
'subscription-app': ['profiles/subscription-app/', 'profiles/app/', ''],
};
/** Source file of one template for a profile. Pure apart from existsSync. */
export function templateFor(profile: AppProfile, name: string): string {
for (const dir of CHAIN[profile]) if (existsSync(join(dir, name))) return join(dir, name);
/** Key (path under templates/) of one template for a profile. Pure: looks it up in the embedded list. */
export function templateKey(profile: AppProfile, name: string): string {
for (const dir of CHAIN[profile]) if (TEMPLATE_TEXT[dir + name] !== undefined) return dir + name;
throw new Error(`template ${name} not found`);
}
/** Source file of one template for a profile (in the storebound folder; the compiled sidecar has none). */
export const templateFor = (profile: AppProfile, name: string): string => join(T, ...templateKey(profile, name).split('/'));
/** Template text: the embedded copy (the same bytes as the file; tests/apps.test.ts checks it). */
export const templateText = (profile: AppProfile, name: string): string => TEMPLATE_TEXT[templateKey(profile, name)]!;
export async function run(args: Args): Promise<void> {
const root = resolve(args.str('dir', '.'));
const profile = args.str('profile', 'app') as AppProfile;
if (!PROFILES.includes(profile)) throw new Error(`--profile ${profile}: one of ${PROFILES.join(', ')}`);
log('init', `profile ${profile} (templates are starting points: edit every answer to match your app)`);
const dry = args.has('dry');
log('init', `profile ${profile}${dry ? ' (dry run: nothing is written)' : ''} (templates are starting points: edit every answer to match your app)`);
for (const [from, to] of FILES) {
const dest = join(root, to);
if (relative(root, dest).startsWith('..')) throw new Error(`template target outside the project: ${to}`);
if (existsSync(dest)) { log('init', `keep ${to} (exists)`); continue; }
if (dry) { log('init', `would create ${to}`); continue; }
mkdirSync(dirname(dest), { recursive: true });
copyFileSync(templateFor(profile, from), dest);
writeFileSync(dest, templateText(profile, from));
log('init', `create ${to}`);
}
const gi = join(root, '.gitignore');
const cur = existsSync(gi) ? readFileSync(gi, 'utf8') : '';
if (dry) { if (!/^\/?\.storebound\/?$/m.test(cur)) log('init', 'would add .storebound/ to .gitignore'); return; }
if (!/^\/?\.storebound\/?$/m.test(cur)) {
if (cur) appendFileSync(gi, `${cur.endsWith('\n') ? '' : '\n'}# storebound: credentials, fonts, temp files\n.storebound/\n`);
else writeFileSync(gi, '# storebound: credentials, fonts, temp files\n.storebound/\n');

View file

@ -1,9 +1,12 @@
// Offline summary of the project config: app name, store ids, languages, products, shots. No network, no credentials.
// storebound inspect [--json]
import { platformsOf, sellsOn } from './lib/config';
// storebound inspect --icon --json the app icon as a data: URL (for the desktop app)
// storebound inspect --listings [--json] listing completeness per language on both stores (+ rendered screenshots)
import { platformsOf, profileOf, sellsOn } from './lib/config';
import type { Ctx } from './lib/ctx';
import type { ProjectSummary } from './lib/desktop-protocol';
import { log, printJson } from './lib/log';
import { findIcon, iconDataUrl, listingCompleteness } from './lib/project-files';
export function summarize(ctx: Ctx): ProjectSummary {
const { config, root, path } = ctx.loaded;
@ -27,10 +30,21 @@ export function summarize(ctx: Ctx): ProjectSummary {
},
shots: !!config.shots,
testflightGroups: config.apple?.testflight?.groups?.length ?? 0,
profile: profileOf(config),
icon: findIcon(config, root),
};
}
export async function run(ctx: Ctx): Promise<void> {
const { config, root } = ctx.loaded;
if (ctx.args.has('icon')) { printJson(iconDataUrl(findIcon(config, root))); return; }
if (ctx.args.has('listings')) {
const l = listingCompleteness(config, root);
if (ctx.args.has('json')) { printJson(l); return; }
for (const p of l.problems) log('inspect', p);
for (const x of l.locales) log('inspect', `${x.lang.padEnd(6)} ${Math.round(x.complete * 100)} % complete${x.screenshots === null ? '' : ` · ${x.screenshots} screenshots`}`);
return;
}
const s = summarize(ctx);
if (ctx.args.has('json')) { printJson(s); return; }
log('inspect', `${s.name} · ${s.platforms.join(' + ')} · ${s.languages.length} languages · ${s.products} products · ${s.subscriptions} subscriptions`);

View file

@ -90,6 +90,10 @@ export interface ProjectSummary {
catalog: { ios: string[]; android: string[] };
shots: boolean;
testflightGroups: number;
/** App profile from the config (app, game, subscription-app). */
profile?: string;
/** Absolute path of the app icon the config or the usual places point at (project.icon reads it), or null. */
icon?: string | null;
}
// ---- App-centric model (one app = one product on up to two platforms; a workspace holds many apps) ----
@ -112,10 +116,14 @@ export interface StoreRelease {
/** The store's own state word (READY_FOR_SALE, inProgress ...). */
state: string;
phase: ReleasePhase;
/** Android staged rollout user fraction (0-1); iOS phased release percentage comes with D2. */
/** Rollout share (0-1): Android staged rollout user fraction, iOS phased release day -> 1, 2, 5, 10, 20, 50, 100 %. */
fraction: number | null;
/** Android track (production, beta, internal ...). */
track: string | null;
/** iOS phased release: day 1-7 and its state (ACTIVE, PAUSED, COMPLETE); null without one. */
phased?: { state: string; day: number | null } | null;
/** When the store record was made (iOS version createdDate), if the store says. */
date?: string | null;
}
/** A release train: one version (e.g. 2.3.0) across both stores. */
@ -143,8 +151,8 @@ export interface AppStatus {
app: AppIdentity | null;
summary: ProjectSummary | null;
check: { ok: boolean; problems: string[]; warnings: string[] } | null;
/** Release trains; `source: none` offline (no store data read). */
release: { source: 'none' | 'live'; current: ReleaseTrain | null; next: ReleaseTrain | null };
/** Release trains; `source: none` offline (no store data read). `all`: every store release read (live only). */
release: { source: 'none' | 'live'; current: ReleaseTrain | null; next: ReleaseTrain | null; all?: StoreRelease[] };
catalog: CatalogParity | null;
/** live only: per-platform read errors ("unknown, never false"). */
storeErrors: { ios?: string; android?: string };
@ -152,3 +160,47 @@ export interface AppStatus {
}
export interface PortfolioResult { apps: AppStatus[]; at: string }
// ---- Offline project reads (D2) ----
/** One listing field of one language on one store: length against the store limit. */
export interface ListingField { field: string; length: number; limit: number; required: boolean; state: 'ok' | 'missing' | 'over' | 'empty-optional' }
/** Listing completeness of one language (config language id) on both stores. */
export interface ListingLocale {
lang: string;
rtl: boolean;
play: { code: string | null; fields: ListingField[] } | null;
apple: { code: string | null; fields: ListingField[] } | null;
/** Rendered screenshots found for this language (renders folder), null when there is no renders folder. */
screenshots: number | null;
/** Required fields present and within limits, 0-1 (both stores). */
complete: number;
}
export interface ListingsResult {
files: { play: string | null; apple: string | null };
/** File-level problems (missing file, unreadable section). */
problems: string[];
locales: ListingLocale[];
}
/** A local review reply draft (.storebound/replies/<store>-<id>.md) with its checks. */
export interface ReplyDraft {
file: string;
store: 'apple' | 'play';
reviewId: string;
approved: boolean;
sent: string | null;
reply: string;
rating: number | null;
title: string | null;
body: string | null;
date: string | null;
issues: { level: 'error' | 'warn'; msg: string }[];
}
export interface DraftsResult { dir: string; drafts: ReplyDraft[]; problems: string[] }
/** project.icon: the icon as a data: URL (PNG / JPEG / WebP / SVG, at most 1.5 MB), or null. */
export interface IconResult { path: string | null; dataUrl: string | null }

View file

@ -33,13 +33,36 @@ export function applePhase(state: string): ReleasePhase {
return 'other';
}
/** Apple's phased release schedule: share of users with automatic updates on day 1-7. */
export const PHASED_SCHEDULE = [0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1] as const;
/** Phased release of a version (`apple status --json` phased[versionId]) -> rollout share, or null. */
export function phasedFraction(p: { state?: string; currentDayNumber?: number | null } | null | undefined): number | null {
if (!p?.state) return null;
if (p.state === 'COMPLETE') return 1;
const d = typeof p.currentDayNumber === 'number' ? Math.min(7, Math.max(1, Math.round(p.currentDayNumber))) : null;
return d ? PHASED_SCHEDULE[d - 1]! : p.state === 'INACTIVE' ? 0 : null;
}
export function appleReleases(data: unknown): StoreRelease[] {
const versions = ((data as J)?.versions ?? []) as J[];
const builds = new Map((((data as J)?.builds ?? []) as J[]).map(b => [b.id, b.attributes?.version] as const));
const phasedById = (((data as J)?.phased ?? {}) as Record<string, J | null>);
return versions.filter(v => typeof v?.attributes?.versionString === 'string' && (v.attributes.platform ?? 'IOS') === 'IOS').map(v => {
const state = String(v.attributes.appVersionState ?? v.attributes.appStoreState ?? 'UNKNOWN');
const buildId = v.relationships?.build?.data?.id;
return { store: 'ios', version: v.attributes.versionString as string, build: (buildId && builds.get(buildId)) ? String(builds.get(buildId)) : null, state, phase: applePhase(state), fraction: null, track: null };
let phase = applePhase(state);
const pr = (typeof v.id === 'string' ? phasedById[v.id] : null) ?? null;
const prState = typeof pr?.attributes?.phasedReleaseState === 'string' ? String(pr.attributes.phasedReleaseState) : null;
const day = typeof pr?.attributes?.currentDayNumber === 'number' ? pr.attributes.currentDayNumber as number : null;
const fraction = phase === 'live' && prState ? phasedFraction({ state: prState, currentDayNumber: day }) : null;
// live but still rolling out (phased release on, not complete): the same as a Play staged rollout
if (phase === 'live' && prState === 'ACTIVE') phase = 'rollout';
if (phase === 'live' && prState === 'PAUSED') phase = 'halted';
const r: StoreRelease = { store: 'ios', version: v.attributes.versionString as string, build: (buildId && builds.get(buildId)) ? String(builds.get(buildId)) : null, state, phase, fraction, track: null };
if (prState) r.phased = { state: prState, day };
if (typeof v.attributes.createdDate === 'string') r.date = v.attributes.createdDate;
return r;
});
}
@ -65,14 +88,14 @@ const PHASE_RANK: Record<ReleasePhase, number> = { live: 0, rollout: 1, halted:
const pick = (rs: StoreRelease[]): StoreRelease | null => [...rs].sort((a, b) => PHASE_RANK[a.phase] - PHASE_RANK[b.phase])[0] ?? null;
/**
* Release trains: one version across both stores. current = the highest version that is live (fully) on a store;
* next = the highest version above it on either store (review, testing, rollout, draft ...). A store without that
* version has null in the train.
* Release trains: one version across both stores. current = the highest version that reaches users on a store (live,
* or rolling out: a staged rollout or an iOS phased release, also when halted / paused); next = the highest version
* above it on either store (review, testing, draft ...). A store without that version has null in the train.
*/
export function releaseTrains(ios: StoreRelease[], android: StoreRelease[]): { current: ReleaseTrain | null; next: ReleaseTrain | null } {
const all = [...ios, ...android].filter((r): r is StoreRelease & { version: string } => !!r.version);
const train = (v: string): ReleaseTrain => ({ version: v, ios: pick(all.filter(r => r.store === 'ios' && r.version === v)), android: pick(all.filter(r => r.store === 'android' && r.version === v)) });
const live = all.filter(r => r.phase === 'live').map(r => r.version).sort(cmpVersion).at(-1) ?? null;
const live = all.filter(r => r.phase === 'live' || r.phase === 'rollout' || r.phase === 'halted').map(r => r.version).sort(cmpVersion).at(-1) ?? null;
const above = all.filter(r => !live || cmpVersion(r.version, live) > 0).map(r => r.version).sort(cmpVersion).at(-1) ?? null;
return { current: live ? train(live) : null, next: above ? train(above) : null };
}

180
cli/lib/project-files.ts Normal file
View file

@ -0,0 +1,180 @@
// Offline reads of a project's own files for the desktop app (serve.ts): the app icon, listing completeness per
// language on both stores, and the local review reply drafts. Tolerant on purpose: a broken file becomes a problem
// line, never an exception, so one bad section does not hide the rest ("unknown, never false").
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
import { extname, isAbsolute, join, resolve } from 'node:path';
import { type ShipConfig, playCodes } from './config';
import { APPLE_LIMITS, len, PLAY_LIMITS } from './copy';
import type { DraftsResult, IconResult, ListingField, ListingLocale, ListingsResult, ReplyDraft } from './desktop-protocol';
import { parseFrontMatter, stringifyFrontMatter } from './frontmatter';
import { checkReply, parseDraft } from './reviews';
const IMAGE = /\.(png|jpe?g|webp|svg)$/i;
export const ICON_MAX_BYTES = 1_500_000;
/** Icon candidates, most specific first: icons.composite, the rendered store icons, play.icon, the usual places. */
export function iconCandidates(config: Pick<ShipConfig, 'icons' | 'play'>, root: string): string[] {
const r = (p: string) => (isAbsolute(p) ? p : resolve(root, p));
const out: string[] = [];
if (config.icons?.composite) out.push(r(config.icons.composite));
if (config.icons?.out) out.push(r(join(config.icons.out, 'app-store-1024.png')), r(join(config.icons.out, 'play-512.png')));
if (config.play?.icon) out.push(r(config.play.icon));
for (const p of ['store/icons/app-store-1024.png', 'store/icons/play-512.png', 'store/icon.png', 'store/icon-1024.png', 'icon.png', 'assets/icon.png',
'resources/icon.png', 'assets/icon-only.png', 'public/icon-512.png', 'web/icon-512.png']) out.push(r(p));
return [...new Set(out)];
}
/** First candidate that exists and is an image file, or null. */
export function findIcon(config: Pick<ShipConfig, 'icons' | 'play'>, root: string): string | null {
for (const p of iconCandidates(config, root)) {
try { if (IMAGE.test(p) && statSync(p).isFile()) return p; } catch { /* next */ }
}
return null;
}
const MIME: Record<string, string> = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.svg': 'image/svg+xml' };
/** The icon as a data: URL for the desktop window (its CSP allows data: images only). Too big or unreadable -> null. */
export function iconDataUrl(path: string | null): IconResult {
if (!path) return { path: null, dataUrl: null };
try {
const st = statSync(path);
if (!st.isFile() || st.size > ICON_MAX_BYTES) return { path, dataUrl: null };
const mime = MIME[extname(path).toLowerCase()];
if (!mime) return { path, dataUrl: null };
return { path, dataUrl: `data:${mime};base64,${readFileSync(path).toString('base64')}` };
} catch { return { path, dataUrl: null }; }
}
/** "### heading" sub-sections of a "## " section with their first fenced block (like lib/copy.ts, never throws). */
function blocks(section: string): { heading: string; text: string }[] {
const out: { heading: string; text: string }[] = [];
for (const part of section.split(/^### /m).slice(1)) {
const heading = part.split('\n')[0]!.trim();
const m = /^```[^\n]*\n([\s\S]*?)\n```/m.exec(part);
out.push({ heading, text: m ? m[1]!.trim() : '' });
}
return out;
}
function field(name: string, text: string | undefined, limit: number, required: boolean): ListingField {
const n = text ? len(text) : 0;
const state: ListingField['state'] = !n ? (required ? 'missing' : 'empty-optional') : n > limit ? 'over' : 'ok';
return { field: name, length: n, limit, required, state };
}
/** Play sections by Play language code: { title, short, full, whatsNew } texts. */
export function playSections(md: string): Map<string, Record<string, string | undefined>> {
const out = new Map<string, Record<string, string | undefined>>();
for (const sec of md.split(/^## /m).slice(1)) {
const m = /^<!--\s*play:\s*([^>]+?)\s*-->$/m.exec(sec);
if (!m) continue;
const bs = blocks(sec);
const find = (re: RegExp): string | undefined => bs.find(b => re.test(b.heading))?.text;
const f = { title: find(/\btitle\b/i), short: find(/\bshort\b/i), full: find(/\bfull\b/i), whatsNew: find(/what'?s new|release notes/i) };
for (const lang of m[1]!.split(',').map(s => s.trim()).filter(Boolean)) out.set(lang, f);
}
return out;
}
/** App Store sections by App Store Connect locale: field -> text. */
export function appleSections(md: string): Map<string, Record<string, string | undefined>> {
const out = new Map<string, Record<string, string | undefined>>();
for (const sec of md.split(/^## /m).slice(1)) {
const locale = sec.split(/[\s·]/)[0]!.trim();
if (!/^[a-z]{2,3}(-[A-Za-z]{2,4})?$/.test(locale)) continue;
const f: Record<string, string | undefined> = {};
for (const b of blocks(sec)) if (b.heading in APPLE_LIMITS) f[b.heading] = b.text;
out.set(locale, f);
}
return out;
}
function countImages(dir: string): number {
let n = 0;
try {
for (const e of readdirSync(dir, { withFileTypes: true })) {
if (e.isDirectory()) n += countImages(join(dir, e.name));
else if (/\.(png|jpe?g)$/i.test(e.name)) n++;
}
} catch { /* unreadable: 0 */ }
return n;
}
/** Listing completeness per config language, both stores, plus rendered screenshots per language. */
export function listingCompleteness(config: ShipConfig, root: string): ListingsResult {
const problems: string[] = [];
const read = (rel: string | undefined, fallback: string): { path: string | null; text: string | null } => {
const p = resolve(root, rel ?? fallback);
if (!existsSync(p)) { problems.push(`${rel ?? fallback}: file not found`); return { path: null, text: null }; }
try { return { path: p, text: readFileSync(p, 'utf8') }; } catch (e) { problems.push(`${rel ?? fallback}: ${(e as Error).message}`); return { path: p, text: null }; }
};
const playFile = config.play ? read(config.play.listing, 'store/listing.md') : { path: null, text: null };
const appleFile = config.apple ? read(config.apple.listing, 'store/appstore.md') : { path: null, text: null };
const play = playFile.text !== null ? playSections(playFile.text) : null;
const apple = appleFile.text !== null ? appleSections(appleFile.text) : null;
const rendersDir = resolve(root, config.renders ?? config.shots?.out ?? 'store/renders');
const hasRenders = existsSync(rendersDir);
const locales: ListingLocale[] = config.languages.map(l => {
let req = 0, good = 0;
const tally = (fs: ListingField[]) => { for (const f of fs) if (f.required) { req++; if (f.state === 'ok') good++; } return fs; };
const pc = config.play ? playCodes(l)[0] ?? null : null;
const ps = pc && play ? play.get(pc) : undefined;
const playPart = config.play ? {
code: pc,
fields: tally([
field('title', ps?.title ?? (ps ? config.app.name : undefined), PLAY_LIMITS.title, true),
field('short', ps?.short, PLAY_LIMITS.short, true),
field('full', ps?.full, PLAY_LIMITS.full, true),
field('whatsNew', ps?.whatsNew, PLAY_LIMITS.whatsNew, false),
]),
} : null;
const ac = config.apple ? l.apple ?? null : null;
const as = ac && apple ? apple.get(ac) : undefined;
const applePart = config.apple ? {
code: ac,
fields: tally([
field('name', as?.name ?? (as ? config.app.name : undefined), APPLE_LIMITS.name, true),
field('subtitle', as?.subtitle, APPLE_LIMITS.subtitle, true),
field('promotionalText', as?.promotionalText, APPLE_LIMITS.promotionalText, true),
field('keywords', as?.keywords, APPLE_LIMITS.keywords, true),
field('description', as?.description, APPLE_LIMITS.description, true),
field('whatsNew', as?.whatsNew, APPLE_LIMITS.whatsNew, false),
]),
} : null;
const screenshots = hasRenders ? countImages(join(rendersDir, l.id)) : null;
return { lang: l.id, rtl: !!l.rtl, play: playPart, apple: applePart, screenshots, complete: req ? good / req : 0 };
});
return { files: { play: playFile.path, apple: appleFile.path }, problems, locales };
}
/** Local reply drafts with their send checks. Unparsable files become problems. */
export function readReplyDrafts(dir: string): DraftsResult {
const out: DraftsResult = { dir, drafts: [], problems: [] };
if (!existsSync(dir)) return out;
for (const name of readdirSync(dir).filter(n => n.endsWith('.md')).sort()) {
const file = join(dir, name);
try {
const text = readFileSync(file, 'utf8');
const d = parseDraft(file, text);
const { data, body } = parseFrontMatter(text);
const quote = body.split(/^## Reply\s*$/m)[0]!.split('\n').filter(l => l.startsWith('>')).map(l => l.replace(/^>\s?/, '')).join('\n').trim();
const num = (v: unknown): number | null => (typeof v === 'number' ? v : typeof v === 'string' && /^\d+$/.test(v) ? Number(v) : null);
const str = (v: unknown): string | null => (typeof v === 'string' && v ? v : null);
const draft: ReplyDraft = {
file, store: d.store, reviewId: d.reviewId, approved: d.approved, sent: d.sent, reply: d.reply,
rating: num(data.rating), title: str(data.title) ?? (/^# [★☆]*\s*(.+)$/m.exec(body)?.[1]?.trim() || null), body: quote || null, date: str(data.date),
issues: d.reply ? checkReply(d.reply, d.store) : [],
};
out.drafts.push(draft);
} catch (e) { out.problems.push(`${name}: ${(e as Error).message}`); }
}
return out;
}
/** Front matter `approved: <bool>` set in a draft file text; the body unchanged. */
export function setApproved(text: string, approved: boolean): string {
const { data, body } = parseFrontMatter(text);
if (data.store !== 'apple' && data.store !== 'play') throw new Error('not a review reply draft (front matter "store" missing)');
return stringifyFrontMatter({ ...data, approved }, body);
}

51
cli/lib/template-files.ts Normal file
View file

@ -0,0 +1,51 @@
// Every file under templates/, embedded as text so `storebound init` also works from the compiled desktop sidecar
// (a `bun build --compile` binary has no templates folder next to it). tests/apps.test.ts checks this list against the
// folder: add a line here when a template is added.
import t0 from '../../templates/app-privacy.md' with { type: 'text' };
import t1 from '../../templates/appstore.md' with { type: 'text' };
import t2 from '../../templates/credentials.example.json' with { type: 'text' };
import t3 from '../../templates/data-safety.csv' with { type: 'text' };
import t4 from '../../templates/declarations.md' with { type: 'text' };
import t5 from '../../templates/listing.md' with { type: 'text' };
import t6 from '../../templates/privacy-policy.html' with { type: 'text' };
import t7 from '../../templates/profiles/app/app-privacy.md' with { type: 'text' };
import t8 from '../../templates/profiles/app/appstore.md' with { type: 'text' };
import t9 from '../../templates/profiles/app/declarations.md' with { type: 'text' };
import t10 from '../../templates/profiles/app/listing.md' with { type: 'text' };
import t11 from '../../templates/profiles/app/privacy-policy.html' with { type: 'text' };
import t12 from '../../templates/profiles/app/shots-copy.json' with { type: 'text' };
import t13 from '../../templates/profiles/app/storebound.config.ts' with { type: 'text' };
import t14 from '../../templates/profiles/subscription-app/app-privacy.md' with { type: 'text' };
import t15 from '../../templates/profiles/subscription-app/appstore.md' with { type: 'text' };
import t16 from '../../templates/profiles/subscription-app/declarations.md' with { type: 'text' };
import t17 from '../../templates/profiles/subscription-app/listing.md' with { type: 'text' };
import t18 from '../../templates/profiles/subscription-app/storebound.config.ts' with { type: 'text' };
import t19 from '../../templates/shots-copy.json' with { type: 'text' };
import t20 from '../../templates/storebound.config.ts' with { type: 'text' };
import t21 from '../../templates/testers.csv' with { type: 'text' };
/** Template text by its path under templates/ (forward slashes). */
export const TEMPLATE_TEXT: Record<string, string> = {
'app-privacy.md': t0 as unknown as string,
'appstore.md': t1 as unknown as string,
'credentials.example.json': t2 as unknown as string,
'data-safety.csv': t3 as unknown as string,
'declarations.md': t4 as unknown as string,
'listing.md': t5 as unknown as string,
'privacy-policy.html': t6 as unknown as string,
'profiles/app/app-privacy.md': t7 as unknown as string,
'profiles/app/appstore.md': t8 as unknown as string,
'profiles/app/declarations.md': t9 as unknown as string,
'profiles/app/listing.md': t10 as unknown as string,
'profiles/app/privacy-policy.html': t11 as unknown as string,
'profiles/app/shots-copy.json': t12 as unknown as string,
'profiles/app/storebound.config.ts': t13 as unknown as string,
'profiles/subscription-app/app-privacy.md': t14 as unknown as string,
'profiles/subscription-app/appstore.md': t15 as unknown as string,
'profiles/subscription-app/declarations.md': t16 as unknown as string,
'profiles/subscription-app/listing.md': t17 as unknown as string,
'profiles/subscription-app/storebound.config.ts': t18 as unknown as string,
'shots-copy.json': t19 as unknown as string,
'storebound.config.ts': t20 as unknown as string,
'testers.csv': t21 as unknown as string,
};

View file

@ -88,3 +88,28 @@ export function detectTools(env: Record<string, string | undefined> = process.en
out.push(bin('git', 'git', 'release notes from history, analytics compare', { kind: 'link', url: 'https://git-scm.com/downloads', note: 'Install git from your OS package manager.' }, ['--version']));
return out;
}
/**
* Commands that install a tool on this OS (shown by `storebound doctor` and the desktop Dependencies screen, never
* run by storebound). Package managers only; the desktop app can also download ffmpeg and Chrome for Testing itself.
*/
export function installCommands(id: ToolId | 'playwright', platform: NodeJS.Platform = process.platform): string[] {
const mac = platform === 'darwin', win = platform === 'win32';
switch (id) {
case 'ffmpeg': case 'ffprobe': return mac ? ['brew install ffmpeg'] : win ? ['winget install --id Gyan.FFmpeg'] : ['sudo apt install ffmpeg', 'sudo dnf install ffmpeg'];
case 'chrome': return ['bunx playwright install chromium', ...(mac ? ['brew install --cask google-chrome'] : win ? ['winget install --id Google.Chrome'] : [])];
case 'playwright': return ['bun add -d playwright'];
case 'xcode': return mac ? ['xcode-select --install'] : [];
case 'simctl': return mac ? ['Install Xcode from the App Store, then: sudo xcode-select -s /Applications/Xcode.app'] : [];
case 'adb': return mac ? ['brew install --cask android-platform-tools'] : win ? ['winget install --id Google.PlatformTools'] : ['sudo apt install adb'];
case 'git': return mac ? ['xcode-select --install', 'brew install git'] : win ? ['winget install --id Git.Git'] : ['sudo apt install git'];
}
}
/** Where playwright resolves from (the project, then the storebound folder), or null. */
export function findPlaywright(bases: string[]): string | null {
for (const base of bases) {
try { return Bun.resolveSync('playwright', base); } catch { /* next */ }
}
return null;
}

View file

@ -2,6 +2,8 @@
// storebound reviews list [--store apple|play] [--days 14] [--unanswered] [--rating 1,2] [--json]
// storebound reviews draft [--store apple|play] [--days 14] [--rating 1,2,3] [--all] [--dir .storebound/replies] [--dry]
// storebound reviews send [--dir .storebound/replies] [--dry] [--yes]
// storebound reviews drafts [--json] the local drafts with the checks `send` applies (offline)
// storebound reviews approve <draft file> [--undo] [--dry] sets approved: true (false) in one draft (local file)
// `draft` writes one Markdown file per unanswered review into .storebound/replies/ (gitignored): front matter
// (store, review_id, rating, approved: false), the review, and an empty "## Reply" section. Existing files are never
// overwritten (your edits stay). The owner or an agent with the review-replies skill writes the reply; the owner sets
@ -9,7 +11,7 @@
// confirmation, then writes `sent: <time>` into the file. Replies are public: `send` is not an MCP tool.
// Google Play's API only returns reviews created or edited in the last 7 days.
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { join, relative, resolve } from 'node:path';
import { ascClient, type J } from './apple/asc';
import type { Ctx } from './lib/ctx';
import { confirm } from './lib/ctx';
@ -19,6 +21,7 @@ import {
type Review, sendPlan,
} from './lib/reviews';
import { textTable } from './lib/table';
import { readReplyDrafts, setApproved } from './lib/project-files';
import { playClient } from './play/client';
const TAG = 'reviews';
@ -139,5 +142,34 @@ export async function run(ctx: Ctx): Promise<void> {
done(TAG, `${sent}/${plan.send.length} sent (Apple shows replies within about 24 hours)`);
return;
}
throw new Error('usage: storebound reviews list | draft | send');
if (sub === 'drafts') {
// read-only: the local drafts with the checks `send` applies (no network)
const r = readReplyDrafts(dir);
if (a.has('json')) { printJson(r); return; }
console.log(textTable(['store', 'review', 'state', 'chars', 'checks'], r.drafts.map(d => [d.store, d.reviewId, d.sent ? `sent ${d.sent.slice(0, 10)}` : d.approved ? 'approved' : 'draft',
[...d.reply].length, d.issues.map(i => `${i.level}: ${i.msg}`).join('; ')])));
for (const p of r.problems) warn(TAG, p);
done(TAG, `${r.drafts.length} draft(s) in ${dir}`);
return;
}
if (sub === 'approve') {
// marks one draft approved (or not, with --undo); local file only, nothing is sent
const file = a.get('file') ?? a._[1];
if (!file) throw new Error('usage: storebound reviews approve <draft file> [--undo] [--dry]');
const p = resolve(dir, file);
if (relative(dir, p).startsWith('..') || !p.endsWith('.md') || !existsSync(p)) throw new Error(`no draft ${file} in ${dir}`);
const text = readFileSync(p, 'utf8');
const d = parseDraft(p, text);
const approved = !a.has('undo');
if (approved) {
const errors = checkReply(d.reply, d.store).filter(i => i.level === 'error');
if (errors.length) throw new Error(`${file}: ${errors.map(i => i.msg).join('; ')}`);
}
if (a.has('dry')) { done(TAG, `would set approved: ${approved} in ${p} (dry run)`); return; }
writeFileSync(p, setApproved(text, approved));
done(TAG, `${approved ? 'approved' : 'approval removed'}: ${p} (send with storebound reviews send)`);
return;
}
throw new Error('usage: storebound reviews list | draft | drafts | approve | send');
}

View file

@ -37,12 +37,36 @@ export const FORBIDDEN_METHOD_WORDS = /submit|release|publish|rollout|resume|com
/** Read tools whose command prints a structured result with --json. */
export const JSON_TOOLS = new Set(['check', 'check_aso', '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']);
'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']);
/**
* Methods only the desktop profile has (not MCP tools): offline reads of the project's own files, and two local
* writes the owner confirms in a native dialog. Approving a reply draft is the owner's decision, so AI tools do not get
* it; `project.init` writes the templates into a new folder (the host passes that folder, it has no config yet).
*/
export const DESKTOP_ONLY: ToolDef[] = [
{ name: 'project_icon', title: 'App icon', command: ['inspect', '--icon'], write: false, network: false,
description: 'The app icon (icons.composite, the rendered store icons, play.icon or the usual places) as a data: URL, at most 1.5 MB.' },
{ name: 'project_listings', title: 'Listing completeness', command: ['inspect', '--listings'], write: false, network: false,
description: 'Per config language and store: listing fields present and within the store limits (store/listing.md, store/appstore.md), and rendered screenshots per language.' },
{ name: 'reviews_drafts', title: 'Reply drafts', command: ['reviews', 'drafts'], write: false, network: false,
description: 'The local review reply drafts (.storebound/replies) with the checks `reviews send` applies: approved, sent, length, no incentives, no personal data.' },
{ name: 'reviews_approve', title: 'Approve a reply draft', command: ['reviews', 'approve'], write: true, network: false, idempotent: true,
description: 'Sets approved: true (or false with undo) in one local reply draft after its checks pass. Nothing is sent: replies go out with `storebound reviews send` in a terminal.',
props: { file: { type: 'string', pattern: '^(apple|play)-[A-Za-z0-9._-]{1,120}\\.md$', description: 'Draft file name in .storebound/replies' }, undo: { type: 'boolean', default: false } },
required: ['file'], args: i => [String(i.file), ...(i.undo === true ? ['--undo'] : [])] },
{ name: 'project_init', title: 'Start an app folder', command: ['init'], write: true, network: false, idempotent: true,
description: 'Copies the storebound templates (config, listing, screenshot copy, declarations, privacy policy) for a profile into an empty app folder; existing files are kept.',
props: { profile: { type: 'string', enum: ['app', 'game', 'subscription-app'], default: 'app' } }, args: i => ['--profile', String(i.profile ?? 'app')] },
];
/** Desktop-only methods whose `project` is a folder without a config yet. */
const NEW_PROJECT = new Set(['project_init']);
/** `apple_testflight_status` -> `apple.testflight_status`: first underscore becomes the namespace dot. */
export const methodName = (tool: string): string => tool.replace('_', '.');
export const DESKTOP_TOOLS: ToolDef[] = TOOLS.filter(t => !DESKTOP_EXCLUDED.has(t.name));
export const DESKTOP_TOOLS: ToolDef[] = [...TOOLS.filter(t => !DESKTOP_EXCLUDED.has(t.name)), ...DESKTOP_ONLY];
const byMethod = new Map(DESKTOP_TOOLS.map(t => [methodName(t.name), t] as const));
function argsSchema(t: ToolDef): MethodDescriptor['args'] {
@ -97,6 +121,17 @@ function credentialsOf(v: unknown): Record<string, string> {
return pickCallEnv(v as Record<string, unknown>);
}
/** Absolute existing folder without a storebound config (project.init), else an error. */
export function checkNewProject(p: unknown): string {
if (typeof p !== 'string' || !p || !isAbsolute(p)) throw new RpcError(ERR.invalidParams, 'project: absolute folder path required');
const dir = resolve(p);
let isDir = false;
try { isDir = statSync(dir).isDirectory(); } catch { /* missing */ }
if (!isDir) throw new RpcError(ERR.invalidParams, `project: not a folder: ${dir}`);
if (CONFIG_NAMES.some(n => existsSync(join(dir, n)))) throw new RpcError(ERR.invalidParams, `project: ${dir} already has a storebound config`);
return dir;
}
/** One sidecar session: state is the secret (after hello), the token guard and the running requests. */
export class Session {
private guard: TokenGuard | null = null;
@ -170,7 +205,7 @@ export class Session {
private async tool(method: string, t: ToolDef, params: Json, id: Id): Promise<ToolResult> {
for (const k of Object.keys(params)) if (!['project', 'args', 'dryRun', 'confirmToken', 'credentials'].includes(k)) throw new RpcError(ERR.invalidParams, `unknown param: ${k}`);
const project = checkProject(params.project);
const project = NEW_PROJECT.has(t.name) ? checkNewProject(params.project) : checkProject(params.project);
const args = (params.args ?? {}) as Json;
if (typeof args !== 'object' || args === null || Array.isArray(args)) throw new RpcError(ERR.invalidParams, 'args must be an object');
if ('dry_run' in args) throw new RpcError(ERR.invalidParams, 'args.dry_run: use params.dryRun');
@ -240,7 +275,8 @@ export class Session {
const [apple, play] = await Promise.all([summary.apple ? store(['apple', 'status', '--json']) : undefined, summary.play ? store(['play', 'status', '--json']) : undefined]);
if (apple?.error) e.storeErrors.ios = apple.error;
if (play?.error) e.storeErrors.android = play.error;
e.release = { source: 'live', ...releaseTrains(apple?.data ? appleReleases(apple.data) : [], play?.data ? playReleases(play.data) : []) };
const ios = apple?.data ? appleReleases(apple.data) : [], android = play?.data ? playReleases(play.data) : [];
e.release = { source: 'live', ...releaseTrains(ios, android), all: [...ios, ...android] };
e.catalog = catalogParity(summary, apple?.data ? appleProductIds(apple.data) : undefined, play?.data ? playProductIds(play.data) : undefined);
}
e.ok = e.check.ok && !e.storeErrors.ios && !e.storeErrors.android && (e.catalog?.ok ?? true);

View file

@ -1,7 +1,10 @@
// Playwright is not a dependency of storebound: it is resolved from the project (or the storebound folder), so a project
// that never renders screenshots never downloads a browser. Launch order: Playwright's own Chromium, then an installed
// Google Chrome (channel "chrome"), so `bunx playwright install chromium` is optional when Chrome is there.
// Playwright is an optional peer dependency of storebound, resolved from the project (or the storebound folder), so a
// project that never renders screenshots never downloads a browser. The compiled desktop sidecar carries its own
// playwright-core (tools/build-sidecars.ts bundles it) and renders with the Chrome for Testing the desktop app manages
// (STOREBOUND_CHROME), so desktop users need neither playwright nor a browser in their project.
// Launch order: STOREBOUND_CHROME, Playwright's own Chromium, then an installed Google Chrome (channel "chrome").
import { join } from 'node:path';
import { compiled } from '../lib/runner';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async function chromium(root: string): Promise<any> {
@ -11,6 +14,8 @@ async function chromium(root: string): Promise<any> {
return (await import(p)).chromium;
} catch { /* next */ }
}
// only reached in the compiled sidecar: the bundled playwright-core (not a runtime dependency of the npm package)
if (compiled()) return (await import('playwright-core')).chromium;
throw new Error('playwright not found: in your project run `bun add -d playwright` (and `bunx playwright install chromium` if Google Chrome is not installed)');
}

4
cli/text-modules.d.ts vendored Normal file
View file

@ -0,0 +1,4 @@
// Template files imported as text (lib/template-files.ts, `with { type: 'text' }`).
declare module '*.md' { const text: string; export default text; }
declare module '*.csv' { const text: string; export default text; }
declare module '*.html' { const text: string; export default text; }