From 0ace432e87c394a3f1a40aa1d1ce830a0c9c80e6 Mon Sep 17 00:00:00 2001 From: CRT Date: Sun, 11 Oct 2026 03:34:45 +0800 Subject: [PATCH 1/3] 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) --- CHANGELOG.md | 15 +++ README.md | 1 + cli/apple/status.ts | 12 ++- cli/doctor.ts | 52 +++++++++++ cli/index.ts | 1 + cli/init.ts | 35 ++++--- cli/inspect.ts | 16 +++- cli/lib/desktop-protocol.ts | 58 +++++++++++- cli/lib/portfolio.ts | 33 ++++++- cli/lib/project-files.ts | 180 ++++++++++++++++++++++++++++++++++++ cli/lib/template-files.ts | 51 ++++++++++ cli/lib/tools.ts | 25 +++++ cli/reviews.ts | 36 +++++++- cli/serve.ts | 44 ++++++++- cli/shots/browser.ts | 11 ++- cli/text-modules.d.ts | 4 + package.json | 9 ++ tests/desktop-d2.test.ts | 165 +++++++++++++++++++++++++++++++++ tests/portfolio.test.ts | 21 ++++- tests/serve.test.ts | 38 +++++++- tools/build-sidecars.ts | 38 +++++++- tsconfig.json | 3 +- 22 files changed, 808 insertions(+), 40 deletions(-) create mode 100644 cli/doctor.ts create mode 100644 cli/lib/project-files.ts create mode 100644 cli/lib/template-files.ts create mode 100644 cli/text-modules.d.ts create mode 100644 tests/desktop-d2.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 73ddfd8..6d47dfb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,21 @@ Releases / Catalog / Listings / Health / Reviews / TestFlight, App folders, Accounts, Dependencies, Settings), store keys in the OS keychain, native confirm dialogs with the dry run before any write. See `docs/desktop.md`. - `--json` on `catalog diff` goes through the same machine-readable result line. +- **`storebound doctor`** (`--json`): ffmpeg, ffprobe, Chrome, playwright, Xcode tools, simctl, adb and git with + versions (the same detection as the desktop Dependencies screen) and the install commands for this OS. It runs none. +- `playwright` is an optional peer dependency (it was only documented before). The compiled desktop sidecar bundles + `playwright-core` and renders with the app's Chrome for Testing (`STOREBOUND_CHROME`), so desktop users need neither. +- `inspect --icon` / `inspect --listings` (listing completeness per language on both stores, rendered screenshots), + `reviews drafts [--json]` (local reply drafts with the send checks), `reviews approve [--undo] [--dry]`, + `init --dry`; templates are embedded so `init` works from a single-file binary. +- `apple status --json` includes the phased release of the newest live versions; release trains now count a staged + rollout or iOS phased release (also halted / paused) as the current train. +- **Desktop D2** (`apps/desktop`): redesigned shell (command palette, toasts with progress and cancel, skeletons, + illustrated empty states, first-run guide), release timeline per app, catalog parity matrix, listing completeness, + health sparklines against the Play thresholds, reviews inbox with star distribution and draft approval, TestFlight + groups and builds, store readiness with fix hints; offline cache of the last reads (SQLite, "last read" stamps); + one-click ffmpeg (pinned SHA-256) and Chrome for Testing (Google's code signature) downloads into app data; + English and Turkish with an i18n check, 7:1 text contrast checked in both themes. - `tools/build-sidecars.ts`: single-file executables for macOS (arm64, x64), Linux (x64, arm64) and Windows (x64), re-signed ad hoc on macOS and checked for build-machine paths. The MCP server now also runs from such a binary. diff --git a/README.md b/README.md index cf6c315..6b431da 100644 --- a/README.md +++ b/README.md @@ -182,6 +182,7 @@ run in the background with a log (`storebound shots render > .storebound/render. | `validate [--apple] [--play]` | API, read-only | readiness report with ordered blockers plus the local renders checks (`--no-local` skips); exit 1 while any blocker is left | | `whats-new [--since ]` | local | draft player-facing release notes from git log into both listing files | | `privacy-manifest --ios ` | local | PrivacyInfo.xcprivacy, required-reason APIs, SDKs without manifests | +| `doctor [--json]` | local | which local tools are here (ffmpeg, Chrome, playwright, Xcode, adb, git) and how to install the missing ones | | `icons` | local | App Store 1024 (no alpha), Play 512, web, Capacitor sources, Android legacy launcher icons | diff --git a/cli/apple/status.ts b/cli/apple/status.ts index 31ef125..74ee204 100644 --- a/cli/apple/status.ts +++ b/cli/apple/status.ts @@ -54,7 +54,17 @@ export async function run(ctx: Ctx): Promise { 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 = {}; + 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)' : ''}`); diff --git a/cli/doctor.ts b/cli/doctor.ts new file mode 100644 index 0000000..0ddf74c --- /dev/null +++ b/cli/doctor.ts @@ -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 = 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 { + 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.`); +} diff --git a/cli/index.ts b/cli/index.ts index 58e8553..9986970 100755 --- a/cli/index.ts +++ b/cli/index.ts @@ -13,6 +13,7 @@ const PLAIN: Record Promise, 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 )'], }; const COMMANDS: Record Promise, string]> = { diff --git a/cli/init.ts b/cli/init.ts index e5ba529..4d224fe 100644 --- a/cli/init.ts +++ b/cli/init.ts @@ -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//, then the profile it builds on, then templates/. -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 = { - '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 { 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'); diff --git a/cli/inspect.ts b/cli/inspect.ts index ec36d6b..22520f3 100644 --- a/cli/inspect.ts +++ b/cli/inspect.ts @@ -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 { + 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`); diff --git a/cli/lib/desktop-protocol.ts b/cli/lib/desktop-protocol.ts index 40a182b..ac8019c 100644 --- a/cli/lib/desktop-protocol.ts +++ b/cli/lib/desktop-protocol.ts @@ -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/-.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 } diff --git a/cli/lib/portfolio.ts b/cli/lib/portfolio.ts index 76d2e64..848b326 100644 --- a/cli/lib/portfolio.ts +++ b/cli/lib/portfolio.ts @@ -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); 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 = { 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 }; } diff --git a/cli/lib/project-files.ts b/cli/lib/project-files.ts new file mode 100644 index 0000000..eb6276e --- /dev/null +++ b/cli/lib/project-files.ts @@ -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, 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, 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 = { '.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> { + const out = new Map>(); + for (const sec of md.split(/^## /m).slice(1)) { + const m = /^$/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> { + const out = new Map>(); + 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 = {}; + 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: ` 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); +} diff --git a/cli/lib/template-files.ts b/cli/lib/template-files.ts new file mode 100644 index 0000000..9ba695a --- /dev/null +++ b/cli/lib/template-files.ts @@ -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 = { + '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, +}; diff --git a/cli/lib/tools.ts b/cli/lib/tools.ts index a3960cb..2e145c2 100644 --- a/cli/lib/tools.ts +++ b/cli/lib/tools.ts @@ -88,3 +88,28 @@ export function detectTools(env: Record = 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; +} diff --git a/cli/reviews.ts b/cli/reviews.ts index 0df436a..832bbb5 100644 --- a/cli/reviews.ts +++ b/cli/reviews.ts @@ -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 [--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: